diff --git a/.cargo/config.toml b/.cargo/config.toml index c5ddbf8067..89b6018d2f 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -9,9 +9,12 @@ rustflags = [ "-Aclippy::all", "-Dclippy::correctness", + "-Dclippy::complexity", "-Aclippy::if-same-then-else", + "-Aclippy::manual-inspect", "-Asuspicious-double-ref-op", - "-Dclippy::complexity", + "-Aclippy::clone_on_copy", # Too common + "-Aclippy::needless_lifetimes", # Backward compat? "-Aclippy::zero-prefixed-literal", # 00_1000_000 "-Aclippy::type_complexity", # raison d'etre "-Aclippy::nonminimal-bool", # maybe @@ -28,5 +31,5 @@ rustflags = [ "-Aclippy::while_immutable_condition", # false positives "-Aclippy::needless_option_as_deref", # false positives "-Aclippy::derivable_impls", # false positives - "-Aclippy::stable_sort_primitive", # prefer stable sort + "-Aclippy::explicit_counter_loop" # irrelevant ] diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 4eb3909b3a..8e8671bd35 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -20,7 +20,7 @@ jobs: with: components: rustfmt target: wasm32-unknown-unknown - toolchain: 1.77.0 + toolchain: 1.81.0 - name: Generate WeightInfo Files run: make generate-bifrost-weights - name: Commit Automatically diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index c3cb51fb3c..c8db0fe2a3 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -25,12 +25,16 @@ jobs: - name: Install toolchain uses: dtolnay/rust-toolchain@master with: - toolchain: 1.77.0 + toolchain: 1.81.0 components: rustfmt, clippy target: wasm32-unknown-unknown + - name: Cargo check-all + run: | + make check-all + - name: Cargo clippy run: | - make clippy + make clippy-all - name: Test All run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 461c4486ce..0568bf570a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,7 +25,7 @@ jobs: with: components: rustfmt target: wasm32-unknown-unknown - toolchain: 1.77.0 + toolchain: 1.81.0 - name: Download kusama strool result uses: actions/download-artifact@v4 diff --git a/Cargo.lock b/Cargo.lock index 44c86f8270..d3ee2365e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,11 +23,11 @@ dependencies = [ [[package]] name = "addr2line" -version = "0.22.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" dependencies = [ - "gimli 0.29.0", + "gimli 0.28.0", ] [[package]] @@ -48,9 +48,9 @@ dependencies = [ [[package]] name = "aes" -version = "0.8.4" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "ac1f845298e95f983ff1944b728ae08b8cebab80d684f0a832ed0fc74dfa27e2" dependencies = [ "cfg-if", "cipher 0.4.4", @@ -68,7 +68,7 @@ dependencies = [ "cipher 0.4.4", "ctr", "ghash", - "subtle 2.6.1", + "subtle 2.5.0", ] [[package]] @@ -78,7 +78,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", - "getrandom 0.2.15", + "getrandom", "once_cell", "version_check", "zerocopy", @@ -86,18 +86,18 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +checksum = "6748e8def348ed4d14996fa801f4122cd763fff530258cdc03f64b25f89d3a5a" dependencies = [ "memchr", ] [[package]] name = "allocator-api2" -version = "0.2.18" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" [[package]] name = "always-assert" @@ -131,58 +131,57 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.14" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" +checksum = "6e2e1ebcb11de5c03c67de28a7df593d32191b44939c482e97702baaaa6ab6a5" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", - "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" -version = "1.0.8" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "anstyle-parse" -version = "0.2.4" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" +checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" +checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.48.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.3" +version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" +checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" dependencies = [ "anstyle", - "windows-sys 0.52.0", + "windows-sys 0.48.0", ] [[package]] name = "anyhow" -version = "1.0.86" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" +checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" [[package]] name = "approx" @@ -204,7 +203,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -218,18 +217,6 @@ dependencies = [ "ark-std", ] -[[package]] -name = "ark-bls12-377-ext" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20c7021f180a0cbea0380eba97c2af3c57074cdaffe0eef7e840e1c9f2841e55" -dependencies = [ - "ark-bls12-377", - "ark-ec", - "ark-models-ext", - "ark-std", -] - [[package]] name = "ark-bls12-381" version = "0.4.0" @@ -242,45 +229,6 @@ dependencies = [ "ark-std", ] -[[package]] -name = "ark-bls12-381-ext" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1dc4b3d08f19e8ec06e949712f95b8361e43f1391d94f65e4234df03480631c" -dependencies = [ - "ark-bls12-381", - "ark-ec", - "ark-ff", - "ark-models-ext", - "ark-serialize", - "ark-std", -] - -[[package]] -name = "ark-bw6-761" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e0605daf0cc5aa2034b78d008aaf159f56901d92a52ee4f6ecdfdac4f426700" -dependencies = [ - "ark-bls12-377", - "ark-ec", - "ark-ff", - "ark-std", -] - -[[package]] -name = "ark-bw6-761-ext" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccee5fba47266f460067588ee1bf070a9c760bf2050c1c509982c5719aadb4f2" -dependencies = [ - "ark-bw6-761", - "ark-ec", - "ark-ff", - "ark-models-ext", - "ark-std", -] - [[package]] name = "ark-ec" version = "0.4.2" @@ -295,60 +243,9 @@ dependencies = [ "hashbrown 0.13.2", "itertools 0.10.5", "num-traits", - "rayon", "zeroize", ] -[[package]] -name = "ark-ed-on-bls12-377" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b10d901b9ac4b38f9c32beacedfadcdd64e46f8d7f8e88c1ae1060022cf6f6c6" -dependencies = [ - "ark-bls12-377", - "ark-ec", - "ark-ff", - "ark-std", -] - -[[package]] -name = "ark-ed-on-bls12-377-ext" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524a4fb7540df2e1a8c2e67a83ba1d1e6c3947f4f9342cc2359fc2e789ad731d" -dependencies = [ - "ark-ec", - "ark-ed-on-bls12-377", - "ark-ff", - "ark-models-ext", - "ark-std", -] - -[[package]] -name = "ark-ed-on-bls12-381-bandersnatch" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9cde0f2aa063a2a5c28d39b47761aa102bda7c13c84fc118a61b87c7b2f785c" -dependencies = [ - "ark-bls12-381", - "ark-ec", - "ark-ff", - "ark-std", -] - -[[package]] -name = "ark-ed-on-bls12-381-bandersnatch-ext" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d15185f1acb49a07ff8cbe5f11a1adc5a93b19e211e325d826ae98e98e124346" -dependencies = [ - "ark-ec", - "ark-ed-on-bls12-381-bandersnatch", - "ark-ff", - "ark-models-ext", - "ark-std", -] - [[package]] name = "ark-ff" version = "0.4.2" @@ -392,19 +289,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "ark-models-ext" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9eab5d4b5ff2f228b763d38442adc9b084b0a465409b059fac5c2308835ec2" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-serialize", - "ark-std", - "derivative", -] - [[package]] name = "ark-poly" version = "0.4.2" @@ -418,35 +302,6 @@ dependencies = [ "hashbrown 0.13.2", ] -[[package]] -name = "ark-scale" -version = "0.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f69c00b3b529be29528a6f2fd5fa7b1790f8bed81b9cdca17e326538545a179" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-serialize", - "ark-std", - "parity-scale-codec", - "scale-info", -] - -[[package]] -name = "ark-secret-scalar" -version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-serialize", - "ark-std", - "ark-transcript 0.0.2 (git+https://github.com/w3f/ring-vrf?rev=e9782f9)", - "digest 0.10.7", - "getrandom_or_panic", - "zeroize", -] - [[package]] name = "ark-serialize" version = "0.4.2" @@ -477,42 +332,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" dependencies = [ "num-traits", - "rand 0.8.5", - "rayon", -] - -[[package]] -name = "ark-transcript" -version = "0.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "563084372d89271122bd743ef0a608179726f5fad0566008ba55bd0f756489b8" -dependencies = [ - "ark-ff", - "ark-serialize", - "ark-std", - "digest 0.10.7", - "rand_core 0.6.4", - "sha3", -] - -[[package]] -name = "ark-transcript" -version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" -dependencies = [ - "ark-ff", - "ark-serialize", - "ark-std", - "digest 0.10.7", - "rand_core 0.6.4", - "sha3", + "rand", ] [[package]] name = "array-bytes" -version = "6.2.3" +version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d5dde061bd34119e902bbb2d9b90c5692635cf59fb91d582c2b68043f1b8293" +checksum = "6f840fb7195bcfc5e17ea40c26e5ce6d5b9ce5d584466e17703209657e459ae0" [[package]] name = "arrayref" @@ -541,8 +368,24 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f6fd5ddaf0351dff5b8da21b2fb4ff8e08ddd02857f0bf69c47639106c0fff0" dependencies = [ - "asn1-rs-derive", - "asn1-rs-impl", + "asn1-rs-derive 0.4.0", + "asn1-rs-impl 0.1.0", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ad1373757efa0f70ec53939aabc7152e1591cb485208052993070ac8d2429d" +dependencies = [ + "asn1-rs-derive 0.5.0", + "asn1-rs-impl 0.2.0", "displaydoc", "nom", "num-traits", @@ -563,6 +406,18 @@ dependencies = [ "synstructure 0.12.6", ] +[[package]] +name = "asn1-rs-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7378575ff571966e99a744addeff0bff98b8ada0dedf1956d59e634db95eaac1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.90", + "synstructure 0.13.1", +] + [[package]] name = "asn1-rs-impl" version = "0.1.0" @@ -574,6 +429,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.90", +] + [[package]] name = "assert_matches" version = "1.5.0" @@ -591,28 +457,17 @@ dependencies = [ "futures-core", ] -[[package]] -name = "async-channel" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite 0.2.14", -] - [[package]] name = "async-executor" -version = "1.13.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" +checksum = "6fa3dc5f2a8564f07759c008b9109dc0d39de92a88d5588b8a5036d286383afb" dependencies = [ + "async-lock 2.8.0", "async-task", "concurrent-queue", - "fastrand 2.1.0", - "futures-lite 2.3.0", + "fastrand 1.9.0", + "futures-lite 1.13.0", "slab", ] @@ -642,9 +497,9 @@ dependencies = [ "log", "parking", "polling 2.8.0", - "rustix 0.37.27", + "rustix 0.37.23", "slab", - "socket2 0.4.10", + "socket2 0.4.9", "waker-fn", ] @@ -660,8 +515,8 @@ dependencies = [ "futures-io", "futures-lite 2.3.0", "parking", - "polling 3.7.2", - "rustix 0.38.34", + "polling 3.4.0", + "rustix 0.38.21", "slab", "tracing", "windows-sys 0.52.0", @@ -682,62 +537,46 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener 5.3.1", + "event-listener 5.2.0", "event-listener-strategy", - "pin-project-lite 0.2.14", + "pin-project-lite", ] [[package]] name = "async-net" -version = "1.8.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0434b1ed18ce1cf5769b8ac540e33f01fa9471058b5e89da9e06f3c882a8c12f" +checksum = "4051e67316bc7eff608fe723df5d32ed639946adcd69e07df41fd42a7b411f1f" dependencies = [ "async-io 1.13.0", + "autocfg", "blocking", "futures-lite 1.13.0", ] [[package]] name = "async-process" -version = "1.8.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6438ba0a08d81529c69b36700fa2f95837bfe3e776ab39cde9c14d9149da88" +checksum = "7a9d28b1d97e08915212e2e45310d47854eafa69600756fc735fb788f75199c9" dependencies = [ "async-io 1.13.0", "async-lock 2.8.0", - "async-signal", + "autocfg", "blocking", "cfg-if", - "event-listener 3.1.0", + "event-listener 2.5.3", "futures-lite 1.13.0", - "rustix 0.38.34", + "rustix 0.37.23", + "signal-hook", "windows-sys 0.48.0", ] -[[package]] -name = "async-signal" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfb3634b73397aa844481f814fad23bbf07fdb0eabec10f2eb95e58944b1ec32" -dependencies = [ - "async-io 2.3.3", - "async-lock 3.4.0", - "atomic-waker", - "cfg-if", - "futures-core", - "futures-io", - "rustix 0.38.34", - "signal-hook-registry", - "slab", - "windows-sys 0.52.0", -] - [[package]] name = "async-task" -version = "4.7.1" +version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" +checksum = "ecc7ab41815b3c653ccd2978ec3255c81349336702dfdf62ee6f7069b12a3aae" [[package]] name = "async-trait" @@ -747,7 +586,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -760,7 +599,7 @@ dependencies = [ "futures-sink", "futures-util", "memchr", - "pin-project-lite 0.2.14", + "pin-project-lite", ] [[package]] @@ -780,65 +619,54 @@ checksum = "a8ab6b55fe97976e46f91ddbed8d147d966475dc29b2032757ba47e02376fbc3" [[package]] name = "atomic-waker" -version = "1.1.2" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1181e1e0d1fce796a03db1ae795d67167da795f9cf4a39c37589e85ef57f26d3" + +[[package]] +name = "attohttpc" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +checksum = "8d9a9bf8b79a749ee0b911b91b671cc2b6c670bdbc7e3dfd537576ddc94bb2a2" +dependencies = [ + "http 0.2.9", + "log", + "url", +] [[package]] name = "auto_impl" -version = "1.2.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c87f3f15e7794432337fc718554eaa4dc8f04c9677a950ffe366f20a162ae42" +checksum = "fee3da8ef1276b0bee5dd1c7258010d8fffd31801447323115a25560e1327b89" dependencies = [ + "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.85", + "syn 1.0.109", ] [[package]] name = "autocfg" -version = "1.3.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" -version = "0.3.73" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" +checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" dependencies = [ - "addr2line 0.22.0", + "addr2line 0.21.0", "cc", "cfg-if", "libc", "miniz_oxide", - "object 0.36.1", + "object 0.32.2", "rustc-demangle", ] -[[package]] -name = "bandersnatch_vrfs" -version = "0.0.4" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" -dependencies = [ - "ark-bls12-381", - "ark-ec", - "ark-ed-on-bls12-381-bandersnatch", - "ark-ff", - "ark-serialize", - "ark-std", - "dleq_vrf", - "fflonk", - "merlin", - "rand_chacha 0.3.1", - "rand_core 0.6.4", - "ring 0.1.0", - "sha2 0.10.8", - "sp-ark-bls12-381", - "sp-ark-ed-on-bls12-381-bandersnatch", - "zeroize", -] - [[package]] name = "base-x" version = "0.2.11" @@ -859,9 +687,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.7" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" [[package]] name = "base64" @@ -903,7 +731,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -933,7 +761,7 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-core", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -960,7 +788,7 @@ dependencies = [ "serde", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -995,7 +823,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1020,12 +848,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] name = "bifrost-cli" -version = "0.15.3" +version = "0.16.0" dependencies = [ "bifrost-primitives", "bifrost-service", @@ -1074,7 +902,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -1095,7 +923,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", ] @@ -1115,7 +943,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -1145,7 +973,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm-builder", ] @@ -1172,7 +1000,7 @@ dependencies = [ "bifrost-primitives", "parity-scale-codec", "sp-api", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -1205,7 +1033,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1228,6 +1056,8 @@ dependencies = [ "orml-tokens", "orml-traits", "pallet-balances", + "pallet-evm-accounts", + "pallet-traits", "pallet-transaction-payment", "pallet-xcm", "parity-scale-codec", @@ -1237,7 +1067,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1310,7 +1140,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -1342,7 +1172,6 @@ dependencies = [ "bifrost-stable-asset", "bifrost-stable-pool", "bifrost-stable-pool-rpc-runtime-api", - "bifrost-system-maker", "bifrost-system-staking", "bifrost-token-issuer", "bifrost-vbnc-convert", @@ -1426,6 +1255,7 @@ dependencies = [ "sp-block-builder", "sp-consensus-aura", "sp-core", + "sp-debug-derive", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -1433,7 +1263,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -1444,7 +1274,7 @@ dependencies = [ "strum 0.26.3", "strum_macros 0.26.4", "substrate-wasm-builder", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", "zenlink-protocol", "zenlink-protocol-runtime-api", "zenlink-stable-amm", @@ -1472,7 +1302,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "substrate-fixed", ] @@ -1504,7 +1334,6 @@ dependencies = [ "bifrost-stable-asset", "bifrost-stable-pool", "bifrost-stable-pool-rpc-runtime-api", - "bifrost-system-maker", "bifrost-system-staking", "bifrost-vesting", "bifrost-vstoken-conversion", @@ -1567,6 +1396,7 @@ dependencies = [ "pallet-evm-chain-id", "pallet-evm-precompile-blake2", "pallet-evm-precompile-bn128", + "pallet-evm-precompile-call-permit", "pallet-evm-precompile-dispatch", "pallet-evm-precompile-modexp", "pallet-evm-precompile-sha3fips", @@ -1599,7 +1429,7 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-common", - "primitive-types 0.12.2", + "primitive-types", "scale-info", "serde", "serde_json", @@ -1609,6 +1439,7 @@ dependencies = [ "sp-block-builder", "sp-consensus-aura", "sp-core", + "sp-debug-derive", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -1616,7 +1447,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -1627,7 +1458,7 @@ dependencies = [ "strum 0.26.3", "strum_macros 0.26.4", "substrate-wasm-builder", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", "zenlink-protocol", "zenlink-protocol-runtime-api", ] @@ -1646,7 +1477,7 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-executor", "zenlink-protocol", @@ -1759,7 +1590,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -1800,7 +1631,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1920,7 +1751,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-timestamp", "sp-transaction-pool", "sp-trie", @@ -1966,7 +1797,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1996,7 +1827,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2040,7 +1871,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -2068,7 +1899,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -2096,7 +1927,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2125,49 +1956,16 @@ dependencies = [ "bifrost-primitives", "parity-scale-codec", "sp-api", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] -name = "bifrost-system-maker" -version = "0.8.0" +name = "bifrost-system-staking" +version = "4.0.0-dev" dependencies = [ "bifrost-asset-registry", "bifrost-currencies", - "bifrost-primitives", - "bifrost-slp", - "bifrost-vtoken-minting", - "cumulus-primitives-core", - "frame-benchmarking", - "frame-support", - "frame-system", - "hex-literal 0.4.1", - "log", - "orml-tokens", - "orml-traits", - "orml-xtokens", - "pallet-balances", - "pallet-xcm", - "parity-scale-codec", - "scale-info", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "zenlink-protocol", -] - -[[package]] -name = "bifrost-system-staking" -version = "4.0.0-dev" -dependencies = [ - "bifrost-asset-registry", - "bifrost-currencies", - "bifrost-farming", + "bifrost-farming", "bifrost-primitives", "bifrost-runtime-common", "bifrost-slp", @@ -2189,7 +1987,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2214,7 +2012,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -2235,7 +2033,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm-builder", ] @@ -2253,7 +2051,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -2276,7 +2074,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm-builder", ] @@ -2307,7 +2105,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2337,7 +2135,7 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-core", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -2362,7 +2160,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2388,15 +2186,15 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-executor", ] [[package]] name = "binary-merkle-tree" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "hash-db 0.16.0", "log", @@ -2423,13 +2221,13 @@ dependencies = [ "lazy_static", "lazycell", "peeking_take_while", - "prettyplease 0.2.20", + "prettyplease 0.2.25", "proc-macro2", "quote", "regex", "rustc-hash", "shlex", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -2521,31 +2319,31 @@ dependencies = [ [[package]] name = "blake2b_simd" -version = "1.0.2" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23285ad32269793932e830392f2fe2f83e26488fd3ec778883a93c8323735780" +checksum = "3c2f0dc9a68c6317d884f97cc36cf5a3d20ba14ce404227df55e1af708ab04bc" dependencies = [ "arrayref", "arrayvec 0.7.4", - "constant_time_eq 0.3.0", + "constant_time_eq 0.2.6", ] [[package]] name = "blake2s_simd" -version = "1.0.2" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94230421e395b9920d23df13ea5d77a20e1725331f90fbbf6df6040b33f756ae" +checksum = "6637f448b9e61dfadbdcbae9a885fadee1f3eaffb1f8d3c1965d3ade8bdfd44f" dependencies = [ "arrayref", "arrayvec 0.7.4", - "constant_time_eq 0.3.0", + "constant_time_eq 0.2.6", ] [[package]] name = "blake3" -version = "1.5.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9ec96fe9a81b5e365f9db71fe00edc4fe4ca2cc7dcb7861f0603012a7caa210" +checksum = "0231f06152bf547e9c2b5194f247cd97aacf6dcd8b15d8e5ec0663f64580da87" dependencies = [ "arrayref", "arrayvec 0.7.4", @@ -2574,15 +2372,17 @@ dependencies = [ [[package]] name = "blocking" -version = "1.6.1" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" +checksum = "77231a1c8f801696fc0123ec6150ce92cffb8e164a02afb9c8ddee0e9b65ad65" dependencies = [ - "async-channel 2.3.1", + "async-channel", + "async-lock 2.8.0", "async-task", - "futures-io", - "futures-lite 2.3.0", - "piper", + "atomic-waker", + "fastrand 1.9.0", + "futures-lite 1.13.0", + "log", ] [[package]] @@ -2608,8 +2408,8 @@ dependencies = [ [[package]] name = "bp-xcm-bridge-hub-router" -version = "0.6.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.14.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "scale-info", @@ -2625,22 +2425,22 @@ checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" [[package]] name = "bs58" -version = "0.5.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +checksum = "f5353f36341f7451062466f0b755b96ac3a9547e4d7f6b70d603fc721a7d7896" dependencies = [ "tinyvec", ] [[package]] name = "bstr" -version = "0.2.17" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +checksum = "6798148dccfbff0fae41c7574d2fa8f1ef3492fba0face179de5d8d447d67b05" dependencies = [ - "lazy_static", "memchr", - "regex-automata 0.1.10", + "regex-automata 0.3.6", + "serde", ] [[package]] @@ -2660,9 +2460,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.16.0" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" [[package]] name = "byte-slice-cast" @@ -2678,21 +2478,21 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" [[package]] name = "bytemuck" -version = "1.16.1" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" [[package]] name = "byteorder" -version = "1.5.0" +version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.6.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" [[package]] name = "bzip2-sys" @@ -2717,18 +2517,18 @@ dependencies = [ [[package]] name = "camino" -version = "1.1.7" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0ec6b951b160caa93cc0c7b209e5a3bff7aae9062213451ac99493cd844c239" +checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c" dependencies = [ "serde", ] [[package]] name = "cargo-platform" -version = "0.1.8" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" +checksum = "2cfa25e60aea747ec7e1124f238816749faa93759c6ff5b31f1ccdda137f4479" dependencies = [ "serde", ] @@ -2741,22 +2541,34 @@ checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a" dependencies = [ "camino", "cargo-platform", - "semver 1.0.23", + "semver 1.0.18", "serde", "serde_json", "thiserror", ] +[[package]] +name = "case" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6c0e7b807d60291f42f33f58480c0bfafe28ed08286446f45e463728cf9c1c" + [[package]] name = "cc" -version = "1.1.5" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "324c74f2155653c90b04f25b2a47a8a631360cb908f92a772695f430c7e31052" +checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" dependencies = [ "jobserver", "libc", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cexpr" version = "0.6.0" @@ -2768,9 +2580,9 @@ dependencies = [ [[package]] name = "cfg-expr" -version = "0.15.8" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +checksum = "03915af431787e6ffdcc74c645077518c6b6e01f80b761e0fbbfa288536311b3" dependencies = [ "smallvec", ] @@ -2823,16 +2635,16 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.38" +version = "0.4.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", "num-traits", "wasm-bindgen", - "windows-targets 0.52.6", + "windows-targets 0.48.5", ] [[package]] @@ -2845,7 +2657,7 @@ dependencies = [ "multibase", "multihash 0.17.0", "serde", - "unsigned-varint", + "unsigned-varint 0.7.2", ] [[package]] @@ -2858,7 +2670,7 @@ dependencies = [ "multibase", "multihash 0.18.1", "serde", - "unsigned-varint", + "unsigned-varint 0.7.2", ] [[package]] @@ -2883,9 +2695,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.8.1" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" dependencies = [ "glob", "libc", @@ -2894,9 +2706,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.18" +version = "4.5.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0956a43b323ac1afaffc053ed5c4b7c1f1800bacd1683c353aabbb752515dd3" +checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b" dependencies = [ "clap_builder", "clap_derive", @@ -2904,9 +2716,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.18" +version = "4.5.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d72166dd41634086d5803a47eb71ae740e61d84709c36f3c34110173db3961b" +checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1" dependencies = [ "anstream", "anstyle", @@ -2924,23 +2736,24 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "clap_lex" -version = "0.7.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "coarsetime" -version = "0.1.34" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13b3839cf01bb7960114be3ccf2340f541b6d0c81f8690b007b2b39f750f7e5d" +checksum = "a90d114103adbc625300f346d4d09dfb4ab1c4a8df6868435dd903392ecf4354" dependencies = [ "libc", - "wasix", + "once_cell", + "wasi", "wasm-bindgen", ] @@ -2956,15 +2769,15 @@ dependencies = [ [[package]] name = "colorchoice" -version = "1.0.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" +checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "combine" -version = "4.6.7" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +checksum = "35ed6e9d84f0b51a7f52daf1c7d71dd136fd7a3f41a8462b8cdb8c78d920fad4" dependencies = [ "bytes", "memchr", @@ -2972,30 +2785,15 @@ dependencies = [ [[package]] name = "comfy-table" -version = "7.1.1" +version = "7.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b34115915337defe99b2aff5c2ce6771e5fbc4079f4b506301f5cf394c8452f7" +checksum = "7c64043d6c7b7a4c58e39e7efccfdea7b93d885a795d0c054a69dbbf4dd52686" dependencies = [ - "strum 0.26.3", - "strum_macros 0.26.4", + "strum 0.25.0", + "strum_macros 0.25.3", "unicode-width", ] -[[package]] -name = "common" -version = "0.1.0" -source = "git+https://github.com/w3f/ring-proof#652286c32f96beb9ce7f5793f5e2c2c923f63b73" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", - "fflonk", - "getrandom_or_panic", - "rand_core 0.6.4", -] - [[package]] name = "common-path" version = "1.0.0" @@ -3004,9 +2802,9 @@ checksum = "2382f75942f4b3be3690fe4f86365e9c853c1587d6ee58212cebf6e2a9ccd101" [[package]] name = "concurrent-queue" -version = "2.5.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c" dependencies = [ "crossbeam-utils", ] @@ -3026,27 +2824,29 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.9.6" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" [[package]] name = "const-random" -version = "0.1.18" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +checksum = "368a7a772ead6ce7e1de82bfb04c485f3db8ec744f72925af5735e29a22cc18e" dependencies = [ "const-random-macro", + "proc-macro-hack", ] [[package]] name = "const-random-macro" -version = "0.1.16" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +checksum = "9d7d6ab3c3a2282db210df5f02c4dab6e0a7057af0fb7ebd4070f30fe05c0ddb" dependencies = [ - "getrandom 0.2.15", + "getrandom", "once_cell", + "proc-macro-hack", "tiny-keccak", ] @@ -3056,6 +2856,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" +[[package]] +name = "constant_time_eq" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6" + [[package]] name = "constant_time_eq" version = "0.3.0" @@ -3064,9 +2870,9 @@ checksum = "f7144d30dcf0fafbce74250a3963025d8d52177934239851c917d29f1df280c2" [[package]] name = "constcat" -version = "0.3.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd7e35aee659887cbfb97aaf227ac12cad1a9d7c71e55ff3376839ed4e282d08" +checksum = "f272d0c4cf831b4fa80ee529c7707f76585986e910e1fbce1d7921970bc1a241" [[package]] name = "convert_case" @@ -3120,9 +2926,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.12" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] @@ -3227,9 +3033,9 @@ dependencies = [ [[package]] name = "crc" -version = "3.2.1" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636" +checksum = "c2b432c56615136f8dba245fed7ec3d5518c500a31108661067e61e72fe7e6bc" dependencies = [ "crc-catalog", ] @@ -3242,46 +3048,55 @@ checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" [[package]] name = "crc32fast" -version = "1.4.2" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" dependencies = [ "cfg-if", ] [[package]] name = "crossbeam-deque" -version = "0.8.5" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" dependencies = [ + "cfg-if", "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" dependencies = [ + "autocfg", + "cfg-if", "crossbeam-utils", + "memoffset 0.9.0", + "scopeguard", ] [[package]] name = "crossbeam-queue" -version = "0.3.11" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" +checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" dependencies = [ + "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.20" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +dependencies = [ + "cfg-if", +] [[package]] name = "crunchy" @@ -3291,13 +3106,13 @@ checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" [[package]] name = "crypto-bigint" -version = "0.5.5" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +checksum = "cf4c2f4e1afd912bc40bfd6fed5d9dc1f288e0ba01bfcc835cc5bc3eb13efe15" dependencies = [ "generic-array 0.14.7", - "rand_core 0.6.4", - "subtle 2.6.1", + "rand_core", + "subtle 2.5.0", "zeroize", ] @@ -3308,7 +3123,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array 0.14.7", - "rand_core 0.6.4", + "rand_core", "typenum", ] @@ -3329,7 +3144,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" dependencies = [ "generic-array 0.14.7", - "subtle 2.6.1", + "subtle 2.5.0", ] [[package]] @@ -3343,8 +3158,8 @@ dependencies = [ [[package]] name = "cumulus-client-cli" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "clap", "parity-scale-codec", @@ -3360,8 +3175,8 @@ dependencies = [ [[package]] name = "cumulus-client-collator" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-client-consensus-common", "cumulus-client-network", @@ -3383,8 +3198,8 @@ dependencies = [ [[package]] name = "cumulus-client-consensus-aura" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-client-collator", @@ -3396,6 +3211,7 @@ dependencies = [ "cumulus-relay-chain-interface", "futures 0.3.31", "parity-scale-codec", + "parking_lot 0.12.3", "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-overseer", @@ -3406,6 +3222,7 @@ dependencies = [ "sc-consensus-babe", "sc-consensus-slots", "sc-telemetry", + "sc-utils", "schnellru", "sp-api", "sp-application-crypto", @@ -3420,13 +3237,14 @@ dependencies = [ "sp-state-machine", "sp-timestamp", "substrate-prometheus-endpoint", + "tokio", "tracing", ] [[package]] name = "cumulus-client-consensus-common" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-client-pov-recovery", @@ -3448,14 +3266,15 @@ dependencies = [ "sp-runtime", "sp-timestamp", "sp-trie", + "sp-version", "substrate-prometheus-endpoint", "tracing", ] [[package]] name = "cumulus-client-consensus-proposer" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "anyhow", "async-trait", @@ -3469,8 +3288,8 @@ dependencies = [ [[package]] name = "cumulus-client-network" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-relay-chain-interface", @@ -3479,21 +3298,24 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", "polkadot-node-primitives", + "polkadot-node-subsystem", "polkadot-parachain-primitives", "polkadot-primitives", "sc-client-api", + "sp-api", "sp-blockchain", "sp-consensus", "sp-core", "sp-runtime", "sp-state-machine", + "sp-version", "tracing", ] [[package]] name = "cumulus-client-parachain-inherent" -version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.11.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -3502,22 +3324,20 @@ dependencies = [ "cumulus-test-relay-sproof-builder", "parity-scale-codec", "sc-client-api", - "scale-info", "sp-api", "sp-crypto-hashing", "sp-inherents", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-trie", "tracing", ] [[package]] name = "cumulus-client-pov-recovery" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -3529,19 +3349,21 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-overseer", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-client-api", "sc-consensus", + "sp-api", "sp-consensus", "sp-maybe-compressed-blob", "sp-runtime", + "sp-version", "tracing", ] [[package]] name = "cumulus-client-service" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-client-cli", "cumulus-client-collator", @@ -3577,8 +3399,8 @@ dependencies = [ [[package]] name = "cumulus-pallet-aura-ext" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-pallet-parachain-system", "frame-support", @@ -3590,13 +3412,12 @@ dependencies = [ "sp-application-crypto", "sp-consensus-aura", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "cumulus-pallet-parachain-system" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.2" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bytes", "cumulus-pallet-parachain-system-proc-macro", @@ -3616,12 +3437,12 @@ dependencies = [ "polkadot-runtime-parachains", "scale-info", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-inherents", "sp-io", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-trie", "sp-version", "staging-xcm", @@ -3632,18 +3453,18 @@ dependencies = [ [[package]] name = "cumulus-pallet-parachain-system-proc-macro" version = "0.6.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "cumulus-pallet-xcm" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-primitives-core", "frame-support", @@ -3652,14 +3473,13 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", ] [[package]] name = "cumulus-pallet-xcmp-queue" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bounded-collections", "bp-xcm-bridge-hub-router", @@ -3676,7 +3496,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -3684,8 +3503,8 @@ dependencies = [ [[package]] name = "cumulus-primitives-aura" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "polkadot-core-primitives", @@ -3693,13 +3512,12 @@ dependencies = [ "sp-api", "sp-consensus-aura", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "cumulus-primitives-core" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "polkadot-core-primitives", @@ -3708,15 +3526,14 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-trie", "staging-xcm", ] [[package]] name = "cumulus-primitives-parachain-inherent" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -3726,37 +3543,33 @@ dependencies = [ "sp-inherents", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-trie", ] [[package]] name = "cumulus-primitives-proof-size-hostfunction" -version = "0.2.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.10.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", + "sp-runtime-interface", "sp-trie", ] [[package]] name = "cumulus-primitives-timestamp" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-primitives-core", - "futures 0.3.31", - "parity-scale-codec", "sp-inherents", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-timestamp", ] [[package]] name = "cumulus-primitives-utility" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-primitives-core", "frame-support", @@ -3767,7 +3580,6 @@ dependencies = [ "polkadot-runtime-parachains", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -3775,8 +3587,8 @@ dependencies = [ [[package]] name = "cumulus-relay-chain-inprocess-interface" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -3799,8 +3611,8 @@ dependencies = [ [[package]] name = "cumulus-relay-chain-interface" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -3812,13 +3624,14 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-state-machine", + "sp-version", "thiserror", ] [[package]] name = "cumulus-relay-chain-minimal-node" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", "async-trait", @@ -3826,15 +3639,8 @@ dependencies = [ "cumulus-relay-chain-interface", "cumulus-relay-chain-rpc-interface", "futures 0.3.31", - "parking_lot 0.12.3", - "polkadot-availability-recovery", - "polkadot-collator-protocol", "polkadot-core-primitives", "polkadot-network-bridge", - "polkadot-node-collation-generation", - "polkadot-node-core-chain-api", - "polkadot-node-core-prospective-parachains", - "polkadot-node-core-runtime-api", "polkadot-node-network-protocol", "polkadot-node-subsystem-util", "polkadot-overseer", @@ -3859,8 +3665,8 @@ dependencies = [ [[package]] name = "cumulus-relay-chain-rpc-interface" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -3872,7 +3678,7 @@ dependencies = [ "parity-scale-codec", "pin-project", "polkadot-overseer", - "rand 0.8.5", + "rand", "sc-client-api", "sc-rpc-api", "sc-service", @@ -3887,7 +3693,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-state-machine", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-version", "thiserror", "tokio", @@ -3898,31 +3704,17 @@ dependencies = [ [[package]] name = "cumulus-test-relay-sproof-builder" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-primitives-core", "parity-scale-codec", "polkadot-primitives", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-trie", ] -[[package]] -name = "curve25519-dalek" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b9fdf9972b2bd6af2d913799d9ebc165ea4d2e65878e329d9c6b372c4491b61" -dependencies = [ - "byteorder", - "digest 0.9.0", - "rand_core 0.5.1", - "subtle 2.6.1", - "zeroize", -] - [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -3935,19 +3727,19 @@ dependencies = [ "digest 0.10.7", "fiat-crypto", "rustc_version", - "subtle 2.6.1", + "subtle 2.5.0", "zeroize", ] [[package]] name = "curve25519-dalek-derive" -version = "0.1.1" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +checksum = "83fdaf97f4804dcebfa5862639bc9ce4121e82140bec2a987ac5140294865b5b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -3958,7 +3750,7 @@ checksum = "1c359b7249347e46fb28804470d071c921156ad62b3eef5d34e2ba867533dec8" dependencies = [ "byteorder", "digest 0.9.0", - "rand_core 0.6.4", + "rand_core", "subtle-ng", "zeroize", ] @@ -3987,7 +3779,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -4004,33 +3796,33 @@ checksum = "50c49547d73ba8dcfd4ad7325d64c6d5391ff4224d498fc39a6f3f49825a530d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "dashmap" -version = "5.5.3" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +checksum = "edd72493923899c6f10c641bdbdeddc7183d6396641d99c1a0d1597f37f92e28" dependencies = [ "cfg-if", - "hashbrown 0.14.5", + "hashbrown 0.14.3", "lock_api", "once_cell", - "parking_lot_core 0.9.10", + "parking_lot_core 0.9.8", ] [[package]] name = "data-encoding" -version = "2.6.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" +checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" [[package]] name = "data-encoding-macro" -version = "0.1.15" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1559b6cba622276d6d63706db152618eeb15b89b3e4041446b05876e352e639" +checksum = "c904b33cc60130e1aeea4956ab803d08a3f4a0ca82d64ed757afac3891f2bb99" dependencies = [ "data-encoding", "data-encoding-macro-internal", @@ -4038,9 +3830,9 @@ dependencies = [ [[package]] name = "data-encoding-macro-internal" -version = "0.1.13" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "332d754c0af53bc87c108fed664d121ecf59207ec4196041f04d6ab9002ad33f" +checksum = "8fdf3fce3ce863539ec1d7fd1b6dcc3c645663376b43ed376bbf887733e4f772" dependencies = [ "data-encoding", "syn 1.0.109", @@ -4048,9 +3840,9 @@ dependencies = [ [[package]] name = "der" -version = "0.7.9" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" +checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" dependencies = [ "const-oid", "zeroize", @@ -4062,7 +3854,21 @@ version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbd676fbbab537128ef0278adb5576cf363cff6aa22a7b24effe97347cfab61e" dependencies = [ - "asn1-rs", + "asn1-rs 0.5.2", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "der-parser" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553" +dependencies = [ + "asn1-rs 0.6.1", "displaydoc", "nom", "num-bigint", @@ -4098,7 +3904,7 @@ checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -4111,7 +3917,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -4147,7 +3953,7 @@ dependencies = [ "block-buffer 0.10.4", "const-oid", "crypto-common", - "subtle 2.6.1", + "subtle 2.5.0", ] [[package]] @@ -4194,29 +4000,13 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", -] - -[[package]] -name = "dleq_vrf" -version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-scale", - "ark-secret-scalar", - "ark-serialize", - "ark-std", - "ark-transcript 0.0.2 (git+https://github.com/w3f/ring-vrf?rev=e9782f9)", - "arrayvec 0.7.4", - "zeroize", + "syn 2.0.90", ] [[package]] @@ -4240,9 +4030,9 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.85", + "syn 2.0.90", "termcolor", - "toml 0.8.14", + "toml 0.8.8", "walkdir", ] @@ -4260,9 +4050,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "downcast-rs" -version = "1.2.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" [[package]] name = "dtoa" @@ -4293,56 +4083,33 @@ dependencies = [ [[package]] name = "dyn-clone" -version = "1.0.17" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" +checksum = "545b22097d44f8a9581187cdf93de7a71e4722bf51200cfaba810865b49a495d" [[package]] name = "ecdsa" -version = "0.16.9" +version = "0.16.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" dependencies = [ "der", "digest 0.10.7", "elliptic-curve", "rfc6979", "serdect", - "signature 2.2.0", + "signature", "spki", ] [[package]] name = "ed25519" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7" -dependencies = [ - "signature 1.6.4", -] - -[[package]] -name = "ed25519" -version = "2.2.3" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +checksum = "60f6d271ca33075c88028be6f04d502853d63a5ece419d269c15315d4fc1cf1d" dependencies = [ "pkcs8", - "signature 2.2.0", -] - -[[package]] -name = "ed25519-dalek" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" -dependencies = [ - "curve25519-dalek 3.2.0", - "ed25519 1.5.3", - "rand 0.7.3", - "serde", - "sha2 0.9.9", - "zeroize", + "signature", ] [[package]] @@ -4351,12 +4118,12 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" dependencies = [ - "curve25519-dalek 4.1.3", - "ed25519 2.2.3", - "rand_core 0.6.4", + "curve25519-dalek", + "ed25519", + "rand_core", "serde", "sha2 0.10.8", - "subtle 2.6.1", + "subtle 2.5.0", "zeroize", ] @@ -4366,20 +4133,20 @@ version = "4.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9" dependencies = [ - "curve25519-dalek 4.1.3", - "ed25519 2.2.3", - "hashbrown 0.14.5", + "curve25519-dalek", + "ed25519", + "hashbrown 0.14.3", "hex", - "rand_core 0.6.4", + "rand_core", "sha2 0.10.8", "zeroize", ] [[package]] name = "either" -version = "1.13.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" dependencies = [ "serde", ] @@ -4397,10 +4164,10 @@ dependencies = [ "generic-array 0.14.7", "group", "pkcs8", - "rand_core 0.6.4", + "rand_core", "sec1", "serdect", - "subtle 2.6.1", + "subtle 2.5.0", "zeroize", ] @@ -4431,38 +4198,38 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "enumflags2" -version = "0.7.10" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d232db7f5956f3f14313dc2f87985c58bd2c695ce124c8cdd984e08e15ac133d" +checksum = "c041f5090df68b32bcd905365fd51769c8b9d553fe87fde0b683534f10c01bd2" dependencies = [ "enumflags2_derive", ] [[package]] name = "enumflags2_derive" -version = "0.7.10" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de0d48a183585823424a4ce1aa132d174a6a81bd540895822eb4c8373a8e49e8" +checksum = "5e9a1f9f7d83e59740248a6e14ecf93929ade55027844dfcea78beafccc15745" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "enumn" -version = "0.1.13" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fd000fd6988e73bbe993ea3db9b1aa64906ab88766d654973924340c8cddb42" +checksum = "c2ad8cef1d801a4686bfd8919f0b30eac4c8e48968c437a6405ded4fb5272d2b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -4492,12 +4259,23 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.9" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +checksum = "6b30f669a7961ef1631673d2766cc92f52d64f7ef354d4fe0ddfd30ed52f0f4f" dependencies = [ + "errno-dragonfly", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", "libc", - "windows-sys 0.52.0", ] [[package]] @@ -4519,9 +4297,9 @@ checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" dependencies = [ "crunchy", "fixed-hash", - "impl-codec 0.6.0", + "impl-codec", "impl-rlp", - "impl-serde 0.4.0", + "impl-serde", "scale-info", "tiny-keccak", ] @@ -4570,12 +4348,12 @@ checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" dependencies = [ "ethbloom", "fixed-hash", - "impl-codec 0.6.0", + "impl-codec", "impl-rlp", - "impl-serde 0.4.0", - "primitive-types 0.12.2", + "impl-serde", + "primitive-types", "scale-info", - "uint 0.9.5", + "uint", ] [[package]] @@ -4586,24 +4364,13 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "event-listener" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d93877bcde0eb80ca09131a08d23f0a5c18a620b01db137dba666d18cd9b30c2" -dependencies = [ - "concurrent-queue", - "parking", - "pin-project-lite 0.2.14", -] - -[[package]] -name = "event-listener" -version = "5.3.1" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" +checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" dependencies = [ "concurrent-queue", "parking", - "pin-project-lite 0.2.14", + "pin-project-lite", ] [[package]] @@ -4612,8 +4379,8 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ - "event-listener 5.3.1", - "pin-project-lite 0.2.14", + "event-listener 5.2.0", + "pin-project-lite", ] [[package]] @@ -4630,7 +4397,7 @@ dependencies = [ "evm-runtime", "log", "parity-scale-codec", - "primitive-types 0.12.2", + "primitive-types", "rlp", "scale-info", "serde", @@ -4644,7 +4411,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d1da6cedc5cedb4208e59467106db0d1f50db01b920920589f8e672c02fdc04f" dependencies = [ "parity-scale-codec", - "primitive-types 0.12.2", + "primitive-types", "scale-info", "serde", ] @@ -4658,7 +4425,7 @@ dependencies = [ "environmental", "evm-core", "evm-runtime", - "primitive-types 0.12.2", + "primitive-types", ] [[package]] @@ -4670,7 +4437,7 @@ dependencies = [ "auto_impl", "environmental", "evm-core", - "primitive-types 0.12.2", + "primitive-types", "sha3", ] @@ -4692,10 +4459,10 @@ dependencies = [ "blake2 0.10.6", "file-guard", "fs-err", - "prettyplease 0.2.20", + "prettyplease 0.2.25", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -4710,6 +4477,12 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" +[[package]] +name = "faster-hex" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51e2ce894d53b295cf97b05685aa077950ff3e8541af83217fc720a6437169f8" + [[package]] name = "fastrand" version = "1.9.0" @@ -4742,17 +4515,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb42427514b063d97ce21d5199f36c0c307d981434a6be32582bc79fe5bd2303" dependencies = [ "expander", - "indexmap 2.2.6", + "indexmap 2.2.3", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "fc-api" version = "1.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "async-trait", "fp-storage", @@ -4764,7 +4537,7 @@ dependencies = [ [[package]] name = "fc-consensus" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "async-trait", "fp-consensus", @@ -4780,7 +4553,7 @@ dependencies = [ [[package]] name = "fc-db" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "async-trait", "ethereum 0.15.0", @@ -4810,7 +4583,7 @@ dependencies = [ [[package]] name = "fc-mapping-sync" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fc-db", "fc-storage", @@ -4833,7 +4606,7 @@ dependencies = [ [[package]] name = "fc-rpc" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "ethereum-types", @@ -4853,7 +4626,7 @@ dependencies = [ "pallet-evm", "parity-scale-codec", "prometheus", - "rand 0.8.5", + "rand", "rlp", "sc-client-api", "sc-consensus-aura", @@ -4872,12 +4645,12 @@ dependencies = [ "sp-consensus", "sp-consensus-aura", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-inherents", "sp-io", "sp-runtime", "sp-state-machine", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-timestamp", "substrate-prometheus-endpoint", "thiserror", @@ -4887,7 +4660,7 @@ dependencies = [ [[package]] name = "fc-rpc-core" version = "1.1.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "ethereum-types", @@ -4902,7 +4675,7 @@ dependencies = [ [[package]] name = "fc-storage" version = "1.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "ethereum-types", @@ -4913,7 +4686,7 @@ dependencies = [ "sp-api", "sp-io", "sp-runtime", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", ] [[package]] @@ -4932,28 +4705,15 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" dependencies = [ - "rand_core 0.6.4", - "subtle 2.6.1", -] - -[[package]] -name = "fflonk" -version = "0.1.0" -source = "git+https://github.com/w3f/fflonk#1e854f35e9a65d08b11a86291405cdc95baa0a35" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", - "merlin", + "rand_core", + "subtle 2.5.0", ] [[package]] name = "fiat-crypto" -version = "0.2.9" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "27573eac26f4dd11e2b1916c3fe1baa56407c83c71a773a8ba17ec0bca03b6b7" [[package]] name = "file-guard" @@ -4977,14 +4737,14 @@ dependencies = [ [[package]] name = "filetime" -version = "0.2.23" +version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd" +checksum = "d4029edd3e734da6fe05b6cd7bd2960760a616bd2ddd0d59a0124746d6272af0" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.4.1", - "windows-sys 0.52.0", + "redox_syscall 0.3.5", + "windows-sys 0.48.0", ] [[package]] @@ -5010,7 +4770,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" dependencies = [ "byteorder", - "rand 0.8.5", + "rand", "rustc-hex", "static_assertions", ] @@ -5021,17 +4781,6 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" -[[package]] -name = "flate2" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" -dependencies = [ - "crc32fast", - "libz-sys", - "miniz_oxide", -] - [[package]] name = "float-cmp" version = "0.9.0" @@ -5076,8 +4825,8 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "fork-tree" -version = "12.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", ] @@ -5104,10 +4853,10 @@ dependencies = [ [[package]] name = "fp-account" version = "1.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "hex", - "impl-serde 0.4.0", + "impl-serde", "libsecp256k1", "log", "parity-scale-codec", @@ -5116,13 +4865,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", + "staging-xcm", ] [[package]] name = "fp-consensus" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "parity-scale-codec", @@ -5133,7 +4883,7 @@ dependencies = [ [[package]] name = "fp-dynamic-fee" version = "1.0.0" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "async-trait", "sp-core", @@ -5143,7 +4893,7 @@ dependencies = [ [[package]] name = "fp-ethereum" version = "1.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "ethereum-types", @@ -5155,7 +4905,7 @@ dependencies = [ [[package]] name = "fp-evm" version = "3.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "evm", "frame-support", @@ -5170,7 +4920,7 @@ dependencies = [ [[package]] name = "fp-rpc" version = "3.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "ethereum-types", @@ -5186,7 +4936,7 @@ dependencies = [ [[package]] name = "fp-self-contained" version = "1.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "frame-support", "parity-scale-codec", @@ -5198,7 +4948,7 @@ dependencies = [ [[package]] name = "fp-storage" version = "2.0.0" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "parity-scale-codec", "serde", @@ -5212,8 +4962,8 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frame-benchmarking" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "frame-support", "frame-support-procedural", @@ -5229,16 +4979,15 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", + "sp-storage", "static_assertions", ] [[package]] name = "frame-benchmarking-cli" -version = "32.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "42.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "Inflector", "array-bytes", @@ -5255,7 +5004,7 @@ dependencies = [ "linked-hash-map", "log", "parity-scale-codec", - "rand 0.8.5", + "rand", "rand_pcg", "sc-block-builder", "sc-chain-spec", @@ -5271,35 +5020,35 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-database", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-genesis-builder", "sp-inherents", "sp-io", "sp-keystore", "sp-runtime", "sp-state-machine", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-trie", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-wasm-interface", "thiserror", "thousands", ] [[package]] name = "frame-election-provider-solution-type" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "14.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "frame-election-provider-support" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-election-provider-solution-type", "frame-support", @@ -5310,13 +5059,12 @@ dependencies = [ "sp-core", "sp-npos-elections", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "frame-executive" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "aquamarine", "frame-support", @@ -5328,8 +5076,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", ] [[package]] @@ -5346,8 +5093,8 @@ dependencies = [ [[package]] name = "frame-metadata-hash-extension" -version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.5.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", "docify", @@ -5361,8 +5108,8 @@ dependencies = [ [[package]] name = "frame-support" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "aquamarine", "array-bytes", @@ -5385,7 +5132,7 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-crypto-hashing-proc-macro", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-debug-derive", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -5393,8 +5140,8 @@ dependencies = [ "sp-runtime", "sp-staking", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", + "sp-tracing", "sp-weights", "static_assertions", "tt-call", @@ -5402,8 +5149,8 @@ dependencies = [ [[package]] name = "frame-support-procedural" -version = "23.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "30.0.4" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "Inflector", "cfg-expr", @@ -5412,39 +5159,39 @@ dependencies = [ "frame-support-procedural-tools", "itertools 0.11.0", "macro_magic", - "proc-macro-warning", + "proc-macro-warning 1.0.0", "proc-macro2", "quote", "sp-crypto-hashing", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "frame-support-procedural-tools" -version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "frame-support-procedural-tools-derive" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "12.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "frame-system" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "cfg-if", "docify", @@ -5456,15 +5203,15 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-version", "sp-weights", ] [[package]] name = "frame-system-benchmarking" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -5473,38 +5220,34 @@ dependencies = [ "scale-info", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "frame-system-rpc-runtime-api" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ + "docify", "parity-scale-codec", "sp-api", ] [[package]] name = "frame-try-runtime" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "parity-scale-codec", "sp-api", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "fs-err" -version = "2.11.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41" -dependencies = [ - "autocfg", -] +checksum = "0845fa252299212f0389d64ba26f34fa32cfe41588355f21ed507c59a0f64541" [[package]] name = "fs2" @@ -5522,7 +5265,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29f9df8a11882c4e3335eb2d18a0137c505d9ca927470b0cac9c6f0ae07d28f7" dependencies = [ - "rustix 0.38.34", + "rustix 0.38.21", "windows-sys 0.48.0", ] @@ -5553,6 +5296,16 @@ dependencies = [ "futures-util", ] +[[package]] +name = "futures-bounded" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b07bbbe7d7e78809544c6f718d875627addc73a7c3582447abc052cd3dc67e0" +dependencies = [ + "futures-timer", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.31" @@ -5609,7 +5362,7 @@ dependencies = [ "futures-io", "memchr", "parking", - "pin-project-lite 0.2.14", + "pin-project-lite", "waker-fn", ] @@ -5619,11 +5372,8 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ - "fastrand 2.1.0", "futures-core", - "futures-io", - "parking", - "pin-project-lite 0.2.14", + "pin-project-lite", ] [[package]] @@ -5634,18 +5384,17 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "futures-rustls" -version = "0.22.2" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2411eed028cdf8c8034eaf21f9915f956b6c3abec4d4c7949ee67f0721127bd" +checksum = "35bd3cf68c183738046838e300353e4716c674dc5e56890de4826801a6622a28" dependencies = [ "futures-io", - "rustls 0.20.9", - "webpki", + "rustls 0.21.7", ] [[package]] @@ -5665,6 +5414,10 @@ name = "futures-timer" version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" +dependencies = [ + "gloo-timers", + "send_wrapper 0.4.0", +] [[package]] name = "futures-util" @@ -5680,7 +5433,7 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite 0.2.14", + "pin-project-lite", "pin-utils", "slab", ] @@ -5726,25 +5479,14 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.9.0+wasi-snapshot-preview1", -] - -[[package]] -name = "getrandom" -version = "0.2.15" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" dependencies = [ "cfg-if", "js-sys", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", "wasm-bindgen", ] @@ -5754,17 +5496,17 @@ version = "0.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea1015b5a70616b688dc230cfe50c8af89d972cb132d5a622814d29773b10b9" dependencies = [ - "rand 0.8.5", - "rand_core 0.6.4", + "rand", + "rand_core", ] [[package]] name = "ghash" -version = "0.5.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +checksum = "d930750de5717d2dd0b8c0d42c076c0e884c81a73e6cab859bbd2339c71e3e40" dependencies = [ - "opaque-debug 0.3.1", + "opaque-debug 0.3.0", "polyval", ] @@ -5781,31 +5523,71 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.1" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" dependencies = [ "fallible-iterator 0.3.0", "stable_deref_trait", ] -[[package]] -name = "gimli" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" - [[package]] name = "glob" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +[[package]] +name = "gloo-net" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43aaa242d1239a8822c15c645f02166398da4f8b5c4bae795c1f5b44e9eee173" +dependencies = [ + "futures-channel", + "futures-core", + "futures-sink", + "gloo-utils", + "http 0.2.9", + "js-sys", + "pin-project", + "serde", + "serde_json", + "thiserror", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "gloo-timers" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b995a66bb87bebce9a0f4a95aed01daca4872c050bfcb21653361c03bc35e5c" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "gloo-utils" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5555354113b18c547c1d3a98fbf7fb32a9ff4f6fa112ce823a21641a0ba3aa" +dependencies = [ + "js-sys", + "serde", + "serde_json", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "governor" -version = "0.6.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68a7f542ee6b35af73b06abc0dad1c1bae89964e4e253bc4b587b91c9637867b" +checksum = "821239e5672ff23e2a7060901fa622950bbd80b649cdaadd78d1c1767ed14eb4" dependencies = [ "cfg-if", "dashmap", @@ -5814,11 +5596,9 @@ dependencies = [ "no-std-compat", "nonzero_ext", "parking_lot 0.12.3", - "portable-atomic", "quanta", - "rand 0.8.5", + "rand", "smallvec", - "spinning_top", ] [[package]] @@ -5828,8 +5608,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core 0.6.4", - "subtle 2.6.1", + "rand_core", + "subtle 2.5.0", ] [[package]] @@ -5843,8 +5623,27 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http", - "indexmap 2.2.6", + "http 0.2.9", + "indexmap 2.2.3", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "h2" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http 1.1.0", + "indexmap 2.2.3", "slab", "tokio", "tokio-util", @@ -5853,9 +5652,9 @@ dependencies = [ [[package]] name = "handlebars" -version = "5.1.2" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08485b96a0e6393e9e4d1b8d48cf74ad6c063cd905eb33f42c1ce3f0377539b" +checksum = "ab283476b99e66691dee3f1640fea91487a8d81f50fb5ecc75538f8f8879a1e4" dependencies = [ "log", "pest", @@ -5903,9 +5702,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.5" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ "ahash", "allocator-api2", @@ -5918,7 +5717,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "hashbrown 0.14.5", + "hashbrown 0.14.3", ] [[package]] @@ -5938,15 +5737,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - -[[package]] -name = "hermit-abi" -version = "0.4.0" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" [[package]] name = "hex" @@ -5956,9 +5749,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hex-conservative" -version = "0.1.2" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212ab92002354b4819390025006c897e8140934349e8635c9b077f47b4dcbd20" +checksum = "30ed443af458ccb6d81c1e7e661545f94d3176752fb1df2f543b902a1e0f51e2" [[package]] name = "hex-literal" @@ -5974,9 +5767,9 @@ checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" [[package]] name = "hkdf" -version = "0.12.4" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" dependencies = [ "hmac 0.12.1", ] @@ -6011,15 +5804,6 @@ dependencies = [ "hmac 0.8.1", ] -[[package]] -name = "home" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" -dependencies = [ - "windows-sys 0.52.0", -] - [[package]] name = "hostname" version = "0.3.1" @@ -6033,9 +5817,20 @@ dependencies = [ [[package]] name = "http" -version = "0.2.12" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" dependencies = [ "bytes", "fnv", @@ -6044,26 +5839,43 @@ dependencies = [ [[package]] name = "http-body" -version = "0.4.6" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ "bytes", - "http", - "pin-project-lite 0.2.14", + "http 0.2.9", + "pin-project-lite", ] [[package]] -name = "http-range-header" -version = "0.3.1" +name = "http-body" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" +checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" +dependencies = [ + "bytes", + "http 1.1.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "pin-project-lite", +] [[package]] name = "httparse" -version = "1.9.4" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" [[package]] name = "httpdate" @@ -6079,21 +5891,21 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "hyper" -version = "0.14.30" +version = "0.14.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a152ddd61dfaec7273fe8419ab357f33aee0d914c5f4efbf0d96fa749eea5ec9" +checksum = "f361cde2f109281a220d4307746cdfd5ee3f410da58a70377762396775634b33" dependencies = [ "bytes", "futures-channel", "futures-core", "futures-util", - "h2", - "http", - "http-body", + "h2 0.3.26", + "http 0.2.9", + "http-body 0.4.5", "httparse", "httpdate", "itoa", - "pin-project-lite 0.2.14", + "pin-project-lite", "socket2 0.5.7", "tokio", "tower-service", @@ -6101,6 +5913,27 @@ dependencies = [ "want", ] +[[package]] +name = "hyper" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2 0.4.5", + "http 1.1.0", + "http-body 1.0.0", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + [[package]] name = "hyper-rustls" version = "0.24.2" @@ -6108,27 +5941,65 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" dependencies = [ "futures-util", - "http", - "hyper", + "http 0.2.9", + "hyper 0.14.29", "log", - "rustls 0.21.12", + "rustls 0.21.7", "rustls-native-certs 0.6.3", "tokio", "tokio-rustls 0.24.1", ] +[[package]] +name = "hyper-rustls" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" +dependencies = [ + "futures-util", + "http 1.1.0", + "hyper 1.3.1", + "hyper-util", + "log", + "rustls 0.23.10", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.0", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b875924a60b96e5d7b9ae7b066540b1dd1cbd90d1828f54c92e02a283351c56" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "hyper 1.3.1", + "pin-project-lite", + "socket2 0.5.7", + "tokio", + "tower", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" -version = "0.1.60" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows-core", + "windows 0.48.0", ] [[package]] @@ -6197,38 +6068,37 @@ dependencies = [ "rtnetlink", "system-configuration", "tokio", - "windows", + "windows 0.51.1", ] [[package]] -name = "impl-codec" -version = "0.6.0" +name = "igd-next" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" +checksum = "064d90fec10d541084e7b39ead8875a5a80d9114a2b18791565253bae25f49e4" dependencies = [ - "parity-scale-codec", + "async-trait", + "attohttpc", + "bytes", + "futures 0.3.31", + "http 0.2.9", + "hyper 0.14.29", + "log", + "rand", + "tokio", + "url", + "xmltree", ] [[package]] name = "impl-codec" -version = "0.7.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67aa010c1e3da95bf151bd8b4c059b2ed7e75387cdb969b4f8f2723a43f9941" +checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" dependencies = [ "parity-scale-codec", ] -[[package]] -name = "impl-num-traits" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "803d15461ab0dcc56706adf266158acbc44ccf719bf7d0af30705f58b90a4b8c" -dependencies = [ - "integer-sqrt", - "num-traits", - "uint 0.10.0", -] - [[package]] name = "impl-rlp" version = "0.3.0" @@ -6247,15 +6117,6 @@ dependencies = [ "serde", ] -[[package]] -name = "impl-serde" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a143eada6a1ec4aefa5049037a26a6d597bfd64f8c026d07b77133e02b7dd0b" -dependencies = [ - "serde", -] - [[package]] name = "impl-trait-for-tuples" version = "0.2.2" @@ -6269,18 +6130,18 @@ dependencies = [ [[package]] name = "include_dir" -version = "0.7.4" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +checksum = "18762faeff7122e89e0857b02f7ce6fcc0d101d5e9ad2ad7846cc01d61b7f19e" dependencies = [ "include_dir_macros", ] [[package]] name = "include_dir_macros" -version = "0.7.4" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" +checksum = "b139284b5cf57ecfa712bcc66950bb635b31aff41c188e8a4cfc758eca374a3f" dependencies = [ "proc-macro2", "quote", @@ -6299,12 +6160,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.2.6" +version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +checksum = "233cf39063f058ea2caae4091bf4a3ef70a653afbc026f5c4a4135d114e3c177" dependencies = [ "equivalent", - "hashbrown 0.14.5", + "hashbrown 0.14.3", ] [[package]] @@ -6324,9 +6185,9 @@ dependencies = [ [[package]] name = "instant" -version = "0.1.13" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ "cfg-if", ] @@ -6352,7 +6213,7 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi 0.3.9", + "hermit-abi", "libc", "windows-sys 0.48.0", ] @@ -6377,19 +6238,19 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.9.0" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" [[package]] name = "is-terminal" -version = "0.4.12" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" dependencies = [ - "hermit-abi 0.3.9", - "libc", - "windows-sys 0.52.0", + "hermit-abi", + "rustix 0.38.21", + "windows-sys 0.48.0", ] [[package]] @@ -6401,12 +6262,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "is_terminal_polyfill" -version = "1.70.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" - [[package]] name = "itertools" version = "0.10.5" @@ -6426,48 +6281,62 @@ dependencies = [ ] [[package]] -name = "itertools" -version = "0.12.1" +name = "itoa" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" + +[[package]] +name = "jni" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec" dependencies = [ - "either", + "cesu8", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", ] [[package]] -name = "itoa" -version = "1.0.11" +name = "jni-sys" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" [[package]] name = "jobserver" -version = "0.1.31" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e" +checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2" dependencies = [ "libc", ] [[package]] name = "js-sys" -version = "0.3.69" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" dependencies = [ "wasm-bindgen", ] [[package]] name = "jsonrpsee" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfdb12a2381ea5b2e68c3469ec604a007b367778cdb14d09612c8069ebd616ad" +checksum = "62b089779ad7f80768693755a031cc14a7766aba707cbe886674e3f79e9b7e47" dependencies = [ + "jsonrpsee-client-transport", "jsonrpsee-core", + "jsonrpsee-http-client", "jsonrpsee-proc-macros", "jsonrpsee-server", "jsonrpsee-types", + "jsonrpsee-wasm-client", "jsonrpsee-ws-client", "tokio", "tracing", @@ -6475,20 +6344,24 @@ dependencies = [ [[package]] name = "jsonrpsee-client-transport" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4978087a58c3ab02efc5b07c5e5e2803024536106fd5506f558db172c889b3aa" +checksum = "08163edd8bcc466c33d79e10f695cdc98c00d1e6ddfb95cec41b6b0279dd5432" dependencies = [ + "base64 0.22.1", + "futures-channel", "futures-util", - "http", + "gloo-net", + "http 1.1.0", "jsonrpsee-core", "pin-project", - "rustls-native-certs 0.7.1", + "rustls 0.23.10", "rustls-pki-types", - "soketto", + "rustls-platform-verifier", + "soketto 0.8.0", "thiserror", "tokio", - "tokio-rustls 0.25.0", + "tokio-rustls 0.26.0", "tokio-util", "tracing", "url", @@ -6496,20 +6369,23 @@ dependencies = [ [[package]] name = "jsonrpsee-core" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4b257e1ec385e07b0255dde0b933f948b5c8b8c28d42afda9587c3a967b896d" +checksum = "79712302e737d23ca0daa178e752c9334846b08321d439fd89af9a384f8c830b" dependencies = [ "anyhow", "async-trait", "beef", + "bytes", "futures-timer", "futures-util", - "hyper", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", "jsonrpsee-types", "parking_lot 0.12.3", "pin-project", - "rand 0.8.5", + "rand", "rustc-hash", "serde", "serde_json", @@ -6517,37 +6393,67 @@ dependencies = [ "tokio", "tokio-stream", "tracing", + "wasm-bindgen-futures", +] + +[[package]] +name = "jsonrpsee-http-client" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d90064e04fb9d7282b1c71044ea94d0bbc6eff5621c66f1a0bce9e9de7cf3ac" +dependencies = [ + "async-trait", + "base64 0.22.1", + "http-body 1.0.0", + "hyper 1.3.1", + "hyper-rustls 0.27.2", + "hyper-util", + "jsonrpsee-core", + "jsonrpsee-types", + "rustls 0.23.10", + "rustls-platform-verifier", + "serde", + "serde_json", + "thiserror", + "tokio", + "tower", + "tracing", + "url", ] [[package]] name = "jsonrpsee-proc-macros" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d0bb047e79a143b32ea03974a6bf59b62c2a4c5f5d42a381c907a8bbb3f75c0" +checksum = "7895f186d5921065d96e16bd795e5ca89ac8356ec423fafc6e3d7cf8ec11aee4" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "jsonrpsee-server" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12d8b6a9674422a8572e0b0abb12feeb3f2aeda86528c80d0350c2bd0923ab41" +checksum = "654afab2e92e5d88ebd8a39d6074483f3f2bfdf91c5ac57fe285e7127cdd4f51" dependencies = [ + "anyhow", "futures-util", - "http", - "hyper", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", + "hyper 1.3.1", + "hyper-util", "jsonrpsee-core", "jsonrpsee-types", "pin-project", "route-recognizer", "serde", "serde_json", - "soketto", + "soketto 0.8.0", "thiserror", "tokio", "tokio-stream", @@ -6558,24 +6464,35 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150d6168405890a7a3231a3c74843f58b8959471f6df76078db2619ddee1d07d" +checksum = "d9c465fbe385238e861fdc4d1c85e04ada6c1fd246161d26385c1b311724d2af" dependencies = [ - "anyhow", "beef", + "http 1.1.0", "serde", "serde_json", "thiserror", ] +[[package]] +name = "jsonrpsee-wasm-client" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4727ac037f834c6f04c0912cada7532dbddb54e92fbc64e33d6cb8c24af313c9" +dependencies = [ + "jsonrpsee-client-transport", + "jsonrpsee-core", + "jsonrpsee-types", +] + [[package]] name = "jsonrpsee-ws-client" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58b9db2dfd5bb1194b0ce921504df9ceae210a345bc2f6c5a61432089bbab070" +checksum = "1c28759775f5cb2f1ea9667672d3fe2b0e701d1f4b7b67954e60afe7fd058b5e" dependencies = [ - "http", + "http 1.1.0", "jsonrpsee-client-transport", "jsonrpsee-core", "jsonrpsee-types", @@ -6598,9 +6515,9 @@ dependencies = [ [[package]] name = "keccak" -version = "0.1.5" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" +checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940" dependencies = [ "cpufeatures", ] @@ -6646,9 +6563,9 @@ dependencies = [ [[package]] name = "landlock" -version = "0.3.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9baa9eeb6e315942429397e617a190f4fdc696ef1ee0342939d641029cbb4ea7" +checksum = "1530c5b973eeed4ac216af7e24baf5737645a6272e361f1fb95710678b67d9cc" dependencies = [ "enumflags2", "libc", @@ -6657,11 +6574,11 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" dependencies = [ - "spin 0.9.8", + "spin 0.5.2", ] [[package]] @@ -6696,7 +6613,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm-builder", ] @@ -6758,7 +6675,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -6766,18 +6683,18 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.155" +version = "0.2.167" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" [[package]] name = "libloading" -version = "0.8.4" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" dependencies = [ "cfg-if", - "windows-targets 0.52.6", + "winapi", ] [[package]] @@ -6788,14 +6705,15 @@ checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" [[package]] name = "libp2p" -version = "0.51.4" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f35eae38201a993ece6bdc823292d6abd1bffed1c4d0f4a3517d2bd8e1d917fe" +checksum = "e94495eb319a85b70a68b85e2389a95bb3555c71c49025b78c691a854a7e6464" dependencies = [ "bytes", + "either", "futures 0.3.31", "futures-timer", - "getrandom 0.2.15", + "getrandom", "instant", "libp2p-allow-block-list", "libp2p-connection-limits", @@ -6812,18 +6730,21 @@ dependencies = [ "libp2p-request-response", "libp2p-swarm", "libp2p-tcp", + "libp2p-upnp", "libp2p-wasm-ext", "libp2p-websocket", "libp2p-yamux", - "multiaddr", + "multiaddr 0.18.1", "pin-project", + "rw-stream-sink", + "thiserror", ] [[package]] name = "libp2p-allow-block-list" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "510daa05efbc25184458db837f6f9a5143888f1caa742426d92e1833ddd38a50" +checksum = "55b46558c5c0bf99d3e2a1a38fd54ff5476ca66dd1737b12466a1824dd219311" dependencies = [ "libp2p-core", "libp2p-identity", @@ -6833,9 +6754,9 @@ dependencies = [ [[package]] name = "libp2p-connection-limits" -version = "0.1.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4caa33f1d26ed664c4fe2cca81a08c8e07d4c1c04f2f4ac7655c2dd85467fda0" +checksum = "2f5107ad45cb20b2f6c3628c7b6014b996fcb13a88053f4569c872c6e30abf58" dependencies = [ "libp2p-core", "libp2p-identity", @@ -6845,9 +6766,9 @@ dependencies = [ [[package]] name = "libp2p-core" -version = "0.39.2" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c1df63c0b582aa434fb09b2d86897fa2b419ffeccf934b36f87fcedc8e835c2" +checksum = "dd44289ab25e4c9230d9246c475a22241e301b23e8f4061d3bdef304a1a99713" dependencies = [ "either", "fnv", @@ -6856,50 +6777,53 @@ dependencies = [ "instant", "libp2p-identity", "log", - "multiaddr", - "multihash 0.17.0", + "multiaddr 0.18.1", + "multihash 0.19.1", "multistream-select", "once_cell", "parking_lot 0.12.3", "pin-project", "quick-protobuf", - "rand 0.8.5", + "rand", "rw-stream-sink", "smallvec", "thiserror", - "unsigned-varint", + "unsigned-varint 0.7.2", "void", ] [[package]] name = "libp2p-dns" -version = "0.39.0" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146ff7034daae62077c415c2376b8057368042df6ab95f5432ad5e88568b1554" +checksum = "e6a18db73084b4da2871438f6239fef35190b05023de7656e877c18a00541a3b" dependencies = [ + "async-trait", "futures 0.3.31", "libp2p-core", + "libp2p-identity", "log", "parking_lot 0.12.3", "smallvec", - "trust-dns-resolver 0.22.0", + "trust-dns-resolver", ] [[package]] name = "libp2p-identify" -version = "0.42.2" +version = "0.43.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5455f472243e63b9c497ff320ded0314254a9eb751799a39c283c6f20b793f3c" +checksum = "45a96638a0a176bec0a4bcaebc1afa8cf909b114477209d7456ade52c61cd9cd" dependencies = [ "asynchronous-codec", "either", "futures 0.3.31", + "futures-bounded", "futures-timer", "libp2p-core", "libp2p-identity", "libp2p-swarm", "log", - "lru 0.10.1", + "lru 0.12.3", "quick-protobuf", "quick-protobuf-codec", "smallvec", @@ -6909,27 +6833,27 @@ dependencies = [ [[package]] name = "libp2p-identity" -version = "0.1.3" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "276bb57e7af15d8f100d3c11cbdd32c6752b7eef4ba7a18ecf464972c07abcce" +checksum = "999ec70441b2fb35355076726a6bc466c932e9bdc66f6a11c6c0aa17c7ab9be0" dependencies = [ - "bs58 0.4.0", - "ed25519-dalek 2.1.1", - "log", - "multiaddr", - "multihash 0.17.0", + "bs58 0.5.0", + "ed25519-dalek", + "hkdf", + "multihash 0.19.1", "quick-protobuf", - "rand 0.8.5", + "rand", "sha2 0.10.8", "thiserror", + "tracing", "zeroize", ] [[package]] name = "libp2p-kad" -version = "0.43.3" +version = "0.44.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39d5ef876a2b2323d63c258e63c2f8e36f205fe5a11f0b3095d59635650790ff" +checksum = "16ea178dabba6dde6ffc260a8e0452ccdc8f79becf544946692fff9d412fc29d" dependencies = [ "arrayvec 0.7.4", "asynchronous-codec", @@ -6944,20 +6868,21 @@ dependencies = [ "libp2p-swarm", "log", "quick-protobuf", - "rand 0.8.5", + "quick-protobuf-codec", + "rand", "sha2 0.10.8", "smallvec", "thiserror", - "uint 0.9.5", - "unsigned-varint", + "uint", + "unsigned-varint 0.7.2", "void", ] [[package]] name = "libp2p-mdns" -version = "0.43.1" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19983e1f949f979a928f2c603de1cf180cc0dc23e4ac93a62651ccb18341460b" +checksum = "42a2567c305232f5ef54185e9604579a894fd0674819402bb0ac0246da82f52a" dependencies = [ "data-encoding", "futures 0.3.31", @@ -6966,9 +6891,9 @@ dependencies = [ "libp2p-identity", "libp2p-swarm", "log", - "rand 0.8.5", + "rand", "smallvec", - "socket2 0.4.10", + "socket2 0.5.7", "tokio", "trust-dns-proto 0.22.0", "void", @@ -6976,63 +6901,69 @@ dependencies = [ [[package]] name = "libp2p-metrics" -version = "0.12.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a42ec91e227d7d0dafa4ce88b333cdf5f277253873ab087555c92798db2ddd46" +checksum = "239ba7d28f8d0b5d77760dc6619c05c7e88e74ec8fbbe97f856f20a56745e620" dependencies = [ + "instant", "libp2p-core", "libp2p-identify", + "libp2p-identity", "libp2p-kad", "libp2p-ping", "libp2p-swarm", + "once_cell", "prometheus-client", ] [[package]] name = "libp2p-noise" -version = "0.42.2" +version = "0.43.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3673da89d29936bc6435bafc638e2f184180d554ce844db65915113f86ec5e" +checksum = "d2eeec39ad3ad0677551907dd304b2f13f17208ccebe333bef194076cd2e8921" dependencies = [ "bytes", - "curve25519-dalek 3.2.0", + "curve25519-dalek", "futures 0.3.31", "libp2p-core", "libp2p-identity", "log", + "multiaddr 0.18.1", + "multihash 0.19.1", "once_cell", "quick-protobuf", - "rand 0.8.5", + "rand", "sha2 0.10.8", "snow", "static_assertions", "thiserror", - "x25519-dalek 1.1.1", + "x25519-dalek", "zeroize", ] [[package]] name = "libp2p-ping" -version = "0.42.0" +version = "0.43.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e57759c19c28a73ef1eb3585ca410cefb72c1a709fcf6de1612a378e4219202" +checksum = "e702d75cd0827dfa15f8fd92d15b9932abe38d10d21f47c50438c71dd1b5dae3" dependencies = [ "either", "futures 0.3.31", "futures-timer", "instant", "libp2p-core", + "libp2p-identity", "libp2p-swarm", "log", - "rand 0.8.5", + "rand", "void", ] [[package]] name = "libp2p-quic" -version = "0.7.0-alpha.3" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6b26abd81cd2398382a1edfe739b539775be8a90fa6914f39b2ab49571ec735" +checksum = "130d451d83f21b81eb7b35b360bc7972aeafb15177784adc56528db082e6b927" dependencies = [ "bytes", "futures 0.3.31", @@ -7043,18 +6974,20 @@ dependencies = [ "libp2p-tls", "log", "parking_lot 0.12.3", - "quinn-proto", - "rand 0.8.5", - "rustls 0.20.9", + "quinn 0.10.2", + "rand", + "ring 0.16.20", + "rustls 0.21.7", + "socket2 0.5.7", "thiserror", "tokio", ] [[package]] name = "libp2p-request-response" -version = "0.24.1" +version = "0.25.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffdb374267d42dc5ed5bc53f6e601d4a64ac5964779c6e40bb9e4f14c1e30d5" +checksum = "d8e3b4d67870478db72bac87bfc260ee6641d0734e0e3e275798f089c3fecfd4" dependencies = [ "async-trait", "futures 0.3.31", @@ -7062,15 +6995,17 @@ dependencies = [ "libp2p-core", "libp2p-identity", "libp2p-swarm", - "rand 0.8.5", + "log", + "rand", "smallvec", + "void", ] [[package]] name = "libp2p-swarm" -version = "0.42.2" +version = "0.43.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "903b3d592d7694e56204d211f29d31bc004be99386644ba8731fc3e3ef27b296" +checksum = "580189e0074af847df90e75ef54f3f30059aedda37ea5a1659e8b9fca05c0141" dependencies = [ "either", "fnv", @@ -7081,7 +7016,9 @@ dependencies = [ "libp2p-identity", "libp2p-swarm-derive", "log", - "rand 0.8.5", + "multistream-select", + "once_cell", + "rand", "smallvec", "tokio", "void", @@ -7089,36 +7026,39 @@ dependencies = [ [[package]] name = "libp2p-swarm-derive" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fba456131824ab6acd4c7bf61e9c0f0a3014b5fc9868ccb8e10d344594cdc4f" +checksum = "c4d5ec2a3df00c7836d7696c136274c9c59705bac69133253696a6c932cd1d74" dependencies = [ "heck 0.4.1", + "proc-macro-warning 0.4.2", + "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.90", ] [[package]] name = "libp2p-tcp" -version = "0.39.0" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d33698596d7722d85d3ab0c86c2c322254fce1241e91208e3679b4eb3026cf" +checksum = "b558dd40d1bcd1aaaed9de898e9ec6a436019ecc2420dd0016e712fbb61c5508" dependencies = [ "futures 0.3.31", "futures-timer", "if-watch", "libc", "libp2p-core", + "libp2p-identity", "log", - "socket2 0.4.10", + "socket2 0.5.7", "tokio", ] [[package]] name = "libp2p-tls" -version = "0.1.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff08d13d0dc66e5e9ba6279c1de417b84fa0d0adc3b03e5732928c180ec02781" +checksum = "8218d1d5482b122ccae396bbf38abdcb283ecc96fa54760e1dfd251f0546ac61" dependencies = [ "futures 0.3.31", "futures-rustls", @@ -7126,51 +7066,69 @@ dependencies = [ "libp2p-identity", "rcgen", "ring 0.16.20", - "rustls 0.20.9", + "rustls 0.21.7", + "rustls-webpki 0.101.4", "thiserror", - "webpki", - "x509-parser 0.14.0", + "x509-parser 0.15.1", "yasna", ] +[[package]] +name = "libp2p-upnp" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82775a47b34f10f787ad3e2a22e2c1541e6ebef4fe9f28f3ac553921554c94c1" +dependencies = [ + "futures 0.3.31", + "futures-timer", + "igd-next", + "libp2p-core", + "libp2p-swarm", + "log", + "tokio", + "void", +] + [[package]] name = "libp2p-wasm-ext" -version = "0.39.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77dff9d32353a5887adb86c8afc1de1a94d9e8c3bc6df8b2201d7cdf5c848f43" +checksum = "1e5d8e3a9e07da0ef5b55a9f26c009c8fb3c725d492d8bb4b431715786eea79c" dependencies = [ "futures 0.3.31", "js-sys", "libp2p-core", - "parity-send-wrapper", + "send_wrapper 0.6.0", "wasm-bindgen", "wasm-bindgen-futures", ] [[package]] name = "libp2p-websocket" -version = "0.41.0" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111273f7b3d3510524c752e8b7a5314b7f7a1fee7e68161c01a7d72cbb06db9f" +checksum = "004ee9c4a4631435169aee6aad2f62e3984dc031c43b6d29731e8e82a016c538" dependencies = [ "either", "futures 0.3.31", "futures-rustls", "libp2p-core", + "libp2p-identity", "log", "parking_lot 0.12.3", - "quicksink", + "pin-project-lite", "rw-stream-sink", - "soketto", + "soketto 0.8.0", + "thiserror", "url", - "webpki-roots", + "webpki-roots 0.25.2", ] [[package]] name = "libp2p-yamux" -version = "0.43.1" +version = "0.44.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd21d950662700a385d4c6d68e2f5f54d778e97068cdd718522222ef513bda" +checksum = "8eedcb62824c4300efb9cfd4e2a6edaf3ca097b9e68b36dabe45a44469fd6a85" dependencies = [ "futures 0.3.31", "libp2p-core", @@ -7179,16 +7137,6 @@ dependencies = [ "yamux", ] -[[package]] -name = "libredox" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" -dependencies = [ - "bitflags 2.6.0", - "libc", -] - [[package]] name = "librocksdb-sys" version = "0.11.0+8.1.1" @@ -7217,7 +7165,7 @@ dependencies = [ "libsecp256k1-core", "libsecp256k1-gen-ecmult", "libsecp256k1-gen-genmult", - "rand 0.8.5", + "rand", "serde", "sha2 0.9.9", "typenum", @@ -7231,7 +7179,7 @@ checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" dependencies = [ "crunchy", "digest 0.9.0", - "subtle 2.6.1", + "subtle 2.5.0", ] [[package]] @@ -7265,9 +7213,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.18" +version = "1.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c15da26e5af7e25c90b37a2d75cdbf940cf4a55316de9d84c679c9b8bfabf82e" +checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" dependencies = [ "cc", "pkg-config", @@ -7300,9 +7248,9 @@ dependencies = [ [[package]] name = "linregress" -version = "0.5.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4de04dcecc58d366391f9920245b85ffa684558a5ef6e7736e754347c3aea9c2" +checksum = "4de0b5f52a9f84544d268f5fabb71b38962d6aa3c6600b8bcd27d44ccf9c9c45" dependencies = [ "nalgebra", ] @@ -7321,9 +7269,9 @@ checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "linux-raw-sys" -version = "0.4.14" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" [[package]] name = "lioness" @@ -7339,31 +7287,31 @@ dependencies = [ [[package]] name = "litep2p" -version = "0.5.0" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f02542ae3a94b4c4ffa37dc56388c923e286afa3bf65452e3984b50b2a2f316" +checksum = "0f46c51c205264b834ceed95c8b195026e700494bc3991aaba3b4ea9e20626d9" dependencies = [ "async-trait", "bs58 0.4.0", "bytes", "cid 0.10.1", - "ed25519-dalek 1.0.1", + "ed25519-dalek", "futures 0.3.31", "futures-timer", "hex-literal 0.4.1", - "indexmap 2.2.6", + "indexmap 2.2.3", "libc", "mockall 0.12.1", - "multiaddr", + "multiaddr 0.17.1", "multihash 0.17.0", "network-interface", "nohash-hasher", "parking_lot 0.12.3", "pin-project", - "prost 0.11.9", + "prost 0.12.6", "prost-build 0.11.9", - "quinn", - "rand 0.8.5", + "quinn 0.9.4", + "rand", "rcgen", "ring 0.16.20", "rustls 0.20.9", @@ -7381,22 +7329,22 @@ dependencies = [ "tokio-tungstenite", "tokio-util", "tracing", - "trust-dns-resolver 0.23.2", - "uint 0.9.5", - "unsigned-varint", + "trust-dns-resolver", + "uint", + "unsigned-varint 0.8.0", "url", "webpki", - "x25519-dalek 2.0.1", - "x509-parser 0.15.1", + "x25519-dalek", + "x509-parser 0.16.0", "yasna", "zeroize", ] [[package]] name = "lock_api" -version = "0.4.12" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" dependencies = [ "autocfg", "scopeguard", @@ -7410,18 +7358,18 @@ checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "lru" -version = "0.10.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "718e8fae447df0c7e1ba7f5189829e63fd536945c8988d61444c19039f16b670" -dependencies = [ - "hashbrown 0.13.2", -] +checksum = "eedb2bdbad7e0634f83989bf596f497b070130daaa398ab22d84c39e266deec5" [[package]] name = "lru" -version = "0.11.1" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a83fb7698b3643a0e34f9ae6f2e8f0178c0fd42f8b59d493aa271ff3a5bf21" +checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" +dependencies = [ + "hashbrown 0.14.3", +] [[package]] name = "lru-cache" @@ -7434,9 +7382,9 @@ dependencies = [ [[package]] name = "lz4" -version = "1.25.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6eab492fe7f8651add23237ea56dbf11b3c4ff762ab83d40a47f11433421f91" +checksum = "7e9e2dd86df36ce760a60f6ff6ad526f7ba1f14ba0356f8254fb6905e6494df1" dependencies = [ "libc", "lz4-sys", @@ -7444,9 +7392,9 @@ dependencies = [ [[package]] name = "lz4-sys" -version = "1.9.5" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9764018d143cc854c9f17f0b907de70f14393b1f502da6375dce70f00514eb3" +checksum = "57d27b317e207b10f69f5e75494119e391a96f48861ae870d1da6edac98ca900" dependencies = [ "cc", "libc", @@ -7461,6 +7409,15 @@ dependencies = [ "libc", ] +[[package]] +name = "mach2" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b955cdeb2a02b9117f121ce63aa52d08ade45de53e48fe6a38b39c10f6f709" +dependencies = [ + "libc", +] + [[package]] name = "macro_magic" version = "0.5.1" @@ -7470,7 +7427,7 @@ dependencies = [ "macro_magic_core", "macro_magic_macros", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -7484,7 +7441,7 @@ dependencies = [ "macro_magic_core_macros", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -7495,7 +7452,7 @@ checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -7506,7 +7463,7 @@ checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" dependencies = [ "macro_magic_core", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -7532,9 +7489,9 @@ checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" [[package]] name = "matrixmultiply" -version = "0.3.8" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7574c1cf36da4798ab73da5b215bbf444f50718207754cb522201d78d1cd0ff2" +checksum = "090126dc04f95dc0d1c1c91f61bdd474b3930ca064c1edc8a849da2c6cbe1e77" dependencies = [ "autocfg", "rawpointer", @@ -7548,11 +7505,11 @@ checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memfd" -version = "0.6.4" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2cffa4ad52c6f791f4f8b15f0c05f9824b2ced1160e88cc393d64fff9a8ac64" +checksum = "ffc89ccdc6e10d6907450f753537ebc5c5d3460d2e4e62ea74bd571db62c0f9e" dependencies = [ - "rustix 0.38.34", + "rustix 0.37.23", ] [[package]] @@ -7566,9 +7523,9 @@ dependencies = [ [[package]] name = "memmap2" -version = "0.9.4" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe751422e4a8caa417e13c3ea66452215d7d63e19e604f4980461212f3ae1322" +checksum = "45fd3a57831bf88bc63f8cebc0cf956116276e97fef3966103e96416209f7c92" dependencies = [ "libc", ] @@ -7582,6 +7539,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "memoffset" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" +dependencies = [ + "autocfg", +] + [[package]] name = "memory-db" version = "0.32.0" @@ -7594,7 +7560,7 @@ dependencies = [ [[package]] name = "merkle-distributor" version = "0.1.0" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "frame-support", "frame-system", @@ -7607,7 +7573,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -7632,7 +7598,7 @@ checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d" dependencies = [ "byteorder", "keccak", - "rand_core 0.6.4", + "rand_core", "zeroize", ] @@ -7643,7 +7609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69672161530e8aeca1d1400fbf3f1a1747ff60ea604265a4e906c2442df20532" dependencies = [ "futures 0.3.31", - "rand 0.8.5", + "rand", "thrift", ] @@ -7655,22 +7621,22 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.4" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" dependencies = [ "adler", ] [[package]] name = "mio" -version = "0.8.11" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" dependencies = [ "libc", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.48.0", + "wasi", + "windows-sys 0.52.0", ] [[package]] @@ -7684,24 +7650,24 @@ dependencies = [ "bitflags 1.3.2", "blake2 0.10.6", "c2-chacha", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "either", "hashlink", "lioness", "log", "parking_lot 0.12.3", - "rand 0.8.5", - "rand_chacha 0.3.1", + "rand", + "rand_chacha", "rand_distr", - "subtle 2.6.1", + "subtle 2.5.0", "thiserror", "zeroize", ] [[package]] name = "mmr-gadget" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "log", @@ -7719,8 +7685,8 @@ dependencies = [ [[package]] name = "mmr-rpc" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "jsonrpsee", "parity-scale-codec", @@ -7758,7 +7724,7 @@ dependencies = [ "fragile", "lazy_static", "mockall_derive 0.12.1", - "predicates 3.1.0", + "predicates 3.0.3", "predicates-tree", ] @@ -7783,7 +7749,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -7792,7 +7758,7 @@ version = "2.21.0" dependencies = [ "ethereum 0.14.0", "sha3", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -7820,22 +7786,41 @@ dependencies = [ "percent-encoding", "serde", "static_assertions", - "unsigned-varint", + "unsigned-varint 0.7.2", "url", ] [[package]] -name = "multibase" -version = "0.9.1" +name = "multiaddr" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b3539ec3c1f04ac9748a260728e855f261b4977f5c3406612c884564f329404" +checksum = "8b852bc02a2da5feed68cd14fa50d0774b92790a5bdbfa932a813926c8472070" dependencies = [ - "base-x", + "arrayref", + "byteorder", "data-encoding", - "data-encoding-macro", -] - -[[package]] + "libp2p-identity", + "multibase", + "multihash 0.19.1", + "percent-encoding", + "serde", + "static_assertions", + "unsigned-varint 0.7.2", + "url", +] + +[[package]] +name = "multibase" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b3539ec3c1f04ac9748a260728e855f261b4977f5c3406612c884564f329404" +dependencies = [ + "base-x", + "data-encoding", + "data-encoding-macro", +] + +[[package]] name = "multihash" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -7846,10 +7831,10 @@ dependencies = [ "blake3", "core2", "digest 0.10.7", - "multihash-derive 0.8.1", + "multihash-derive", "sha2 0.10.8", "sha3", - "unsigned-varint", + "unsigned-varint 0.7.2", ] [[package]] @@ -7863,10 +7848,10 @@ dependencies = [ "blake3", "core2", "digest 0.10.7", - "multihash-derive 0.8.1", + "multihash-derive", "sha2 0.10.8", "sha3", - "unsigned-varint", + "unsigned-varint 0.7.2", ] [[package]] @@ -7876,36 +7861,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "076d548d76a0e2a0d4ab471d0b1c36c577786dfc4471242035d97a12a735c492" dependencies = [ "core2", - "unsigned-varint", -] - -[[package]] -name = "multihash-codetable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d815ecb3c8238d00647f8630ede7060a642c9f704761cd6082cb4028af6935" -dependencies = [ - "blake2b_simd", - "blake2s_simd", - "blake3", - "core2", - "digest 0.10.7", - "multihash-derive 0.9.0", - "ripemd", - "serde", - "sha1", - "sha2 0.10.8", - "sha3", - "strobe-rs", + "unsigned-varint 0.7.2", ] [[package]] name = "multihash-derive" -version = "0.8.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6d4752e6230d8ef7adf7bd5d8c4b1f6561c1014c5ba9a37445ccefe18aa1db" +checksum = "fc076939022111618a5026d3be019fd8b366e76314538ff9a1b59ffbcbf98bcd" dependencies = [ - "proc-macro-crate 1.1.3", + "proc-macro-crate 1.3.1", "proc-macro-error", "proc-macro2", "quote", @@ -7913,62 +7878,31 @@ dependencies = [ "synstructure 0.12.6", ] -[[package]] -name = "multihash-derive" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "890e72cb7396cb99ed98c1246a97b243cc16394470d94e0bc8b0c2c11d84290e" -dependencies = [ - "core2", - "multihash 0.19.1", - "multihash-derive-impl", -] - -[[package]] -name = "multihash-derive-impl" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3958713ce794e12f7c6326fac9aa274c68d74c4881dd37b3e2662b8a2046bb19" -dependencies = [ - "proc-macro-crate 2.0.0", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.85", - "synstructure 0.13.1", -] - [[package]] name = "multimap" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" -[[package]] -name = "multimap" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" - [[package]] name = "multistream-select" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8552ab875c1313b97b8d20cb857b9fd63e2d1d6a0a1b53ce9821e575405f27a" +checksum = "ea0df8e5eec2298a62b326ee4f0d7fe1a6b90a09dfcf9df37b38f947a8c42f19" dependencies = [ "bytes", "futures 0.3.31", "log", "pin-project", "smallvec", - "unsigned-varint", + "unsigned-varint 0.7.2", ] [[package]] name = "nalgebra" -version = "0.32.6" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4" +checksum = "307ed9b18cc2423f29e83f84fd23a8e73628727990181f18641a8b5dc2ab1caa" dependencies = [ "approx", "matrixmultiply", @@ -7982,13 +7916,13 @@ dependencies = [ [[package]] name = "nalgebra-macros" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc" +checksum = "91761aed67d03ad966ef783ae962ef9bbaca728d2dd7ceb7939ec110fffad998" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 1.0.109", ] [[package]] @@ -7997,7 +7931,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7bddcd3bf5144b6392de80e04c347cd7fab2508f6df16a85fc496ecd5cec39bc" dependencies = [ - "rand 0.8.5", + "rand", ] [[package]] @@ -8006,7 +7940,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" dependencies = [ - "getrandom 0.2.15", + "getrandom", ] [[package]] @@ -8081,9 +8015,9 @@ dependencies = [ [[package]] name = "netlink-sys" -version = "0.8.6" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416060d346fbaf1f23f9512963e3e878f1a78e707cb699ba9215761754244307" +checksum = "6471bf08e7ac0135876a9581bf3217ef0333c191c128d34878079f42ee150411" dependencies = [ "bytes", "futures 0.3.31", @@ -8094,9 +8028,9 @@ dependencies = [ [[package]] name = "network-interface" -version = "1.1.4" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a43439bf756eed340bdf8feba761e2d50c7d47175d87545cd5cbe4a137c4d1" +checksum = "ae72fd9dbd7f55dda80c00d66acc3b2130436fcba9ea89118fc508eaae48dfb0" dependencies = [ "cc", "libc", @@ -8285,7 +8219,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.3.9", + "hermit-abi", "libc", ] @@ -8304,10 +8238,10 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" dependencies = [ - "proc-macro-crate 1.1.3", + "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -8332,21 +8266,21 @@ dependencies = [ ] [[package]] -name = "object" -version = "0.36.1" +name = "oid-registry" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" +checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" dependencies = [ - "memchr", + "asn1-rs 0.5.2", ] [[package]] name = "oid-registry" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" +checksum = "1c958dd45046245b9c3c2547369bb634eb461670b2e7e0de552905801a648d1d" dependencies = [ - "asn1-rs", + "asn1-rs 0.6.1", ] [[package]] @@ -8363,15 +8297,15 @@ checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" [[package]] name = "opaque-debug" -version = "0.3.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "openssl" -version = "0.10.66" +version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ "bitflags 2.6.0", "cfg-if", @@ -8390,7 +8324,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -8401,18 +8335,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.3.1+3.3.1" +version = "300.2.3+3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7259953d42a81bf137fbbd73bd30a8e1914d6dce43c2b90ed575783a22608b91" +checksum = "5cff92b6f71555b61bb9315f7c64da3ca43d87531622120fea0195fc761b4843" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.103" +version = "0.9.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9e8deee91df40a943c71b917e5874b951d32a802526c85721ce3b776c929d6" +checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2" dependencies = [ "cc", "libc", @@ -8429,9 +8363,9 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "orchestra" -version = "0.3.6" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92829eef0328a3d1cd22a02c0e51deb92a5362df3e7d21a4e9bdc38934694e66" +checksum = "41f6bbacc8c189a3f2e45e0fd0436e5d97f194db888e721bdbc3973e7dbed4c2" dependencies = [ "async-trait", "dyn-clonable", @@ -8446,12 +8380,12 @@ dependencies = [ [[package]] name = "orchestra-proc-macro" -version = "0.3.6" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1344346d5af32c95bbddea91b18a88cc83eac394192d20ef2fc4c40a74332355" +checksum = "f7b1d40dd8f367db3c65bec8d3dd47d4a604ee8874480738f93191bddab4e0e0" dependencies = [ "expander", - "indexmap 2.2.6", + "indexmap 2.2.3", "itertools 0.11.0", "petgraph", "proc-macro-crate 3.1.0", @@ -8471,8 +8405,8 @@ dependencies = [ [[package]] name = "orml-oracle" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-benchmarking", "frame-support", @@ -8486,13 +8420,13 @@ dependencies = [ "sp-application-crypto", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] name = "orml-tokens" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "frame-system", @@ -8503,13 +8437,13 @@ dependencies = [ "serde", "sp-arithmetic", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] name = "orml-traits" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "impl-trait-for-tuples", @@ -8522,14 +8456,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", ] [[package]] name = "orml-unknown-tokens" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "frame-system", @@ -8537,14 +8471,14 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", ] [[package]] name = "orml-utilities" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "parity-scale-codec", @@ -8553,41 +8487,41 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] name = "orml-xcm" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "frame-system", "pallet-xcm", "parity-scale-codec", "scale-info", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", ] [[package]] name = "orml-xcm-support" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "orml-traits", "parity-scale-codec", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-executor", ] [[package]] name = "orml-xtokens" -version = "0.13.0" -source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-v1.13.0#f571fa22652850cd94b7918446ae509ae0595d98" +version = "1.0.0" +source = "git+https://github.com/bifrost-io/open-runtime-module-library?branch=release-polkadot-stable2407#815f776cd326f7fb8ba37c7193c3a34e42c796e5" dependencies = [ "frame-support", "frame-system", @@ -8600,7 +8534,7 @@ dependencies = [ "serde", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-executor", ] @@ -8613,8 +8547,8 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "pallet-asset-conversion" -version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "19.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8627,13 +8561,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-asset-rate" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8642,13 +8575,12 @@ dependencies = [ "scale-info", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-asset-tx-payment" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8660,29 +8592,28 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-assets" -version = "29.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "impl-trait-for-tuples", "log", "parity-scale-codec", "scale-info", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-aura" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -8693,13 +8624,12 @@ dependencies = [ "sp-application-crypto", "sp-consensus-aura", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-authority-discovery" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -8709,13 +8639,12 @@ dependencies = [ "sp-application-crypto", "sp-authority-discovery", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-authorship" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -8723,13 +8652,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-babe" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8747,13 +8675,12 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-bags-list" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "aquamarine", "docify", @@ -8768,14 +8695,13 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", ] [[package]] name = "pallet-balances" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -8785,13 +8711,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-base-fee" version = "1.0.0" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", "frame-support", @@ -8804,8 +8729,8 @@ dependencies = [ [[package]] name = "pallet-beefy" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -8819,13 +8744,12 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-beefy-mmr" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", "binary-merkle-tree", @@ -8844,13 +8768,12 @@ dependencies = [ "sp-io", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-bounties" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8862,13 +8785,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-broker" -version = "0.6.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "frame-benchmarking", @@ -8881,13 +8803,12 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-child-bounties" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8900,13 +8821,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-collator-selection" -version = "9.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "18.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8916,17 +8836,16 @@ dependencies = [ "pallet-balances", "pallet-session", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-collective" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8937,13 +8856,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-conviction-voting" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "assert_matches", "frame-benchmarking", @@ -8954,13 +8872,12 @@ dependencies = [ "serde", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-delegated-staking" -version = "1.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "4.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -8968,13 +8885,12 @@ dependencies = [ "scale-info", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-democracy" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -8986,13 +8902,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-dynamic-fee" version = "4.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-dynamic-fee", "fp-evm", @@ -9006,8 +8921,8 @@ dependencies = [ [[package]] name = "pallet-election-provider-multi-phase" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -9016,21 +8931,20 @@ dependencies = [ "log", "pallet-election-provider-support-benchmarking", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", "sp-arithmetic", "sp-core", "sp-io", "sp-npos-elections", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "strum 0.26.3", ] [[package]] name = "pallet-election-provider-support-benchmarking" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -9038,13 +8952,12 @@ dependencies = [ "parity-scale-codec", "sp-npos-elections", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-elections-phragmen" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9057,13 +8970,12 @@ dependencies = [ "sp-npos-elections", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-ethereum" version = "4.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "ethereum 0.15.0", "ethereum-types", @@ -9085,7 +8997,7 @@ dependencies = [ [[package]] name = "pallet-evm" version = "6.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "environmental", "evm", @@ -9121,7 +9033,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] @@ -9135,7 +9047,7 @@ dependencies = [ [[package]] name = "pallet-evm-chain-id" version = "1.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "frame-support", "frame-system", @@ -9146,7 +9058,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-blake2" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", ] @@ -9154,17 +9066,46 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-bn128" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", "sp-core", "substrate-bn", ] +[[package]] +name = "pallet-evm-precompile-call-permit" +version = "0.1.3" +dependencies = [ + "derive_more", + "evm", + "fp-evm", + "frame-support", + "frame-system", + "hex-literal 0.4.1", + "libsecp256k1", + "log", + "num_enum", + "pallet-balances", + "pallet-evm", + "pallet-timestamp", + "parity-scale-codec", + "paste", + "precompile-utils", + "scale-info", + "serde", + "sha3", + "slices", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-evm-precompile-dispatch" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", "frame-support", @@ -9176,7 +9117,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-modexp" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", "num", @@ -9185,7 +9126,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-sha3fips" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", "tiny-keccak", @@ -9194,7 +9135,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-simple" version = "2.0.0-dev" -source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-v1.13.0#24a48ebc221399d129712eff41787ad800dc8a26" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" dependencies = [ "fp-evm", "ripemd", @@ -9203,8 +9144,8 @@ dependencies = [ [[package]] name = "pallet-fast-unstake" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9217,13 +9158,12 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-grandpa" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9240,13 +9180,12 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-identity" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "enumflags2", "frame-benchmarking", @@ -9257,13 +9196,12 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-im-online" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9277,13 +9215,12 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-indices" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9294,13 +9231,12 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-membership" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9311,13 +9247,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-message-queue" -version = "31.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "40.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "environmental", "frame-benchmarking", @@ -9330,14 +9265,13 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-weights", ] [[package]] name = "pallet-mmr" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9349,13 +9283,12 @@ dependencies = [ "sp-io", "sp-mmr-primitives", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-multisig" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9365,13 +9298,12 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-nis" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9381,13 +9313,12 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-nomination-pools" -version = "25.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -9399,14 +9330,13 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", ] [[package]] name = "pallet-nomination-pools-benchmarking" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "35.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -9419,26 +9349,24 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-nomination-pools-runtime-api" -version = "23.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "32.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "pallet-nomination-pools", "parity-scale-codec", "sp-api", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-offences" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -9449,13 +9377,12 @@ dependencies = [ "serde", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-offences-benchmarking" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -9473,13 +9400,12 @@ dependencies = [ "scale-info", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-parameters" -version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.8.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9491,13 +9417,12 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-preimage" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9508,7 +9433,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] @@ -9534,14 +9458,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", ] [[package]] name = "pallet-proxy" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9550,13 +9474,12 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-ranked-collective" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9569,13 +9492,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-recovery" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9584,13 +9506,12 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-referenda" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "assert_matches", "frame-benchmarking", @@ -9603,13 +9524,12 @@ dependencies = [ "sp-arithmetic", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-root-testing" -version = "4.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -9618,13 +9538,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-scheduler" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9635,14 +9554,13 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-weights", ] [[package]] name = "pallet-session" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -9657,14 +9575,13 @@ dependencies = [ "sp-session", "sp-staking", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-trie", ] [[package]] name = "pallet-session-benchmarking" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9672,34 +9589,32 @@ dependencies = [ "pallet-session", "pallet-staking", "parity-scale-codec", - "rand 0.8.5", + "rand", "sp-runtime", "sp-session", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-society" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", "frame-system", "log", "parity-scale-codec", - "rand_chacha 0.3.1", + "rand_chacha", "scale-info", "sp-arithmetic", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-staking" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -9709,31 +9624,30 @@ dependencies = [ "pallet-authorship", "pallet-session", "parity-scale-codec", - "rand_chacha 0.3.1", + "rand_chacha", "scale-info", "serde", "sp-application-crypto", "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-staking-reward-curve" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "12.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "pallet-staking-reward-fn" -version = "19.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "log", "sp-arithmetic", @@ -9741,8 +9655,8 @@ dependencies = [ [[package]] name = "pallet-staking-runtime-api" -version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "sp-api", @@ -9751,8 +9665,8 @@ dependencies = [ [[package]] name = "pallet-state-trie-migration" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9763,13 +9677,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-sudo" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9779,13 +9692,12 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-timestamp" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9797,15 +9709,14 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-timestamp", ] [[package]] name = "pallet-tips" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9818,7 +9729,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] @@ -9838,7 +9748,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -9846,8 +9756,8 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -9857,13 +9767,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-transaction-payment-rpc" -version = "30.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "jsonrpsee", "pallet-transaction-payment-rpc-runtime-api", @@ -9878,8 +9787,8 @@ dependencies = [ [[package]] name = "pallet-transaction-payment-rpc-runtime-api" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "pallet-transaction-payment", "parity-scale-codec", @@ -9890,8 +9799,8 @@ dependencies = [ [[package]] name = "pallet-treasury" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9904,13 +9813,12 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-tx-pause" -version = "9.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "18.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "docify", "frame-benchmarking", @@ -9922,13 +9830,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-utility" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9938,13 +9845,12 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-vesting" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9953,13 +9859,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-whitelist" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -9968,13 +9873,12 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "pallet-xcm" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bounded-collections", "frame-benchmarking", @@ -9988,17 +9892,17 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", - "xcm-fee-payment-runtime-api", + "tracing", + "xcm-runtime-apis", ] [[package]] name = "pallet-xcm-benchmarks" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-benchmarking", "frame-support", @@ -10008,7 +9912,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -10016,8 +9919,8 @@ dependencies = [ [[package]] name = "parachains-common" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-primitives-core", "cumulus-primitives-utility", @@ -10038,7 +9941,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -10052,8 +9954,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e69bf016dc406eff7d53a7d3f7cf1c2e72c82b9088aac1118591e36dd2cd3e9" dependencies = [ "bitcoin_hashes 0.13.0", - "rand 0.7.3", - "rand_core 0.5.1", + "rand", + "rand_core", "serde", "unicode-normalization", ] @@ -10073,7 +9975,7 @@ dependencies = [ "lz4", "memmap2 0.5.10", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "siphasher", "snap", "winapi", @@ -10106,12 +10008,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "parity-send-wrapper" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9777aa91b8ad9dd5aaa04a9b6bcb02c7f1deb952fca5a66034d5e63afc5c6f" - [[package]] name = "parity-wasm" version = "0.45.0" @@ -10120,9 +10016,9 @@ checksum = "e1ad0aff30c1da14b1254fcb2af73e1fa9a28670e584a626f53a369d0e157304" [[package]] name = "parking" -version = "2.2.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" +checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e" [[package]] name = "parking_lot" @@ -10142,7 +10038,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", - "parking_lot_core 0.9.10", + "parking_lot_core 0.9.8", ] [[package]] @@ -10161,15 +10057,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.10" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.3", + "redox_syscall 0.3.5", "smallvec", - "windows-targets 0.52.6", + "windows-targets 0.48.5", ] [[package]] @@ -10185,8 +10081,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" dependencies = [ "base64ct", - "rand_core 0.6.4", - "subtle 2.6.1", + "rand_core", + "subtle 2.5.0", ] [[package]] @@ -10228,20 +10124,19 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.11" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd53dff83f26735fdc1ca837098ccf133605d794cdae66acfc2bfac3ec809d95" +checksum = "1acb4a4365a13f749a93f1a094a7805e5cfa0955373a9de860d962eaa3a5fe5a" dependencies = [ - "memchr", "thiserror", "ucd-trie", ] [[package]] name = "pest_derive" -version = "2.7.11" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a548d2beca6773b1c244554d36fcf8548a8a58e74156968211567250e48e49a" +checksum = "666d00490d4ac815001da55838c500eafb0320019bbaa44444137c48b443a853" dependencies = [ "pest", "pest_generator", @@ -10249,22 +10144,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.11" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c93a82e8d145725dcbaf44e5ea887c8a869efdcc28706df2d08c69e17077183" +checksum = "68ca01446f50dbda87c1786af8770d535423fa8a53aec03b8f4e3d7eb10e0929" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "pest_meta" -version = "2.7.11" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a941429fea7e08bedec25e4f6785b6ffaacc6b755da98df5ef3e7dcf4a124c4f" +checksum = "56af0a30af74d0445c0bf6d9d051c979b516a1a5af790d251daee76005420a48" dependencies = [ "once_cell", "pest", @@ -10273,40 +10168,34 @@ dependencies = [ [[package]] name = "petgraph" -version = "0.6.5" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +checksum = "e1d3afd2628e69da2be385eb6f2fd57c8ac7977ceeff6dc166ff1657b0e386a9" dependencies = [ "fixedbitset", - "indexmap 2.2.6", + "indexmap 2.2.3", ] [[package]] name = "pin-project" -version = "1.1.5" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" +checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.5" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" +checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] -[[package]] -name = "pin-project-lite" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" - [[package]] name = "pin-project-lite" version = "0.2.14" @@ -10319,17 +10208,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" -[[package]] -name = "piper" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1d5c74c9876f070d3e8fd503d748c7d974c3e48da8f41350fa5222ef9b4391" -dependencies = [ - "atomic-waker", - "fastrand 2.1.0", - "futures-io", -] - [[package]] name = "pkcs8" version = "0.10.2" @@ -10342,14 +10220,14 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.30" +version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" [[package]] name = "polkadot-approval-distribution" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "futures 0.3.31", @@ -10362,14 +10240,14 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "tracing-gum", ] [[package]] name = "polkadot-availability-bitfield-distribution" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "always-assert", "futures 0.3.31", @@ -10378,14 +10256,14 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "tracing-gum", ] [[package]] name = "polkadot-availability-distribution" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "derive_more", "fatality", @@ -10397,7 +10275,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-network", "schnellru", "sp-core", @@ -10408,8 +10286,8 @@ dependencies = [ [[package]] name = "polkadot-availability-recovery" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "fatality", @@ -10421,7 +10299,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-network", "schnellru", "thiserror", @@ -10441,8 +10319,8 @@ dependencies = [ [[package]] name = "polkadot-cli" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cfg-if", "clap", @@ -10469,8 +10347,8 @@ dependencies = [ [[package]] name = "polkadot-collator-protocol" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "fatality", @@ -10491,26 +10369,25 @@ dependencies = [ [[package]] name = "polkadot-core-primitives" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "scale-info", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "polkadot-dispute-distribution" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "derive_more", "fatality", "futures 0.3.31", "futures-timer", - "indexmap 2.2.6", + "indexmap 2.2.3", "parity-scale-codec", "polkadot-erasure-coding", "polkadot-node-network-protocol", @@ -10528,8 +10405,8 @@ dependencies = [ [[package]] name = "polkadot-erasure-coding" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "polkadot-node-primitives", @@ -10542,8 +10419,8 @@ dependencies = [ [[package]] name = "polkadot-gossip-support" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "futures-timer", @@ -10551,8 +10428,8 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", - "rand_chacha 0.3.1", + "rand", + "rand_chacha", "sc-network", "sc-network-common", "sp-application-crypto", @@ -10564,8 +10441,8 @@ dependencies = [ [[package]] name = "polkadot-network-bridge" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "always-assert", "async-trait", @@ -10587,8 +10464,8 @@ dependencies = [ [[package]] name = "polkadot-node-collation-generation" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "parity-scale-codec", @@ -10605,8 +10482,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-approval-voting" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "derive_more", @@ -10622,9 +10499,9 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", - "rand 0.8.5", - "rand_chacha 0.3.1", - "rand_core 0.6.4", + "rand", + "rand_chacha", + "rand_core", "sc-keystore", "schnellru", "schnorrkel 0.11.4", @@ -10638,8 +10515,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-av-store" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "futures 0.3.31", @@ -10660,8 +10537,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-backing" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "fatality", @@ -10680,8 +10557,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-bitfield-signing" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "polkadot-node-subsystem", @@ -10695,8 +10572,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-candidate-validation" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "futures 0.3.31", @@ -10710,14 +10587,16 @@ dependencies = [ "polkadot-overseer", "polkadot-parachain-primitives", "polkadot-primitives", + "sp-application-crypto", + "sp-keystore", "sp-maybe-compressed-blob", "tracing-gum", ] [[package]] name = "polkadot-node-core-chain-api" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "polkadot-node-metrics", @@ -10730,8 +10609,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-chain-selection" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "futures-timer", @@ -10747,8 +10626,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-dispute-coordinator" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "fatality", "futures 0.3.31", @@ -10766,8 +10645,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-parachains-inherent" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "futures 0.3.31", @@ -10783,14 +10662,11 @@ dependencies = [ [[package]] name = "polkadot-node-core-prospective-parachains" -version = "6.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ - "bitvec", "fatality", "futures 0.3.31", - "parity-scale-codec", - "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", @@ -10800,8 +10676,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-provisioner" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "fatality", @@ -10818,8 +10694,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-pvf" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "always-assert", "array-bytes", @@ -10836,7 +10712,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-parachain-primitives", "polkadot-primitives", - "rand 0.8.5", + "rand", "slotmap", "sp-core", "tempfile", @@ -10847,8 +10723,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-pvf-checker" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "polkadot-node-primitives", @@ -10863,8 +10739,8 @@ dependencies = [ [[package]] name = "polkadot-node-core-pvf-common" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cpu-time", "futures 0.3.31", @@ -10880,17 +10756,17 @@ dependencies = [ "seccompiler", "sp-core", "sp-crypto-hashing", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-io", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", "thiserror", "tracing-gum", ] [[package]] name = "polkadot-node-core-runtime-api" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "polkadot-node-metrics", @@ -10904,8 +10780,8 @@ dependencies = [ [[package]] name = "polkadot-node-jaeger" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "lazy_static", "log", @@ -10923,10 +10799,10 @@ dependencies = [ [[package]] name = "polkadot-node-metrics" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ - "bs58 0.5.1", + "bs58 0.5.0", "futures 0.3.31", "futures-timer", "log", @@ -10942,10 +10818,10 @@ dependencies = [ [[package]] name = "polkadot-node-network-protocol" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ - "async-channel 1.9.0", + "async-channel", "async-trait", "bitvec", "derive_more", @@ -10956,7 +10832,7 @@ dependencies = [ "polkadot-node-jaeger", "polkadot-node-primitives", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-authority-discovery", "sc-network", "sc-network-types", @@ -10968,8 +10844,8 @@ dependencies = [ [[package]] name = "polkadot-node-primitives" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "bounded-vec", @@ -10991,8 +10867,8 @@ dependencies = [ [[package]] name = "polkadot-node-subsystem" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "polkadot-node-jaeger", "polkadot-node-subsystem-types", @@ -11001,8 +10877,8 @@ dependencies = [ [[package]] name = "polkadot-node-subsystem-types" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "bitvec", @@ -11031,8 +10907,8 @@ dependencies = [ [[package]] name = "polkadot-node-subsystem-util" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "derive_more", @@ -11055,7 +10931,7 @@ dependencies = [ "polkadot-overseer", "polkadot-primitives", "prioritized-metered-channel", - "rand 0.8.5", + "rand", "sc-client-api", "schnellru", "sp-application-crypto", @@ -11067,8 +10943,8 @@ dependencies = [ [[package]] name = "polkadot-overseer" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "futures 0.3.31", @@ -11089,8 +10965,8 @@ dependencies = [ [[package]] name = "polkadot-parachain-primitives" -version = "6.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "14.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bounded-collections", "derive_more", @@ -11100,14 +10976,13 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-weights", ] [[package]] name = "polkadot-primitives" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "hex-literal 0.4.1", @@ -11128,13 +11003,12 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "polkadot-rpc" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "jsonrpsee", "mmr-rpc", @@ -11168,8 +11042,8 @@ dependencies = [ [[package]] name = "polkadot-runtime-common" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitvec", "frame-benchmarking", @@ -11210,7 +11084,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -11219,21 +11092,20 @@ dependencies = [ [[package]] name = "polkadot-runtime-metrics" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ - "bs58 0.5.1", + "bs58 0.5.0", "frame-benchmarking", "parity-scale-codec", "polkadot-primitives", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", ] [[package]] name = "polkadot-runtime-parachains" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "bitflags 1.3.2", "bitvec", @@ -11258,9 +11130,8 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-metrics", - "rand 0.8.5", - "rand_chacha 0.3.1", - "rustc-hex", + "rand", + "rand_chacha", "scale-info", "serde", "sp-api", @@ -11273,7 +11144,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "staging-xcm", "staging-xcm-executor", "static_assertions", @@ -11281,8 +11151,8 @@ dependencies = [ [[package]] name = "polkadot-service" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "frame-benchmarking", @@ -11384,7 +11254,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-state-machine", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-timestamp", "sp-transaction-pool", "sp-version", @@ -11394,20 +11264,20 @@ dependencies = [ "thiserror", "tracing-gum", "westend-runtime", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] name = "polkadot-statement-distribution" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "arrayvec 0.7.4", "bitvec", "fatality", "futures 0.3.31", "futures-timer", - "indexmap 2.2.6", + "indexmap 2.2.3", "parity-scale-codec", "polkadot-node-network-protocol", "polkadot-node-primitives", @@ -11422,8 +11292,8 @@ dependencies = [ [[package]] name = "polkadot-statement-table" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "polkadot-primitives", @@ -11480,7 +11350,7 @@ dependencies = [ "polkavm-common", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -11490,7 +11360,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ba81f7b5faac81e528eb6158a6f3c9e0bb1008e0ffa19653bc8dea925ecb429" dependencies = [ "polkavm-derive-impl", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -11499,8 +11369,8 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c7be503e60cf56c0eb785f90aaba4b583b36bff00e93997d93fef97f9553c39" dependencies = [ - "gimli 0.28.1", - "hashbrown 0.14.5", + "gimli 0.28.0", + "hashbrown 0.14.3", "log", "object 0.32.2", "polkavm-common", @@ -11526,21 +11396,20 @@ dependencies = [ "concurrent-queue", "libc", "log", - "pin-project-lite 0.2.14", + "pin-project-lite", "windows-sys 0.48.0", ] [[package]] name = "polling" -version = "3.7.2" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" +checksum = "30054e72317ab98eddd8561db0f6524df3367636884b7b21b703e4b280a84a14" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi 0.4.0", - "pin-project-lite 0.2.14", - "rustix 0.38.34", + "pin-project-lite", + "rustix 0.38.21", "tracing", "windows-sys 0.52.0", ] @@ -11552,28 +11421,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" dependencies = [ "cpufeatures", - "opaque-debug 0.3.1", + "opaque-debug 0.3.0", "universal-hash", ] [[package]] name = "polyval" -version = "0.6.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +checksum = "d52cff9d1d4dee5fe6d03729099f4a310a41179e0a10dbf542039873f2e826fb" dependencies = [ "cfg-if", "cpufeatures", - "opaque-debug 0.3.1", + "opaque-debug 0.3.0", "universal-hash", ] -[[package]] -name = "portable-atomic" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0" - [[package]] name = "powerfmt" version = "0.2.0" @@ -11586,6 +11449,49 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +[[package]] +name = "precompile-utils" +version = "0.1.0" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" +dependencies = [ + "derive_more", + "environmental", + "evm", + "fp-evm", + "frame-support", + "frame-system", + "hex", + "hex-literal 0.4.1", + "impl-trait-for-tuples", + "log", + "num_enum", + "pallet-evm", + "parity-scale-codec", + "precompile-utils-macro", + "scale-info", + "serde", + "similar-asserts", + "sp-core", + "sp-io", + "sp-runtime", + "sp-weights", + "staging-xcm", +] + +[[package]] +name = "precompile-utils-macro" +version = "0.1.0" +source = "git+https://github.com/bifrost-io/frontier?branch=release-polkadot-stable2407#81ebdfa2d6b75e2ef85311ffda6a8f1fe56e3834" +dependencies = [ + "case", + "num_enum", + "prettyplease 0.2.25", + "proc-macro2", + "quote", + "sp-crypto-hashing", + "syn 1.0.109", +] + [[package]] name = "predicates" version = "2.1.5" @@ -11602,11 +11508,12 @@ dependencies = [ [[package]] name = "predicates" -version = "3.1.0" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" +checksum = "09963355b9f467184c04017ced4a2ba2d75cbcb4e7462690d388233253d4b1a9" dependencies = [ "anstyle", + "itertools 0.10.5", "predicates-core", ] @@ -11638,38 +11545,26 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.20" +version = "0.2.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" +checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" dependencies = [ "proc-macro2", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "primitive-types" -version = "0.12.2" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" +checksum = "9f3486ccba82358b11a77516035647c34ba167dfa53312630de83b12bd4f3d66" dependencies = [ "fixed-hash", - "impl-codec 0.6.0", + "impl-codec", "impl-rlp", - "impl-serde 0.4.0", + "impl-serde", "scale-info", - "uint 0.9.5", -] - -[[package]] -name = "primitive-types" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d15600a7d856470b7d278b3fe0e311fe28c2526348549f8ef2ff7db3299c87f5" -dependencies = [ - "fixed-hash", - "impl-codec 0.7.0", - "impl-num-traits", - "uint 0.10.0", + "uint", ] [[package]] @@ -11690,21 +11585,12 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "1.1.3" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" dependencies = [ - "thiserror", - "toml 0.5.11", -] - -[[package]] -name = "proc-macro-crate" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" -dependencies = [ - "toml_edit 0.20.7", + "once_cell", + "toml_edit 0.19.15", ] [[package]] @@ -11713,7 +11599,7 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d37c51ca738a55da99dc0c4a34860fd675453b8b36209178c2249bb13651284" dependencies = [ - "toml_edit 0.21.1", + "toml_edit 0.21.0", ] [[package]] @@ -11740,22 +11626,39 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + [[package]] name = "proc-macro-warning" -version = "1.0.2" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1eaa7fa0aa1929ffdf7eeb6eac234dde6268914a14ad44d23521ab6a9b258e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.90", +] + +[[package]] +name = "proc-macro-warning" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "834da187cfe638ae8abb0203f0b33e5ccdb02a28e7199f2f47b3e2754f50edca" +checksum = "9b698b0b09d40e9b7c1a47b132d66a8b54bcd20583d9b6d06e4535e383b4405c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "proc-macro2" -version = "1.0.89" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -11776,9 +11679,9 @@ dependencies = [ [[package]] name = "prometheus-client" -version = "0.19.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6fa99d535dd930d1249e6c79cb3c2915f9172a540fe2b02a4c8f9ca954721e" +checksum = "3c99afa9a01501019ac3a14d71d9f94050346f55ca471ce90c799a15c58f61e2" dependencies = [ "dtoa", "itoa", @@ -11794,7 +11697,7 @@ checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -11828,7 +11731,7 @@ dependencies = [ "itertools 0.10.5", "lazy_static", "log", - "multimap 0.8.3", + "multimap", "petgraph", "prettyplease 0.1.25", "prost 0.11.9", @@ -11841,22 +11744,22 @@ dependencies = [ [[package]] name = "prost-build" -version = "0.12.6" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4" +checksum = "80b776a1b2dc779f5ee0641f8ade0125bc1298dd41a9a0c16d8bd57b42d222b1" dependencies = [ "bytes", "heck 0.5.0", - "itertools 0.12.1", + "itertools 0.11.0", "log", - "multimap 0.10.0", + "multimap", "once_cell", "petgraph", - "prettyplease 0.2.20", + "prettyplease 0.2.25", "prost 0.12.6", - "prost-types 0.12.6", + "prost-types 0.12.4", "regex", - "syn 2.0.85", + "syn 2.0.90", "tempfile", ] @@ -11880,10 +11783,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.11.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -11897,9 +11800,9 @@ dependencies = [ [[package]] name = "prost-types" -version = "0.12.6" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0" +checksum = "3235c33eb02c1f1e212abdbe34c78b264b038fb58ca612664343271e36e55ffe" dependencies = [ "prost 0.12.6", ] @@ -11915,15 +11818,16 @@ dependencies = [ [[package]] name = "quanta" -version = "0.12.3" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5167a477619228a0b284fac2674e3c388cba90631d7b7de620e6f1fcd08da5" +checksum = "a17e662a7a8291a865152364c20c7abc5e60486ab2001e8ec10b24862de0b9ab" dependencies = [ "crossbeam-utils", "libc", + "mach2", "once_cell", "raw-cpuid", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", "web-sys", "winapi", ] @@ -11945,44 +11849,51 @@ dependencies = [ [[package]] name = "quick-protobuf-codec" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1693116345026436eb2f10b677806169c1a1260c1c60eaaffe3fb5a29ae23d8b" +checksum = "f8ededb1cd78531627244d51dd0c7139fbe736c7d57af0092a76f0ffb2f56e98" dependencies = [ "asynchronous-codec", "bytes", "quick-protobuf", "thiserror", - "unsigned-varint", + "unsigned-varint 0.7.2", ] [[package]] -name = "quicksink" -version = "0.1.2" +name = "quinn" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77de3c815e5a160b1539c6592796801df2043ae35e123b46d73380cfa57af858" +checksum = "2e8b432585672228923edbbf64b8b12c14e1112f62e88737655b4a083dbcd78e" dependencies = [ - "futures-core", - "futures-sink", - "pin-project-lite 0.1.12", + "bytes", + "pin-project-lite", + "quinn-proto 0.9.6", + "quinn-udp 0.3.2", + "rustc-hash", + "rustls 0.20.9", + "thiserror", + "tokio", + "tracing", + "webpki", ] [[package]] name = "quinn" -version = "0.9.4" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e8b432585672228923edbbf64b8b12c14e1112f62e88737655b4a083dbcd78e" +checksum = "8cc2c5017e4b43d5995dcea317bc46c1e09404c0a9664d2908f7f02dfe943d75" dependencies = [ "bytes", - "pin-project-lite 0.2.14", - "quinn-proto", - "quinn-udp", + "futures-io", + "pin-project-lite", + "quinn-proto 0.10.6", + "quinn-udp 0.4.1", "rustc-hash", - "rustls 0.20.9", + "rustls 0.21.7", "thiserror", "tokio", "tracing", - "webpki", ] [[package]] @@ -11992,7 +11903,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94b0b33c13a79f669c85defaf4c275dc86a0c0372807d0ca3d78e0bb87274863" dependencies = [ "bytes", - "rand 0.8.5", + "rand", "ring 0.16.20", "rustc-hash", "rustls 0.20.9", @@ -12003,6 +11914,23 @@ dependencies = [ "webpki", ] +[[package]] +name = "quinn-proto" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "141bf7dfde2fbc246bfd3fe12f2455aa24b0fbd9af535d8c86c7bd1381ff2b1a" +dependencies = [ + "bytes", + "rand", + "ring 0.16.20", + "rustc-hash", + "rustls 0.21.7", + "slab", + "thiserror", + "tinyvec", + "tracing", +] + [[package]] name = "quinn-udp" version = "0.3.2" @@ -12010,17 +11938,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "641538578b21f5e5c8ea733b736895576d0fe329bb883b937db6f4d163dbaaf4" dependencies = [ "libc", - "quinn-proto", - "socket2 0.4.10", + "quinn-proto 0.9.6", + "socket2 0.4.9", "tracing", "windows-sys 0.42.0", ] +[[package]] +name = "quinn-udp" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "055b4e778e8feb9f93c4e439f71dc2156ef13360b432b799e179a8c4cdf0b1d7" +dependencies = [ + "bytes", + "libc", + "socket2 0.5.7", + "tracing", + "windows-sys 0.48.0", +] + [[package]] name = "quote" -version = "1.0.37" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -12031,19 +11972,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" -[[package]] -name = "rand" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" -dependencies = [ - "getrandom 0.1.16", - "libc", - "rand_chacha 0.2.2", - "rand_core 0.5.1", - "rand_hc", -] - [[package]] name = "rand" version = "0.8.5" @@ -12051,18 +11979,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" -dependencies = [ - "ppv-lite86", - "rand_core 0.5.1", + "rand_chacha", + "rand_core", ] [[package]] @@ -12072,16 +11990,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" -dependencies = [ - "getrandom 0.1.16", + "rand_core", ] [[package]] @@ -12090,7 +11999,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.15", + "getrandom", ] [[package]] @@ -12100,16 +12009,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand 0.8.5", -] - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core 0.5.1", + "rand", ] [[package]] @@ -12118,16 +12018,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" dependencies = [ - "rand_core 0.6.4", + "rand_core", ] [[package]] name = "raw-cpuid" -version = "11.1.0" +version = "10.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb9ee317cfe3fbd54b36a511efc1edd42e216903c9cd575e686dd68a2ba90d8d" +checksum = "6c297679cb867470fa8c9f67dbba74a78d78e3e98d7cf2b08d6d71540f797332" dependencies = [ - "bitflags 2.6.0", + "bitflags 1.3.2", ] [[package]] @@ -12179,30 +12079,30 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.4.1" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "redox_syscall" -version = "0.5.3" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ - "bitflags 2.6.0", + "bitflags 1.3.2", ] [[package]] name = "redox_users" -version = "0.4.5" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" dependencies = [ - "getrandom 0.2.15", - "libredox", + "getrandom", + "redox_syscall 0.2.16", "thiserror", ] @@ -12220,22 +12120,22 @@ dependencies = [ [[package]] name = "ref-cast" -version = "1.0.23" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" +checksum = "acde58d073e9c79da00f2b5b84eed919c8326832648a5b109b3fce1bb1175280" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.23" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" +checksum = "7f7473c2cfcf90008193dd0e3e16599455cb601a9fce322b5bb55de799664925" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -12265,14 +12165,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.5" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" +checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.7", - "regex-syntax 0.8.4", + "regex-automata 0.4.3", + "regex-syntax 0.8.2", ] [[package]] @@ -12286,13 +12186,19 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.7" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" + +[[package]] +name = "regex-automata" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.4", + "regex-syntax 0.8.2", ] [[package]] @@ -12303,9 +12209,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.4" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "resolv-conf" @@ -12324,24 +12230,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ "hmac 0.12.1", - "subtle 2.6.1", -] - -[[package]] -name = "ring" -version = "0.1.0" -source = "git+https://github.com/w3f/ring-proof#652286c32f96beb9ce7f5793f5e2c2c923f63b73" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", - "ark-transcript 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "arrayvec 0.7.4", - "blake2 0.10.6", - "common", - "fflonk", + "subtle 2.5.0", ] [[package]] @@ -12361,17 +12250,16 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.8" +version = "0.17.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +checksum = "688c63d65483050968b2a8937f7995f443e27041a0f7700aa59b0822aedebb74" dependencies = [ "cc", - "cfg-if", - "getrandom 0.2.15", + "getrandom", "libc", "spin 0.9.8", "untrusted 0.9.0", - "windows-sys 0.52.0", + "windows-sys 0.48.0", ] [[package]] @@ -12417,8 +12305,8 @@ dependencies = [ [[package]] name = "rococo-runtime" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "binary-merkle-tree", "bitvec", @@ -12504,8 +12392,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -12513,13 +12400,13 @@ dependencies = [ "staging-xcm-executor", "static_assertions", "substrate-wasm-builder", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] name = "rococo-runtime-constants" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "polkadot-primitives", @@ -12540,13 +12427,13 @@ checksum = "afab94fb28594581f62d981211a9a4d53cc8130bbcbbb89a0440d9b8e81a7746" [[package]] name = "rpassword" -version = "7.3.1" +version = "7.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80472be3c897911d0137b2d2b9055faf6eeac5b14e324073d83bc17b191d7e3f" +checksum = "6678cf63ab3491898c0d021b493c94c9b221d91295294a2a5746eacbe5928322" dependencies = [ "libc", "rtoolbox", - "windows-sys 0.48.0", + "winapi", ] [[package]] @@ -12566,19 +12453,19 @@ dependencies = [ [[package]] name = "rtoolbox" -version = "0.0.2" +version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c247d24e63230cdb56463ae328478bd5eac8b8faa8c69461a77e8e323afac90e" +checksum = "034e22c514f5c0cb8a10ff341b9b048b5ceb21591f31c8f44c43b960f9b3524a" dependencies = [ "libc", - "windows-sys 0.48.0", + "winapi", ] [[package]] name = "rustc-demangle" -version = "0.1.24" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustc-hash" @@ -12598,7 +12485,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver 1.0.23", + "semver 1.0.18", ] [[package]] @@ -12612,9 +12499,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.36.17" +version = "0.36.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "305efbd14fde4139eb501df5f136994bb520b033fa9fbdce287507dc23b8c7ed" +checksum = "c37f1bd5ef1b5422177b7646cba67430579cfe2ace80f284fee876bca52ad941" dependencies = [ "bitflags 1.3.2", "errno", @@ -12626,9 +12513,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.27" +version = "0.37.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fea8ca367a3a01fe35e6943c400addf443c0f57670e6ec51196f71a4b8762dd2" +checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" dependencies = [ "bitflags 1.3.2", "errno", @@ -12640,15 +12527,15 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.34" +version = "0.38.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" +checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" dependencies = [ "bitflags 2.6.0", "errno", "libc", - "linux-raw-sys 0.4.14", - "windows-sys 0.52.0", + "linux-raw-sys 0.4.10", + "windows-sys 0.48.0", ] [[package]] @@ -12657,7 +12544,6 @@ version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" dependencies = [ - "log", "ring 0.16.20", "sct", "webpki", @@ -12665,27 +12551,28 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.12" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" +checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" dependencies = [ "log", - "ring 0.17.8", - "rustls-webpki 0.101.7", + "ring 0.16.20", + "rustls-webpki 0.101.4", "sct", ] [[package]] name = "rustls" -version = "0.22.4" +version = "0.23.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" +checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402" dependencies = [ "log", - "ring 0.17.8", + "once_cell", + "ring 0.17.7", "rustls-pki-types", - "rustls-webpki 0.102.5", - "subtle 2.6.1", + "rustls-webpki 0.102.4", + "subtle 2.5.0", "zeroize", ] @@ -12696,19 +12583,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" dependencies = [ "openssl-probe", - "rustls-pemfile 1.0.4", + "rustls-pemfile 1.0.3", "schannel", "security-framework", ] [[package]] name = "rustls-native-certs" -version = "0.7.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a88d6d420651b496bdd98684116959239430022a115c1240e6c3993be0b15fba" +checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792" dependencies = [ "openssl-probe", - "rustls-pemfile 2.1.2", + "rustls-pemfile 2.0.0", "rustls-pki-types", "schannel", "security-framework", @@ -12716,20 +12603,20 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.4" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ - "base64 0.21.7", + "base64 0.21.2", ] [[package]] name = "rustls-pemfile" -version = "2.1.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" +checksum = "35e4980fa29e4c4b212ffb3db068a564cbf560e51d3944b7c88bd8bf5bec64f4" dependencies = [ - "base64 0.22.1", + "base64 0.21.2", "rustls-pki-types", ] @@ -12739,32 +12626,59 @@ version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" +[[package]] +name = "rustls-platform-verifier" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f0d26fa1ce3c790f9590868f0109289a044acb954525f933e2aa3b871c157d" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls 0.23.10", + "rustls-native-certs 0.7.0", + "rustls-platform-verifier-android", + "rustls-webpki 0.102.4", + "security-framework", + "security-framework-sys", + "webpki-roots 0.26.3", + "winapi", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e217e7fdc8466b5b35d30f8c0a30febd29173df4a3a0c2115d306b9c4117ad" + [[package]] name = "rustls-webpki" -version = "0.101.7" +version = "0.101.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +checksum = "7d93931baf2d282fff8d3a532bbfd7653f734643161b87e3e01e59a04439bf0d" dependencies = [ - "ring 0.17.8", - "untrusted 0.9.0", + "ring 0.16.20", + "untrusted 0.7.1", ] [[package]] name = "rustls-webpki" -version = "0.102.5" +version = "0.102.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78" +checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" dependencies = [ - "ring 0.17.8", + "ring 0.17.7", "rustls-pki-types", "untrusted 0.9.0", ] [[package]] name = "rustversion" -version = "1.0.17" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ruzstd" @@ -12779,9 +12693,9 @@ dependencies = [ [[package]] name = "rw-stream-sink" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26338f5e09bb721b85b135ea05af7767c90b52f6de4f087d4f4a3a9d64e7dc04" +checksum = "d8c9026ff5d2f23da5e45bbc283f156383001bfb09c4e44256d02c1a685fe9a1" dependencies = [ "futures 0.3.31", "pin-project", @@ -12790,15 +12704,15 @@ dependencies = [ [[package]] name = "ryu" -version = "1.0.18" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "safe_arch" -version = "0.7.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3460605018fdc9612bce72735cba0d27efbcd9904780d44c7e3a9948f96148a" +checksum = "f398075ce1e6a179b46f51bd88d0598b92b00d3551f1a2d4ac49e771b56ac354" dependencies = [ "bytemuck", ] @@ -12814,19 +12728,19 @@ dependencies = [ [[package]] name = "sc-allocator" -version = "23.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "29.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "log", "sp-core", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-wasm-interface", "thiserror", ] [[package]] name = "sc-authority-discovery" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "futures 0.3.31", @@ -12835,12 +12749,11 @@ dependencies = [ "libp2p", "linked_hash_set", "log", - "multihash 0.17.0", - "multihash-codetable", + "multihash 0.19.1", "parity-scale-codec", "prost 0.12.6", - "prost-build 0.12.6", - "rand 0.8.5", + "prost-build 0.12.4", + "rand", "sc-client-api", "sc-network", "sc-network-types", @@ -12856,8 +12769,8 @@ dependencies = [ [[package]] name = "sc-basic-authorship" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "futures-timer", @@ -12878,8 +12791,8 @@ dependencies = [ [[package]] name = "sc-block-builder" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.42.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "sp-api", @@ -12893,13 +12806,13 @@ dependencies = [ [[package]] name = "sc-chain-spec" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", "docify", "log", - "memmap2 0.9.4", + "memmap2 0.9.3", "parity-scale-codec", "sc-chain-spec-derive", "sc-client-api", @@ -12915,24 +12828,24 @@ dependencies = [ "sp-io", "sp-runtime", "sp-state-machine", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", ] [[package]] name = "sc-chain-spec-derive" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "12.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "sc-cli" -version = "0.36.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.46.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", "chrono", @@ -12945,7 +12858,7 @@ dependencies = [ "names", "parity-bip39", "parity-scale-codec", - "rand 0.8.5", + "rand", "regex", "rpassword", "sc-client-api", @@ -12972,8 +12885,8 @@ dependencies = [ [[package]] name = "sc-client-api" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "fnv", "futures 0.3.31", @@ -12988,19 +12901,19 @@ dependencies = [ "sp-consensus", "sp-core", "sp-database", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-runtime", "sp-state-machine", "sp-statement-store", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-trie", "substrate-prometheus-endpoint", ] [[package]] name = "sc-client-db" -version = "0.35.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "hash-db 0.16.0", "kvdb", @@ -13025,12 +12938,11 @@ dependencies = [ [[package]] name = "sc-consensus" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "futures 0.3.31", - "futures-timer", "log", "mockall 0.11.4", "parking_lot 0.12.3", @@ -13050,8 +12962,8 @@ dependencies = [ [[package]] name = "sc-consensus-aura" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "futures 0.3.31", @@ -13079,8 +12991,8 @@ dependencies = [ [[package]] name = "sc-consensus-babe" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "fork-tree", @@ -13115,8 +13027,8 @@ dependencies = [ [[package]] name = "sc-consensus-babe-rpc" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "jsonrpsee", @@ -13137,11 +13049,11 @@ dependencies = [ [[package]] name = "sc-consensus-beefy" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "23.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", - "async-channel 1.9.0", + "async-channel", "async-trait", "fnv", "futures 0.3.31", @@ -13173,8 +13085,8 @@ dependencies = [ [[package]] name = "sc-consensus-beefy-rpc" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "23.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "futures 0.3.31", "jsonrpsee", @@ -13193,8 +13105,8 @@ dependencies = [ [[package]] name = "sc-consensus-epochs" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "fork-tree", "parity-scale-codec", @@ -13206,8 +13118,8 @@ dependencies = [ [[package]] name = "sc-consensus-grandpa" -version = "0.19.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.29.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "ahash", "array-bytes", @@ -13220,7 +13132,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -13250,8 +13162,8 @@ dependencies = [ [[package]] name = "sc-consensus-grandpa-rpc" -version = "0.19.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.29.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "finality-grandpa", "futures 0.3.31", @@ -13270,8 +13182,8 @@ dependencies = [ [[package]] name = "sc-consensus-manual-seal" -version = "0.35.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.45.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "assert_matches", "async-trait", @@ -13305,8 +13217,8 @@ dependencies = [ [[package]] name = "sc-consensus-slots" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "futures 0.3.31", @@ -13328,8 +13240,8 @@ dependencies = [ [[package]] name = "sc-executor" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.40.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", @@ -13339,62 +13251,62 @@ dependencies = [ "schnellru", "sp-api", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-io", "sp-panic-handler", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", "sp-trie", "sp-version", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-wasm-interface", "tracing", ] [[package]] name = "sc-executor-common" -version = "0.29.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.35.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "polkavm", "sc-allocator", "sp-maybe-compressed-blob", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-wasm-interface", "thiserror", "wasm-instrument", ] [[package]] name = "sc-executor-polkavm" -version = "0.29.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.32.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "log", "polkavm", "sc-executor-common", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-wasm-interface", ] [[package]] name = "sc-executor-wasmtime" -version = "0.29.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.35.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "anyhow", "cfg-if", "libc", "log", "parking_lot 0.12.3", - "rustix 0.36.17", + "rustix 0.36.15", "sc-allocator", "sc-executor-common", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", + "sp-wasm-interface", "wasmtime", ] [[package]] name = "sc-informant" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "ansi_term", "futures 0.3.31", @@ -13410,8 +13322,8 @@ dependencies = [ [[package]] name = "sc-keystore" -version = "25.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "33.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", "parking_lot 0.12.3", @@ -13424,8 +13336,8 @@ dependencies = [ [[package]] name = "sc-mixnet" -version = "0.4.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.14.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", "arrayvec 0.7.4", @@ -13435,7 +13347,7 @@ dependencies = [ "futures-timer", "log", "mixnet", - "multiaddr", + "multiaddr 0.18.1", "parity-scale-codec", "parking_lot 0.12.3", "sc-client-api", @@ -13453,11 +13365,11 @@ dependencies = [ [[package]] name = "sc-network" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", - "async-channel 1.9.0", + "async-channel", "async-trait", "asynchronous-codec", "bytes", @@ -13478,8 +13390,8 @@ dependencies = [ "partial_sort", "pin-project", "prost 0.12.6", - "prost-build 0.12.6", - "rand 0.8.5", + "prost-build 0.12.4", + "rand", "sc-client-api", "sc-network-common", "sc-network-types", @@ -13496,7 +13408,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", - "unsigned-varint", + "unsigned-varint 0.7.2", "void", "wasm-timer", "zeroize", @@ -13504,15 +13416,15 @@ dependencies = [ [[package]] name = "sc-network-common" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "bitflags 1.3.2", "futures 0.3.31", "libp2p-identity", "parity-scale-codec", - "prost-build 0.12.6", + "prost-build 0.12.4", "sc-consensus", "sc-network-types", "sp-consensus", @@ -13522,13 +13434,12 @@ dependencies = [ [[package]] name = "sc-network-gossip" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "ahash", "futures 0.3.31", "futures-timer", - "libp2p", "log", "sc-network", "sc-network-common", @@ -13542,16 +13453,16 @@ dependencies = [ [[package]] name = "sc-network-light" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", - "async-channel 1.9.0", + "async-channel", "futures 0.3.31", "log", "parity-scale-codec", "prost 0.12.6", - "prost-build 0.12.6", + "prost-build 0.12.4", "sc-client-api", "sc-network", "sc-network-types", @@ -13563,11 +13474,11 @@ dependencies = [ [[package]] name = "sc-network-sync" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", - "async-channel 1.9.0", + "async-channel", "async-trait", "fork-tree", "futures 0.3.31", @@ -13577,7 +13488,7 @@ dependencies = [ "mockall 0.11.4", "parity-scale-codec", "prost 0.12.6", - "prost-build 0.12.6", + "prost-build 0.12.4", "sc-client-api", "sc-consensus", "sc-network", @@ -13600,12 +13511,11 @@ dependencies = [ [[package]] name = "sc-network-transactions" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", "futures 0.3.31", - "libp2p", "log", "parity-scale-codec", "sc-network", @@ -13620,39 +13530,39 @@ dependencies = [ [[package]] name = "sc-network-types" -version = "0.10.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.12.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ - "bs58 0.5.1", - "ed25519-dalek 2.1.1", + "bs58 0.5.0", + "ed25519-dalek", "libp2p-identity", "litep2p", - "multiaddr", - "multihash 0.17.0", - "rand 0.8.5", + "log", + "multiaddr 0.18.1", + "multihash 0.19.1", + "rand", "thiserror", "zeroize", ] [[package]] name = "sc-offchain" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", "bytes", "fnv", "futures 0.3.31", "futures-timer", - "hyper", - "hyper-rustls", - "libp2p", + "hyper 0.14.29", + "hyper-rustls 0.24.2", "log", "num_cpus", "once_cell", "parity-scale-codec", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "sc-client-api", "sc-network", "sc-network-common", @@ -13661,7 +13571,7 @@ dependencies = [ "sc-utils", "sp-api", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-keystore", "sp-offchain", "sp-runtime", @@ -13671,8 +13581,8 @@ dependencies = [ [[package]] name = "sc-proposer-metrics" -version = "0.17.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.18.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "log", "substrate-prometheus-endpoint", @@ -13680,8 +13590,8 @@ dependencies = [ [[package]] name = "sc-rpc" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "futures 0.3.31", "jsonrpsee", @@ -13712,8 +13622,8 @@ dependencies = [ [[package]] name = "sc-rpc-api" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "jsonrpsee", "parity-scale-codec", @@ -13732,17 +13642,19 @@ dependencies = [ [[package]] name = "sc-rpc-server" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "forwarded-header-value", "futures 0.3.31", "governor", - "http", - "hyper", + "http 1.1.0", + "http-body-util", + "hyper 1.3.1", "ip_network", "jsonrpsee", "log", + "serde", "serde_json", "substrate-prometheus-endpoint", "tokio", @@ -13752,8 +13664,8 @@ dependencies = [ [[package]] name = "sc-rpc-spec-v2" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", "futures 0.3.31", @@ -13763,7 +13675,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "sc-chain-spec", "sc-client-api", "sc-rpc", @@ -13784,8 +13696,8 @@ dependencies = [ [[package]] name = "sc-service" -version = "0.35.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.45.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "directories", @@ -13797,7 +13709,7 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", "pin-project", - "rand 0.8.5", + "rand", "sc-chain-spec", "sc-client-api", "sc-client-db", @@ -13827,12 +13739,12 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-keystore", "sp-runtime", "sp-session", "sp-state-machine", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-transaction-pool", "sp-transaction-storage-proof", "sp-trie", @@ -13848,8 +13760,8 @@ dependencies = [ [[package]] name = "sc-state-db" -version = "0.30.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.36.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "log", "parity-scale-codec", @@ -13859,8 +13771,8 @@ dependencies = [ [[package]] name = "sc-storage-monitor" -version = "0.16.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.22.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "clap", "fs4", @@ -13872,8 +13784,8 @@ dependencies = [ [[package]] name = "sc-sync-state-rpc" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "jsonrpsee", "parity-scale-codec", @@ -13891,14 +13803,14 @@ dependencies = [ [[package]] name = "sc-sysinfo" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "derive_more", "futures 0.3.31", "libc", "log", - "rand 0.8.5", + "rand", "rand_pcg", "regex", "sc-telemetry", @@ -13907,13 +13819,13 @@ dependencies = [ "sp-core", "sp-crypto-hashing", "sp-io", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] name = "sc-telemetry" -version = "15.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "24.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "chrono", "futures 0.3.31", @@ -13921,7 +13833,7 @@ dependencies = [ "log", "parking_lot 0.12.3", "pin-project", - "rand 0.8.5", + "rand", "sc-network", "sc-utils", "serde", @@ -13932,8 +13844,8 @@ dependencies = [ [[package]] name = "sc-tracing" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "ansi_term", "chrono", @@ -13953,7 +13865,7 @@ dependencies = [ "sp-core", "sp-rpc", "sp-runtime", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", "thiserror", "tracing", "tracing-log", @@ -13963,18 +13875,18 @@ dependencies = [ [[package]] name = "sc-tracing-proc-macro" version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "sc-transaction-pool" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "futures 0.3.31", @@ -13992,7 +13904,7 @@ dependencies = [ "sp-core", "sp-crypto-hashing", "sp-runtime", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", "sp-transaction-pool", "substrate-prometheus-endpoint", "thiserror", @@ -14000,8 +13912,8 @@ dependencies = [ [[package]] name = "sc-transaction-pool-api" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "futures 0.3.31", @@ -14016,10 +13928,10 @@ dependencies = [ [[package]] name = "sc-utils" -version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ - "async-channel 1.9.0", + "async-channel", "futures 0.3.31", "futures-timer", "lazy_static", @@ -14086,11 +13998,11 @@ checksum = "f0cded6518aa0bd6c1be2b88ac81bf7044992f0f154bfbabd5ad34f43512abcb" [[package]] name = "schannel" -version = "0.1.23" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.48.0", ] [[package]] @@ -14114,7 +14026,7 @@ dependencies = [ "arrayvec 0.7.4", "curve25519-dalek-ng", "merlin", - "rand_core 0.6.4", + "rand_core", "sha2 0.9.9", "subtle-ng", "zeroize", @@ -14129,13 +14041,13 @@ dependencies = [ "aead", "arrayref", "arrayvec 0.7.4", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "getrandom_or_panic", "merlin", - "rand_core 0.6.4", + "rand_core", "serde_bytes", "sha2 0.10.8", - "subtle 2.6.1", + "subtle 2.5.0", "zeroize", ] @@ -14153,12 +14065,12 @@ checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152" [[package]] name = "sct" -version = "0.7.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" dependencies = [ - "ring 0.17.8", - "untrusted 0.9.0", + "ring 0.16.20", + "untrusted 0.7.1", ] [[package]] @@ -14171,7 +14083,7 @@ dependencies = [ "crc", "fxhash", "log", - "rand 0.8.5", + "rand", "slab", "thiserror", ] @@ -14187,7 +14099,7 @@ dependencies = [ "generic-array 0.14.7", "pkcs8", "serdect", - "subtle 2.6.1", + "subtle 2.5.0", "zeroize", ] @@ -14229,22 +14141,23 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.11.1" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" dependencies = [ "bitflags 2.6.0", "core-foundation", "core-foundation-sys", "libc", + "num-bigint", "security-framework-sys", ] [[package]] name = "security-framework-sys" -version = "2.11.1" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf" +checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7" dependencies = [ "core-foundation-sys", "libc", @@ -14261,9 +14174,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.23" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" dependencies = [ "serde", ] @@ -14274,51 +14187,64 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +[[package]] +name = "send_wrapper" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f638d531eccd6e23b980caf34876660d38e265409d8e99b397ab71eb3612fad0" + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + [[package]] name = "serde" -version = "1.0.210" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] [[package]] name = "serde_bytes" -version = "0.11.15" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "387cc504cb06bb40a96c8e04e951fe01854cf6bc921053c954e4a606d9675c6a" +checksum = "ab33ec92f677585af6d88c65593ae2375adde54efdbf16d597f2cbc7a6d368ff" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.210" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "serde_json" -version = "1.0.120" +version = "1.0.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" +checksum = "4ab380d7d9f22ef3f21ad3e6c1ebe8e4fc7a2000ccba2e4d71fc96f15b2cb609" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] [[package]] name = "serde_spanned" -version = "0.6.6" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" +checksum = "12022b835073e5b11e90a14f86838ceb1c8fb0325b72416845c487ac0fa95e80" dependencies = [ "serde", ] @@ -14343,7 +14269,7 @@ dependencies = [ "cfg-if", "cpufeatures", "digest 0.9.0", - "opaque-debug 0.3.1", + "opaque-debug 0.3.0", ] [[package]] @@ -14371,9 +14297,9 @@ dependencies = [ [[package]] name = "sha1-asm" -version = "0.5.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "286acebaf8b67c1130aedffad26f594eff0c1292389158135327d2e23aed582b" +checksum = "2ba6947745e7f86be3b8af00b7355857085dbdf8901393c89514510eb61f4e21" dependencies = [ "cc", ] @@ -14388,7 +14314,7 @@ dependencies = [ "cfg-if", "cpufeatures", "digest 0.9.0", - "opaque-debug 0.3.1", + "opaque-debug 0.3.0", ] [[package]] @@ -14414,9 +14340,9 @@ dependencies = [ [[package]] name = "sharded-slab" -version = "0.1.7" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" dependencies = [ "lazy_static", ] @@ -14428,28 +14354,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] -name = "signal-hook-registry" -version = "1.4.2" +name = "signal-hook" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", + "signal-hook-registry", ] [[package]] -name = "signature" -version = "1.6.4" +name = "signal-hook-registry" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] [[package]] name = "signature" -version = "2.2.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" dependencies = [ "digest 0.10.7", - "rand_core 0.6.4", + "rand_core", ] [[package]] @@ -14467,9 +14397,9 @@ dependencies = [ [[package]] name = "similar" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640" +checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" dependencies = [ "bstr", "unicode-segmentation", @@ -14521,23 +14451,34 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "826167069c09b99d56f31e9ae5c99049e932a98c9dc2dac47645b08dbbf76ba7" +[[package]] +name = "slices" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2086e458a369cdca838e9f6ed04b4cc2e3ce636d99abb80c9e2eada107749cf" +dependencies = [ + "faster-hex", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "slot-range-helper" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "enumn", "parity-scale-codec", "paste", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "slotmap" -version = "1.0.7" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbff4acf519f630b3a3ddcfaea6c06b42174d9a44bc70c620e9ed1649d58b82a" +checksum = "e1e08e261d0e8f5c43123b7adf3e4ca1690d655377ac93a03b2c9d3e98de1342" dependencies = [ "version_check", ] @@ -14554,7 +14495,7 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13f2b548cd8447f8de0fdf1c592929f70f4fc7039a05e47404b0d096ec6987a1" dependencies = [ - "async-channel 1.9.0", + "async-channel", "async-executor", "async-fs", "async-io 1.13.0", @@ -14574,10 +14515,10 @@ dependencies = [ "arrayvec 0.7.4", "async-lock 2.8.0", "atomic-take", - "base64 0.21.7", + "base64 0.21.2", "bip39", "blake2-rfc", - "bs58 0.5.1", + "bs58 0.5.0", "chacha20", "crossbeam-queue", "derive_more", @@ -14587,7 +14528,7 @@ dependencies = [ "fnv", "futures-lite 1.13.0", "futures-util", - "hashbrown 0.14.5", + "hashbrown 0.14.3", "hex", "hmac 0.12.1", "itertools 0.11.0", @@ -14601,8 +14542,8 @@ dependencies = [ "pbkdf2", "pin-project", "poly1305", - "rand 0.8.5", - "rand_chacha 0.3.1", + "rand", + "rand_chacha", "ruzstd", "schnorrkel 0.10.2", "serde", @@ -14612,10 +14553,10 @@ dependencies = [ "siphasher", "slab", "smallvec", - "soketto", + "soketto 0.7.1", "twox-hash", "wasmi", - "x25519-dalek 2.0.1", + "x25519-dalek", "zeroize", ] @@ -14625,9 +14566,9 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "256b5bad1d6b49045e95fe87492ce73d5af81545d8b4d8318a872d2007024c33" dependencies = [ - "async-channel 1.9.0", + "async-channel", "async-lock 2.8.0", - "base64 0.21.7", + "base64 0.21.2", "blake2-rfc", "derive_more", "either", @@ -14636,16 +14577,16 @@ dependencies = [ "futures-channel", "futures-lite 1.13.0", "futures-util", - "hashbrown 0.14.5", + "hashbrown 0.14.3", "hex", "itertools 0.11.0", "log", - "lru 0.11.1", + "lru 0.11.0", "no-std-net", "parking_lot 0.12.3", "pin-project", - "rand 0.8.5", - "rand_chacha 0.3.1", + "rand", + "rand_chacha", "serde", "serde_json", "siphasher", @@ -14657,9 +14598,9 @@ dependencies = [ [[package]] name = "snap" -version = "1.1.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" +checksum = "5e9f0ab6ef7eb7353d9119c170a436d1bf248eea575ac42d19d12f4e34130831" [[package]] name = "snow" @@ -14670,19 +14611,19 @@ dependencies = [ "aes-gcm", "blake2 0.10.6", "chacha20poly1305", - "curve25519-dalek 4.1.3", - "rand_core 0.6.4", - "ring 0.17.8", + "curve25519-dalek", + "rand_core", + "ring 0.17.7", "rustc_version", "sha2 0.10.8", - "subtle 2.6.1", + "subtle 2.5.0", ] [[package]] name = "socket2" -version = "0.4.10" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" +checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" dependencies = [ "libc", "winapi", @@ -14706,32 +14647,46 @@ checksum = "41d1c5305e39e09653383c2c7244f2f78b3bcae37cf50c64cb4789c9f5096ec2" dependencies = [ "base64 0.13.1", "bytes", - "flate2", "futures 0.3.31", - "http", "httparse", "log", - "rand 0.8.5", + "rand", "sha-1 0.9.8", ] +[[package]] +name = "soketto" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37468c595637c10857701c990f93a40ce0e357cedb0953d1c26c8d8027f9bb53" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures 0.3.31", + "http 1.1.0", + "httparse", + "log", + "rand", + "sha1", +] + [[package]] name = "sp-api" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ + "docify", "hash-db 0.16.0", "log", "parity-scale-codec", "scale-info", "sp-api-proc-macro", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-metadata-ir", "sp-runtime", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-trie", "sp-version", "thiserror", @@ -14739,8 +14694,8 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" -version = "15.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "20.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "Inflector", "blake2 0.10.6", @@ -14748,26 +14703,25 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "sp-application-crypto" -version = "30.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "scale-info", "serde", "sp-core", "sp-io", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "sp-arithmetic" -version = "23.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "26.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "docify", "integer-sqrt", @@ -14775,32 +14729,13 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "static_assertions", ] -[[package]] -name = "sp-ark-bls12-381" -version = "0.4.2" -source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" -dependencies = [ - "ark-bls12-381-ext", - "sp-crypto-ec-utils", -] - -[[package]] -name = "sp-ark-ed-on-bls12-381-bandersnatch" -version = "0.4.2" -source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" -dependencies = [ - "ark-ed-on-bls12-381-bandersnatch-ext", - "sp-crypto-ec-utils", -] - [[package]] name = "sp-authority-discovery" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "scale-info", @@ -14811,8 +14746,8 @@ dependencies = [ [[package]] name = "sp-block-builder" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "sp-api", "sp-inherents", @@ -14821,26 +14756,27 @@ dependencies = [ [[package]] name = "sp-blockchain" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "futures 0.3.31", - "log", "parity-scale-codec", "parking_lot 0.12.3", "schnellru", "sp-api", "sp-consensus", + "sp-core", "sp-database", "sp-runtime", "sp-state-machine", "thiserror", + "tracing", ] [[package]] name = "sp-consensus" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.40.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "futures 0.3.31", @@ -14854,8 +14790,8 @@ dependencies = [ [[package]] name = "sp-consensus-aura" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.40.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "parity-scale-codec", @@ -14870,8 +14806,8 @@ dependencies = [ [[package]] name = "sp-consensus-babe" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.40.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "async-trait", "parity-scale-codec", @@ -14888,8 +14824,8 @@ dependencies = [ [[package]] name = "sp-consensus-beefy" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "lazy_static", "parity-scale-codec", @@ -14908,8 +14844,8 @@ dependencies = [ [[package]] name = "sp-consensus-grandpa" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "21.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "finality-grandpa", "log", @@ -14925,8 +14861,8 @@ dependencies = [ [[package]] name = "sp-consensus-slots" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.40.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "scale-info", @@ -14936,21 +14872,20 @@ dependencies = [ [[package]] name = "sp-core" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", - "bandersnatch_vrfs", "bitflags 1.3.2", "blake2 0.10.6", "bounded-collections", - "bs58 0.5.1", + "bs58 0.5.0", "dyn-clonable", "ed25519-zebra", "futures 0.3.31", "hash-db 0.16.0", "hash256-std-hasher", - "impl-serde 0.4.0", + "impl-serde", "itertools 0.11.0", "k256", "libsecp256k1", @@ -14960,19 +14895,19 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", "paste", - "primitive-types 0.12.2", - "rand 0.8.5", + "primitive-types", + "rand", "scale-info", "schnorrkel 0.11.4", "secp256k1", "secrecy", "serde", "sp-crypto-hashing", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-debug-derive", + "sp-externalities", + "sp-runtime-interface", + "sp-std", + "sp-storage", "ss58-registry", "substrate-bip39", "thiserror", @@ -14981,30 +14916,10 @@ dependencies = [ "zeroize", ] -[[package]] -name = "sp-crypto-ec-utils" -version = "0.10.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" -dependencies = [ - "ark-bls12-377", - "ark-bls12-377-ext", - "ark-bls12-381", - "ark-bls12-381-ext", - "ark-bw6-761", - "ark-bw6-761-ext", - "ark-ec", - "ark-ed-on-bls12-377", - "ark-ed-on-bls12-377-ext", - "ark-ed-on-bls12-381-bandersnatch", - "ark-ed-on-bls12-381-bandersnatch-ext", - "ark-scale", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk)", -] - [[package]] name = "sp-crypto-hashing" version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "blake2b_simd", "byteorder", @@ -15017,17 +14932,17 @@ dependencies = [ [[package]] name = "sp-crypto-hashing-proc-macro" version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "quote", "sp-crypto-hashing", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "sp-database" version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "kvdb", "parking_lot 0.12.3", @@ -15036,47 +14951,27 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", -] - -[[package]] -name = "sp-debug-derive" -version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.85", -] - -[[package]] -name = "sp-externalities" -version = "0.25.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" -dependencies = [ - "environmental", - "parity-scale-codec", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "syn 2.0.90", ] [[package]] name = "sp-externalities" -version = "0.25.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" +version = "0.29.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "environmental", "parity-scale-codec", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-storage", ] [[package]] name = "sp-genesis-builder" -version = "0.8.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "scale-info", @@ -15087,8 +14982,8 @@ dependencies = [ [[package]] name = "sp-inherents" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -15100,11 +14995,12 @@ dependencies = [ [[package]] name = "sp-io" -version = "30.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "bytes", - "ed25519-dalek 2.1.1", + "docify", + "ed25519-dalek", "libsecp256k1", "log", "parity-scale-codec", @@ -15113,12 +15009,11 @@ dependencies = [ "secp256k1", "sp-core", "sp-crypto-hashing", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-keystore", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", "sp-trie", "tracing", "tracing-core", @@ -15126,8 +15021,8 @@ dependencies = [ [[package]] name = "sp-keyring" -version = "31.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "sp-core", "sp-runtime", @@ -15136,19 +15031,19 @@ dependencies = [ [[package]] name = "sp-keystore" -version = "0.34.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.40.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", ] [[package]] name = "sp-maybe-compressed-blob" version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "thiserror", "zstd 0.12.4", @@ -15156,8 +15051,8 @@ dependencies = [ [[package]] name = "sp-metadata-ir" -version = "0.6.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.7.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "frame-metadata", "parity-scale-codec", @@ -15166,8 +15061,8 @@ dependencies = [ [[package]] name = "sp-mixnet" -version = "0.4.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.12.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "scale-info", @@ -15177,8 +15072,8 @@ dependencies = [ [[package]] name = "sp-mmr-primitives" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "log", "parity-scale-codec", @@ -15187,15 +15082,15 @@ dependencies = [ "serde", "sp-api", "sp-core", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-debug-derive", "sp-runtime", "thiserror", ] [[package]] name = "sp-npos-elections" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "parity-scale-codec", "scale-info", @@ -15207,8 +15102,8 @@ dependencies = [ [[package]] name = "sp-offchain" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "sp-api", "sp-core", @@ -15218,7 +15113,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "backtrace", "lazy_static", @@ -15227,8 +15122,8 @@ dependencies = [ [[package]] name = "sp-rpc" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "32.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "rustc-hash", "serde", @@ -15237,8 +15132,8 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "31.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "39.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "docify", "either", @@ -15248,7 +15143,7 @@ dependencies = [ "num-traits", "parity-scale-codec", "paste", - "rand 0.8.5", + "rand", "scale-info", "serde", "simple-mermaid", @@ -15256,78 +15151,47 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-io", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-weights", + "tracing", ] [[package]] name = "sp-runtime-interface" -version = "24.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" -dependencies = [ - "bytes", - "impl-trait-for-tuples", - "parity-scale-codec", - "polkavm-derive", - "primitive-types 0.12.2", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-runtime-interface-proc-macro 17.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "static_assertions", -] - -[[package]] -name = "sp-runtime-interface" -version = "24.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "bytes", "impl-trait-for-tuples", "parity-scale-codec", "polkavm-derive", - "primitive-types 0.13.1", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk)", - "sp-runtime-interface-proc-macro 17.0.0 (git+https://github.com/paritytech/polkadot-sdk)", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk)", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "primitive-types", + "sp-externalities", + "sp-runtime-interface-proc-macro", + "sp-std", + "sp-storage", + "sp-tracing", + "sp-wasm-interface", "static_assertions", ] [[package]] name = "sp-runtime-interface-proc-macro" -version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" -dependencies = [ - "Inflector", - "expander", - "proc-macro-crate 3.1.0", - "proc-macro2", - "quote", - "syn 2.0.85", -] - -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" +version = "18.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "Inflector", "expander", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "sp-session" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "35.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "scale-info", @@ -15340,8 +15204,8 @@ dependencies = [ [[package]] name = "sp-staking" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", @@ -15353,17 +15217,17 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.35.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.43.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "hash-db 0.16.0", "log", "parity-scale-codec", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "smallvec", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-panic-handler", "sp-trie", "thiserror", @@ -15373,66 +15237,49 @@ dependencies = [ [[package]] name = "sp-statement-store" -version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "18.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "aes-gcm", - "curve25519-dalek 4.1.3", - "ed25519-dalek 2.1.1", + "curve25519-dalek", + "ed25519-dalek", "hkdf", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", "sha2 0.10.8", "sp-api", "sp-application-crypto", "sp-core", "sp-crypto-hashing", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "sp-runtime", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-runtime-interface", "thiserror", - "x25519-dalek 2.0.1", + "x25519-dalek", ] [[package]] name = "sp-std" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" - -[[package]] -name = "sp-std" -version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" - -[[package]] -name = "sp-storage" -version = "19.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" -dependencies = [ - "impl-serde 0.4.0", - "parity-scale-codec", - "ref-cast", - "serde", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", -] +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" [[package]] name = "sp-storage" -version = "19.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" +version = "21.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ - "impl-serde 0.5.0", + "impl-serde", "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-debug-derive", ] [[package]] name = "sp-timestamp" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "parity-scale-codec", @@ -15443,19 +15290,8 @@ dependencies = [ [[package]] name = "sp-tracing" -version = "16.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" -dependencies = [ - "parity-scale-codec", - "tracing", - "tracing-core", - "tracing-subscriber", -] - -[[package]] -name = "sp-tracing" -version = "16.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "tracing", @@ -15465,8 +15301,8 @@ dependencies = [ [[package]] name = "sp-transaction-pool" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "sp-api", "sp-runtime", @@ -15474,8 +15310,8 @@ dependencies = [ [[package]] name = "sp-transaction-storage-proof" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "async-trait", "parity-scale-codec", @@ -15488,8 +15324,8 @@ dependencies = [ [[package]] name = "sp-trie" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "ahash", "hash-db 0.16.0", @@ -15498,11 +15334,11 @@ dependencies = [ "nohash-hasher", "parity-scale-codec", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "scale-info", "schnellru", "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-externalities", "thiserror", "tracing", "trie-db", @@ -15511,36 +15347,36 @@ dependencies = [ [[package]] name = "sp-version" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ - "impl-serde 0.4.0", + "impl-serde", "parity-scale-codec", "parity-wasm", "scale-info", "serde", "sp-crypto-hashing-proc-macro", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "sp-version-proc-macro", "thiserror", ] [[package]] name = "sp-version-proc-macro" -version = "13.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "14.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "parity-scale-codec", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "sp-wasm-interface" -version = "20.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "21.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -15549,21 +15385,10 @@ dependencies = [ "wasmtime", ] -[[package]] -name = "sp-wasm-interface" -version = "20.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#d4b01add06139b39b9ce69216f06b827f7f388a7" -dependencies = [ - "anyhow", - "impl-trait-for-tuples", - "log", - "parity-scale-codec", -] - [[package]] name = "sp-weights" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "31.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "bounded-collections", "parity-scale-codec", @@ -15571,7 +15396,7 @@ dependencies = [ "serde", "smallvec", "sp-arithmetic", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-debug-derive", ] [[package]] @@ -15589,20 +15414,11 @@ dependencies = [ "lock_api", ] -[[package]] -name = "spinning_top" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300" -dependencies = [ - "lock_api", -] - [[package]] name = "spki" -version = "0.7.3" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +checksum = "9d1e996ef02c474957d681f1b05213dfb0abab947b446a62d37770b23500184a" dependencies = [ "base64ct", "der", @@ -15610,9 +15426,9 @@ dependencies = [ [[package]] name = "sqlformat" -version = "0.2.4" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f895e3734318cc55f1fe66258926c9b910c124d47520339efecbb6c59cec7c1f" +checksum = "7bba3a93db0cc4f7bdece8bb09e77e2e785c20bfebf79eb8340ed80708048790" dependencies = [ "nom", "unicode_categories", @@ -15650,7 +15466,7 @@ dependencies = [ "futures-util", "hashlink", "hex", - "indexmap 2.2.6", + "indexmap 2.2.3", "log", "memchr", "native-tls", @@ -15730,9 +15546,9 @@ dependencies = [ [[package]] name = "ss58-registry" -version = "1.47.0" +version = "1.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4743ce898933fbff7bbf414f497c459a782d496269644b3d650a398ae6a487ba" +checksum = "5e6915280e2d0db8911e5032a5c275571af6bdded2916abd691a659be25d3439" dependencies = [ "Inflector", "num-format", @@ -15751,8 +15567,8 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "staging-node-inspect" -version = "0.12.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.22.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "clap", "parity-scale-codec", @@ -15769,8 +15585,8 @@ dependencies = [ [[package]] name = "staging-parachain-info" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.16.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-primitives-core", "frame-support", @@ -15778,13 +15594,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", ] [[package]] name = "staging-xcm" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "14.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "array-bytes", "bounded-collections", @@ -15801,8 +15616,8 @@ dependencies = [ [[package]] name = "staging-xcm-builder" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -15815,7 +15630,6 @@ dependencies = [ "sp-arithmetic", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-weights", "staging-xcm", "staging-xcm-executor", @@ -15823,23 +15637,22 @@ dependencies = [ [[package]] name = "staging-xcm-executor" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "environmental", "frame-benchmarking", "frame-support", "impl-trait-for-tuples", - "log", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-weights", "staging-xcm", + "tracing", ] [[package]] @@ -15896,24 +15709,11 @@ dependencies = [ "tracing", ] -[[package]] -name = "strobe-rs" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabb238a1cccccfa4c4fb703670c0d157e1256c1ba695abf1b93bd2bb14bab2d" -dependencies = [ - "bitflags 1.3.2", - "byteorder", - "keccak", - "subtle 2.6.1", - "zeroize", -] - [[package]] name = "strsim" -version = "0.11.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01" [[package]] name = "strum" @@ -15921,6 +15721,12 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" + [[package]] name = "strum" version = "0.26.3" @@ -15943,6 +15749,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.90", +] + [[package]] name = "strum_macros" version = "0.26.4" @@ -15953,13 +15772,13 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] name = "substrate-bip39" -version = "0.4.7" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.6.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ "hmac 0.12.1", "pbkdf2", @@ -15977,14 +15796,14 @@ dependencies = [ "byteorder", "crunchy", "lazy_static", - "rand 0.8.5", + "rand", "rustc-hex", ] [[package]] name = "substrate-build-script-utils" version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" [[package]] name = "substrate-fixed" @@ -15999,9 +15818,10 @@ dependencies = [ [[package]] name = "substrate-frame-rpc-system" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ + "docify", "frame-system-rpc-runtime-api", "futures 0.3.31", "jsonrpsee", @@ -16019,9 +15839,11 @@ dependencies = [ [[package]] name = "substrate-prometheus-endpoint" version = "0.17.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" dependencies = [ - "hyper", + "http-body-util", + "hyper 1.3.1", + "hyper-util", "log", "prometheus", "thiserror", @@ -16030,8 +15852,8 @@ dependencies = [ [[package]] name = "substrate-state-trie-migration-rpc" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "37.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "jsonrpsee", "parity-scale-codec", @@ -16057,8 +15879,8 @@ dependencies = [ [[package]] name = "substrate-wasm-builder" -version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "24.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "array-bytes", "build-helper", @@ -16074,11 +15896,11 @@ dependencies = [ "sp-core", "sp-io", "sp-maybe-compressed-blob", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-tracing", "sp-version", "strum 0.26.3", "tempfile", - "toml 0.8.14", + "toml 0.8.8", "walkdir", "wasm-opt", ] @@ -16091,9 +15913,9 @@ checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" [[package]] name = "subtle" -version = "2.6.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" [[package]] name = "subtle-ng" @@ -16114,9 +15936,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.85" +version = "2.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5023162dfcd14ef8f32034d8bcd4cc5ddc61ef7a247c024a33e24e1f24d21b56" +checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" dependencies = [ "proc-macro2", "quote", @@ -16143,7 +15965,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -16175,39 +15997,40 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "target-lexicon" -version = "0.12.15" +version = "0.12.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4873307b7c257eddcb50c9bedf158eb669578359fb28428bef438fec8e6ba7c2" +checksum = "9d0e916b1148c8e263850e1ebcbd046f333e0683c724876bb0da63ea4373dc8a" [[package]] name = "tempfile" -version = "3.10.1" +version = "3.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" +checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" dependencies = [ "cfg-if", "fastrand 2.1.0", - "rustix 0.38.34", - "windows-sys 0.52.0", + "redox_syscall 0.4.1", + "rustix 0.38.21", + "windows-sys 0.48.0", ] [[package]] name = "termcolor" -version = "1.4.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" dependencies = [ "winapi-util", ] [[package]] name = "terminal_size" -version = "0.3.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21bebf2b7c9e0a515f6e0f8c51dc0f8e4696391e6f1ff30379559f8365fb0df7" +checksum = "5352447f921fda68cf61b4101566c0bdb5104eff6804d0678e5227580ab6a4e9" dependencies = [ - "rustix 0.38.34", - "windows-sys 0.48.0", + "rustix 0.38.21", + "windows-sys 0.59.0", ] [[package]] @@ -16218,42 +16041,42 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.62" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2675633b1499176c2dff06b0856a27976a8f9d436737b4cf4f312d4d91d8bbb" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-core" -version = "1.0.50" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c001ee18b7e5e3f62cbf58c7fe220119e68d902bb7443179c0c8aef30090e999" +checksum = "0d97345f6437bb2004cd58819d8a9ef8e36cdd7661c2abc4bbde0a7c40d9f497" dependencies = [ "thiserror-core-impl", ] [[package]] name = "thiserror-core-impl" -version = "1.0.50" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4c60d69f36615a077cc7663b9cb8e42275722d23e58a7fa3d2c7f2915d09d04" +checksum = "10ac1c5050e43014d16b2f94d0d2ce79e65ffdd8b38d8048f9c8f6a8a6da62ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 1.0.109", ] [[package]] name = "thiserror-impl" -version = "1.0.62" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d20468752b09f49e909e55a5d338caa8bedf615594e9d80bc4c565d30faf798c" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -16264,9 +16087,9 @@ checksum = "3bf63baf9f5039dadc247375c29eb13706706cfde997d0330d05aa63a77d8820" [[package]] name = "thread_local" -version = "1.1.8" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" dependencies = [ "cfg-if", "once_cell", @@ -16357,9 +16180,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.8.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" dependencies = [ "tinyvec_macros", ] @@ -16372,32 +16195,31 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.38.1" +version = "1.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2caba9f80616f438e09748d5acda951967e1ea58508ef53d9c6402485a46df" +checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" dependencies = [ "backtrace", "bytes", "libc", "mio", - "num_cpus", "parking_lot 0.12.3", - "pin-project-lite 0.2.14", + "pin-project-lite", "signal-hook-registry", "socket2 0.5.7", "tokio-macros", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "tokio-macros" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -16406,29 +16228,29 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.12", + "rustls 0.21.7", "tokio", ] [[package]] name = "tokio-rustls" -version = "0.25.0" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.22.4", + "rustls 0.23.10", "rustls-pki-types", "tokio", ] [[package]] name = "tokio-stream" -version = "0.1.15" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af" +checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" dependencies = [ "futures-core", - "pin-project-lite 0.2.14", + "pin-project-lite", "tokio", "tokio-util", ] @@ -16441,7 +16263,7 @@ checksum = "212d5dcb2a1ce06d81107c3d0ffa3121fe974b73f068c8282cb1c32328113b6c" dependencies = [ "futures-util", "log", - "rustls 0.21.12", + "rustls 0.21.7", "rustls-native-certs 0.6.3", "tokio", "tokio-rustls 0.24.1", @@ -16458,7 +16280,7 @@ dependencies = [ "futures-core", "futures-io", "futures-sink", - "pin-project-lite 0.2.14", + "pin-project-lite", "tokio", ] @@ -16473,58 +16295,47 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.14" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335" +checksum = "a1a195ec8c9da26928f773888e0742ca3ca1040c6cd859c919c9f59c1954ab35" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.15", + "toml_edit 0.21.0", ] [[package]] name = "toml_datetime" -version = "0.6.6" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" +checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.20.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" -dependencies = [ - "indexmap 2.2.6", - "toml_datetime", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.21.1" +version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.2.6", + "indexmap 2.2.3", "toml_datetime", - "winnow 0.5.40", + "winnow", ] [[package]] name = "toml_edit" -version = "0.22.15" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1" +checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" dependencies = [ - "indexmap 2.2.6", + "indexmap 2.2.3", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.13", + "winnow", ] [[package]] @@ -16536,7 +16347,8 @@ dependencies = [ "futures-core", "futures-util", "pin-project", - "pin-project-lite 0.2.14", + "pin-project-lite", + "tokio", "tower-layer", "tower-service", "tracing", @@ -16544,18 +16356,16 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" +checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "bitflags 2.6.0", "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-range-header", - "pin-project-lite 0.2.14", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", + "pin-project-lite", "tower-layer", "tower-service", ] @@ -16579,7 +16389,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "log", - "pin-project-lite 0.2.14", + "pin-project-lite", "tracing-attributes", "tracing-core", ] @@ -16592,7 +16402,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -16617,8 +16427,8 @@ dependencies = [ [[package]] name = "tracing-gum" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "15.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "coarsetime", "polkadot-primitives", @@ -16629,13 +16439,13 @@ dependencies = [ [[package]] name = "tracing-gum-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "expander", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -16663,7 +16473,6 @@ dependencies = [ "sharded-slab", "smallvec", "thread_local", - "time", "tracing", "tracing-core", "tracing-log", @@ -16671,9 +16480,9 @@ dependencies = [ [[package]] name = "trie-db" -version = "0.29.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c992b4f40c234a074d48a757efeabb1a6be88af84c0c23f7ca158950cb0ae7f" +checksum = "65ed83be775d85ebb0e272914fff6462c39b3ddd6dc67b5c1c41271aad280c69" dependencies = [ "hash-db 0.16.0", "log", @@ -16716,9 +16525,9 @@ dependencies = [ "idna 0.2.3", "ipnet", "lazy_static", - "rand 0.8.5", + "rand", "smallvec", - "socket2 0.4.10", + "socket2 0.4.9", "thiserror", "tinyvec", "tokio", @@ -16742,7 +16551,7 @@ dependencies = [ "idna 0.4.0", "ipnet", "once_cell", - "rand 0.8.5", + "rand", "smallvec", "thiserror", "tinyvec", @@ -16751,26 +16560,6 @@ dependencies = [ "url", ] -[[package]] -name = "trust-dns-resolver" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aff21aa4dcefb0a1afbfac26deb0adc93888c7d295fb63ab273ef276ba2b7cfe" -dependencies = [ - "cfg-if", - "futures-util", - "ipconfig", - "lazy_static", - "lru-cache", - "parking_lot 0.12.3", - "resolv-conf", - "smallvec", - "thiserror", - "tokio", - "tracing", - "trust-dns-proto 0.22.0", -] - [[package]] name = "trust-dns-resolver" version = "0.23.2" @@ -16783,7 +16572,7 @@ dependencies = [ "lru-cache", "once_cell", "parking_lot 0.12.3", - "rand 0.8.5", + "rand", "resolv-conf", "smallvec", "thiserror", @@ -16794,9 +16583,9 @@ dependencies = [ [[package]] name = "try-lock" -version = "0.2.5" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" [[package]] name = "tt-call" @@ -16813,11 +16602,11 @@ dependencies = [ "byteorder", "bytes", "data-encoding", - "http", + "http 0.2.9", "httparse", "log", - "rand 0.8.5", - "rustls 0.21.12", + "rand", + "rustls 0.21.7", "sha1", "thiserror", "url", @@ -16832,15 +16621,15 @@ checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", "digest 0.10.7", - "rand 0.7.3", + "rand", "static_assertions", ] [[package]] name = "typenum" -version = "1.17.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "ucd-trie" @@ -16860,29 +16649,17 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "uint" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "909988d098b2f738727b161a106cfc7cab00c539c2687a8836f8e565976fb53e" -dependencies = [ - "byteorder", - "crunchy", - "hex", - "static_assertions", -] - [[package]] name = "unicode-bidi" -version = "0.3.15" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" +checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.12" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" [[package]] name = "unicode-normalization" @@ -16901,9 +16678,9 @@ checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "unicode-width" -version = "0.1.13" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" [[package]] name = "unicode-xid" @@ -16924,7 +16701,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ "crypto-common", - "subtle 2.6.1", + "subtle 2.5.0", ] [[package]] @@ -16937,6 +16714,15 @@ dependencies = [ "bytes", "futures-io", "futures-util", +] + +[[package]] +name = "unsigned-varint" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb066959b24b5196ae73cb057f45598450d2c5f71460e98c49b738086eff9c06" +dependencies = [ + "bytes", "tokio-util", ] @@ -16977,9 +16763,9 @@ checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" [[package]] name = "utf8parse" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "valuable" @@ -17007,9 +16793,9 @@ checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" [[package]] name = "w3f-bls" -version = "0.1.4" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c5da5fa2c6afa2c9158eaa7cd9aee249765eb32b5fb0c63ad8b9e79336a47ec" +checksum = "7335e4c132c28cc43caef6adb339789e599e39adbe78da0c4d547fad48cbc331" dependencies = [ "ark-bls12-377", "ark-bls12-381", @@ -17020,9 +16806,9 @@ dependencies = [ "arrayref", "constcat", "digest 0.10.7", - "rand 0.8.5", - "rand_chacha 0.3.1", - "rand_core 0.6.4", + "rand", + "rand_chacha", + "rand_core", "sha2 0.10.8", "sha3", "thiserror", @@ -17031,15 +16817,15 @@ dependencies = [ [[package]] name = "waker-fn" -version = "1.2.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" +checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" [[package]] name = "walkdir" -version = "2.5.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" dependencies = [ "same-file", "winapi-util", @@ -17054,32 +16840,17 @@ dependencies = [ "try-lock", ] -[[package]] -name = "wasi" -version = "0.9.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" - [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -[[package]] -name = "wasix" -version = "0.12.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1fbb4ef9bbca0c1170e0b00dd28abc9e3b68669821600cad1caaed606583c6d" -dependencies = [ - "wasi 0.11.0+wasi-snapshot-preview1", -] - [[package]] name = "wasm-bindgen" -version = "0.2.92" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -17087,24 +16858,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.92" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.42" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" dependencies = [ "cfg-if", "js-sys", @@ -17114,9 +16885,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.92" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -17124,22 +16895,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.92" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.92" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" [[package]] name = "wasm-instrument" @@ -17152,9 +16923,9 @@ dependencies = [ [[package]] name = "wasm-opt" -version = "0.116.1" +version = "0.116.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fd87a4c135535ffed86123b6fb0f0a5a0bc89e50416c942c5f0662c645f679c" +checksum = "fc942673e7684671f0c5708fc18993569d184265fd5223bb51fc8e5b9b6cfd52" dependencies = [ "anyhow", "libc", @@ -17299,12 +17070,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c86437fa68626fe896e5afc69234bb2b5894949083586535f200385adfd71213" dependencies = [ "anyhow", - "base64 0.21.7", + "base64 0.21.2", "bincode", "directories-next", "file-per-thread-logger", "log", - "rustix 0.36.17", + "rustix 0.36.15", "serde", "sha2 0.10.8", "toml 0.5.11", @@ -17400,7 +17171,7 @@ checksum = "6e0554b84c15a27d76281d06838aed94e13a77d7bf604bbbaf548aa20eb93846" dependencies = [ "object 0.30.4", "once_cell", - "rustix 0.36.17", + "rustix 0.36.15", ] [[package]] @@ -17428,10 +17199,10 @@ dependencies = [ "log", "mach", "memfd", - "memoffset", + "memoffset 0.8.0", "paste", - "rand 0.8.5", - "rustix 0.36.17", + "rand", + "rustix 0.36.15", "wasmtime-asm-macros", "wasmtime-environ", "wasmtime-jit-debug", @@ -17452,9 +17223,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.69" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" dependencies = [ "js-sys", "wasm-bindgen", @@ -17466,23 +17237,29 @@ version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53" dependencies = [ - "ring 0.17.8", + "ring 0.17.7", "untrusted 0.9.0", ] [[package]] name = "webpki-roots" -version = "0.22.6" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14247bb57be4f377dfb94c72830b8ce8fc6beac03cf4bf7b9732eadd414123fc" + +[[package]] +name = "webpki-roots" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87" +checksum = "bd7c23921eeb1713a4e851530e9b9756e4fb0e89978582942612524cf09f01cd" dependencies = [ - "webpki", + "rustls-pki-types", ] [[package]] name = "westend-runtime" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "17.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "binary-merkle-tree", "bitvec", @@ -17553,7 +17330,6 @@ dependencies = [ "polkadot-primitives", "polkadot-runtime-common", "polkadot-runtime-parachains", - "rustc-hex", "scale-info", "serde", "serde_derive", @@ -17575,8 +17351,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-storage", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -17584,13 +17359,13 @@ dependencies = [ "staging-xcm-executor", "substrate-wasm-builder", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] name = "westend-runtime-constants" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "polkadot-primitives", @@ -17605,21 +17380,20 @@ dependencies = [ [[package]] name = "which" -version = "4.4.2" +version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269" dependencies = [ "either", - "home", + "libc", "once_cell", - "rustix 0.38.34", ] [[package]] name = "wide" -version = "0.7.25" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2caba658a80831539b30698ae9862a72db6697dfdd7151e46920f5f2755c3ce2" +checksum = "aa469ffa65ef7e0ba0f164183697b89b854253fd31aeb92358b7b6155177d62f" dependencies = [ "bytemuck", "safe_arch", @@ -17627,9 +17401,9 @@ dependencies = [ [[package]] name = "widestring" -version = "1.1.0" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311" +checksum = "653f141f39ec16bba3c5abe400a0c60da7468261cc2cbf36805022876bc721a8" [[package]] name = "winapi" @@ -17649,11 +17423,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.8" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ - "windows-sys 0.52.0", + "winapi", ] [[package]] @@ -17662,6 +17436,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows" version = "0.51.1" @@ -17723,6 +17506,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-targets" version = "0.42.2" @@ -17903,18 +17695,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - -[[package]] -name = "winnow" -version = "0.6.13" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" +checksum = "7c2e3184b9c4e92ad5167ca73039d0c42476302ab603e2fec4487511f38ccefc" dependencies = [ "memchr", ] @@ -17940,40 +17723,28 @@ dependencies = [ [[package]] name = "x25519-dalek" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a0c105152107e3b96f6a00a65e86ce82d9b125230e1c4302940eca58ff71f4f" -dependencies = [ - "curve25519-dalek 3.2.0", - "rand_core 0.5.1", - "zeroize", -] - -[[package]] -name = "x25519-dalek" -version = "2.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +checksum = "fb66477291e7e8d2b0ff1bcb900bf29489a9692816d79874bea351e7a8b6de96" dependencies = [ - "curve25519-dalek 4.1.3", - "rand_core 0.6.4", + "curve25519-dalek", + "rand_core", "serde", "zeroize", ] [[package]] name = "x509-parser" -version = "0.14.0" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0ecbeb7b67ce215e40e3cc7f2ff902f94a223acf44995934763467e7b1febc8" +checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" dependencies = [ - "asn1-rs", - "base64 0.13.1", + "asn1-rs 0.5.2", "data-encoding", - "der-parser", + "der-parser 8.2.0", "lazy_static", "nom", - "oid-registry", + "oid-registry 0.6.1", "rusticata-macros", "thiserror", "time", @@ -17981,16 +17752,16 @@ dependencies = [ [[package]] name = "x509-parser" -version = "0.15.1" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" +checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69" dependencies = [ - "asn1-rs", + "asn1-rs 0.6.1", "data-encoding", - "der-parser", + "der-parser 9.0.0", "lazy_static", "nom", - "oid-registry", + "oid-registry 0.7.0", "rusticata-macros", "thiserror", "time", @@ -17998,8 +17769,8 @@ dependencies = [ [[package]] name = "xcm-emulator" -version = "0.5.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "0.15.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "cumulus-pallet-parachain-system", "cumulus-pallet-xcmp-queue", @@ -18024,42 +17795,41 @@ dependencies = [ "sp-crypto-hashing", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", + "sp-tracing", "staging-xcm", "staging-xcm-executor", ] [[package]] -name = "xcm-fee-payment-runtime-api" -version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +name = "xcm-procedural" +version = "10.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#fe4e09d674c954238de06265123a74ac42075aba" +dependencies = [ + "Inflector", + "proc-macro2", + "quote", + "syn 2.0.90", +] + +[[package]] +name = "xcm-runtime-apis" +version = "0.3.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "parity-scale-codec", "scale-info", "sp-api", - "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", "sp-weights", "staging-xcm", -] - -[[package]] -name = "xcm-procedural" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" -dependencies = [ - "Inflector", - "proc-macro2", - "quote", - "syn 2.0.85", + "staging-xcm-executor", ] [[package]] name = "xcm-simulator" -version = "7.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0#d5160c1d567cc73c7df6c816d41e21aa3adb188d" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#c29cf6e1a276d194f2245c20561e37a38c273929" dependencies = [ "frame-support", "frame-system", @@ -18072,23 +17842,39 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", ] +[[package]] +name = "xml-rs" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791978798f0597cfc70478424c2b4fdc2b7a8024aaff78497ef00f24ef674193" + +[[package]] +name = "xmltree" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d8a75eaf6557bb84a65ace8609883db44a29951042ada9b393151532e41fcb" +dependencies = [ + "xml-rs", +] + [[package]] name = "yamux" -version = "0.10.2" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d9ba232399af1783a58d8eb26f6b5006fbefe2dc9ef36bd283324792d03ea5" +checksum = "9ed0164ae619f2dc144909a9f082187ebb5893693d8c0196e8085283ccd4b776" dependencies = [ "futures 0.3.31", "log", "nohash-hasher", "parking_lot 0.12.3", - "rand 0.8.5", + "pin-project", + "rand", "static_assertions", ] @@ -18104,7 +17890,7 @@ dependencies = [ [[package]] name = "zenlink-protocol" version = "0.4.4" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "cumulus-primitives-core", "frame-benchmarking", @@ -18119,14 +17905,14 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "staging-xcm", ] [[package]] name = "zenlink-protocol-rpc" version = "0.4.4" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "jsonrpsee", "parity-scale-codec", @@ -18142,18 +17928,18 @@ dependencies = [ [[package]] name = "zenlink-protocol-runtime-api" version = "0.4.4" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "parity-scale-codec", "sp-api", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "zenlink-protocol", ] [[package]] name = "zenlink-stable-amm" version = "0.1.0" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "frame-support", "frame-system", @@ -18164,13 +17950,13 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", ] [[package]] name = "zenlink-stable-amm-rpc" version = "0.1.0" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "jsonrpsee", "parity-scale-codec", @@ -18184,18 +17970,18 @@ dependencies = [ [[package]] name = "zenlink-stable-amm-runtime-api" version = "0.1.0" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "parity-scale-codec", "sp-api", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "zenlink-stable-amm", ] [[package]] name = "zenlink-swap-router" version = "0.1.0" -source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-v1.13.0#870ec20d64a994f6ab1ae87c6b819f07d3311319" +source = "git+https://github.com/bifrost-io/Zenlink-DEX-Module?branch=release-polkadot-stable2407#e34674fb77c86f2d11dc3d60fcab58f5f94a07bf" dependencies = [ "frame-support", "frame-system", @@ -18206,29 +17992,29 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.13.0)", + "sp-std", "zenlink-protocol", "zenlink-stable-amm", ] [[package]] name = "zerocopy" -version = "0.7.35" +version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.35" +version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -18248,7 +18034,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.85", + "syn 2.0.90", ] [[package]] @@ -18291,10 +18077,11 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.12+zstd.1.5.6" +version = "2.0.8+zstd.1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a4e40c320c3cb459d9a9ff6de98cff88f4751ee9275d140e2be94a2b74e4c13" +checksum = "5556e6ee25d32df2586c098bbfa278803692a20d0ab9565e049480d52707ec8c" dependencies = [ "cc", + "libc", "pkg-config", ] diff --git a/Cargo.toml b/Cargo.toml index ac54297589..188cf7facd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,3 @@ -cargo-features = ["resolver"] - [workspace] members = [ "node/cli", @@ -23,7 +21,6 @@ members = [ "pallets/vtoken-minting", "pallets/vtoken-voting", "pallets/system-staking", - "pallets/deprecated/system-maker", "pallets/fee-share", "pallets/parachain-staking", "pallets/bb-bnc", @@ -37,6 +34,7 @@ members = [ "runtime/bifrost-kusama", "runtime/bifrost-polkadot/src/evm/evm-utility/macro", + "runtime/bifrost-polkadot/src/evm/precompiles/call-permit", "runtime/bifrost-polkadot", "integration-tests" @@ -84,7 +82,6 @@ bifrost-slpx = { path = "pallets/slpx", default-featur bifrost-stable-asset = { path = "pallets/stable-asset", default-features = false } bifrost-stable-pool = { path = "pallets/stable-pool", default-features = false } bifrost-stable-pool-rpc-runtime-api = { path = "pallets/stable-pool/rpc/runtime-api", default-features = false } -bifrost-system-maker = { path = "pallets/deprecated/system-maker", default-features = false } bifrost-system-staking = { path = "pallets/system-staking", default-features = false } bifrost-token-issuer = { path = "pallets/token-issuer", default-features = false } bifrost-vbnc-convert = { path = "pallets/vbnc-convert", default-features = false } @@ -100,214 +97,203 @@ lend-market = { path = "pallets/lend-market", default lend-market-rpc-runtime-api = { path = "pallets/lend-market/rpc/runtime-api", default-features = false } leverage-staking = { path = "pallets/leverage-staking", default-features = false } module-evm-utility-macro = { path = "runtime/bifrost-polkadot/src/evm/evm-utility/macro", default-features = false } +pallet-evm-precompile-call-permit = { path = "runtime/bifrost-polkadot/src/evm/precompiles/call-permit", default-features = false } pallet-evm-accounts = { path = "pallets/evm-accounts", default-features = false } pallet-evm-accounts-rpc-runtime-api = { path = "pallets/evm-accounts/rpc/runtime-api", default-features = false } pallet-prices = { path = "pallets/prices", default-features = false } pallet-traits = { path = "pallets/traits", default-features = false } # Zenlink -merkle-distributor = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0", default-features = false } -zenlink-protocol = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0", default-features = false } -zenlink-protocol-rpc = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0" } -zenlink-protocol-runtime-api = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0", default-features = false } -zenlink-stable-amm = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0", default-features = false } -zenlink-stable-amm-rpc = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0" } -zenlink-stable-amm-runtime-api = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0", default-features = false } -zenlink-swap-router = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-v1.13.0", default-features = false } +merkle-distributor = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407", default-features = false } +zenlink-protocol = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407", default-features = false } +zenlink-protocol-rpc = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407" } +zenlink-protocol-runtime-api = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407", default-features = false } +zenlink-stable-amm = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407", default-features = false } +zenlink-stable-amm-rpc = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407" } +zenlink-stable-amm-runtime-api = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407", default-features = false } +zenlink-swap-router = { git = "https://github.com/bifrost-io/Zenlink-DEX-Module", branch = "release-polkadot-stable2407", default-features = false } # Orml -orml-tokens = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-traits = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-unknown-tokens = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-utilities = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-xcm = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-xcm-support = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-xtokens = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } -orml-oracle = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-v1.13.0", default-features = false } +orml-tokens = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-traits = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-unknown-tokens = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-utilities = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-xcm = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-xcm-support = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-xtokens = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } +orml-oracle = { git = "https://github.com/bifrost-io/open-runtime-module-library", branch = "release-polkadot-stable2407", default-features = false } # Frontier -fc-api = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fc-consensus = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fc-db = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fc-mapping-sync = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fc-rpc = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fc-rpc-core = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fc-storage = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-account = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-consensus = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-dynamic-fee = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-evm = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-rpc = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-self-contained = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -fp-storage = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-base-fee = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-dynamic-fee = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-ethereum = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-chain-id = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-precompile-blake2 = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-precompile-bn128 = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-precompile-dispatch = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-precompile-modexp = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-precompile-sha3fips = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-evm-precompile-simple = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-v1.13.0", default-features = false } +fc-api = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fc-consensus = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fc-db = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fc-mapping-sync = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fc-rpc = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fc-rpc-core = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fc-storage = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-account = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-consensus = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-dynamic-fee = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-evm = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-rpc = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-self-contained = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +fp-storage = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-base-fee = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-dynamic-fee = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-ethereum = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-chain-id = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-precompile-blake2 = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-precompile-bn128 = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-precompile-dispatch = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-precompile-modexp = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-precompile-sha3fips = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +pallet-evm-precompile-simple = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } +precompile-utils = { git = "https://github.com/bifrost-io/frontier", branch = "release-polkadot-stable2407", default-features = false } # polkadot-sdk (wasm) -cumulus-client-collator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-client-consensus-proposer = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-pallet-aura-ext = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-pallet-parachain-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-primitives-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-primitives-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-primitives-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -cumulus-test-relay-sproof-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-assets = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-asset-rate = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-authority-discovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-bounties = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-conviction-voting = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-democracy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-elections-phragmen = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-identity = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-im-online = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-indices = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-multisig = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-preimage = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-proxy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-ranked-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-recovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-referenda = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-scheduler = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-tips = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-tx-pause = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-treasury = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-whitelist = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -parachains-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -parachain-info = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", package = "staging-parachain-info", default-features = false } -polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -polkadot-parachain-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-application-crypto = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-authority-discovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-consensus-slots = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-debug-derive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-externalities = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-maybe-compressed-blob = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-npos-elections = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-runtime-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-state-machine = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-storage = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-trie = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-wasm-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } -sp-weights = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } +cumulus-client-collator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-client-consensus-proposer = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-pallet-aura-ext = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-pallet-parachain-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-primitives-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-primitives-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-primitives-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +cumulus-test-relay-sproof-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-assets = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-asset-rate = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-bounties = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-conviction-voting = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-democracy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-elections-phragmen = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-identity = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-indices = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-multisig = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-preimage = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-proxy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-ranked-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-referenda = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-scheduler = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-tips = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-tx-pause = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-treasury = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-whitelist = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +parachains-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +parachain-info = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", package = "staging-parachain-info", default-features = false } +polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +polkadot-parachain-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-debug-derive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-storage = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-trie = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } +sp-weights = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } substrate-fixed = { git = "https://github.com/encointer/substrate-fixed", default-features = false } -xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", package = "staging-xcm", default-features = false } -xcm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", package = "staging-xcm-builder", default-features = false } -xcm-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", package = "staging-xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", default-features = false } +xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", package = "staging-xcm", default-features = false } +xcm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", package = "staging-xcm-builder", default-features = false } +xcm-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", package = "staging-xcm-executor", default-features = false } +xcm-runtime-apis = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false } # polkadot-sdk (client) -cumulus-client-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-consensus-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-consensus-relay-chain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-pov-recovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-client-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-relay-chain-inprocess-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-relay-chain-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-relay-chain-minimal-node = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -cumulus-relay-chain-rpc-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -node-inspect = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0", package = "staging-node-inspect" } -pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -polkadot-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -polkadot-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-consensus-manual-seal = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-consensus-slots = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-network-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-rpc-server = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-sysinfo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sp-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -sp-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -substrate-prometheus-endpoint = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -try-runtime-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -xcm-emulator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } -xcm-simulator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.13.0" } +cumulus-client-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +cumulus-client-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +cumulus-client-consensus-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +cumulus-client-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +cumulus-client-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +cumulus-client-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +cumulus-relay-chain-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +node-inspect = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", package = "staging-node-inspect" } +pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +polkadot-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +polkadot-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-consensus-manual-seal = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-consensus-slots = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-network-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-sysinfo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +sp-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +substrate-prometheus-endpoint = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +xcm-emulator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } +xcm-simulator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" } # Other +affix = "0.1.2" +case = "1.0" +slices = "0.2.0" +derive_more = "0.99.18" +libsecp256k1 = { version = "0.7", default-features = false } +environmental = { version = "1.1.2", default-features = false } +prettyplease = "0.1.18" +macrotest = "1.0.9" +trybuild = "1.0" async-trait = { version = "0.1.83" } bstringify = { version = "0.1.2" } clap = { version = "4.5.18" } @@ -320,14 +306,14 @@ futures = { version = "0.3.31" } hex = { version = "0.4.3", default-features = false } hex-literal = { version = "0.4.1" } impl-trait-for-tuples = { version = "0.2.2" } -jsonrpsee = { version = "0.22.5" } +jsonrpsee = { version = "0.23.2" } log = { version = "0.4.22", default-features = false } num-bigint = { version = "0.4.6", default-features = false } num-traits = { version = "0.2.19", default-features = false } num_enum = { version = "0.7.3", default-features = false } parity-scale-codec = { version = "3.6.12", default-features = false } paste = { version = "1.0.15" } -primitive-types = { version = "0.12.0", default-features = false } +primitive-types = { version = "0.12.1", default-features = false } proc-macro2 = { version = "1.0.89" } quote = { version = "1.0.20" } scale-info = { version = "2.11.3", default-features = false } @@ -380,7 +366,6 @@ crossbeam-deque = { opt-level = 3 } crypto-mac = { opt-level = 3 } curve25519-dalek = { opt-level = 3 } ed25519-dalek = { opt-level = 3 } -flate2 = { opt-level = 3 } futures-channel = { opt-level = 3 } hashbrown = { opt-level = 3 } hmac = { opt-level = 3 } diff --git a/Dockerfile b/Dockerfile index bed52bf549..89a325a08d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,8 +18,8 @@ FROM rust:buster as builder RUN apt-get update && apt-get install time cmake clang libclang-dev llvm protobuf-compiler -y -RUN rustup toolchain install 1.77.0 -RUN rustup target add wasm32-unknown-unknown --toolchain 1.77.0 +RUN rustup toolchain install 1.81.0 +RUN rustup target add wasm32-unknown-unknown --toolchain 1.81.0 WORKDIR /app COPY . /app diff --git a/Makefile b/Makefile index e72e6af149..7eb9310a8b 100644 --- a/Makefile +++ b/Makefile @@ -25,9 +25,17 @@ build-bifrost-polkadot-release: build-all-release: copy-genesis-config-release cargo build -p bifrost-cli --locked --features "with-all-runtime" --release -.PHONY: check-all # cargo check all runtime -check-all: format - SKIP_WASM_BUILD= cargo check -p bifrost-cli --locked --features "with-all-runtime,runtime-benchmarks,try-runtime" +.PHONY: check-all # cargo check all +check-all: check-bin check-runtimes + +.PHONY: check-bin # cargo check bin +check-bin: + SKIP_WASM_BUILD= cargo check -p bifrost-cli --features "with-all-runtime runtime-benchmarks try-runtime" + +.PHONY: check-runtimes # cargo check all runtime +check-runtimes: + SKIP_WASM_BUILD= cargo check -p bifrost-polkadot-runtime --features on-chain-release-build + SKIP_WASM_BUILD= cargo check -p bifrost-kusama-runtime --features on-chain-release-build .PHONY: test-all # cargo test all test-all: test-runtimes test-benchmarks test-vtoken-voting-kusama @@ -54,15 +62,26 @@ copy-genesis-config-release: .PHONY: format # cargo fmt format: - cargo +nightly fmt --all + cargo fmt --all + +.PHONY: clippy-all +clippy-all: format-check runtime-clippy runtime-benchmarks-clippy try-runtime-clippy + +.PHONY: runtime-clippy +runtime-clippy: + SKIP_WASM_BUILD= cargo clippy --features "with-all-runtime,on-chain-release-build" -- -D warnings + +.PHONY: runtime-benchmarks-clippy +runtime-benchmarks-clippy: + SKIP_WASM_BUILD= cargo clippy --features "with-all-runtime,on-chain-release-build,runtime-benchmarks" -- -D warnings + +.PHONY: try-runtime-clippy +try-runtime-clippy: + SKIP_WASM_BUILD= cargo clippy --features "with-all-runtime,on-chain-release-build,try-runtime" -- -D warnings .PHONY: format-check # cargo fmt check format-check: - cargo +nightly fmt --all -- --check - -.PHONY: clippy # cargo clippy -clippy: format-check - cargo clippy --all --all-targets --features "with-all-runtime,runtime-benchmarks,try-runtime" -- -D warnings + cargo fmt --all -- --check .PHONY: benchmarking-staking # benchmarking staking pallet benchmarking-staking: diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 334332f4b3..afc59d9ad1 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-integration-tests" version = "0.8.0" -authors = ["hqwangningbo <2536935847@qq.com>"] +authors = ["Liebi Technologies "] edition = "2021" [dev-dependencies] @@ -49,3 +49,6 @@ xcm-builder = { workspace = true } xcm-emulator = { workspace = true } xcm-executor = { workspace = true } xcm-simulator = { workspace = true } + +[features] +try-runtime = [] diff --git a/integration-tests/src/mock/bifrost.rs b/integration-tests/src/mock/bifrost.rs index 915cb879b1..75d362433a 100644 --- a/integration-tests/src/mock/bifrost.rs +++ b/integration-tests/src/mock/bifrost.rs @@ -309,6 +309,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = (); type AssetIdMaps = AssetIdMaps; type TreasuryAccount = BifrostTreasuryAccount; + type BlockNumberProvider = System; } impl bifrost_asset_registry::Config for Runtime { diff --git a/integration-tests/src/mock/mock_message_queue/mod.rs b/integration-tests/src/mock/mock_message_queue/mod.rs index d209c10743..0aa74e8f7a 100644 --- a/integration-tests/src/mock/mock_message_queue/mod.rs +++ b/integration-tests/src/mock/mock_message_queue/mod.rs @@ -114,11 +114,15 @@ pub mod module { Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), // As far as the caller is concerned, this was dispatched without error, so // we just report the weight used. - Outcome::Incomplete { used, error } => - (Ok(used), Event::Fail(Some(hash), error)), + Outcome::Incomplete { used, error } => { + (Ok(used), Event::Fail(Some(hash), error)) + } } - }, - Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), + } + Err(()) => ( + Err(XcmError::UnhandledXcmVersion), + Event::BadVersion(Some(hash)), + ), }; Self::deposit_event(event); result @@ -161,7 +165,7 @@ pub mod module { match maybe_versioned { Err(_) => { Self::deposit_event(Event::InvalidFormat(id)); - }, + } Ok(versioned) => match Xcm::try_from(versioned) { Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), Ok(x) => { @@ -174,7 +178,7 @@ pub mod module { ); >::append(x); Self::deposit_event(Event::ExecutedDownward(id, outcome)); - }, + } }, } } diff --git a/integration-tests/src/mock/mod.rs b/integration-tests/src/mock/mod.rs index 52aa34ef9a..2facb22429 100644 --- a/integration-tests/src/mock/mod.rs +++ b/integration-tests/src/mock/mod.rs @@ -71,7 +71,9 @@ pub type RelayXcmPallet = pallet_xcm::Pallet; pub fn para_ext(para_id: u32) -> TestExternalities { use bifrost::{MessageQueue, Runtime, System}; - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); bifrost_asset_registry::GenesisConfig:: { currency: vec![(CurrencyId::Token2(0), 1_000_000, None)], @@ -99,12 +101,16 @@ pub fn para_ext(para_id: u32) -> TestExternalities { pub fn relay_ext() -> TestExternalities { use relaychain::{Runtime, System}; - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - - pallet_balances::GenesisConfig:: { balances: vec![(ALICE, 100_000_000_000)] } - .assimilate_storage(&mut t) + let mut t = frame_system::GenesisConfig::::default() + .build_storage() .unwrap(); + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, 100_000_000_000)], + } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/integration-tests/src/mock/relaychain.rs b/integration-tests/src/mock/relaychain.rs index 57bc0358c6..0b55baf3fc 100644 --- a/integration-tests/src/mock/relaychain.rs +++ b/integration-tests/src/mock/relaychain.rs @@ -117,8 +117,10 @@ parameter_types! { pub UniversalLocation: InteriorLocation = [GlobalConsensus(PolkadotNetwork::get())].into(); } -pub type SovereignAccountOf = - (ChildParachainConvertsVia, AccountId32Aliases); +pub type SovereignAccountOf = ( + ChildParachainConvertsVia, + AccountId32Aliases, +); pub type LocalAssetTransactor = FungibleAdapter, SovereignAccountOf, AccountId, ()>; diff --git a/integration-tests/src/tests/send_relay_chain_asset.rs b/integration-tests/src/tests/send_relay_chain_asset.rs index 61b621bf5b..09f1e6b1dd 100644 --- a/integration-tests/src/tests/send_relay_chain_asset.rs +++ b/integration-tests/src/tests/send_relay_chain_asset.rs @@ -49,11 +49,21 @@ fn send_relay_chain_asset_to_relay_chain() { CurrencyId::Token2(0), 50_000_000_000, Box::new( - Location::new(1, [Junction::AccountId32 { network: None, id: BOB.into() }]).into() + Location::new( + 1, + [Junction::AccountId32 { + network: None, + id: BOB.into() + }] + ) + .into() ), WeightLimit::Unlimited )); - assert_eq!(BifrostTokens::free_balance(CurrencyId::Token2(0), &ALICE), 50_000_000_000); + assert_eq!( + BifrostTokens::free_balance(CurrencyId::Token2(0), &ALICE), + 50_000_000_000 + ); }); Relay::execute_with(|| { diff --git a/integration-tests/src/tests/slp.rs b/integration-tests/src/tests/slp.rs index 799aa9e7d9..ca75a259eb 100644 --- a/integration-tests/src/tests/slp.rs +++ b/integration-tests/src/tests/slp.rs @@ -63,7 +63,11 @@ fn cross_dot_to_bifrost(to: AccountId32, amount: u128) { Some(to.clone()).into(), Box::new(VersionedLocation::V4(Parachain(2030).into())), Box::new(VersionedLocation::V4( - Junction::AccountId32 { id: to.into(), network: None }.into() + Junction::AccountId32 { + id: to.into(), + network: None + } + .into() )), Box::new(VersionedAssets::V4((Here, amount / 10).into())), 0, diff --git a/node/cli/Cargo.toml b/node/cli/Cargo.toml index 216b3d4aa3..6b240bcde6 100644 --- a/node/cli/Cargo.toml +++ b/node/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bifrost-cli" -version = "0.15.3" +version = "0.16.0" authors = ["Liebi Technologies "] description = "Bifrost Parachain Node" build = "build.rs" diff --git a/node/cli/src/cli.rs b/node/cli/src/cli.rs index 364b66adcd..8651af6c87 100644 --- a/node/cli/src/cli.rs +++ b/node/cli/src/cli.rs @@ -132,6 +132,10 @@ impl RelayChainCli { bifrost_service::chain_spec::RelayExtensions::try_get(¶_config.chain_spec); let chain_id = extension.map(|e| e.relay_chain.clone()); let base_path = para_config.base_path.path().join("polkadot"); - Self { base_path: Some(base_path), chain_id, base: Parser::parse_from(relay_chain_args) } + Self { + base_path: Some(base_path), + chain_id, + base: Parser::parse_from(relay_chain_args), + } } } diff --git a/node/cli/src/command.rs b/node/cli/src/command.rs index f415a92b14..c9cfc26ba1 100644 --- a/node/cli/src/command.rs +++ b/node/cli/src/command.rs @@ -16,6 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::{Cli, RelayChainCli, Subcommand}; use bifrost_service::{self as service, IdentifyVariant}; use cumulus_client_service::storage_proof_size::HostFunctions as ReclaimHostFunctions; use cumulus_primitives_core::ParaId; @@ -27,8 +28,7 @@ use sc_cli::{ }; use sc_service::config::{BasePath, PrometheusConfig}; use sp_runtime::traits::{AccountIdConversion, HashingFor}; - -use crate::{Cli, RelayChainCli, Subcommand}; +use std::net::SocketAddr; fn get_exec_name() -> Option { std::env::current_exe() @@ -51,30 +51,59 @@ fn load_spec(id: &str) -> std::result::Result, String> { }; #[allow(unreachable_code)] Ok(match id { - #[cfg(any(feature = "with-bifrost-kusama-runtime", feature = "with-bifrost-runtime"))] - "bifrost" | "bifrost-kusama" => - Box::new(service::chain_spec::bifrost_kusama::ChainSpec::from_json_bytes( + #[cfg(any( + feature = "with-bifrost-kusama-runtime", + feature = "with-bifrost-runtime" + ))] + "bifrost" | "bifrost-kusama" => Box::new( + service::chain_spec::bifrost_kusama::ChainSpec::from_json_bytes( &include_bytes!("../../service/res/bifrost-kusama.json")[..], - )?), - #[cfg(any(feature = "with-bifrost-kusama-runtime", feature = "with-bifrost-runtime"))] - "bifrost-genesis" | "bifrost-kusama-genesis" => - Box::new(service::chain_spec::bifrost_kusama::chainspec_config()), - #[cfg(any(feature = "with-bifrost-kusama-runtime", feature = "with-bifrost-runtime"))] - "bifrost-local" | "bifrost-kusama-local" => - Box::new(service::chain_spec::bifrost_kusama::local_testnet_config()), - #[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] - "bifrost-polkadot" => - Box::new(service::chain_spec::bifrost_polkadot::ChainSpec::from_json_bytes( + )?, + ), + #[cfg(any( + feature = "with-bifrost-kusama-runtime", + feature = "with-bifrost-runtime" + ))] + "bifrost-genesis" | "bifrost-kusama-genesis" => { + Box::new(service::chain_spec::bifrost_kusama::chainspec_config()) + } + #[cfg(any( + feature = "with-bifrost-kusama-runtime", + feature = "with-bifrost-runtime" + ))] + "bifrost-local" | "bifrost-kusama-local" => { + Box::new(service::chain_spec::bifrost_kusama::local_testnet_config()) + } + #[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" + ))] + "bifrost-polkadot" => Box::new( + service::chain_spec::bifrost_polkadot::ChainSpec::from_json_bytes( &include_bytes!("../../service/res/bifrost-polkadot.json")[..], - )?), - #[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] + )?, + ), + #[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" + ))] "bifrost-polkadot-genesis" => Box::new(service::chain_spec::bifrost_polkadot::chainspec_config()), - #[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] - "bifrost-polkadot-local" => - Box::new(service::chain_spec::bifrost_polkadot::local_testnet_config()), - #[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] + #[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" + ))] + "bifrost-polkadot-local" => { + Box::new(service::chain_spec::bifrost_polkadot::local_testnet_config()) + } + #[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" + ))] "bifrost-paseo" => Box::new(service::chain_spec::bifrost_polkadot::paseo_config()), - #[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] + #[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" + ))] "bifrost-polkadot-dev" => Box::new(service::chain_spec::bifrost_polkadot::dev_config()), path => { let path = std::path::PathBuf::from(path); @@ -84,9 +113,9 @@ fn load_spec(id: &str) -> std::result::Result, String> { feature = "with-bifrost-runtime" ))] { - Box::new(service::chain_spec::bifrost_polkadot::ChainSpec::from_json_file( - path, - )?) + Box::new( + service::chain_spec::bifrost_polkadot::ChainSpec::from_json_file(path)?, + ) } #[cfg(not(any( feature = "with-bifrost-polkadot-runtime", @@ -109,7 +138,7 @@ fn load_spec(id: &str) -> std::result::Result, String> { } else { return Err(service::UNKNOWN_RUNTIME.into()); } - }, + } }) } @@ -232,7 +261,7 @@ pub fn run() -> Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - }, + } Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -248,7 +277,7 @@ pub fn run() -> Result<()> { )) }); }) - }, + } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -258,10 +287,13 @@ pub fn run() -> Result<()> { with_runtime_or_err!(chain_spec, { return runner.async_run(|config| { let components = new_partial(&config, false)?; - Ok((cmd.run(components.client, config.database), components.task_manager)) + Ok(( + cmd.run(components.client, config.database), + components.task_manager, + )) }); }) - }, + } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -271,10 +303,13 @@ pub fn run() -> Result<()> { with_runtime_or_err!(chain_spec, { return runner.async_run(|config| { let components = new_partial(&config, false)?; - Ok((cmd.run(components.client, config.chain_spec), components.task_manager)) + Ok(( + cmd.run(components.client, config.chain_spec), + components.task_manager, + )) }); }) - }, + } Some(Subcommand::ExportGenesisHead(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -285,14 +320,14 @@ pub fn run() -> Result<()> { cmd.run(partials.client) }); }) - }, + } Some(Subcommand::ExportGenesisWasm(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|_config| { let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?; cmd.run(&*spec) }) - }, + } Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -301,7 +336,7 @@ pub fn run() -> Result<()> { with_runtime_or_err!(chain_spec, { return runner.sync_run(|config| cmd.run::(config)); }) - }, + } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -316,14 +351,16 @@ pub fn run() -> Result<()> { )) }); }) - }, + } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { let polkadot_cli = RelayChainCli::new( &config, - [RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()), + [RelayChainCli::executable_name()] + .iter() + .chain(cli.relay_chain_args.iter()), ); let polkadot_config = SubstrateCli::create_configuration( @@ -335,7 +372,7 @@ pub fn run() -> Result<()> { cmd.run(config, polkadot_config) }) - }, + } Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; let chain_spec = &runner.config().chain_spec; @@ -350,7 +387,7 @@ pub fn run() -> Result<()> { )) }); }) - }, + } Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Sign(cmd)) => cmd.run(), Some(Subcommand::Verify(cmd)) => cmd.run(), @@ -362,7 +399,7 @@ pub fn run() -> Result<()> { // Switch on the concrete benchmark sub-command- match cmd { - BenchmarkCmd::Pallet(cmd) => + BenchmarkCmd::Pallet(cmd) => { if cfg!(feature = "runtime-benchmarks") { with_runtime_or_err!(chain_spec, { return runner.sync_run(|config| { @@ -375,7 +412,8 @@ pub fn run() -> Result<()> { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into()) - }, + } + } BenchmarkCmd::Block(cmd) => runner.sync_run(|config| { with_runtime_or_err!(config.chain_spec, { { @@ -385,13 +423,14 @@ pub fn run() -> Result<()> { }) }), #[cfg(not(feature = "runtime-benchmarks"))] - BenchmarkCmd::Storage(_) => + BenchmarkCmd::Storage(_) => { return Err(sc_cli::Error::Input( "Compile with --features=runtime-benchmarks \ to enable storage benchmarks." .into(), ) - .into()), + .into()) + } #[cfg(feature = "runtime-benchmarks")] BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| { with_runtime_or_err!(config.chain_spec, { @@ -404,14 +443,15 @@ pub fn run() -> Result<()> { }) }), BenchmarkCmd::Overhead(_) => Err("Unsupported benchmarking command".into()), - BenchmarkCmd::Machine(cmd) => - runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())), + BenchmarkCmd::Machine(cmd) => { + runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())) + } // NOTE: this allows the Client to leniently implement // new benchmark commands without requiring a companion MR. #[allow(unreachable_patterns)] _ => Err("Benchmarking sub-command unsupported".into()), } - }, + } None => { let runner = cli.create_runner(&cli.run.normalize())?; let collator_options = cli.run.collator_options(); @@ -431,7 +471,9 @@ pub fn run() -> Result<()> { let polkadot_cli = RelayChainCli::new( &config, - [RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()), + [RelayChainCli::executable_name()] + .iter() + .chain(cli.relay_chain_args.iter()), ); let id = ParaId::from(para_id); @@ -450,8 +492,22 @@ pub fn run() -> Result<()> { info!("Parachain id: {:?}", id); info!("Parachain Account: {}", parachain_account); - info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" }); - info!("Is dev modle: {}", if config.chain_spec.is_dev() { "yes" } else { "no" }); + info!( + "Is collating: {}", + if config.role.is_authority() { + "yes" + } else { + "no" + } + ); + info!( + "Is dev modle: {}", + if config.chain_spec.is_dev() { + "yes" + } else { + "no" + } + ); with_runtime_or_err!(config.chain_spec, { { @@ -469,7 +525,7 @@ pub fn run() -> Result<()> { } }) }) - }, + } } } @@ -512,7 +568,9 @@ impl CliConfiguration for RelayChainCli { default_listen_port: u16, chain_spec: &Box, ) -> Result> { - self.base.base.prometheus_config(default_listen_port, chain_spec) + self.base + .base + .prometheus_config(default_listen_port, chain_spec) } fn init( @@ -531,7 +589,11 @@ impl CliConfiguration for RelayChainCli { fn chain_id(&self, is_dev: bool) -> Result { let chain_id = self.base.base.chain_id(is_dev)?; - Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id }) + Ok(if chain_id.is_empty() { + self.chain_id.clone().unwrap_or_default() + } else { + chain_id + }) } fn role(&self, is_dev: bool) -> Result { @@ -550,6 +612,14 @@ impl CliConfiguration for RelayChainCli { self.base.base.rpc_methods() } + fn rpc_max_connections(&self) -> Result { + self.base.base.rpc_max_connections() + } + + fn rpc_addr(&self, default_listen_port: u16) -> Result> { + self.base.base.rpc_addr(default_listen_port) + } + fn rpc_cors(&self, is_dev: bool) -> Result>> { self.base.base.rpc_cors(is_dev) } diff --git a/node/rpc/Cargo.toml b/node/rpc/Cargo.toml index 8ada17b5be..f4b06acea9 100644 --- a/node/rpc/Cargo.toml +++ b/node/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-rpc" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/node/rpc/src/eth.rs b/node/rpc/src/eth.rs index f9c31b83a3..9d512059d8 100644 --- a/node/rpc/src/eth.rs +++ b/node/rpc/src/eth.rs @@ -233,7 +233,13 @@ where io.merge(Web3::new(client.clone()).into_rpc())?; io.merge( - Debug::new(client.clone(), frontier_backend, storage_override, block_data_cache).into_rpc(), + Debug::new( + client.clone(), + frontier_backend, + storage_override, + block_data_cache, + ) + .into_rpc(), )?; io.merge(TxPool::new(client, graph).into_rpc())?; diff --git a/node/rpc/src/lib.rs b/node/rpc/src/lib.rs index 7f1b7d55e4..3610a0fb1b 100644 --- a/node/rpc/src/lib.rs +++ b/node/rpc/src/lib.rs @@ -118,7 +118,11 @@ where P: TransactionPool + Sync + Send + 'static, { let mut module = RpcExtension::new(()); - let FullDeps { client, pool, deny_unsafe } = deps; + let FullDeps { + client, + pool, + deny_unsafe, + } = deps; module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; @@ -161,7 +165,12 @@ where P: TransactionPool + Sync + Send + 'static, { let mut module = RpcExtension::new(()); - let FullDepsPolkadot { client, pool, deny_unsafe, command_sink } = deps; + let FullDepsPolkadot { + client, + pool, + deny_unsafe, + command_sink, + } = deps; module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; diff --git a/node/service/res/bifrost-kusama.json b/node/service/res/bifrost-kusama.json index 2a4953acee..693c98e00e 100644 --- a/node/service/res/bifrost-kusama.json +++ b/node/service/res/bifrost-kusama.json @@ -16,7 +16,7 @@ ], "protocolId": "bifrost", "properties": { - "ss58Format": 6, + "ss58Format": 0, "tokenDecimals": [ 12, 12, diff --git a/node/service/res/bifrost-paseo.json b/node/service/res/bifrost-paseo.json index 983c31933f..f4b882021d 100644 --- a/node/service/res/bifrost-paseo.json +++ b/node/service/res/bifrost-paseo.json @@ -16,7 +16,7 @@ ], "protocolId": "bifrost", "properties": { - "ss58Format": 6, + "ss58Format": 0, "tokenDecimals": [ 12, 12, diff --git a/node/service/res/bifrost-polkadot.json b/node/service/res/bifrost-polkadot.json index e6fe2d8aea..8da781bbaf 100644 --- a/node/service/res/bifrost-polkadot.json +++ b/node/service/res/bifrost-polkadot.json @@ -16,7 +16,7 @@ ], "protocolId": "bifrost_polkadot", "properties": { - "ss58Format": 6, + "ss58Format": 0, "tokenDecimals": [ 12 ], @@ -26,7 +26,7 @@ }, "relayChain": "polkadot", "paraId": 2030, - "evmSince": 5331574, + "evmSince": 5331575, "codeSubstitutes": {}, "genesis": { "raw": { diff --git a/node/service/res/stage/bifrost-stage.json b/node/service/res/stage/bifrost-stage.json index 654e1378bd..fa81ae35ce 100644 --- a/node/service/res/stage/bifrost-stage.json +++ b/node/service/res/stage/bifrost-stage.json @@ -17,7 +17,7 @@ "protocolId": "bifrost", "forkId": null, "properties": { - "ss58Format": 6, + "ss58Format": 0, "tokenDecimals": [ 12, 12, diff --git a/node/service/src/chain_spec/bifrost_kusama.rs b/node/service/src/chain_spec/bifrost_kusama.rs index 4a307e7eab..d54bb889ae 100644 --- a/node/service/src/chain_spec/bifrost_kusama.rs +++ b/node/service/src/chain_spec/bifrost_kusama.rs @@ -72,7 +72,11 @@ pub fn inflation_config() -> InflationInfo { }; InflationInfo { // staking expectations - expect: Range { min: 100_000 * DOLLARS, ideal: 200_000 * DOLLARS, max: 500_000 * DOLLARS }, + expect: Range { + min: 100_000 * DOLLARS, + ideal: 200_000 * DOLLARS, + max: 500_000 * DOLLARS, + }, // annual inflation annual, round: to_round_inflation(annual), @@ -197,7 +201,11 @@ pub fn local_testnet_config() -> ChainSpec { // eCSrvbA5gGNQr7VZ48fkCX5vkt1H16F8Np9g2hYssRXHZJF hex!["6d6f646c62662f7374616b650000000000000000000000000000000000000000"].into(), ]; - let balances = endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT())).collect(); + let balances = endowed_accounts + .iter() + .cloned() + .map(|x| (x, ENDOWMENT())) + .collect(); let vestings = endowed_accounts .iter() .cloned() @@ -308,24 +316,31 @@ pub fn chainspec_config() -> ChainSpec { let balances = balances_configs .into_iter() .flat_map(|bc| bc.balances) - .fold(BTreeMap::::new(), |mut acc, (account_id, amount)| { - if let Some(balance) = acc.get_mut(&account_id) { - *balance = balance + .fold( + BTreeMap::::new(), + |mut acc, (account_id, amount)| { + if let Some(balance) = acc.get_mut(&account_id) { + *balance = balance + .checked_add(amount) + .expect("balance cannot overflow when building genesis"); + } else { + acc.insert(account_id.clone(), amount); + } + + total_issuance = total_issuance .checked_add(amount) - .expect("balance cannot overflow when building genesis"); - } else { - acc.insert(account_id.clone(), amount); - } - - total_issuance = total_issuance - .checked_add(amount) - .expect("total insurance cannot overflow when building genesis"); - acc - }) + .expect("total insurance cannot overflow when building genesis"); + acc + }, + ) .into_iter() .collect(); - assert_eq!(total_issuance, 32_000_000 * DOLLARS, "total issuance must be equal to 320 million"); + assert_eq!( + total_issuance, + 32_000_000 * DOLLARS, + "total issuance must be equal to 320 million" + ); let vesting_configs: Vec = config_from_json_files(exe_dir.join("res/genesis_config/vesting")).unwrap(); @@ -348,7 +363,10 @@ pub fn chainspec_config() -> ChainSpec { invulnerables, vec![], balances, - vesting_configs.into_iter().flat_map(|vc| vc.vesting).collect(), + vesting_configs + .into_iter() + .flat_map(|vc| vc.vesting) + .collect(), BifrostKusamaChainId::get().into(), vec![], // council membership vec![], // technical committee membership diff --git a/node/service/src/chain_spec/bifrost_polkadot.rs b/node/service/src/chain_spec/bifrost_polkadot.rs index 2a0d91f381..ce9b268f88 100644 --- a/node/service/src/chain_spec/bifrost_polkadot.rs +++ b/node/service/src/chain_spec/bifrost_polkadot.rs @@ -17,7 +17,6 @@ // along with this program. If not, see . use crate::chain_spec::{get_account_id_from_seed, get_from_seed, RelayExtensions}; -use bifrost_kusama_runtime::constants::currency::Perbill; use bifrost_parachain_staking::{InflationInfo, Range}; use bifrost_polkadot_runtime::{ constants::currency::DOLLARS, AccountId, Balance, BlockNumber, SS58Prefix, @@ -36,7 +35,7 @@ use hex_literal::hex; use sc_chain_spec::Properties; use sc_service::ChainType; use sp_core::{crypto::UncheckedInto, sr25519, H160, U256}; -use sp_runtime::{FixedU128, Percent}; +use sp_runtime::{FixedU128, Perbill, Percent}; use std::{collections::BTreeMap, str::FromStr}; const DEFAULT_PROTOCOL_ID: &str = "bifrost_polkadot"; @@ -71,7 +70,11 @@ pub fn inflation_config() -> InflationInfo { }; InflationInfo { // staking expectations - expect: Range { min: 100_000 * DOLLARS, ideal: 200_000 * DOLLARS, max: 500_000 * DOLLARS }, + expect: Range { + min: 100_000 * DOLLARS, + ideal: 200_000 * DOLLARS, + max: 500_000 * DOLLARS, + }, // annual inflation annual, round: to_round_inflation(annual), @@ -196,7 +199,11 @@ pub fn local_testnet_config() -> ChainSpec { whitelisted_caller(), // Benchmarking whitelist_account account("bechmarking_account_1", 0, 0), ]; - let balances = endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT())).collect(); + let balances = endowed_accounts + .iter() + .cloned() + .map(|x| (x, ENDOWMENT())) + .collect(); let tokens = endowed_accounts .iter() .flat_map(|x| { @@ -215,24 +222,60 @@ pub fn local_testnet_config() -> ChainSpec { ( BNC, 10_000_000_000, - Some((String::from("Bifrost Native Coin"), String::from("BNC"), 12u8)), + Some(( + String::from("Bifrost Native Coin"), + String::from("BNC"), + 12u8, + )), + ), + ( + DOT, + 1_000_000, + Some((String::from("Polkadot DOT"), String::from("DOT"), 10u8)), ), - (DOT, 1_000_000, Some((String::from("Polkadot DOT"), String::from("DOT"), 10u8))), ( GLMR, 1_000_000_000_000, - Some((String::from("Moonbeam Native Token"), String::from("GLMR"), 18u8)), + Some(( + String::from("Moonbeam Native Token"), + String::from("GLMR"), + 18u8, + )), + ), + ( + DOT_U, + 1_000, + Some((String::from("Tether USD"), String::from("USDT"), 6u8)), + ), + ( + ASTR, + 10_000_000_000_000_000, + Some((String::from("Astar"), String::from("ASTR"), 18u8)), ), - (DOT_U, 1_000, Some((String::from("Tether USD"), String::from("USDT"), 6u8))), - (ASTR, 10_000_000_000_000_000, Some((String::from("Astar"), String::from("ASTR"), 18u8))), ( FIL, 1_000_000_000_000, - Some((String::from("Filecoin Network Token"), String::from("FIL"), 18u8)), + Some(( + String::from("Filecoin Network Token"), + String::from("FIL"), + 18u8, + )), + ), + ( + USDC, + 1_000, + Some((String::from("USD Coin"), String::from("USDC"), 6u8)), + ), + ( + IBTC, + 100, + Some((String::from("interBTC"), String::from("IBTC"), 8u8)), + ), + ( + INTR, + 10_000_000, + Some((String::from("Interlay"), String::from("INTR"), 10u8)), ), - (USDC, 1_000, Some((String::from("USD Coin"), String::from("USDC"), 6u8))), - (IBTC, 100, Some((String::from("interBTC"), String::from("IBTC"), 8u8))), - (INTR, 10_000_000, Some((String::from("Interlay"), String::from("INTR"), 10u8))), ( MANTA, 10_000_000_000_000, @@ -241,14 +284,38 @@ pub fn local_testnet_config() -> ChainSpec { ( BNCS, 10_000_000_000, - Some((String::from("bncs-20 inscription token BNCS"), String::from("BNCS"), 12u8)), + Some(( + String::from("bncs-20 inscription token BNCS"), + String::from("BNCS"), + 12u8, + )), + ), + ( + PINK, + 100_000_000, + Some((String::from("PINK"), String::from("PINK"), 10u8)), + ), + ( + DED, + 1, + Some((String::from("DED"), String::from("DED"), 10u8)), ), - (PINK, 100_000_000, Some((String::from("PINK"), String::from("PINK"), 10u8))), - (DED, 1, Some((String::from("DED"), String::from("DED"), 10u8))), - (PEN, 100_000_000, Some((String::from("Pendulum"), String::from("PEN"), 12u8))), - (WETH, 100_000_000, Some((String::from("SnowBridge WETH"), String::from("SWETH"), 18u8))), + ( + PEN, + 100_000_000, + Some((String::from("Pendulum"), String::from("PEN"), 12u8)), + ), + ( + WETH, + 100_000_000, + Some((String::from("SnowBridge WETH"), String::from("SWETH"), 18u8)), + ), + ]; + let vcurrency = vec![ + VSToken2(DOT_TOKEN_ID), + VToken(TokenSymbol::BNC), + VToken2(DOT_TOKEN_ID), ]; - let vcurrency = vec![VSToken2(DOT_TOKEN_ID), VToken(TokenSymbol::BNC), VToken2(DOT_TOKEN_ID)]; let mut evm_accounts = BTreeMap::new(); evm_accounts.insert( @@ -315,7 +382,11 @@ pub fn dev_config() -> ChainSpec { whitelisted_caller(), // Benchmarking whitelist_account account("bechmarking_account_1", 0, 0), ]; - let balances = endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT())).collect(); + let balances = endowed_accounts + .iter() + .cloned() + .map(|x| (x, ENDOWMENT())) + .collect(); let tokens = endowed_accounts .iter() .flat_map(|x| { @@ -334,24 +405,60 @@ pub fn dev_config() -> ChainSpec { ( BNC, 10_000_000_000, - Some((String::from("Bifrost Native Coin"), String::from("BNC"), 12u8)), + Some(( + String::from("Bifrost Native Coin"), + String::from("BNC"), + 12u8, + )), + ), + ( + DOT, + 1_000_000, + Some((String::from("Polkadot DOT"), String::from("DOT"), 10u8)), ), - (DOT, 1_000_000, Some((String::from("Polkadot DOT"), String::from("DOT"), 10u8))), ( GLMR, 1_000_000_000_000, - Some((String::from("Moonbeam Native Token"), String::from("GLMR"), 18u8)), + Some(( + String::from("Moonbeam Native Token"), + String::from("GLMR"), + 18u8, + )), + ), + ( + DOT_U, + 1_000, + Some((String::from("Tether USD"), String::from("USDT"), 6u8)), + ), + ( + ASTR, + 10_000_000_000_000_000, + Some((String::from("Astar"), String::from("ASTR"), 18u8)), ), - (DOT_U, 1_000, Some((String::from("Tether USD"), String::from("USDT"), 6u8))), - (ASTR, 10_000_000_000_000_000, Some((String::from("Astar"), String::from("ASTR"), 18u8))), ( FIL, 1_000_000_000_000, - Some((String::from("Filecoin Network Token"), String::from("FIL"), 18u8)), + Some(( + String::from("Filecoin Network Token"), + String::from("FIL"), + 18u8, + )), + ), + ( + USDC, + 1_000, + Some((String::from("USD Coin"), String::from("USDC"), 6u8)), + ), + ( + IBTC, + 100, + Some((String::from("interBTC"), String::from("IBTC"), 8u8)), + ), + ( + INTR, + 10_000_000, + Some((String::from("Interlay"), String::from("INTR"), 10u8)), ), - (USDC, 1_000, Some((String::from("USD Coin"), String::from("USDC"), 6u8))), - (IBTC, 100, Some((String::from("interBTC"), String::from("IBTC"), 8u8))), - (INTR, 10_000_000, Some((String::from("Interlay"), String::from("INTR"), 10u8))), ( MANTA, 10_000_000_000_000, @@ -360,14 +467,38 @@ pub fn dev_config() -> ChainSpec { ( BNCS, 10_000_000_000, - Some((String::from("bncs-20 inscription token BNCS"), String::from("BNCS"), 12u8)), + Some(( + String::from("bncs-20 inscription token BNCS"), + String::from("BNCS"), + 12u8, + )), + ), + ( + PINK, + 100_000_000, + Some((String::from("PINK"), String::from("PINK"), 10u8)), + ), + ( + DED, + 1, + Some((String::from("DED"), String::from("DED"), 10u8)), + ), + ( + PEN, + 100_000_000, + Some((String::from("Pendulum"), String::from("PEN"), 12u8)), + ), + ( + WETH, + 100_000_000, + Some((String::from("SnowBridge WETH"), String::from("SWETH"), 18u8)), ), - (PINK, 100_000_000, Some((String::from("PINK"), String::from("PINK"), 10u8))), - (DED, 1, Some((String::from("DED"), String::from("DED"), 10u8))), - (PEN, 100_000_000, Some((String::from("Pendulum"), String::from("PEN"), 12u8))), - (WETH, 100_000_000, Some((String::from("SnowBridge WETH"), String::from("SWETH"), 18u8))), ]; - let vcurrency = vec![VSToken2(DOT_TOKEN_ID), VToken(TokenSymbol::BNC), VToken2(DOT_TOKEN_ID)]; + let vcurrency = vec![ + VSToken2(DOT_TOKEN_ID), + VToken(TokenSymbol::BNC), + VToken2(DOT_TOKEN_ID), + ]; let mut evm_accounts = BTreeMap::new(); evm_accounts.insert( @@ -467,7 +598,11 @@ pub fn paseo_config() -> ChainSpec { // c9eHvgbxTFzijvY3AnAKiRTHhi2hzS5SLCPzCkb4jP79MLu hex!["12d3ab675d6503279133898efe246a63fdc8be685cc3f7bce079aac064108a7a"].into(), ]; - let balances = endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT())).collect(); + let balances = endowed_accounts + .iter() + .cloned() + .map(|x| (x, ENDOWMENT())) + .collect(); let salp_multisig: AccountId = hex!["e4da05f08e89bf6c43260d96f26fffcfc7deae5b465da08669a9d008e64c2c63"].into(); diff --git a/node/service/src/chain_spec/mod.rs b/node/service/src/chain_spec/mod.rs index e1c180ce58..debdc56b48 100644 --- a/node/service/src/chain_spec/mod.rs +++ b/node/service/src/chain_spec/mod.rs @@ -16,9 +16,15 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#[cfg(any(feature = "with-bifrost-kusama-runtime", feature = "with-bifrost-runtime"))] +#[cfg(any( + feature = "with-bifrost-kusama-runtime", + feature = "with-bifrost-runtime" +))] pub mod bifrost_kusama; -#[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] +#[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" +))] pub mod bifrost_polkadot; use bifrost_primitives::BlockNumber; diff --git a/node/service/src/collator_kusama.rs b/node/service/src/collator_kusama.rs index 17fbc8f422..9b11a2c649 100644 --- a/node/service/src/collator_kusama.rs +++ b/node/service/src/collator_kusama.rs @@ -20,7 +20,10 @@ use std::{sync::Arc, time::Duration}; use crate::eth::EthConfiguration; -#[cfg(any(feature = "with-bifrost-kusama-runtime", feature = "with-bifrost-runtime"))] +#[cfg(any( + feature = "with-bifrost-kusama-runtime", + feature = "with-bifrost-runtime" +))] pub use bifrost_kusama_runtime; use bifrost_kusama_runtime::RuntimeApi; use bifrost_primitives::Block; @@ -73,7 +76,11 @@ pub fn new_partial( MaybeFullSelectChain, sc_consensus::import_queue::BasicQueue, sc_transaction_pool::FullPool, - (ParachainBlockImport, Option, Option), + ( + ParachainBlockImport, + Option, + Option, + ), >, sc_service::Error, > { @@ -90,7 +97,9 @@ pub fn new_partial( let heap_pages = config .default_heap_pages - .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ }); + .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { + extra_pages: h as _, + }); let executor = sc_executor::WasmExecutor::::builder() .with_execution_method(config.wasm_method) @@ -112,7 +121,9 @@ pub fn new_partial( let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); let telemetry = telemetry.map(|(worker, telemetry)| { - task_manager.spawn_handle().spawn("telemetry", None, worker.run()); + task_manager + .spawn_handle() + .spawn("telemetry", None, worker.run()); telemetry }); @@ -126,7 +137,11 @@ pub fn new_partial( client.clone(), ); - let select_chain = if dev { Some(LongestChain::new(backend.clone())) } else { None }; + let select_chain = if dev { + Some(LongestChain::new(backend.clone())) + } else { + None + }; let block_import = ParachainBlockImport::new(client.clone(), backend.clone()); @@ -205,7 +220,7 @@ fn start_consensus( task_manager: &TaskManager, relay_chain_interface: Arc, transaction_pool: Arc>, - sync_oracle: Arc>, + _sync_oracle: Arc>, keystore: KeystorePtr, relay_chain_slot_duration: Duration, para_id: ParaId, @@ -237,9 +252,11 @@ fn start_consensus( para_backend: backend.clone(), relay_client: relay_chain_interface, code_hash_provider: move |block_hash| { - client.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash()) + client + .code_at(block_hash) + .ok() + .map(|c| ValidationCode::from(c).hash()) }, - sync_oracle, keystore, collator_key, para_id, @@ -252,11 +269,12 @@ fn start_consensus( reinitialize: false, }; - let fut = - aura::run::( - params, - ); - task_manager.spawn_essential_handle().spawn("aura", None, fut); + let fut = aura::run::( + params, + ); + task_manager + .spawn_essential_handle() + .spawn("aura", None, fut); Ok(()) } diff --git a/node/service/src/collator_polkadot.rs b/node/service/src/collator_polkadot.rs index 188c050f0b..73e4a7de5a 100644 --- a/node/service/src/collator_polkadot.rs +++ b/node/service/src/collator_polkadot.rs @@ -28,7 +28,10 @@ use crate::{ eth::{EthConfiguration, FrontierBackend}, IdentifyVariant, }; -#[cfg(any(feature = "with-bifrost-polkadot-runtime", feature = "with-bifrost-runtime"))] +#[cfg(any( + feature = "with-bifrost-polkadot-runtime", + feature = "with-bifrost-runtime" +))] pub use bifrost_polkadot_runtime; use bifrost_polkadot_runtime::{RuntimeApi, TransactionConverter}; use bifrost_primitives::Block; @@ -108,7 +111,9 @@ pub fn new_partial( let heap_pages = config .default_heap_pages - .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ }); + .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { + extra_pages: h as _, + }); let executor = sc_executor::WasmExecutor::::builder() .with_execution_method(config.wasm_method) @@ -130,7 +135,9 @@ pub fn new_partial( let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); let telemetry = telemetry.map(|(worker, telemetry)| { - task_manager.spawn_handle().spawn("telemetry", None, worker.run()); + task_manager + .spawn_handle() + .spawn("telemetry", None, worker.run()); telemetry }); @@ -144,7 +151,11 @@ pub fn new_partial( client.clone(), ); - let select_chain = if dev { Some(LongestChain::new(backend.clone())) } else { None }; + let select_chain = if dev { + Some(LongestChain::new(backend.clone())) + } else { + None + }; let frontier_backend = Arc::new(FrontierBackend::open( Arc::clone(&client), @@ -247,7 +258,7 @@ fn start_consensus( task_manager: &TaskManager, relay_chain_interface: Arc, transaction_pool: Arc>, - sync_oracle: Arc>, + _sync_oracle: Arc>, keystore: KeystorePtr, relay_chain_slot_duration: Duration, para_id: ParaId, @@ -279,9 +290,11 @@ fn start_consensus( para_backend: backend.clone(), relay_client: relay_chain_interface, code_hash_provider: move |block_hash| { - client.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash()) + client + .code_at(block_hash) + .ok() + .map(|c| ValidationCode::from(c).hash()) }, - sync_oracle, keystore, collator_key, para_id, @@ -294,11 +307,12 @@ fn start_consensus( reinitialize: false, }; - let fut = - aura::run::( - params, - ); - task_manager.spawn_essential_handle().spawn("aura", None, fut); + let fut = aura::run::( + params, + ); + task_manager + .spawn_essential_handle() + .spawn("aura", None, fut); Ok(()) } diff --git a/node/service/src/dev.rs b/node/service/src/dev.rs index f3f82f8a2d..60cda0bfcd 100644 --- a/node/service/src/dev.rs +++ b/node/service/src/dev.rs @@ -22,11 +22,10 @@ use crate::{ collator_polkadot::FullClient, eth::{spawn_frontier_tasks, EthConfiguration}, }; -use bifrost_polkadot_runtime::{constants::time::SLOT_DURATION, TransactionConverter}; +use bifrost_polkadot_runtime::TransactionConverter; use cumulus_client_parachain_inherent::{MockValidationDataInherentDataProvider, MockXcmConfig}; use cumulus_primitives_core::{relay_chain::Hash, ParaId}; use fc_storage::StorageOverrideHandler; -use jsonrpsee::core::async_trait; use sc_client_api::Backend; use sc_network::NetworkBackend; use sc_service::{Configuration, TaskManager}; @@ -40,32 +39,6 @@ pub type FullSelectChain = sc_consensus::LongestChain; thread_local!(static TIMESTAMP: RefCell = const { RefCell::new(0) }); -/// Provide a mock duration starting at 0 in millisecond for timestamp inherent. -/// Each call will increment timestamp by slot_duration making Aura think time has passed. -struct MockTimestampInherentDataProvider; - -#[async_trait] -impl sp_inherents::InherentDataProvider for MockTimestampInherentDataProvider { - async fn provide_inherent_data( - &self, - inherent_data: &mut sp_inherents::InherentData, - ) -> Result<(), sp_inherents::Error> { - TIMESTAMP.with(|x| { - *x.borrow_mut() += SLOT_DURATION; - inherent_data.put_data(sp_timestamp::INHERENT_IDENTIFIER, &*x.borrow()) - }) - } - - async fn try_handle_error( - &self, - _identifier: &sp_inherents::InherentIdentifier, - _error: &[u8], - ) -> Option> { - // The pallet never reports error. - None - } -} - /// Builds a new development service. This service uses manual seal, and mocks /// the parachain inherent. /// Before calling this function, you must set OnTimestampSet in runtime to be (). @@ -95,7 +68,10 @@ where let net_config = sc_network::config::FullNetworkConfiguration::<_, _, Net>::new(¶chain_config.network); let metrics = Net::register_notification_metrics( - parachain_config.prometheus_config.as_ref().map(|cfg| &cfg.registry), + parachain_config + .prometheus_config + .as_ref() + .map(|cfg| &cfg.registry), ); let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = @@ -180,8 +156,9 @@ where let current_para_block = maybe_current_para_block? .ok_or(sp_blockchain::Error::UnknownBlock(block.to_string()))?; - let current_para_block_head = - Some(polkadot_primitives::HeadData(maybe_current_para_head?.encode())); + let current_para_block_head = Some(polkadot_primitives::HeadData( + maybe_current_para_head?.encode(), + )); let mocked_parachain = MockValidationDataInherentDataProvider { current_para_block, diff --git a/node/service/src/eth.rs b/node/service/src/eth.rs index ed19208e04..84f124f98a 100644 --- a/node/service/src/eth.rs +++ b/node/service/src/eth.rs @@ -117,7 +117,13 @@ where backend: Arc>, evm_since: BlockNumberOf, ) -> Self { - Self { inner, client, backend, evm_since, _marker: PhantomData } + Self { + inner, + client, + backend, + evm_since, + _marker: PhantomData, + } } } @@ -134,10 +140,7 @@ where { type Error = ConsensusError; - async fn check_block( - &mut self, - block: BlockCheckParams, - ) -> Result { + async fn check_block(&self, block: BlockCheckParams) -> Result { self.inner.check_block(block).await.map_err(Into::into) } diff --git a/pallets/asset-registry/Cargo.toml b/pallets/asset-registry/Cargo.toml index c6e22cd689..bc394a9e7f 100644 --- a/pallets/asset-registry/Cargo.toml +++ b/pallets/asset-registry/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-asset-registry" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 87eed10a7b..73cc093b05 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -40,14 +40,19 @@ mod benchmarks { minimal_balance: BalanceOf::::unique_saturated_from(0u128), }; - let call = Call::::register_token_metadata { metadata: Box::new(metadata.clone()) }; + let call = Call::::register_token_metadata { + metadata: Box::new(metadata.clone()), + }; #[block] { call.dispatch_bypass_filter(origin)?; } - assert_eq!(CurrencyMetadatas::::get(Token2(0)), Some(metadata.clone())); + assert_eq!( + CurrencyMetadatas::::get(Token2(0)), + Some(metadata.clone()) + ); Ok(()) } @@ -79,7 +84,10 @@ mod benchmarks { call.dispatch_bypass_filter(origin)?; } - assert_eq!(CurrencyMetadatas::::get(CurrencyId::VToken2(0)), Some(v_metadata.clone())); + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VToken2(0)), + Some(v_metadata.clone()) + ); Ok(()) } @@ -112,7 +120,10 @@ mod benchmarks { call.dispatch_bypass_filter(origin)?; } - assert_eq!(LocationToCurrencyIds::::get(location.clone()), Some(Token2(0))); + assert_eq!( + LocationToCurrencyIds::::get(location.clone()), + Some(Token2(0)) + ); assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); assert_eq!( CurrencyIdToWeights::::get(Token2(0)), @@ -200,5 +211,9 @@ mod benchmarks { // // The line generates three steps per benchmark, with repeat=1 and the three steps are // [low, mid, high] of the range. - impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext_benchmark(), crate::mock::Runtime); + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 63e7608154..31e2c617e7 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -110,15 +110,31 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// The asset registered. - AssetRegistered { asset_id: AssetIds, metadata: AssetMetadata> }, + AssetRegistered { + asset_id: AssetIds, + metadata: AssetMetadata>, + }, /// The asset updated. - AssetUpdated { asset_id: AssetIds, metadata: AssetMetadata> }, + AssetUpdated { + asset_id: AssetIds, + metadata: AssetMetadata>, + }, /// The CurrencyId registered. - CurrencyIdRegistered { currency_id: CurrencyId, metadata: AssetMetadata> }, + CurrencyIdRegistered { + currency_id: CurrencyId, + metadata: AssetMetadata>, + }, /// Location Force set. - LocationSet { currency_id: CurrencyId, location: Location, weight: Weight }, + LocationSet { + currency_id: CurrencyId, + location: Location, + weight: Weight, + }, /// The CurrencyId updated. - CurrencyIdUpdated { currency_id: CurrencyId, metadata: AssetMetadata> }, + CurrencyIdUpdated { + currency_id: CurrencyId, + metadata: AssetMetadata>, + }, } /// Next available Foreign AssetId ID. @@ -178,31 +194,33 @@ pub mod pallet { impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (currency_id, metadata) in - self.currency.iter().map(|(currency_id, minimal_balance, metadata)| { - ( - currency_id, - match &metadata { - None => AssetMetadata { - name: currency_id - .name() - .map(|s| s.as_bytes().to_vec()) - .unwrap_or_default(), - symbol: currency_id - .symbol() - .map(|s| s.as_bytes().to_vec()) - .unwrap_or_default(), - decimals: currency_id.decimals().unwrap_or_default(), - minimal_balance: *minimal_balance, + self.currency + .iter() + .map(|(currency_id, minimal_balance, metadata)| { + ( + currency_id, + match &metadata { + None => AssetMetadata { + name: currency_id + .name() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), + symbol: currency_id + .symbol() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), + decimals: currency_id.decimals().unwrap_or_default(), + minimal_balance: *minimal_balance, + }, + Some(metadata) => AssetMetadata { + name: metadata.0.as_bytes().to_vec(), + symbol: metadata.1.as_bytes().to_vec(), + decimals: metadata.2, + minimal_balance: *minimal_balance, + }, }, - Some(metadata) => AssetMetadata { - name: metadata.0.as_bytes().to_vec(), - symbol: metadata.1.as_bytes().to_vec(), - decimals: metadata.2, - minimal_balance: *minimal_balance, - }, - }, - ) - }) { + ) + }) { if let CurrencyId::Token2(_token_id) = *currency_id { Pallet::::get_next_token_id().expect("Token register"); } @@ -214,11 +232,11 @@ pub mod pallet { CurrencyId::VToken(symbol) => { AssetIdMaps::::register_vtoken_metadata(symbol) .expect("VToken register"); - }, + } CurrencyId::VToken2(token_id) => { AssetIdMaps::::register_vtoken2_metadata(token_id) .expect("VToken register"); - }, + } _ => (), } } @@ -274,8 +292,9 @@ pub mod pallet { ) -> DispatchResult { T::RegisterOrigin::ensure_origin(origin)?; - let location: Location = - (*location).try_into().map_err(|()| Error::::BadLocation)?; + let location: Location = (*location) + .try_into() + .map_err(|()| Error::::BadLocation)?; Self::do_register_location(currency_id, &location)?; Self::do_register_weight(currency_id, weight)?; @@ -292,8 +311,9 @@ pub mod pallet { ) -> DispatchResult { T::RegisterOrigin::ensure_origin(origin)?; - let location: Location = - (*location).try_into().map_err(|()| Error::::BadLocation)?; + let location: Location = (*location) + .try_into() + .map_err(|()| Error::::BadLocation)?; let v4_location = Location::try_from(location.clone()).map_err(|_| Error::::BadLocation)?; @@ -307,7 +327,11 @@ pub mod pallet { CurrencyIdToLocations::::insert(currency_id, v4_location); CurrencyIdToWeights::::insert(currency_id, weight); - Pallet::::deposit_event(Event::::LocationSet { currency_id, location, weight }); + Pallet::::deposit_event(Event::::LocationSet { + currency_id, + location, + weight, + }); Ok(()) } @@ -344,7 +368,10 @@ pub mod pallet { // Store the updated metadata CurrencyMetadatas::::insert(currency_id, metadata.clone()); - Self::deposit_event(Event::::CurrencyIdUpdated { currency_id, metadata }); + Self::deposit_event(Event::::CurrencyIdUpdated { + currency_id, + metadata, + }); Ok(()) } @@ -355,7 +382,9 @@ impl Pallet { pub fn get_next_token_id() -> Result { NextTokenId::::try_mutate(|current| -> Result { let id = *current; - *current = current.checked_add(One::one()).ok_or(ArithmeticError::Overflow)?; + *current = current + .checked_add(One::one()) + .ok_or(ArithmeticError::Overflow)?; Ok(id) }) } @@ -367,14 +396,21 @@ impl Pallet { name.extend_from_slice(&token_metadata.symbol); let mut symbol = "v".as_bytes().to_vec(); symbol.extend_from_slice(&token_metadata.symbol); - AssetMetadata { name, symbol, ..token_metadata } + AssetMetadata { + name, + symbol, + ..token_metadata + } } pub fn do_register_metadata( currency_id: CurrencyId, metadata: &AssetMetadata>, ) -> DispatchResult { - ensure!(CurrencyMetadatas::::get(currency_id).is_none(), Error::::CurrencyIdExisted); + ensure!( + CurrencyMetadatas::::get(currency_id).is_none(), + Error::::CurrencyIdExisted + ); CurrencyMetadatas::::insert(currency_id, metadata.clone()); @@ -421,7 +457,9 @@ impl Pallet { } pub fn asset_ids() -> Vec { - LocationToCurrencyIds::::iter_keys().map(|key| AssetId(key)).collect() + LocationToCurrencyIds::::iter_keys() + .map(|key| AssetId(key)) + .collect() } } @@ -452,23 +490,25 @@ impl CurrencyIdMapping>> for A impl CurrencyIdConversion for AssetIdMaps { fn convert_to_token(currency_id: CurrencyId) -> Result { match currency_id { - CurrencyId::VSBond(TokenSymbol::BNC, 2001, 13, 20) => - Ok(CurrencyId::Token(TokenSymbol::KSM)), + CurrencyId::VSBond(TokenSymbol::BNC, 2001, 13, 20) => { + Ok(CurrencyId::Token(TokenSymbol::KSM)) + } CurrencyId::VToken(TokenSymbol::BNC) => Ok(CurrencyId::Native(TokenSymbol::BNC)), - CurrencyId::VToken(token_symbol) | - CurrencyId::VSToken(token_symbol) | - CurrencyId::VSBond(token_symbol, ..) => Ok(CurrencyId::Token(token_symbol)), - CurrencyId::VToken2(token_id) | - CurrencyId::VSToken2(token_id) | - CurrencyId::VSBond2(token_id, ..) => Ok(CurrencyId::Token2(token_id)), + CurrencyId::VToken(token_symbol) + | CurrencyId::VSToken(token_symbol) + | CurrencyId::VSBond(token_symbol, ..) => Ok(CurrencyId::Token(token_symbol)), + CurrencyId::VToken2(token_id) + | CurrencyId::VSToken2(token_id) + | CurrencyId::VSBond2(token_id, ..) => Ok(CurrencyId::Token2(token_id)), _ => Err(()), } } fn convert_to_vtoken(currency_id: CurrencyId) -> Result { match currency_id { - CurrencyId::Token(token_symbol) | CurrencyId::Native(token_symbol) => - Ok(CurrencyId::VToken(token_symbol)), + CurrencyId::Token(token_symbol) | CurrencyId::Native(token_symbol) => { + Ok(CurrencyId::VToken(token_symbol)) + } CurrencyId::Token2(token_id) => Ok(CurrencyId::VToken2(token_id)), _ => Err(()), } @@ -496,9 +536,10 @@ impl CurrencyIdConversion for AssetIdMaps { vs_bond = CurrencyId::VSBond(TokenSymbol::BNC, 2001, 13, 20); } Ok(vs_bond) - }, - CurrencyId::Token2(token_id) => - Ok(CurrencyId::VSBond2(token_id, index, first_slot, last_slot)), + } + CurrencyId::Token2(token_id) => { + Ok(CurrencyId::VSBond2(token_id, index, first_slot, last_slot)) + } _ => Err(()), } } @@ -571,7 +612,9 @@ impl CurrencyIdRegister for AssetIdMaps { let name = scale_info::prelude::format!("Bifrost Stable Pool Token {}", pool_id) .as_bytes() .to_vec(); - let symbol = scale_info::prelude::format!("BLP{}", pool_id).as_bytes().to_vec(); + let symbol = scale_info::prelude::format!("BLP{}", pool_id) + .as_bytes() + .to_vec(); Pallet::::do_register_metadata( CurrencyId::BLP(pool_id), &AssetMetadata { diff --git a/pallets/asset-registry/src/migrations/v0.rs b/pallets/asset-registry/src/migrations/v0.rs index e194e5eef8..a922cbc66e 100644 --- a/pallets/asset-registry/src/migrations/v0.rs +++ b/pallets/asset-registry/src/migrations/v0.rs @@ -31,10 +31,16 @@ pub fn update_blp_metadata(pool_count: u32) -> Weight { let name = scale_info::prelude::format!("Bifrost Stable Pool Token {}", pool_id) .as_bytes() .to_vec(); - let symbol = scale_info::prelude::format!("BLP{}", pool_id).as_bytes().to_vec(); + let symbol = scale_info::prelude::format!("BLP{}", pool_id) + .as_bytes() + .to_vec(); CurrencyMetadatas::::insert( CurrencyId::BLP(pool_id), - &AssetMetadata { name, symbol, ..old_metadata }, + &AssetMetadata { + name, + symbol, + ..old_metadata + }, ) } } @@ -73,11 +79,11 @@ impl OnRuntimeUpgrade for InsertBNCMetadata { LocationToCurrencyIds::::insert(location, BNC); Weight::from(T::DbWeight::get().reads_writes(3 as u64 + 1, 3 as u64 + 1)) - }, + } Err(_) => { log::error!(target: LOG_TARGET, "Conversion failed from BNC_LOCATION to v4_bnc_location."); Weight::from(T::DbWeight::get().reads_writes(1 as u64 + 1, 1 as u64 + 1)) - }, + } } } diff --git a/pallets/asset-registry/src/migrations/v1.rs b/pallets/asset-registry/src/migrations/v1.rs index b74b627116..6e8dcfa661 100644 --- a/pallets/asset-registry/src/migrations/v1.rs +++ b/pallets/asset-registry/src/migrations/v1.rs @@ -72,16 +72,24 @@ impl OnRuntimeUpgrade for MigrateToV1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { - ensure!(Pallet::::on_chain_storage_version() == 0, "must upgrade linearly"); - ensure!(Pallet::::in_code_storage_version() == 1, "must upgrade linearly"); + ensure!( + Pallet::::on_chain_storage_version() == 0, + "must upgrade linearly" + ); + ensure!( + Pallet::::in_code_storage_version() == 1, + "must upgrade linearly" + ); let currency_id_to_locations_count = CurrencyIdToLocations::::iter().count(); log::info!(target: LOG_TARGET, "CurrencyIdToLocations pre-migrate storage count: {:?}", currency_id_to_locations_count); let location_to_currency_ids_count = LocationToCurrencyIds::::iter().count(); log::info!(target: LOG_TARGET, "LocationToCurrencyIds pre-migrate storage count: {:?}", location_to_currency_ids_count); - let combined_data = - (currency_id_to_locations_count as u64, location_to_currency_ids_count as u64); + let combined_data = ( + currency_id_to_locations_count as u64, + location_to_currency_ids_count as u64, + ); Ok(combined_data.encode()) } diff --git a/pallets/asset-registry/src/mock.rs b/pallets/asset-registry/src/mock.rs index 67344b21b6..0259e4375f 100644 --- a/pallets/asset-registry/src/mock.rs +++ b/pallets/asset-registry/src/mock.rs @@ -94,7 +94,9 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self.balances.into_iter().collect::>(), diff --git a/pallets/asset-registry/src/tests.rs b/pallets/asset-registry/src/tests.rs index f16a424167..74a0d2af53 100644 --- a/pallets/asset-registry/src/tests.rs +++ b/pallets/asset-registry/src/tests.rs @@ -50,7 +50,10 @@ fn register_token_metadata_should_work() { Box::new(metadata.clone()) )); - assert_eq!(CurrencyMetadatas::::get(Token2(0)), Some(metadata.clone())) + assert_eq!( + CurrencyMetadatas::::get(Token2(0)), + Some(metadata.clone()) + ) }) } @@ -139,8 +142,14 @@ fn register_multilocation_should_work() { Error::::CurrencyIdExisted ); - assert_eq!(LocationToCurrencyIds::::get(location.clone()), Some(Token2(0))); - assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); + assert_eq!( + LocationToCurrencyIds::::get(location.clone()), + Some(Token2(0)) + ); + assert_eq!( + CurrencyIdToLocations::::get(Token2(0)), + Some(location) + ); assert_eq!( CurrencyIdToWeights::::get(Token2(0)), Some(Weight::from_parts(2000_000_000, 0)) @@ -189,8 +198,14 @@ fn force_set_multilocation_should_work() { Weight::from_parts(2000_000_000, 0) )); - assert_eq!(LocationToCurrencyIds::::get(location.clone()), Some(Token2(0))); - assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); + assert_eq!( + LocationToCurrencyIds::::get(location.clone()), + Some(Token2(0)) + ); + assert_eq!( + CurrencyIdToLocations::::get(Token2(0)), + Some(location) + ); assert_eq!( CurrencyIdToWeights::::get(Token2(0)), Some(Weight::from_parts(2000_000_000, 0)) @@ -230,15 +245,17 @@ fn update_currency_metadata_should_work() { Some(minimal_balance) )); - System::assert_last_event(RuntimeEvent::AssetRegistry(crate::Event::CurrencyIdUpdated { - currency_id, - metadata: AssetMetadata { - name: name.clone(), - symbol: symbol.clone(), - decimals, - minimal_balance, + System::assert_last_event(RuntimeEvent::AssetRegistry( + crate::Event::CurrencyIdUpdated { + currency_id, + metadata: AssetMetadata { + name: name.clone(), + symbol: symbol.clone(), + decimals, + minimal_balance, + }, }, - })); + )); // Verify the updated metadata let updated_metadata = CurrencyMetadatas::::get(currency_id).unwrap(); @@ -281,10 +298,12 @@ fn update_currency_metadata_should_work_no_change() { )); // Verify the event - System::assert_last_event(RuntimeEvent::AssetRegistry(crate::Event::CurrencyIdUpdated { - currency_id, - metadata: old_metadata.clone(), - })); + System::assert_last_event(RuntimeEvent::AssetRegistry( + crate::Event::CurrencyIdUpdated { + currency_id, + metadata: old_metadata.clone(), + }, + )); // Verify the updated metadata let updated_metadata = CurrencyMetadatas::::get(currency_id).unwrap(); diff --git a/pallets/bb-bnc/Cargo.toml b/pallets/bb-bnc/Cargo.toml index 2b9f27443b..e5ebe6bd95 100644 --- a/pallets/bb-bnc/Cargo.toml +++ b/pallets/bb-bnc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bb-bnc" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/bb-bnc/rpc/Cargo.toml b/pallets/bb-bnc/rpc/Cargo.toml index 578fd700f1..e5860aa264 100644 --- a/pallets/bb-bnc/rpc/Cargo.toml +++ b/pallets/bb-bnc/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bb-bnc-rpc" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/bb-bnc/rpc/runtime-api/Cargo.toml b/pallets/bb-bnc/rpc/runtime-api/Cargo.toml index 4ec16fe077..91daec4a2e 100644 --- a/pallets/bb-bnc/rpc/runtime-api/Cargo.toml +++ b/pallets/bb-bnc/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bb-bnc-rpc-runtime-api" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/bb-bnc/rpc/src/lib.rs b/pallets/bb-bnc/rpc/src/lib.rs index f1483120d9..4b4750bd52 100644 --- a/pallets/bb-bnc/rpc/src/lib.rs +++ b/pallets/bb-bnc/rpc/src/lib.rs @@ -63,7 +63,10 @@ where C: BlockIdTo, { pub fn new(client: Arc) -> Self { - Self { client, _marker: PhantomData } + Self { + client, + _marker: PhantomData, + } } } diff --git a/pallets/bb-bnc/src/benchmarking.rs b/pallets/bb-bnc/src/benchmarking.rs index 1e3eab9b53..f6bff885f4 100644 --- a/pallets/bb-bnc/src/benchmarking.rs +++ b/pallets/bb-bnc/src/benchmarking.rs @@ -19,7 +19,7 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg(feature = "runtime-benchmarks")] -use crate::{BalanceOf, Call, Config, Pallet as BbBNC, Pallet}; +use crate::{BalanceOf, Call, Config, Pallet as BbBNC, Pallet, *}; use bifrost_primitives::{CurrencyId, TokenSymbol}; use frame_benchmarking::v2::*; use frame_support::{assert_ok, traits::EnsureOrigin}; @@ -32,6 +32,36 @@ use sp_std::vec; mod benchmarks { use super::*; + #[benchmark] + fn on_initialize() -> Result<(), BenchmarkError> { + assert_ok!(BbBNC::::set_config( + RawOrigin::Root.into(), + Some((4 * 365 * 86400 / 12u32).into()), + Some((7 * 86400 / 12u32).into()) + )); + + let rewards = vec![CurrencyId::Native(TokenSymbol::BNC)]; + + T::MultiCurrency::deposit( + CurrencyId::Native(TokenSymbol::BNC), + &account("seed", 1, 1), + BalanceOf::::unique_saturated_from(100_000_000_000_000u128), + )?; + assert_ok!(BbBNC::::notify_rewards( + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + account("seed", 1, 1), + Some((7 * 86400 / 12u32).into()), + rewards + )); + + #[block] + { + BbBNC::::on_initialize(BlockNumberFor::::from(7 * 86400 / 12u32)); + } + + Ok(()) + } + #[benchmark] fn set_config() -> Result<(), BenchmarkError> { #[extrinsic_call] @@ -170,7 +200,11 @@ mod benchmarks { )); #[extrinsic_call] - _(RawOrigin::Signed(test_account), 0, (7 * 86400 / 12u32 + 365 * 86400 / 12u32).into()); + _( + RawOrigin::Signed(test_account), + 0, + (7 * 86400 / 12u32 + 365 * 86400 / 12u32).into(), + ); Ok(()) } @@ -281,7 +315,12 @@ mod benchmarks { )?; #[extrinsic_call] - _(RawOrigin::Root, account("seed", 1, 1), Some((7 * 86400 / 12u32).into()), rewards); + _( + RawOrigin::Root, + account("seed", 1, 1), + Some((7 * 86400 / 12u32).into()), + rewards, + ); Ok(()) } @@ -419,7 +458,10 @@ mod benchmarks { >::set_block_number((2 * 365 * 86400 / 12u32).into()); #[extrinsic_call] - _(RawOrigin::Signed(test_account), CurrencyId::VToken(TokenSymbol::BNC)); + _( + RawOrigin::Signed(test_account), + CurrencyId::VToken(TokenSymbol::BNC), + ); Ok(()) } @@ -535,10 +577,17 @@ mod benchmarks { >::set_block_number((2 * 86400 / 12u32).into()); #[extrinsic_call] - _(RawOrigin::Signed(test_account), CurrencyId::VToken(TokenSymbol::BNC)); + _( + RawOrigin::Signed(test_account), + CurrencyId::VToken(TokenSymbol::BNC), + ); Ok(()) } - impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext_benchmark(), crate::mock::Runtime); + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/bb-bnc/src/incentive.rs b/pallets/bb-bnc/src/incentive.rs index 1906a23fb7..57f6b4f922 100644 --- a/pallets/bb-bnc/src/incentive.rs +++ b/pallets/bb-bnc/src/incentive.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . use crate::{traits::BbBNCInterface, *}; -use bifrost_primitives::PoolId; +use bifrost_primitives::{PoolId, BNC}; pub use pallet::*; use sp_std::collections::btree_map::BTreeMap; @@ -63,7 +63,8 @@ where impl Pallet { /// Check if the current block number is within the end time of the reward pool pub fn last_time_reward_applicable(pool_id: PoolId) -> BlockNumberFor { - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); if current_block_number < IncentiveConfigs::::get(pool_id).period_finish { current_block_number } else { @@ -76,33 +77,38 @@ impl Pallet { pool_id: PoolId, ) -> Result, BalanceOf>, DispatchError> { let mut conf = IncentiveConfigs::::get(pool_id); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let total_supply = Self::total_supply(current_block_number)?; if total_supply == BalanceOf::::zero() { return Ok(conf.reward_per_token_stored); } // Iterate over each currency and its associated reward rate - conf.reward_rate.iter().try_for_each(|(currency, &reward)| -> DispatchResult { - let increment: BalanceOf = U512::from( - Self::last_time_reward_applicable(pool_id) - .saturating_sub(conf.last_update_time) - .saturated_into::(), - ) - .checked_mul(U512::from(reward.saturated_into::())) - .ok_or(ArithmeticError::Overflow)? - .checked_mul(U512::from(T::Multiplier::get().saturated_into::())) - .ok_or(ArithmeticError::Overflow)? - .checked_div(U512::from(total_supply.saturated_into::())) - .map(|x| u128::try_from(x)) - .ok_or(ArithmeticError::Overflow)? - .map_err(|_| ArithmeticError::Overflow)? - .unique_saturated_into(); - conf.reward_per_token_stored - .entry(*currency) - .and_modify(|total_reward| *total_reward = total_reward.saturating_add(increment)) - .or_insert(increment); - Ok(()) - })?; + conf.reward_rate + .iter() + .try_for_each(|(currency, &reward)| -> DispatchResult { + let increment: BalanceOf = U512::from( + Self::last_time_reward_applicable(pool_id) + .saturating_sub(conf.last_update_time) + .saturated_into::(), + ) + .checked_mul(U512::from(reward.saturated_into::())) + .ok_or(ArithmeticError::Overflow)? + .checked_mul(U512::from(T::Multiplier::get().saturated_into::())) + .ok_or(ArithmeticError::Overflow)? + .checked_div(U512::from(total_supply.saturated_into::())) + .map(|x| u128::try_from(x)) + .ok_or(ArithmeticError::Overflow)? + .map_err(|_| ArithmeticError::Overflow)? + .unique_saturated_into(); + conf.reward_per_token_stored + .entry(*currency) + .and_modify(|total_reward| { + *total_reward = total_reward.saturating_add(increment) + }) + .or_insert(increment); + Ok(()) + })?; IncentiveConfigs::::set(pool_id, conf.clone()); Ok(conf.reward_per_token_stored) @@ -121,68 +127,57 @@ impl Pallet { } else { BTreeMap::, BalanceOf>::default() }; - reward_per_token.iter().try_for_each(|(currency, reward)| -> DispatchResult { - let increment = U256::from(bbbnc_balance.saturated_into::()) - .checked_mul(U256::from( - reward - .saturating_sub( - *UserRewardPerTokenPaid::::get(who) - .get(currency) - .unwrap_or(&BalanceOf::::zero()), - ) - .saturated_into::(), - )) - .ok_or(ArithmeticError::Overflow)? - .checked_div(U256::from(T::Multiplier::get().saturated_into::())) - .ok_or(ArithmeticError::Overflow)?; - // .map(|x| u128::try_from(x)) - // .ok_or(ArithmeticError::Overflow)? - // .map_err(|_| ArithmeticError::Overflow)? - // .unique_saturated_into(); + reward_per_token + .iter() + .try_for_each(|(currency, reward)| -> DispatchResult { + let increment = U256::from(bbbnc_balance.saturated_into::()) + .checked_mul(U256::from( + reward + .saturating_sub( + *UserRewardPerTokenPaid::::get(who) + .get(currency) + .unwrap_or(&BalanceOf::::zero()), + ) + .saturated_into::(), + )) + .ok_or(ArithmeticError::Overflow)? + .checked_div(U256::from(T::Multiplier::get().saturated_into::())) + .ok_or(ArithmeticError::Overflow)?; - // If share information is provided, calculate the reward based on the individual share - // and total share. - match share_info { - Some((share, total_share)) => { - let mut pools = UserFarmingPool::::get(who); - if share.is_zero() { - if let Some(pos) = pools.iter().position(|&x| x == pool_id) { - pools.remove(pos); - } - } else { - pools.try_push(pool_id).map_err(|_| Error::::UserFarmingPoolOverflow)?; + // If share information is provided, calculate the reward based on the individual share + // and total share. + match share_info { + Some((share, total_share)) => { + let reward = increment + .checked_mul(U256::from(share.saturated_into::())) + .ok_or(ArithmeticError::Overflow)? + .checked_div(U256::from(total_share.saturated_into::())) + .map(|x| u128::try_from(x)) + .ok_or(ArithmeticError::Overflow)? + .map_err(|_| ArithmeticError::Overflow)? + .unique_saturated_into(); + rewards + .entry(*currency) + .and_modify(|total_reward| { + *total_reward = total_reward.saturating_add(reward); + }) + .or_insert(reward); } - UserFarmingPool::::insert(who, pools); - let reward = increment - .checked_mul(U256::from(share.saturated_into::())) - .ok_or(ArithmeticError::Overflow)? - .checked_div(U256::from(total_share.saturated_into::())) - .map(|x| u128::try_from(x)) - .ok_or(ArithmeticError::Overflow)? - .map_err(|_| ArithmeticError::Overflow)? - .unique_saturated_into(); - rewards - .entry(*currency) - .and_modify(|total_reward| { - *total_reward = total_reward.saturating_add(reward); - }) - .or_insert(reward); - }, - // If no share information is provided, calculate the reward directly - None => { - let reward = u128::try_from(increment) - .map_err(|_| ArithmeticError::Overflow)? - .unique_saturated_into(); - rewards - .entry(*currency) - .and_modify(|total_reward| { - *total_reward = total_reward.saturating_add(reward); - }) - .or_insert(reward); - }, - } - Ok(()) - })?; + // If no share information is provided, calculate the reward directly + None => { + let reward = u128::try_from(increment) + .map_err(|_| ArithmeticError::Overflow)? + .unique_saturated_into(); + rewards + .entry(*currency) + .and_modify(|total_reward| { + *total_reward = total_reward.saturating_add(reward); + }) + .or_insert(reward); + } + } + Ok(()) + })?; Ok(rewards) } @@ -213,11 +208,6 @@ impl Pallet { /// Update reward for all pools pub fn update_reward_all(who: &AccountIdOf) -> DispatchResult { - UserFarmingPool::::get(who) - .iter() - .try_for_each(|&pool_id| -> DispatchResult { - Self::update_reward(pool_id, Some(who), None) - })?; Self::update_reward(BB_BNC_SYSTEM_POOL_ID, Some(who), None)?; Ok(()) } @@ -233,14 +223,26 @@ impl Pallet { return Ok(()); } // Excit earlier if balance of token is zero if let Some(rewards) = Rewards::::get(who) { - rewards.iter().try_for_each(|(currency, &reward)| -> DispatchResult { - T::MultiCurrency::transfer( - *currency, - &T::IncentivePalletId::get().into_account_truncating(), - who, - reward, - ) - })?; + rewards + .iter() + .try_for_each(|(currency, &reward)| -> DispatchResult { + T::MultiCurrency::transfer( + *currency, + &T::IncentivePalletId::get().into_account_truncating(), + who, + reward, + )?; + if currency == &BNC { + let _vtoken_value = T::VtokenMinting::mint( + who.clone(), + BNC, + reward, + BoundedVec::default(), + None, + )?; + } + Ok(()) + })?; Rewards::::remove(who); Self::deposit_event(Event::Rewarded { who: who.to_owned(), @@ -262,7 +264,8 @@ impl Pallet { }; Self::update_reward(pool_id, None, None)?; let mut conf = IncentiveConfigs::::get(pool_id); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); if current_block_number >= conf.period_finish { Self::add_reward(&account, &mut conf, &rewards, Zero::zero())?; diff --git a/pallets/bb-bnc/src/lib.rs b/pallets/bb-bnc/src/lib.rs index cfffdf1e19..ad6126afa4 100644 --- a/pallets/bb-bnc/src/lib.rs +++ b/pallets/bb-bnc/src/lib.rs @@ -32,17 +32,17 @@ pub mod incentive; pub mod traits; pub mod weights; -use bifrost_primitives::{Balance, CurrencyId, PoolId}; +use bifrost_primitives::{Balance, CurrencyId, FarmingInfo, PoolId, VtokenMintingInterface}; use frame_support::{ pallet_prelude::*, sp_runtime::{ traits::{ - AccountIdConversion, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Convert, - Saturating, UniqueSaturatedInto, Zero, + AccountIdConversion, BlockNumberProvider, CheckedAdd, CheckedDiv, CheckedMul, + CheckedSub, Convert, Saturating, UniqueSaturatedInto, Zero, }, ArithmeticError, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion, }, - PalletId, + transactional, PalletId, }; use frame_system::pallet_prelude::*; pub use incentive::*; @@ -63,6 +63,7 @@ pub type CurrencyIdOf = <::MultiCurrency as MultiCurrency< const BB_LOCK_ID: LockIdentifier = *b"bbbnclck"; const MARKUP_LOCK_ID: LockIdentifier = *b"bbbncmkp"; pub const BB_BNC_SYSTEM_POOL_ID: PoolId = u32::MAX; +pub type PositionId = u128; #[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug, TypeInfo, Default)] pub struct BbConfig { /// Minimum number of TokenType that users can lock @@ -135,13 +136,33 @@ pub mod pallet { /// Maximum number of users per refresh. #[pallet::constant] type MarkupRefreshLimit: Get; + + type VtokenMinting: VtokenMintingInterface< + AccountIdOf, + CurrencyIdOf, + BalanceOf, + >; + + /// The interface to call Farming module functions. + type FarmingInfo: FarmingInfo, CurrencyIdOf, AccountIdOf>; + + #[pallet::constant] + type OneYear: Get>; + + #[pallet::constant] + type FourYears: Get>; + + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// The minimum number of TokenType and minimum time that users can lock has been set. - ConfigSet { config: BbConfig, BlockNumberFor> }, + ConfigSet { + config: BbConfig, BlockNumberFor>, + }, /// A successful call of the `create_lock` function. Minted { /// the user who mint @@ -210,7 +231,10 @@ pub mod pallet { /// The rewards for this round have been added to the system account. RewardAdded { rewards: Vec> }, /// The user has received the reward. - Rewarded { who: AccountIdOf, rewards: Vec<(CurrencyIdOf, BalanceOf)> }, + Rewarded { + who: AccountIdOf, + rewards: Vec<(CurrencyIdOf, BalanceOf)>, + }, /// This currency_id has been refreshed. AllRefreshed { currency_id: CurrencyIdOf }, /// This currency_id has been partially refreshed. @@ -227,7 +251,10 @@ pub mod pallet { value: BalanceOf, }, /// Markup has been withdrawn. - MarkupWithdrawn { who: AccountIdOf, currency_id: CurrencyIdOf }, + MarkupWithdrawn { + who: AccountIdOf, + currency_id: CurrencyIdOf, + }, } #[pallet::error] @@ -248,8 +275,6 @@ pub mod pallet { ExceedsMaxPositions, /// No controller NoController, - /// User farming pool overflow - UserFarmingPoolOverflow, } /// Total supply of locked tokens @@ -290,7 +315,7 @@ pub mod pallet { pub type UserPointHistory = StorageDoubleMap< _, Blake2_128Concat, - u128, + PositionId, Blake2_128Concat, U256, Point, BlockNumberFor>, @@ -299,7 +324,8 @@ pub mod pallet { /// User point epoch. [who => epoch] #[pallet::storage] - pub type UserPointEpoch = StorageMap<_, Blake2_128Concat, u128, U256, ValueQuery>; + pub type UserPointEpoch = + StorageMap<_, Blake2_128Concat, PositionId, U256, ValueQuery>; /// Slope changes. [block => slope] #[pallet::storage] @@ -359,7 +385,7 @@ pub mod pallet { /// The last position of all. #[pallet::storage] - pub type Position = StorageValue<_, u128, ValueQuery>; + pub type Position = StorageValue<_, PositionId, ValueQuery>; /// Positions owned by the user. [who => positions] #[pallet::storage] @@ -367,23 +393,14 @@ pub mod pallet { _, Blake2_128Concat, AccountIdOf, - BoundedVec, - ValueQuery, - >; - - /// The pool ID of the user participating in the farming pool. - #[pallet::storage] - pub type UserFarmingPool = StorageMap< - _, - Blake2_128Concat, - AccountIdOf, - BoundedVec>, + BoundedVec, ValueQuery, >; #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: BlockNumberFor) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { + let n: BlockNumberFor = T::BlockNumberProvider::current_block_number(); let conf = IncentiveConfigs::::get(BB_BNC_SYSTEM_POOL_ID); if n == conf.period_finish { if let Some(e) = Self::notify_reward_amount( @@ -398,11 +415,13 @@ pub mod pallet { "Received invalid justification for {:?}", e, ); - Self::deposit_event(Event::NotifyRewardFailed { rewards: conf.last_reward }); + Self::deposit_event(Event::NotifyRewardFailed { + rewards: conf.last_reward, + }); } } - T::DbWeight::get().writes(1_u64) + T::WeightInfo::on_initialize() } } @@ -466,7 +485,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::increase_amount())] pub fn increase_amount( origin: OriginFor, - position: u128, + position: PositionId, value: BalanceOf, ) -> DispatchResult { let exchanger = ensure_signed(origin)?; @@ -487,7 +506,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::increase_unlock_time())] pub fn increase_unlock_time( origin: OriginFor, - position: u128, + position: PositionId, time: BlockNumberFor, ) -> DispatchResult { let exchanger = ensure_signed(origin)?; @@ -501,7 +520,7 @@ pub mod pallet { /// - `position`: The lock position #[pallet::call_index(4)] #[pallet::weight(T::WeightInfo::withdraw())] - pub fn withdraw(origin: OriginFor, position: u128) -> DispatchResult { + pub fn withdraw(origin: OriginFor, position: PositionId) -> DispatchResult { let exchanger = ensure_signed(origin)?; let user_positions = UserPositions::::get(&exchanger); ensure!(user_positions.contains(&position), Error::::LockNotExist); @@ -550,8 +569,10 @@ pub mod pallet { /// - `position`: The lock position #[pallet::call_index(7)] #[pallet::weight(T::WeightInfo::redeem_unlock())] - pub fn redeem_unlock(origin: OriginFor, position: u128) -> DispatchResult { + pub fn redeem_unlock(origin: OriginFor, position: PositionId) -> DispatchResult { let exchanger = ensure_signed(origin)?; + let user_positions = UserPositions::::get(&exchanger); + ensure!(user_positions.contains(&position), Error::::LockNotExist); Self::redeem_unlock_inner(&exchanger, position) } @@ -573,7 +594,8 @@ pub mod pallet { if !TotalLock::::contains_key(currency_id) { TotalLock::::insert(currency_id, BalanceOf::::zero()); } - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); MarkupCoefficient::::insert( currency_id, MarkupCoefficientInfo { @@ -634,7 +656,7 @@ pub mod pallet { impl Pallet { pub fn _checkpoint( who: &AccountIdOf, - position: u128, + position: PositionId, old_locked: LockedBalance, BlockNumberFor>, new_locked: LockedBalance, BlockNumberFor>, ) -> DispatchResult { @@ -644,7 +666,8 @@ pub mod pallet { let mut u_new = Point::, BlockNumberFor>::default(); let mut new_dslope = 0_i128; let mut g_epoch: U256 = Epoch::::get(); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); if old_locked.end > current_block_number && old_locked.amount > BalanceOf::::zero() { u_old.slope = U256::from(old_locked.amount.saturated_into::()) @@ -656,8 +679,8 @@ pub mod pallet { u_old.bias = u_old .slope .checked_mul( - (old_locked.end.saturated_into::() as i128) - - (current_block_number.saturated_into::() as i128), + (old_locked.end.saturated_into::() as i128) + - (current_block_number.saturated_into::() as i128), ) .ok_or(ArithmeticError::Overflow)?; } @@ -671,8 +694,8 @@ pub mod pallet { u_new.bias = u_new .slope .checked_mul( - (new_locked.end.saturated_into::() as i128) - - (current_block_number.saturated_into::() as i128), + (new_locked.end.saturated_into::() as i128) + - (current_block_number.saturated_into::() as i128), ) .ok_or(ArithmeticError::Overflow)?; } @@ -703,7 +726,9 @@ pub mod pallet { .checked_mul(&T::Week::get()) .ok_or(ArithmeticError::Overflow)?; for _i in 0..255 { - t_i = t_i.checked_add(&T::Week::get()).ok_or(ArithmeticError::Overflow)?; + t_i = t_i + .checked_add(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)?; let mut d_slope = Zero::zero(); if t_i > current_block_number { t_i = current_block_number @@ -725,8 +750,10 @@ pub mod pallet { ) .ok_or(ArithmeticError::Overflow)?; - last_point.slope = - last_point.slope.checked_add(d_slope).ok_or(ArithmeticError::Overflow)?; + last_point.slope = last_point + .slope + .checked_add(d_slope) + .ok_or(ArithmeticError::Overflow)?; if last_point.slope < 0_i128 { //This cannot happen - just in case last_point.slope = 0_i128 @@ -738,7 +765,9 @@ pub mod pallet { last_checkpoint = t_i; last_point.block = t_i; - g_epoch = g_epoch.checked_add(U256::one()).ok_or(ArithmeticError::Overflow)?; + g_epoch = g_epoch + .checked_add(U256::one()) + .ok_or(ArithmeticError::Overflow)?; // Fill for the current block, if applicable if t_i == current_block_number { @@ -772,19 +801,22 @@ pub mod pallet { if old_locked.end > current_block_number { // old_dslope was - u_old.slope, so we cancel that - old_dslope = - old_dslope.checked_add(u_old.slope).ok_or(ArithmeticError::Overflow)?; + old_dslope = old_dslope + .checked_add(u_old.slope) + .ok_or(ArithmeticError::Overflow)?; if new_locked.end == old_locked.end { - old_dslope = - old_dslope.checked_sub(u_new.slope).ok_or(ArithmeticError::Overflow)?; + old_dslope = old_dslope + .checked_sub(u_new.slope) + .ok_or(ArithmeticError::Overflow)?; } // It was a new deposit, not extension SlopeChanges::::insert(old_locked.end, old_dslope); } if new_locked.end > current_block_number { if new_locked.end > old_locked.end { - new_dslope = - new_dslope.checked_sub(u_new.slope).ok_or(ArithmeticError::Overflow)?; + new_dslope = new_dslope + .checked_sub(u_new.slope) + .ok_or(ArithmeticError::Overflow)?; SlopeChanges::::insert(new_locked.end, new_dslope); } // else: we recorded it already in old_dslope @@ -804,19 +836,25 @@ pub mod pallet { pub fn _deposit_for( who: &AccountIdOf, - position: u128, + position: PositionId, value: BalanceOf, unlock_time: BlockNumberFor, locked_balance: LockedBalance, BlockNumberFor>, ) -> DispatchResult { - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let mut _locked = locked_balance; let supply_before = Supply::::get(); - let supply_after = supply_before.checked_add(value).ok_or(ArithmeticError::Overflow)?; + let supply_after = supply_before + .checked_add(value) + .ok_or(ArithmeticError::Overflow)?; Supply::::set(supply_after); let old_locked = _locked.clone(); - _locked.amount = _locked.amount.checked_add(value).ok_or(ArithmeticError::Overflow)?; + _locked.amount = _locked + .amount + .checked_add(value) + .ok_or(ArithmeticError::Overflow)?; if unlock_time != Zero::zero() { _locked.end = unlock_time } @@ -827,7 +865,10 @@ pub mod pallet { let new_locked_balance = UserLocked::::get(who) .checked_add(value) .ok_or(ArithmeticError::Overflow)?; - ensure!(new_locked_balance <= free_balance, Error::::NotEnoughBalance); + ensure!( + new_locked_balance <= free_balance, + Error::::NotEnoughBalance + ); Self::set_ve_locked(who, new_locked_balance)?; } @@ -847,15 +888,19 @@ pub mod pallet { end: _locked.end, now: current_block_number, }); - Self::deposit_event(Event::Supply { supply_before, supply: supply_after }); + Self::deposit_event(Event::Supply { + supply_before, + supply: supply_after, + }); Ok(()) } // Get the current voting power for `position` pub(crate) fn balance_of_position_current_block( - position: u128, + position: PositionId, ) -> Result, DispatchError> { - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let u_epoch = UserPointEpoch::::get(position); if u_epoch == U256::zero() { return Ok(Zero::zero()); @@ -889,10 +934,11 @@ pub mod pallet { // Measure voting power of `position` at block height `block` pub(crate) fn balance_of_position_at( - position: u128, + position: PositionId, block: BlockNumberFor, ) -> Result, DispatchError> { - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); ensure!(block <= current_block_number, Error::::Expired); // Binary search @@ -913,7 +959,9 @@ pub mod pallet { if UserPointHistory::::get(position, _mid).block <= block { _min = _mid } else { - _max = _mid.checked_sub(U256::one()).ok_or(ArithmeticError::Overflow)? + _max = _mid + .checked_sub(U256::one()) + .ok_or(ArithmeticError::Overflow)? } } @@ -974,7 +1022,7 @@ pub mod pallet { pub fn markup_calc( who: &AccountIdOf, - position: u128, + position: PositionId, mut old_locked: LockedBalance, BlockNumberFor>, mut new_locked: LockedBalance, BlockNumberFor>, user_markup_info: Option<&UserMarkupInfo>, @@ -1006,11 +1054,14 @@ pub mod pallet { ensure!(!value.is_zero(), Error::::ArgumentsError); TotalLock::::try_mutate(currency_id, |total_lock| -> DispatchResult { - *total_lock = total_lock.checked_add(value).ok_or(ArithmeticError::Overflow)?; + *total_lock = total_lock + .checked_add(value) + .ok_or(ArithmeticError::Overflow)?; Ok(()) })?; - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let mut user_markup_info = UserMarkupInfos::::get(&who).unwrap_or_default(); let mut locked_token = @@ -1038,11 +1089,13 @@ pub mod pallet { let currency_id_markup_coefficient: FixedU128 = left.checked_add(&right).ok_or(ArithmeticError::Overflow)?; - let new_markup_coefficient = - match markup_coefficient.hardcap.cmp(¤cy_id_markup_coefficient) { - Ordering::Less => markup_coefficient.hardcap, - Ordering::Equal | Ordering::Greater => currency_id_markup_coefficient, - }; + let new_markup_coefficient = match markup_coefficient + .hardcap + .cmp(¤cy_id_markup_coefficient) + { + Ordering::Less => markup_coefficient.hardcap, + Ordering::Equal | Ordering::Greater => currency_id_markup_coefficient, + }; Self::update_markup_info( &who, user_markup_info @@ -1072,7 +1125,11 @@ pub mod pallet { )?; // Locked cannot be updated because it is markup, not a lock vBNC - Self::deposit_event(Event::MarkupDeposited { who: who.clone(), currency_id, value }); + Self::deposit_event(Event::MarkupDeposited { + who: who.clone(), + currency_id, + value, + }); Ok(()) } @@ -1094,8 +1151,9 @@ pub mod pallet { &mut user_markup_info, ); TotalLock::::try_mutate(currency_id, |total_lock| -> DispatchResult { - *total_lock = - total_lock.checked_sub(locked_token.amount).ok_or(ArithmeticError::Overflow)?; + *total_lock = total_lock + .checked_sub(locked_token.amount) + .ok_or(ArithmeticError::Overflow)?; Ok(()) })?; T::MultiCurrency::remove_lock(MARKUP_LOCK_ID, currency_id, &who)?; @@ -1116,14 +1174,18 @@ pub mod pallet { }, )?; - Self::deposit_event(Event::MarkupWithdrawn { who: who.clone(), currency_id }); + Self::deposit_event(Event::MarkupWithdrawn { + who: who.clone(), + currency_id, + }); Ok(()) } pub fn refresh_inner(currency_id: CurrencyIdOf) -> DispatchResult { let markup_coefficient = MarkupCoefficient::::get(currency_id).ok_or(Error::::ArgumentsError)?; - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let limit = T::MarkupRefreshLimit::get(); let mut all_refreshed = true; let mut refresh_count = 0; @@ -1160,11 +1222,13 @@ pub mod pallet { let mut user_markup_info = UserMarkupInfos::::get(&who).ok_or(Error::::LockNotExist)?; - let new_markup_coefficient = - match markup_coefficient.hardcap.cmp(¤cy_id_markup_coefficient) { - Ordering::Less => markup_coefficient.hardcap, - Ordering::Equal | Ordering::Greater => currency_id_markup_coefficient, - }; + let new_markup_coefficient = match markup_coefficient + .hardcap + .cmp(¤cy_id_markup_coefficient) + { + Ordering::Less => markup_coefficient.hardcap, + Ordering::Equal | Ordering::Greater => currency_id_markup_coefficient, + }; Self::update_markup_info( &who, user_markup_info @@ -1213,7 +1277,7 @@ pub mod pallet { pub fn withdraw_no_ensure( who: &AccountIdOf, - position: u128, + position: PositionId, mut _locked: LockedBalance, BlockNumberFor>, if_fast: Option, ) -> DispatchResult { @@ -1224,7 +1288,9 @@ pub mod pallet { Locked::::insert(position, _locked.clone()); let supply_before = Supply::::get(); - let supply_after = supply_before.checked_sub(value).ok_or(ArithmeticError::Overflow)?; + let supply_after = supply_before + .checked_sub(value) + .ok_or(ArithmeticError::Overflow)?; Supply::::set(supply_after); // BNC should be transferred before checkpoint @@ -1232,8 +1298,9 @@ pub mod pallet { positions.retain(|&x| x != position); }); UserPointEpoch::::remove(position); - let new_locked_balance = - UserLocked::::get(who).checked_sub(value).ok_or(ArithmeticError::Underflow)?; + let new_locked_balance = UserLocked::::get(who) + .checked_sub(value) + .ok_or(ArithmeticError::Underflow)?; Self::set_ve_locked(who, new_locked_balance)?; if let Some(fast) = if_fast { if fast != FixedU128::zero() { @@ -1241,15 +1308,24 @@ pub mod pallet { T::TokenType::get(), who, &T::BuyBackAccount::get().into_account_truncating(), - fast.checked_mul_int(value).ok_or(ArithmeticError::Overflow)?, + fast.checked_mul_int(value) + .ok_or(ArithmeticError::Overflow)?, )?; } } Self::_checkpoint(who, position, old_locked, _locked.clone())?; - Self::deposit_event(Event::Withdrawn { who: who.clone(), position, value }); - Self::deposit_event(Event::Supply { supply_before, supply: supply_after }); + T::FarmingInfo::refresh_gauge_pool(who)?; + Self::deposit_event(Event::Withdrawn { + who: who.clone(), + position, + value, + }); + Self::deposit_event(Event::Supply { + supply_before, + supply: supply_after, + }); Ok(()) } @@ -1259,12 +1335,12 @@ pub mod pallet { FixedU128::checked_from_integer(remaining_blocks.saturated_into::()) .and_then(|x| { x.checked_add(&FixedU128::checked_from_integer( - T::Week::get().saturated_into::().checked_mul(52)?, + T::OneYear::get().saturated_into::(), )?) }) // one years .and_then(|x| { x.checked_div(&FixedU128::checked_from_integer( - T::Week::get().saturated_into::().checked_mul(208)?, + T::FourYears::get().saturated_into::(), )?) }) // four years .and_then(|x| Some(x.saturating_pow(2))) @@ -1272,9 +1348,10 @@ pub mod pallet { } /// This function will check the lock and redeem it regardless of whether it has expired. - pub fn redeem_unlock_inner(who: &AccountIdOf, position: u128) -> DispatchResult { + pub fn redeem_unlock_inner(who: &AccountIdOf, position: PositionId) -> DispatchResult { let mut _locked = Locked::::get(position); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); ensure!(_locked.end > current_block_number, Error::::Expired); let fast = Self::redeem_commission(_locked.end - current_block_number)?; Self::withdraw_no_ensure(who, position, _locked, Some(fast)) @@ -1285,7 +1362,7 @@ pub mod pallet { 0 => { // Can not set lock to zero, should remove it. T::MultiCurrency::remove_lock(BB_LOCK_ID, T::TokenType::get(), who)?; - }, + } _ => { T::MultiCurrency::set_lock( BB_LOCK_ID, @@ -1293,10 +1370,361 @@ pub mod pallet { who, new_locked_balance, )?; - }, + } }; UserLocked::::set(who, new_locked_balance); Ok(()) } } } + +impl BbBNCInterface, CurrencyIdOf, BalanceOf, BlockNumberFor> + for Pallet +{ + #[transactional] + fn create_lock_inner( + who: &AccountIdOf, + value: BalanceOf, + unlock_time: BlockNumberFor, + ) -> DispatchResult { + let new_position = Position::::get(); + let mut user_positions = UserPositions::::get(who); + user_positions + .try_push(new_position) + .map_err(|_| Error::::ExceedsMaxPositions)?; + UserPositions::::insert(who, user_positions); + Position::::set(new_position + 1); + + let bb_config = BbConfigs::::get(); + ensure!(value >= bb_config.min_mint, Error::::BelowMinimumMint); + + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); + let _locked: LockedBalance, BlockNumberFor> = + Locked::::get(new_position); + let real_unlock_time: BlockNumberFor = unlock_time + .saturating_add(current_block_number) + .checked_div(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)? + .saturating_add(1u32.into()) + .checked_mul(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)?; + + ensure!( + real_unlock_time >= bb_config.min_block.saturating_add(current_block_number), + Error::::ArgumentsError + ); + let max_block = T::MaxBlock::get() + .saturating_add(current_block_number) + .checked_div(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)? + .saturating_add(1u32.into()) + .checked_mul(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)?; + ensure!(real_unlock_time <= max_block, Error::::ArgumentsError); + ensure!( + _locked.amount == BalanceOf::::zero(), + Error::::LockExist + ); // Withdraw old tokens first + + Self::_deposit_for(who, new_position, value, real_unlock_time, _locked)?; + T::FarmingInfo::refresh_gauge_pool(who)?; + Self::deposit_event(Event::LockCreated { + who: who.to_owned(), + position: new_position, + value: value, + unlock_time: real_unlock_time, + }); + Ok(()) + } + + #[transactional] + fn increase_unlock_time_inner( + who: &AccountIdOf, + position: u128, + unlock_time: BlockNumberFor, + ) -> DispatchResult { + let bb_config = BbConfigs::::get(); + let locked: LockedBalance, BlockNumberFor> = Locked::::get(position); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); + + ensure!(locked.end > current_block_number, Error::::Expired); // Cannot add to expired/non-existent lock + let real_unlock_time: BlockNumberFor = unlock_time + .saturating_add(locked.end) + .checked_div(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)? + .saturating_add(1u32.into()) + .checked_mul(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)?; + ensure!( + real_unlock_time >= bb_config.min_block.saturating_add(current_block_number), + Error::::ArgumentsError + ); + let max_block = T::MaxBlock::get() + .saturating_add(current_block_number) + .checked_div(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)? + .saturating_add(1u32.into()) + .checked_mul(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)?; + ensure!(real_unlock_time <= max_block, Error::::ArgumentsError); + ensure!( + locked.amount > BalanceOf::::zero(), + Error::::LockNotExist + ); + + Self::_deposit_for( + who, + position, + BalanceOf::::zero(), + real_unlock_time, + locked, + )?; + T::FarmingInfo::refresh_gauge_pool(who)?; + Self::deposit_event(Event::UnlockTimeIncreased { + who: who.to_owned(), + position, + unlock_time: real_unlock_time, + }); + Ok(()) + } + + #[transactional] + fn increase_amount_inner( + who: &AccountIdOf, + position: u128, + value: BalanceOf, + ) -> DispatchResult { + let bb_config = BbConfigs::::get(); + ensure!(value >= bb_config.min_mint, Error::::BelowMinimumMint); + let _locked: LockedBalance, BlockNumberFor> = Locked::::get(position); + ensure!( + _locked.amount > BalanceOf::::zero(), + Error::::LockNotExist + ); // Need to be executed after create_lock + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); + ensure!(_locked.end > current_block_number, Error::::Expired); // Cannot add to expired/non-existent lock + Self::_deposit_for(who, position, value, Zero::zero(), _locked)?; + T::FarmingInfo::refresh_gauge_pool(who)?; + Self::deposit_event(Event::AmountIncreased { + who: who.to_owned(), + position, + value, + }); + Ok(()) + } + + #[transactional] + fn deposit_for(who: &AccountIdOf, position: u128, value: BalanceOf) -> DispatchResult { + let _locked: LockedBalance, BlockNumberFor> = Locked::::get(position); + Self::_deposit_for(who, position, value, Zero::zero(), _locked) + } + + #[transactional] + fn withdraw_inner(who: &AccountIdOf, position: u128) -> DispatchResult { + let mut _locked = Locked::::get(position); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); + ensure!(current_block_number >= _locked.end, Error::::Expired); + Self::withdraw_no_ensure(who, position, _locked, None) + } + + fn balance_of( + who: &AccountIdOf, + time: Option>, + ) -> Result, DispatchError> { + match time { + Some(_t) => Self::balance_of_at(who, _t), + None => Self::balance_of_current_block(who), + } + } + + fn find_block_epoch(_block: BlockNumberFor, max_epoch: U256) -> U256 { + let mut _min = U256::zero(); + let mut _max = max_epoch; + for _i in 0..128 { + if _min >= _max { + break; + } + let _mid = (_min + _max + 1) / 2; + + if PointHistory::::get(_mid).block <= _block { + _min = _mid + } else { + _max = _mid - 1 + } + } + _min + } + + fn total_supply(t: BlockNumberFor) -> Result, DispatchError> { + let g_epoch: U256 = Epoch::::get(); + let last_point = PointHistory::::get(g_epoch); + Self::supply_at(last_point, t) + } + + fn supply_at( + point: Point, BlockNumberFor>, + t: BlockNumberFor, + ) -> Result, DispatchError> { + let mut last_point = point; + let mut t_i: BlockNumberFor = last_point + .block + .checked_div(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)? + .checked_mul(&T::Week::get()) + .ok_or(ArithmeticError::Overflow)?; + for _i in 0..255 { + t_i += T::Week::get(); + let mut d_slope = Zero::zero(); + if t_i > t { + t_i = t + } else { + d_slope = SlopeChanges::::get(t_i) + } + + last_point.bias = last_point + .bias + .checked_sub( + last_point + .slope + .checked_mul( + t_i.checked_sub(&last_point.block) + .ok_or(ArithmeticError::Overflow)? + .saturated_into::() + .unique_saturated_into(), + ) + .ok_or(ArithmeticError::Overflow)?, + ) + .ok_or(ArithmeticError::Overflow)?; + + if t_i == t { + break; + } + last_point.slope += d_slope; + last_point.block = t_i + } + + if last_point.bias < 0_i128 { + last_point.bias = 0_i128 + } + Ok(T::VoteWeightMultiplier::get() + .checked_mul((last_point.bias as u128).unique_saturated_into()) + .ok_or(ArithmeticError::Overflow)?) + } + + #[transactional] + fn auto_notify_reward( + pool_id: PoolId, + n: BlockNumberFor, + rewards: Vec>, + ) -> DispatchResult { + let conf = IncentiveConfigs::::get(pool_id); + // If the period is reached or not set, the reward will be notified. + if n == conf.period_finish || conf.period_finish == Default::default() { + Self::notify_reward_amount(pool_id, &conf.incentive_controller, rewards)?; + } + Ok(()) + } + + #[transactional] + fn update_reward( + pool_id: PoolId, + who: Option<&AccountIdOf>, + share_info: Option<(BalanceOf, BalanceOf)>, + ) -> DispatchResult { + Self::update_reward(pool_id, who, share_info) + } + + fn get_rewards( + pool_id: PoolId, + who: &AccountIdOf, + share_info: Option<(BalanceOf, BalanceOf)>, + ) -> DispatchResult { + Self::get_rewards_inner(pool_id, who, share_info) + } + + fn set_incentive( + pool_id: PoolId, + rewards_duration: Option>, + controller: Option>, + ) { + let mut incentive_config = IncentiveConfigs::::get(pool_id); + + if let Some(rewards_duration) = rewards_duration { + incentive_config.rewards_duration = rewards_duration; + }; + if let Some(controller) = controller { + incentive_config.incentive_controller = Some(controller.clone()); + } + IncentiveConfigs::::set(pool_id, incentive_config.clone()); + Self::deposit_event(Event::IncentiveSet { incentive_config }); + } + + #[transactional] + fn add_reward( + who: &AccountIdOf, + conf: &mut IncentiveConfig< + CurrencyIdOf, + BalanceOf, + BlockNumberFor, + AccountIdOf, + >, + rewards: &Vec>, + remaining: BalanceOf, + ) -> DispatchResult { + rewards.iter().try_for_each(|currency| -> DispatchResult { + let reward = T::MultiCurrency::free_balance(*currency, who); + let mut total_reward: BalanceOf = reward; + if remaining != BalanceOf::::zero() { + let leftover: BalanceOf = conf + .reward_rate + .get(currency) + .unwrap_or(&Zero::zero()) + .checked_mul(&remaining) + .ok_or(ArithmeticError::Overflow)?; + total_reward = total_reward.saturating_add(leftover); + } + let currency_amount = T::MultiCurrency::free_balance( + *currency, + &T::IncentivePalletId::get().into_account_truncating(), + ); + // Make sure the new reward is less than or equal to the reward owned by the + // IncentivePalletId + ensure!( + total_reward <= currency_amount.saturating_add(reward), + Error::::NotEnoughBalance + ); + let new_reward = total_reward + .checked_div(T::BlockNumberToBalance::convert(conf.rewards_duration)) + .ok_or(ArithmeticError::Overflow)?; + conf.reward_rate + .entry(*currency) + .and_modify(|total_reward| { + *total_reward = new_reward; + }) + .or_insert(new_reward); + // If the reward in this round is 0, it will only be recorded without transfer. + if reward == BalanceOf::::zero() { + return Ok(()); + } + T::MultiCurrency::transfer( + *currency, + who, + &T::IncentivePalletId::get().into_account_truncating(), + reward, + ) + }) + } + + #[transactional] + fn notify_reward( + pool_id: PoolId, + who: &Option>, + rewards: Vec>, + ) -> DispatchResult { + Self::notify_reward_amount(pool_id, who, rewards) + } +} diff --git a/pallets/bb-bnc/src/mock.rs b/pallets/bb-bnc/src/mock.rs index e82b13f68f..09a82e7779 100644 --- a/pallets/bb-bnc/src/mock.rs +++ b/pallets/bb-bnc/src/mock.rs @@ -217,6 +217,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } ord_parameter_types! { @@ -232,6 +233,8 @@ impl bifrost_asset_registry::Config for Runtime { parameter_types! { pub const BbBNCTokenType: CurrencyId = VBNC; pub const Week: BlockNumber = 50400; // a week + pub const FourYears: BlockNumber = 10483200; // four years + pub const OneYear: BlockNumber = 2620800; // one year pub const MaxBlock: BlockNumber = 10512000; // four years pub const Multiplier: Balance = 10_u128.pow(12); pub const VoteWeightMultiplier: Balance = 1; @@ -254,6 +257,11 @@ impl bb_bnc::Config for Runtime { type VoteWeightMultiplier = VoteWeightMultiplier; type MaxPositions = MaxPositions; type MarkupRefreshLimit = MarkupRefreshLimit; + type VtokenMinting = VtokenMinting; + type FarmingInfo = (); + type FourYears = FourYears; + type OneYear = OneYear; + type BlockNumberProvider = System; } pub struct ParachainId; @@ -319,6 +327,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = (); type AssetIdMaps = AssetIdMaps; type TreasuryAccount = TreasuryAccount; + type BlockNumberProvider = System; } parameter_types! { @@ -398,7 +407,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -423,7 +434,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/bb-bnc/src/tests.rs b/pallets/bb-bnc/src/tests.rs index 9cf05415ae..3b0e142e01 100644 --- a/pallets/bb-bnc/src/tests.rs +++ b/pallets/bb-bnc/src/tests.rs @@ -31,186 +31,394 @@ const POSITIONID1: u128 = 1; #[test] fn create_lock_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + (4 * 365 * 86400 - 5 * 86400) / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(1)), - Point { bias: 9972575751740, slope: 951293, block: 20, amount: 10000000000000 } - ); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(9972575751740)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(9972575751740)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + (4 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(1)), + Point { + bias: 9972575751740, + slope: 951293, + block: 20, + amount: 10000000000000 + } + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(9972575751740) + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(9972575751740) + ); + }); +} + +#[test] +fn create_lock_should_not_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(10_000_000_000_000), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + (4 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_noop!( + BbBNC::create_lock_inner( + &BOB, + 10_000, + System::block_number() + (4 * 365 * 86400 - 5 * 86400) / 12, + ), + Error::::BelowMinimumMint + ); + let positions: Vec = (0..10).collect(); + UserPositions::::set(BOB, BoundedVec::try_from(positions).unwrap()); // Simulate max positions already reached + assert_noop!( + BbBNC::create_lock_inner( + &BOB, + 5_000_000_000_000, + System::block_number() + (2 * 365 * 86400) / 12 + ), + Error::::ExceedsMaxPositions + ); + }); } #[test] fn create_multi_locks_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + (4 * 365 * 86400 - 5 * 86400) / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(1)), - Point { bias: 9972575751740, slope: 951293, block: 20, amount: 10000000000000 } - ); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(9972575751740)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(9972575751740)); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 5_000_000_000_000, - System::block_number() + (2 * 365 * 86400 - 5 * 86400) / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID1, U256::from(1)), - Point { bias: 2493136560680, slope: 475646, block: 20, amount: 5000000000000 } - ); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(12465712312420)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(12465712312420)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + (4 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(1)), + Point { + bias: 9972575751740, + slope: 951293, + block: 20, + amount: 10000000000000 + } + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(9972575751740) + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(9972575751740) + ); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 5_000_000_000_000, + System::block_number() + (2 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID1, U256::from(1)), + Point { + bias: 2493136560680, + slope: 475646, + block: 20, + amount: 5000000000000 + } + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(12465712312420) + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(12465712312420) + ); + }); } #[test] fn increase_unlock_time_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 7 * 86400 / 12); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, - )); - assert_eq!(Locked::::get(POSITIONID0).end, 7963200); - assert_noop!( - BbBNC::increase_unlock_time( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 7 * 86400 / 12); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_eq!(Locked::::get(POSITIONID0).end, 7963200); + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + System::block_number() + 365 * 86400 / 12 + ), + Error::::ArgumentsError + ); + assert_ok!(BbBNC::increase_unlock_time( RuntimeOrigin::signed(BOB), POSITIONID0, - System::block_number() + 365 * 86400 / 12 - ), - Error::::ArgumentsError - ); - assert_ok!(BbBNC::increase_unlock_time( - RuntimeOrigin::signed(BOB), - POSITIONID0, - (365 * 86400 - 5 * 86400) / 12 - ),); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(1)), - Point { bias: 7527391250400, slope: 951293, block: 50400, amount: 10000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).end, 10584000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(10020539944800)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(10020539944800)); - }); + (365 * 86400 - 5 * 86400) / 12 + ),); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(1)), + Point { + bias: 7527391250400, + slope: 951293, + block: 50400, + amount: 10000000000000 + } + ); + assert_eq!(Locked::::get(POSITIONID0).end, 10584000); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(10020539944800) + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(10020539944800) + ); + }); +} + +#[test] +fn increase_unlock_time_should_not_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 7 * 86400 / 12); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + System::block_number() + 365 * 86400 / 12 + ), + Error::::LockNotExist + ); + + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, + )); + + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + System::block_number() + (10 * 365 * 86400) / 12 // Far beyond the maximum + ), + Error::::ArgumentsError + ); + + System::set_block_number(System::block_number() + (5 * 365 * 86400) / 12); + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + 365 * 86400 / 12 + ), + Error::::Expired + ); + }); } #[test] fn increase_unlock_time_should_work2() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 7 * 86400 / 12); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, - )); - assert_eq!(Locked::::get(POSITIONID0).end, 7963200); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(7527391250400)); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 5_000_000_000_000, - System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, - )); - assert_eq!(Locked::::get(POSITIONID1).end, 7963200); - assert_noop!( - BbBNC::increase_unlock_time( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 7 * 86400 / 12); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_eq!(Locked::::get(POSITIONID0).end, 7963200); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(7527391250400) + ); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 5_000_000_000_000, + System::block_number() + (3 * 365 * 86400 - 5 * 86400) / 12, + )); + assert_eq!(Locked::::get(POSITIONID1).end, 7963200); + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + System::block_number() + 365 * 86400 / 12 + ), + Error::::ArgumentsError + ); + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID1, + System::block_number() + 365 * 86400 / 12 + ), + Error::::ArgumentsError + ); + assert_ok!(BbBNC::increase_unlock_time( RuntimeOrigin::signed(BOB), POSITIONID0, - System::block_number() + 365 * 86400 / 12 - ), - Error::::ArgumentsError - ); - assert_noop!( - BbBNC::increase_unlock_time( + (365 * 86400 - 5 * 86400) / 12 + )); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(13784231613600) + ); + assert_ok!(BbBNC::increase_unlock_time( RuntimeOrigin::signed(BOB), POSITIONID1, - System::block_number() + 365 * 86400 / 12 - ), - Error::::ArgumentsError - ); - assert_ok!(BbBNC::increase_unlock_time( - RuntimeOrigin::signed(BOB), - POSITIONID0, - (365 * 86400 - 5 * 86400) / 12 - )); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(13784231613600)); - assert_ok!(BbBNC::increase_unlock_time( - RuntimeOrigin::signed(BOB), - POSITIONID1, - (365 * 86400 - 5 * 86400) / 12 - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(1)), - Point { bias: 7527391250400, slope: 951293, block: 50400, amount: 10000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).end, 10584000); - assert_eq!( - UserPointHistory::::get(POSITIONID1, U256::from(1)), - Point { bias: 3763691668800, slope: 475646, block: 50400, amount: 5000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID1).end, 10584000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(15030804650400)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(15030804650400)); - }); + (365 * 86400 - 5 * 86400) / 12 + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(1)), + Point { + bias: 7527391250400, + slope: 951293, + block: 50400, + amount: 10000000000000 + } + ); + assert_eq!(Locked::::get(POSITIONID0).end, 10584000); + assert_eq!( + UserPointHistory::::get(POSITIONID1, U256::from(1)), + Point { + bias: 3763691668800, + slope: 475646, + block: 50400, + amount: 5000000000000 + } + ); + assert_eq!(Locked::::get(POSITIONID1).end, 10584000); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(15030804650400) + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(15030804650400) + ); + }); } #[test] fn update_reward() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - - System::set_block_number(System::block_number() + 40); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 100_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_eq!(BbBNC::balance_of(&BOB, None), Ok(25407883680)); - assert_eq!(BbBNC::balance_of_position_current_block(0), Ok(25407883680)); - assert_ok!(BbBNC::deposit_for(&BOB, 0, 100_000_000_000)); - assert_ok!(BbBNC::update_reward(BB_BNC_SYSTEM_POOL_ID, Some(&BOB), None)); // TODO - - assert_eq!(BbBNC::balance_of(&BOB, None), Ok(50818438500)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(50818438500)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + + System::set_block_number(System::block_number() + 40); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 100_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_eq!(BbBNC::balance_of(&BOB, None), Ok(25407883680)); + assert_eq!(BbBNC::balance_of_position_current_block(0), Ok(25407883680)); + assert_ok!(BbBNC::deposit_for(&BOB, 0, 100_000_000_000)); + assert_ok!(BbBNC::update_reward( + BB_BNC_SYSTEM_POOL_ID, + Some(&BOB), + None + )); + + assert_eq!(BbBNC::balance_of(&BOB, None), Ok(50818438500)); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(50818438500) + ); + }); } fn asset_registry() { - let items = vec![(KSM, 10 * milli::(KSM)), (BNC, 10 * milli::(BNC))]; + let items = vec![ + (KSM, 10 * milli::(KSM)), + (BNC, 10 * milli::(BNC)), + ]; for (currency_id, metadata) in items.iter().map(|(currency_id, minimal_balance)| { ( currency_id, AssetMetadata { - name: currency_id.name().map(|s| s.as_bytes().to_vec()).unwrap_or_default(), - symbol: currency_id.symbol().map(|s| s.as_bytes().to_vec()).unwrap_or_default(), + name: currency_id + .name() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), + symbol: currency_id + .symbol() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), decimals: currency_id.decimals().unwrap_or_default(), minimal_balance: *minimal_balance, }, @@ -222,577 +430,1219 @@ fn asset_registry() { #[test] fn notify_reward_amount() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - - System::set_block_number(System::block_number() + 40); - assert_ok!(BbBNC::get_rewards(RuntimeOrigin::signed(BOB))); // balance of veBNC is 0 - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 20_000_000_000, - System::block_number() + (4 * 365 * 86400 - 7 * 86400) / 12, - )); - assert_eq!(Tokens::free_balance(KSM, &BOB), 0); - // balance of veBNC is not 0 - assert_ok!(BbBNC::get_rewards(RuntimeOrigin::signed(BOB))); - assert_ok!(BbBNC::increase_amount(RuntimeOrigin::signed(BOB), 0, 80_000_000_000)); - assert_eq!(BbBNC::balance_of(&BOB, None), Ok(99715627680)); - - let rewards = vec![KSM]; - assert_ok!(BbBNC::notify_rewards( - RuntimeOrigin::root(), - ALICE, - Some(7 * 86400 / 12), - rewards.clone() - )); - assert_eq!(Tokens::free_balance(KSM, &BOB), 0); - System::set_block_number(System::block_number() + 20); - assert_eq!(Tokens::free_balance(KSM, &BOB), 0); - assert_ok!(BbBNC::get_rewards(RuntimeOrigin::signed(BOB))); - assert_eq!(Tokens::free_balance(KSM, &BOB), 396819); - System::set_block_number(System::block_number() + 7 * 86400 / 12); - assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &BOB, None)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 999986398); - assert_ok!(Tokens::deposit(KSM, &ALICE, 1_000_000_000)); - assert_ok!(BbBNC::notify_rewards( - RuntimeOrigin::root(), - ALICE, - Some(7 * 86400 / 12), - rewards - )); - assert_ok!(BbBNC::create_lock_inner( - &CHARLIE, - 100_000_000_000, - (4 * 365 * 86400 - 7 * 86400) / 12 - )); - System::set_block_number(System::block_number() + 1 * 86400 / 12); - assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &BOB, None)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 1071241763); - assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &CHARLIE, None)); - assert_eq!(Tokens::free_balance(KSM, &CHARLIE), 71599834); - System::set_block_number(System::block_number() + 7 * 86400 / 12); - assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &CHARLIE, None)); - assert_eq!(Tokens::free_balance(KSM, &CHARLIE), 501203849); - assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &BOB, None)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 1498768947); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + + System::set_block_number(System::block_number() + 40); + assert_ok!(BbBNC::get_rewards(RuntimeOrigin::signed(BOB))); // balance of veBNC is 0 + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 20_000_000_000, + System::block_number() + (4 * 365 * 86400 - 7 * 86400) / 12, + )); + assert_eq!(Tokens::free_balance(KSM, &BOB), 0); + // balance of veBNC is not 0 + assert_ok!(BbBNC::get_rewards(RuntimeOrigin::signed(BOB))); + assert_ok!(BbBNC::increase_amount( + RuntimeOrigin::signed(BOB), + 0, + 80_000_000_000 + )); + assert_eq!(BbBNC::balance_of(&BOB, None), Ok(99715627680)); + + let rewards = vec![KSM]; + assert_ok!(BbBNC::notify_rewards( + RuntimeOrigin::root(), + ALICE, + Some(7 * 86400 / 12), + rewards.clone() + )); + assert_eq!(Tokens::free_balance(KSM, &BOB), 0); + System::set_block_number(System::block_number() + 20); + assert_eq!(Tokens::free_balance(KSM, &BOB), 0); + assert_ok!(BbBNC::get_rewards(RuntimeOrigin::signed(BOB))); + assert_eq!(Tokens::free_balance(KSM, &BOB), 396819); + System::set_block_number(System::block_number() + 7 * 86400 / 12); + assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &BOB, None)); + assert_eq!(Tokens::free_balance(KSM, &BOB), 999986398); + assert_ok!(Tokens::deposit(KSM, &ALICE, 1_000_000_000)); + assert_ok!(BbBNC::notify_rewards( + RuntimeOrigin::root(), + ALICE, + Some(7 * 86400 / 12), + rewards + )); + assert_ok!(BbBNC::create_lock_inner( + &CHARLIE, + 100_000_000_000, + (4 * 365 * 86400 - 7 * 86400) / 12 + )); + System::set_block_number(System::block_number() + 1 * 86400 / 12); + assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &BOB, None)); + assert_eq!(Tokens::free_balance(KSM, &BOB), 1071241763); + assert_ok!(BbBNC::get_rewards_inner( + BB_BNC_SYSTEM_POOL_ID, + &CHARLIE, + None + )); + assert_eq!(Tokens::free_balance(KSM, &CHARLIE), 71599834); + System::set_block_number(System::block_number() + 7 * 86400 / 12); + assert_ok!(BbBNC::get_rewards_inner( + BB_BNC_SYSTEM_POOL_ID, + &CHARLIE, + None + )); + assert_eq!(Tokens::free_balance(KSM, &CHARLIE), 501203849); + assert_ok!(BbBNC::get_rewards_inner(BB_BNC_SYSTEM_POOL_ID, &BOB, None)); + assert_eq!(Tokens::free_balance(KSM, &BOB), 1498768947); + }); } #[test] fn create_lock_to_withdraw() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 7 * 86400 / 12); // a week - assert_ok!(BbBNC::set_config( - RuntimeOrigin::root(), - Some(4 * 365 * 86400 / 12), - Some(14 * 86400 / 12) - )); - let rewards = vec![KSM]; - assert_ok!(BbBNC::notify_rewards( - RuntimeOrigin::root(), - ALICE, - Some(7 * 86400 / 12), - rewards - )); - assert_noop!( - BbBNC::increase_amount(RuntimeOrigin::signed(BOB), POSITIONID0, 50_000_000_000_000), - Error::::LockNotExist - ); - assert_noop!( - BbBNC::increase_unlock_time( - RuntimeOrigin::signed(BOB), - POSITIONID0, - System::block_number() + 365 * 86400 / 12 - ), - Error::::LockNotExist - ); - assert_noop!( - BbBNC::create_lock( - RuntimeOrigin::signed(BOB), + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 7 * 86400 / 12); // a week + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(4 * 365 * 86400 / 12), + Some(14 * 86400 / 12) + )); + let rewards = vec![KSM]; + assert_ok!(BbBNC::notify_rewards( + RuntimeOrigin::root(), + ALICE, + Some(7 * 86400 / 12), + rewards + )); + assert_noop!( + BbBNC::increase_amount(RuntimeOrigin::signed(BOB), POSITIONID0, 50_000_000_000_000), + Error::::LockNotExist + ); + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + System::block_number() + 365 * 86400 / 12 + ), + Error::::LockNotExist + ); + assert_noop!( + BbBNC::create_lock( + RuntimeOrigin::signed(BOB), + 50_000_000_000_000, + System::block_number() + 5 * 365 * 86400 / 12 + ), + Error::::ArgumentsError + ); + assert_noop!( + BbBNC::create_lock(RuntimeOrigin::signed(BOB), 50_000_000_000_000, 1), + Error::::ArgumentsError + ); + assert_noop!( + BbBNC::create_lock(RuntimeOrigin::signed(BOB), 50_000, 7 * 86400 / 12), + Error::::BelowMinimumMint + ); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); + assert_ok!(BbBNC::create_lock_inner( + &BOB, 50_000_000_000_000, - System::block_number() + 5 * 365 * 86400 / 12 - ), - Error::::ArgumentsError - ); - assert_noop!( - BbBNC::create_lock(RuntimeOrigin::signed(BOB), 50_000_000_000_000, 1), - Error::::ArgumentsError - ); - assert_noop!( - BbBNC::create_lock(RuntimeOrigin::signed(BOB), 50_000, 7 * 86400 / 12), - Error::::BelowMinimumMint - ); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); - assert_ok!(BbBNC::create_lock_inner(&BOB, 50_000_000_000_000, 365 * 86400 / 12)); - assert_noop!( - BbBNC::increase_unlock_time( + 365 * 86400 / 12 + )); + assert_noop!( + BbBNC::increase_unlock_time( + RuntimeOrigin::signed(BOB), + POSITIONID0, + System::block_number() + 5 * 365 * 86400 / 12 + ), + Error::::ArgumentsError + ); + assert_eq!( + BbBNC::balance_of_at(&BOB, System::block_number()), + Ok(12705477321600) + ); + assert_eq!( + BbBNC::balance_of_at(&BOB, System::block_number() - 10), + Ok(0) + ); + assert_eq!(BbBNC::balance_of_at(&BOB, 0), Ok(0)); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number() - 10)), + Ok(0) + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(12705477321600) + ); + assert_noop!( + BbBNC::increase_amount(RuntimeOrigin::signed(BOB), 0, 50_000), + Error::::BelowMinimumMint + ); + assert_ok!(BbBNC::increase_amount( RuntimeOrigin::signed(BOB), - POSITIONID0, - System::block_number() + 5 * 365 * 86400 / 12 - ), - Error::::ArgumentsError - ); - assert_eq!(BbBNC::balance_of_at(&BOB, System::block_number()), Ok(12705477321600)); - assert_eq!(BbBNC::balance_of_at(&BOB, System::block_number() - 10), Ok(0)); - assert_eq!(BbBNC::balance_of_at(&BOB, 0), Ok(0)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number() - 10)), Ok(0)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(12705477321600)); - assert_noop!( - BbBNC::increase_amount(RuntimeOrigin::signed(BOB), 0, 50_000), - Error::::BelowMinimumMint - ); - assert_ok!(BbBNC::increase_amount(RuntimeOrigin::signed(BOB), 0, 50_000_000_000_000)); - assert_eq!(BbBNC::balance_of(&BOB, None), Ok(25410957314400)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(25410957314400)); - - assert_noop!( - BbBNC::withdraw(RuntimeOrigin::signed(ALICE), POSITIONID0), - Error::::LockNotExist - ); - assert_noop!( - BbBNC::withdraw(RuntimeOrigin::signed(BOB), POSITIONID0), - Error::::Expired - ); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(25410957314400)); - System::set_block_number(System::block_number() + 2 * 365 * 86400 / 12); - assert_eq!(BbBNC::balance_of(&BOB, None), Ok(0)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(0)); - assert_ok!(BbBNC::withdraw(RuntimeOrigin::signed(BOB), POSITIONID0)); - assert_ok!(BbBNC::withdraw_inner(&BOB, 0)); - assert_ok!(BbBNC::withdraw_inner(&BOB, 1)); - assert_eq!(BbBNC::balance_of(&BOB, None), Ok(0)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(0)); - }); + 0, + 50_000_000_000_000 + )); + assert_eq!(BbBNC::balance_of(&BOB, None), Ok(25410957314400)); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(25410957314400) + ); + + assert_noop!( + BbBNC::withdraw(RuntimeOrigin::signed(ALICE), POSITIONID0), + Error::::LockNotExist + ); + assert_noop!( + BbBNC::withdraw(RuntimeOrigin::signed(BOB), POSITIONID0), + Error::::Expired + ); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(25410957314400) + ); + System::set_block_number(System::block_number() + 2 * 365 * 86400 / 12); + assert_eq!(BbBNC::balance_of(&BOB, None), Ok(0)); + assert_eq!(BbBNC::total_supply(System::block_number()), Ok(0)); + assert_ok!(BbBNC::withdraw(RuntimeOrigin::signed(BOB), POSITIONID0)); + assert_ok!(BbBNC::withdraw_inner(&BOB, 0)); + assert_ok!(BbBNC::withdraw_inner(&BOB, 1)); + assert_eq!(BbBNC::balance_of(&BOB, None), Ok(0)); + assert_eq!(BbBNC::total_supply(System::block_number()), Ok(0)); + }); } #[test] fn overflow() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - assert_ok!(BbBNC::create_lock_inner(&BOB, 100_000_000_000_000, 77000)); - System::set_block_number(77001); - assert_eq!(BbBNC::balance_of(&BOB, Some(77001)), Ok(226398387663)); - assert_eq!(BbBNC::total_supply(System::block_number()), Ok(226398387663)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + assert_ok!(BbBNC::create_lock_inner(&BOB, 100_000_000_000_000, 77000)); + System::set_block_number(77001); + assert_eq!(BbBNC::balance_of(&BOB, Some(77001)), Ok(226398387663)); + assert_eq!( + BbBNC::total_supply(System::block_number()), + Ok(226398387663) + ); + }); } #[test] fn deposit_markup_before_lock_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(100_000_000_000_000_000), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000)); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(2796030953200)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(2796030953200) + ); + }); +} + +#[test] +fn deposit_markup_before_lock_should_not_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + + assert_noop!( + BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000), + Error::::ArgumentsError + ); + + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + + assert_noop!( + BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 0), + Error::::ArgumentsError + ); + + TotalLock::::insert(VBNC, BalanceOf::::max_value()); + assert_noop!( + BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000), + ArithmeticError::Overflow + ); + TotalLock::::remove(VBNC); + + LockedTokens::::insert( + VBNC, + &BOB, + LockedToken { + amount: BalanceOf::::max_value(), + markup_coefficient: FixedU128::saturating_from_integer(1), + refresh_block: System::block_number(), + }, + ); + assert_noop!( + BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000), + ArithmeticError::Overflow + ); + }); } #[test] fn deposit_markup_before_lock_should_work2() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(100_000_000_000_000_000), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000)); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 15_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID1, U256::one()), - Point { bias: 4194046429800, slope: 1570110, block: 20, amount: 16504999999999 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(Locked::::get(POSITIONID1).amount, 15_000_000_000_000); - assert_eq!( - BbBNC::balance_of(&BOB, Some(System::block_number())), - Ok(2796030953200 + 4194046429800) - ); - assert_eq!( - BbBNC::balance_of(&BOB, Some(System::block_number())), - Ok(2796030953200 + 4194046429800) - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 15_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID1, U256::one()), + Point { + bias: 4194046429800, + slope: 1570110, + block: 20, + amount: 16504999999999 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + Locked::::get(POSITIONID1).amount, + 15_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(2796030953200 + 4194046429800) + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(2796030953200 + 4194046429800) + ); + }); } #[test] fn deposit_markup_after_lock_should_work2() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - MOVR, - FixedU128::from_inner(500_000_000_000_000_000), // 0.5 - FixedU128::saturating_from_integer(1), - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(1)), - Point { bias: 2541074835740, slope: 951293, block: 20, amount: 10_000_000_000_000 } - ); - assert_eq!( - Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000 - 10_000_000_000_000) - .is_ok(), - true - ); - assert_eq!(Tokens::ensure_can_withdraw(MOVR, &BOB, 10_000_000_000_000).is_ok(), true); - assert_eq!(UserMarkupInfos::::get(BOB), None); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), MOVR, 9_000_000_000_000)); - assert_eq!( - UserMarkupInfos::::get(BOB), - Some(UserMarkupInfo { - old_markup_coefficient: FixedU128::from_inner(0), - markup_coefficient: FixedU128::from_inner(950_000_000_000_000_000), - }) - ); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), MOVR, 1_000_000_000_000)); - assert_eq!( - UserMarkupInfos::::get(BOB), - Some(UserMarkupInfo { - old_markup_coefficient: FixedU128::from_inner(950_000_000_000_000_000), - markup_coefficient: FixedU128::from_inner(1_000_000_000_000_000_000), - }) - ); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(2)), - Point { bias: 4955097665960, slope: 1855022, block: 20, amount: 19500000000000 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(3)), - Point { bias: 5082152342660, slope: 1902587, block: 20, amount: 20000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(5082152342660)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + MOVR, + FixedU128::from_inner(500_000_000_000_000_000), // 0.5 + FixedU128::saturating_from_integer(1), + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(1)), + Point { + bias: 2541074835740, + slope: 951293, + block: 20, + amount: 10_000_000_000_000 + } + ); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000 - 10_000_000_000_000) + .is_ok(), + true + ); + assert_eq!( + Tokens::ensure_can_withdraw(MOVR, &BOB, 10_000_000_000_000).is_ok(), + true + ); + assert_eq!(UserMarkupInfos::::get(BOB), None); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + MOVR, + 9_000_000_000_000 + )); + assert_eq!( + UserMarkupInfos::::get(BOB), + Some(UserMarkupInfo { + old_markup_coefficient: FixedU128::from_inner(0), + markup_coefficient: FixedU128::from_inner(950_000_000_000_000_000), + }) + ); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + MOVR, + 1_000_000_000_000 + )); + assert_eq!( + UserMarkupInfos::::get(BOB), + Some(UserMarkupInfo { + old_markup_coefficient: FixedU128::from_inner(950_000_000_000_000_000), + markup_coefficient: FixedU128::from_inner(1_000_000_000_000_000_000), + }) + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 4955097665960, + slope: 1855022, + block: 20, + amount: 19500000000000 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(3)), + Point { + bias: 5082152342660, + slope: 1902587, + block: 20, + amount: 20000000000000 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(5082152342660) + ); + }); +} + +#[test] +fn deposit_markup_after_lock_should_not_work2() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + MOVR, + FixedU128::from_inner(500_000_000_000_000_000), // 0.5 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + MOVR, + 9_000_000_000_000 + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + MOVR, + 2_000_000_000_000 + )); + // Currently the hard cap has been reached, markup_coefficient should be 1.0 + assert_eq!( + UserMarkupInfos::::get(BOB), + Some(UserMarkupInfo { + old_markup_coefficient: FixedU128::from_inner(950_000_000_000_000_000), + markup_coefficient: FixedU128::from_inner(1_000_000_000_000_000_000), + }) + ); + + assert_eq!( + UserMarkupInfos::::get(BOB), + Some(UserMarkupInfo { + old_markup_coefficient: FixedU128::from_inner(950_000_000_000_000_000), + markup_coefficient: FixedU128::from_inner(1_000_000_000_000_000_000), + }) + ); + + // Verify that user Point has not been updated + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(3)), + Point { + bias: 5082152342660, + slope: 1902587, + block: 20, + amount: 20000000000000 + } + ); + + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(5082152342660) + ); + }); } #[test] fn deposit_markup_after_lock_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(100_000_000_000_000_000), // 0.1 - FixedU128::saturating_from_integer(1), - )); - - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(1)), - Point { bias: 2541074835740, slope: 951293, block: 20, amount: 10000000000000 } - ); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000)); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(2)), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(2796030953200)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(1)), + Point { + bias: 2541074835740, + slope: 951293, + block: 20, + amount: 10000000000000 + } + ); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(2796030953200) + ); + }); } #[test] fn withdraw_markup_after_lock_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(100_000_000_000_000_000), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000)); - assert_ok!(BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), VBNC)); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(2)), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(3)), - Point { bias: 2541074835740, slope: 951293, block: 20, amount: 10000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(2541074835740)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + assert_ok!(BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), VBNC)); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(3)), + Point { + bias: 2541074835740, + slope: 951293, + block: 20, + amount: 10000000000000 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(2541074835740) + ); + }); } #[test] fn redeem_unlock_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VKSM, - FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VKSM, 10_000_000_000_000)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 1000000000000000).is_ok(), true); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 5082152342660, slope: 1902587, block: 20, amount: 20000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(5082152342660)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1_000_000_000_000_000); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000).is_ok(), false); - assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 0)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 997451711199422); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 997451711199422).is_ok(), true); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VKSM, + FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VKSM, + 10_000_000_000_000 + )); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1000000000000000).is_ok(), + true + ); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 5082152342660, + slope: 1902587, + block: 20, + amount: 20000000000000 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(5082152342660) + ); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1_000_000_000_000_000); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000).is_ok(), + false + ); + assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 0)); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 997451711199422); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 997451711199422).is_ok(), + true + ); + }); } #[test] fn withdraw_markup_after_lock_should_work3() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 15_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(100_000_000_000_000_000), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000)); - assert_ok!(BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), VBNC)); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(2)), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(3)), - Point { bias: 2541074835740, slope: 951293, block: 20, amount: 10000000000000 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID1, U256::from(2)), - Point { bias: 4194046429800, slope: 1570110, block: 20, amount: 16504999999999 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID1, U256::from(3)), - Point { bias: 3811613589200, slope: 1426940, block: 20, amount: 15000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(Locked::::get(POSITIONID1).amount, 15_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(6352688424940)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 15_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + assert_ok!(BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), VBNC)); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(3)), + Point { + bias: 2541074835740, + slope: 951293, + block: 20, + amount: 10000000000000 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID1, U256::from(2)), + Point { + bias: 4194046429800, + slope: 1570110, + block: 20, + amount: 16504999999999 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID1, U256::from(3)), + Point { + bias: 3811613589200, + slope: 1426940, + block: 20, + amount: 15000000000000 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + Locked::::get(POSITIONID1).amount, + 15_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(6352688424940) + ); + }); +} + +#[test] +fn withdraw_markup_after_lock_should_not_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + + assert_noop!( + BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), MOVR), + Error::::ArgumentsError + ); + + assert_ok!(BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), VBNC)); + // + assert_noop!( + BbBNC::withdraw_markup(RuntimeOrigin::signed(BOB), VBNC), + Error::::LockNotExist + ); + + assert_noop!( + BbBNC::withdraw_markup(RuntimeOrigin::signed(ALICE), VBNC), + Error::::LockNotExist + ); + + // Verify the status of UserMarkupiInfos and LockdToken + assert_eq!( + UserMarkupInfos::::get(BOB), + Some(UserMarkupInfo { + old_markup_coefficient: FixedU128::from_inner(100333333333333333), // 0.10033333333333333 + markup_coefficient: FixedU128::from_inner(0), + }) + ); + assert_eq!(LockedTokens::::get(VBNC, &BOB), None); + + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(3)), + Point { + bias: 2541074835740, + slope: 951293, + block: 20, + amount: 10_000_000_000_000 + } + ); + + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(2541074835740) + ); + }); } #[test] fn redeem_unlock_after_360_days_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VKSM, - FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VKSM, 10_000_000_000_000)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 1000000000000000).is_ok(), true); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 5082152342660, slope: 1902587, block: 20, amount: 20000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(5082152342660)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1_000_000_000_000_000); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000).is_ok(), false); - System::set_block_number(System::block_number() + 360 * 86400 / 12); - assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 0)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 999336664330082); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 999336664330082).is_ok(), true); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VKSM, + FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VKSM, + 10_000_000_000_000 + )); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1000000000000000).is_ok(), + true + ); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 5082152342660, + slope: 1902587, + block: 20, + amount: 20000000000000 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(5082152342660) + ); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1_000_000_000_000_000); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000).is_ok(), + false + ); + System::set_block_number(System::block_number() + 360 * 86400 / 12); + assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 0)); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 999336664330082); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 999336664330082).is_ok(), + true + ); + }); +} + +#[test] +fn redeem_unlock_after_360_days_should_not_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VKSM, + FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VKSM, + 10_000_000_000_000 + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + + System::set_block_number(System::block_number() + 360 * 86400 / 12); + assert_noop!( + BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 999), + Error::::LockNotExist + ); + + assert_noop!( + BbBNC::redeem_unlock(RuntimeOrigin::signed(ALICE), 0), + Error::::LockNotExist + ); + }); } #[test] fn redeem_unlock_after_360_days_should_work2() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VKSM, - FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VKSM, 10_000_000_000_000)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 1000000000000000).is_ok(), true); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 15_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 5082152342660, slope: 1902587, block: 20, amount: 20000000000000 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID1, U256::one()), - Point { bias: 7623229849580, slope: 2853881, block: 20, amount: 30000000000000 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(Locked::::get(POSITIONID1).amount, 15_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(12705382192240)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 1_000_000_000_000_000); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000).is_ok(), false); - System::set_block_number(System::block_number() + 360 * 86400 / 12); - assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), POSITIONID0)); - assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), POSITIONID1)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 998341660825205); - assert_eq!(Tokens::ensure_can_withdraw(VBNC, &BOB, 998341660825205).is_ok(), true); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VKSM, + FixedU128::from_inner(FixedU128::DIV / 10), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VKSM, + 10_000_000_000_000 + )); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1000000000000000); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1000000000000000).is_ok(), + true + ); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 15_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 5082152342660, + slope: 1902587, + block: 20, + amount: 20000000000000 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID1, U256::one()), + Point { + bias: 7623229849580, + slope: 2853881, + block: 20, + amount: 30000000000000 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + Locked::::get(POSITIONID1).amount, + 15_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(12705382192240) + ); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 1_000_000_000_000_000); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 1_000_000_000_000_000).is_ok(), + false + ); + System::set_block_number(System::block_number() + 360 * 86400 / 12); + assert_ok!(BbBNC::redeem_unlock( + RuntimeOrigin::signed(BOB), + POSITIONID0 + )); + assert_ok!(BbBNC::redeem_unlock( + RuntimeOrigin::signed(BOB), + POSITIONID1 + )); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 998341660825205); + assert_eq!( + Tokens::ensure_can_withdraw(VBNC, &BOB, 998341660825205).is_ok(), + true + ); + }); } #[test] fn refresh_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - System::set_block_number(System::block_number() + 20); - - assert_ok!(BbBNC::set_config(RuntimeOrigin::root(), Some(0), Some(7 * 86400 / 12))); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(100_000_000_000_000_000), // 0.1 - FixedU128::saturating_from_integer(1), - )); - assert_ok!(BbBNC::deposit_markup(RuntimeOrigin::signed(BOB), VBNC, 10_000_000_000_000)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - assert_ok!(BbBNC::create_lock_inner( - &BOB, - 10_000_000_000_000, - System::block_number() + 365 * 86400 / 12, - )); - assert_ok!(BbBNC::set_markup_coefficient( - RuntimeOrigin::root(), - VBNC, - FixedU128::from_inner(200_000_000_000_000_000), // 0.2 - FixedU128::saturating_from_integer(1), - )); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(2)), - Point { bias: 0, slope: 0, block: 0, amount: 0 } - ); - assert_ok!(BbBNC::refresh_inner(VBNC)); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::one()), - Point { bias: 2796030953200, slope: 1046740, block: 20, amount: 11003333333333 } - ); - assert_eq!( - UserPointHistory::::get(POSITIONID0, U256::from(2)), - Point { bias: 3050984399480, slope: 1142186, block: 20, amount: 12006666666666 } - ); - assert_eq!(Locked::::get(POSITIONID0).amount, 10_000_000_000_000); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(3050984399480)); - assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 0)); - assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + System::set_block_number(System::block_number() + 20); + + assert_ok!(BbBNC::set_config( + RuntimeOrigin::root(), + Some(0), + Some(7 * 86400 / 12) + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(100_000_000_000_000_000), // 0.1 + FixedU128::saturating_from_integer(1), + )); + assert_ok!(BbBNC::deposit_markup( + RuntimeOrigin::signed(BOB), + VBNC, + 10_000_000_000_000 + )); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + assert_ok!(BbBNC::create_lock_inner( + &BOB, + 10_000_000_000_000, + System::block_number() + 365 * 86400 / 12, + )); + assert_ok!(BbBNC::set_markup_coefficient( + RuntimeOrigin::root(), + VBNC, + FixedU128::from_inner(200_000_000_000_000_000), // 0.2 + FixedU128::saturating_from_integer(1), + )); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 0, + slope: 0, + block: 0, + amount: 0 + } + ); + assert_ok!(BbBNC::refresh_inner(VBNC)); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::one()), + Point { + bias: 2796030953200, + slope: 1046740, + block: 20, + amount: 11003333333333 + } + ); + assert_eq!( + UserPointHistory::::get(POSITIONID0, U256::from(2)), + Point { + bias: 3050984399480, + slope: 1142186, + block: 20, + amount: 12006666666666 + } + ); + assert_eq!( + Locked::::get(POSITIONID0).amount, + 10_000_000_000_000 + ); + assert_eq!( + BbBNC::balance_of(&BOB, Some(System::block_number())), + Ok(3050984399480) + ); + assert_ok!(BbBNC::redeem_unlock(RuntimeOrigin::signed(BOB), 0)); + assert_eq!(BbBNC::balance_of(&BOB, Some(System::block_number())), Ok(0)); + }); } diff --git a/pallets/bb-bnc/src/traits.rs b/pallets/bb-bnc/src/traits.rs index 8c18336830..efd6433923 100644 --- a/pallets/bb-bnc/src/traits.rs +++ b/pallets/bb-bnc/src/traits.rs @@ -33,14 +33,14 @@ pub trait BbBNCInterface { fn find_block_epoch(_block: BlockNumber, max_epoch: U256) -> U256; fn create_lock_inner( who: &AccountId, - _value: Balance, - _unlock_time: BlockNumber, + value: Balance, + unlock_time: BlockNumber, ) -> DispatchResult; // Deposit `_value` BNC for `who` and lock until `_unlock_time` fn increase_amount_inner(who: &AccountId, position: u128, value: Balance) -> DispatchResult; // Deposit `_value` additional BNC for `who` without modifying the unlock time fn increase_unlock_time_inner( who: &AccountId, position: u128, - _unlock_time: BlockNumber, + unlock_time: BlockNumber, ) -> DispatchResult; // Extend the unlock time for `who` to `_unlock_time` fn auto_notify_reward( pool_id: PoolId, @@ -75,323 +75,6 @@ pub trait BbBNCInterface { ) -> DispatchResult; } -impl BbBNCInterface, CurrencyIdOf, BalanceOf, BlockNumberFor> - for Pallet -{ - fn create_lock_inner( - who: &AccountIdOf, - _value: BalanceOf, - _unlock_time: BlockNumberFor, - ) -> DispatchResult { - let new_position = Position::::get(); - let mut user_positions = UserPositions::::get(who); - user_positions - .try_push(new_position) - .map_err(|_| Error::::ExceedsMaxPositions)?; - UserPositions::::insert(who, user_positions); - Position::::set(new_position + 1); - - let bb_config = BbConfigs::::get(); - ensure!(_value >= bb_config.min_mint, Error::::BelowMinimumMint); - - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); - let _locked: LockedBalance, BlockNumberFor> = - Locked::::get(new_position); - let unlock_time: BlockNumberFor = _unlock_time - .saturating_add(current_block_number) - .checked_div(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)? - .saturating_add(1u32.into()) - .checked_mul(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)?; - - ensure!( - unlock_time >= bb_config.min_block.saturating_add(current_block_number), - Error::::ArgumentsError - ); - let max_block = T::MaxBlock::get() - .saturating_add(current_block_number) - .checked_div(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)? - .saturating_add(1u32.into()) - .checked_mul(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)?; - ensure!(unlock_time <= max_block, Error::::ArgumentsError); - ensure!(_locked.amount == BalanceOf::::zero(), Error::::LockExist); // Withdraw old tokens first - - Self::_deposit_for(who, new_position, _value, unlock_time, _locked)?; - Self::deposit_event(Event::LockCreated { - who: who.to_owned(), - position: new_position, - value: _value, - unlock_time: _unlock_time, - }); - Ok(()) - } - - fn increase_unlock_time_inner( - who: &AccountIdOf, - position: u128, - _unlock_time: BlockNumberFor, - ) -> DispatchResult { - let bb_config = BbConfigs::::get(); - let _locked: LockedBalance, BlockNumberFor> = Locked::::get(position); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); - - let unlock_time: BlockNumberFor = _unlock_time - .saturating_add(_locked.end) - .checked_div(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)? - .saturating_add(1u32.into()) - .checked_mul(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)?; - - ensure!( - unlock_time >= bb_config.min_block.saturating_add(current_block_number), - Error::::ArgumentsError - ); - let max_block = T::MaxBlock::get() - .saturating_add(current_block_number) - .checked_div(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)? - .saturating_add(1u32.into()) - .checked_mul(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)?; - ensure!(unlock_time <= max_block, Error::::ArgumentsError); - ensure!(_locked.amount > BalanceOf::::zero(), Error::::LockNotExist); - ensure!(_locked.end > current_block_number, Error::::Expired); // Cannot add to expired/non-existent lock - - Self::_deposit_for(who, position, BalanceOf::::zero(), unlock_time, _locked)?; - Self::deposit_event(Event::UnlockTimeIncreased { - who: who.to_owned(), - position, - unlock_time, - }); - Ok(()) - } - - fn increase_amount_inner( - who: &AccountIdOf, - position: u128, - value: BalanceOf, - ) -> DispatchResult { - let bb_config = BbConfigs::::get(); - ensure!(value >= bb_config.min_mint, Error::::BelowMinimumMint); - let _locked: LockedBalance, BlockNumberFor> = Locked::::get(position); - ensure!(_locked.amount > BalanceOf::::zero(), Error::::LockNotExist); // Need to be executed after create_lock - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); - ensure!(_locked.end > current_block_number, Error::::Expired); // Cannot add to expired/non-existent lock - Self::_deposit_for(who, position, value, Zero::zero(), _locked)?; - Self::deposit_event(Event::AmountIncreased { who: who.to_owned(), position, value }); - Ok(()) - } - - fn deposit_for(who: &AccountIdOf, position: u128, value: BalanceOf) -> DispatchResult { - let _locked: LockedBalance, BlockNumberFor> = Locked::::get(position); - Self::_deposit_for(who, position, value, Zero::zero(), _locked) - } - - fn withdraw_inner(who: &AccountIdOf, position: u128) -> DispatchResult { - let mut _locked = Locked::::get(position); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); - ensure!(current_block_number >= _locked.end, Error::::Expired); - Self::withdraw_no_ensure(who, position, _locked, None) - } - - fn balance_of( - who: &AccountIdOf, - time: Option>, - ) -> Result, DispatchError> { - match time { - Some(_t) => Self::balance_of_at(who, _t), - None => Self::balance_of_current_block(who), - } - } - - fn find_block_epoch(_block: BlockNumberFor, max_epoch: U256) -> U256 { - let mut _min = U256::zero(); - let mut _max = max_epoch; - for _i in 0..128 { - if _min >= _max { - break; - } - let _mid = (_min + _max + 1) / 2; - - if PointHistory::::get(_mid).block <= _block { - _min = _mid - } else { - _max = _mid - 1 - } - } - _min - } - - fn total_supply(t: BlockNumberFor) -> Result, DispatchError> { - let g_epoch: U256 = Epoch::::get(); - let last_point = PointHistory::::get(g_epoch); - Self::supply_at(last_point, t) - } - - fn supply_at( - point: Point, BlockNumberFor>, - t: BlockNumberFor, - ) -> Result, DispatchError> { - let mut last_point = point; - let mut t_i: BlockNumberFor = last_point - .block - .checked_div(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)? - .checked_mul(&T::Week::get()) - .ok_or(ArithmeticError::Overflow)?; - for _i in 0..255 { - t_i += T::Week::get(); - let mut d_slope = Zero::zero(); - if t_i > t { - t_i = t - } else { - d_slope = SlopeChanges::::get(t_i) - } - - last_point.bias = last_point - .bias - .checked_sub( - last_point - .slope - .checked_mul( - t_i.checked_sub(&last_point.block) - .ok_or(ArithmeticError::Overflow)? - .saturated_into::() - .unique_saturated_into(), - ) - .ok_or(ArithmeticError::Overflow)?, - ) - .ok_or(ArithmeticError::Overflow)?; - - if t_i == t { - break; - } - last_point.slope += d_slope; - last_point.block = t_i - } - - if last_point.bias < 0_i128 { - last_point.bias = 0_i128 - } - Ok(T::VoteWeightMultiplier::get() - .checked_mul((last_point.bias as u128).unique_saturated_into()) - .ok_or(ArithmeticError::Overflow)?) - } - - fn auto_notify_reward( - pool_id: PoolId, - n: BlockNumberFor, - rewards: Vec>, - ) -> DispatchResult { - let conf = IncentiveConfigs::::get(pool_id); - // If the period is reached or not set, the reward will be notified. - if n == conf.period_finish || conf.period_finish == Default::default() { - Self::notify_reward_amount(pool_id, &conf.incentive_controller, rewards)?; - } - Ok(()) - } - - fn update_reward( - pool_id: PoolId, - who: Option<&AccountIdOf>, - share_info: Option<(BalanceOf, BalanceOf)>, - ) -> DispatchResult { - Self::update_reward(pool_id, who, share_info) - } - - fn get_rewards( - pool_id: PoolId, - who: &AccountIdOf, - share_info: Option<(BalanceOf, BalanceOf)>, - ) -> DispatchResult { - Self::get_rewards_inner(pool_id, who, share_info) - } - - fn set_incentive( - pool_id: PoolId, - rewards_duration: Option>, - controller: Option>, - ) { - let mut incentive_config = IncentiveConfigs::::get(pool_id); - - if let Some(rewards_duration) = rewards_duration { - incentive_config.rewards_duration = rewards_duration; - }; - if let Some(controller) = controller { - incentive_config.incentive_controller = Some(controller.clone()); - } - IncentiveConfigs::::set(pool_id, incentive_config.clone()); - Self::deposit_event(Event::IncentiveSet { incentive_config }); - } - - fn add_reward( - who: &AccountIdOf, - conf: &mut IncentiveConfig< - CurrencyIdOf, - BalanceOf, - BlockNumberFor, - AccountIdOf, - >, - rewards: &Vec>, - remaining: BalanceOf, - ) -> DispatchResult { - rewards.iter().try_for_each(|currency| -> DispatchResult { - let reward = T::MultiCurrency::free_balance(*currency, who); - let mut total_reward: BalanceOf = reward; - if remaining != BalanceOf::::zero() { - let leftover: BalanceOf = conf - .reward_rate - .get(currency) - .unwrap_or(&Zero::zero()) - .checked_mul(&remaining) - .ok_or(ArithmeticError::Overflow)?; - total_reward = total_reward.saturating_add(leftover); - } - let currency_amount = T::MultiCurrency::free_balance( - *currency, - &T::IncentivePalletId::get().into_account_truncating(), - ); - // Make sure the new reward is less than or equal to the reward owned by the - // IncentivePalletId - ensure!( - total_reward <= currency_amount.saturating_add(reward), - Error::::NotEnoughBalance - ); - let new_reward = total_reward - .checked_div(T::BlockNumberToBalance::convert(conf.rewards_duration)) - .ok_or(ArithmeticError::Overflow)?; - conf.reward_rate - .entry(*currency) - .and_modify(|total_reward| { - *total_reward = new_reward; - }) - .or_insert(new_reward); - // If the reward in this round is 0, it will only be recorded without transfer. - if reward == BalanceOf::::zero() { - return Ok(()); - } - T::MultiCurrency::transfer( - *currency, - who, - &T::IncentivePalletId::get().into_account_truncating(), - reward, - ) - }) - } - - fn notify_reward( - pool_id: PoolId, - who: &Option>, - rewards: Vec>, - ) -> DispatchResult { - Self::notify_reward_amount(pool_id, who, rewards) - } -} - impl BbBNCInterface for () where diff --git a/pallets/bb-bnc/src/weights.rs b/pallets/bb-bnc/src/weights.rs index b54a417dd2..0f3a2b5108 100644 --- a/pallets/bb-bnc/src/weights.rs +++ b/pallets/bb-bnc/src/weights.rs @@ -53,6 +53,7 @@ use sp_std::marker::PhantomData; /// Weight functions needed for bb_bnc. pub trait WeightInfo { + fn on_initialize() -> Weight; fn set_config() -> Weight; fn create_lock() -> Weight; fn increase_amount() -> Weight; @@ -69,6 +70,32 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { + /// Storage: `BbBNC::IncentiveConfigs` (r:1 w:1) + /// Proof: `BbBNC::IncentiveConfigs` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `BbBNC::Epoch` (r:1 w:0) + /// Proof: `BbBNC::Epoch` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::PointHistory` (r:1 w:0) + /// Proof: `BbBNC::PointHistory` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn on_initialize() -> Weight { + // Proof Size summary in bytes: + // Measured: `462` + // Estimated: `6196` + // Minimum execution time: 22_033_000 picoseconds. + Weight::from_parts(22_373_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(RocksDbWeight::get().reads(9)) + .saturating_add(RocksDbWeight::get().writes(3)) + } /// Storage: `BbBNC::BbConfigs` (r:1 w:1) /// Proof: `BbBNC::BbConfigs` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `System::Number` (r:1 w:0) diff --git a/pallets/buy-back/Cargo.toml b/pallets/buy-back/Cargo.toml index 1279d6a9f1..b2f7d09bb5 100644 --- a/pallets/buy-back/Cargo.toml +++ b/pallets/buy-back/Cargo.toml @@ -1,5 +1,5 @@ [package] -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" name = "bifrost-buy-back" version = "0.8.0" diff --git a/pallets/buy-back/src/benchmarking.rs b/pallets/buy-back/src/benchmarking.rs index c015d581d0..6a34bfddbe 100644 --- a/pallets/buy-back/src/benchmarking.rs +++ b/pallets/buy-back/src/benchmarking.rs @@ -20,9 +20,9 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::{BalanceOf, Call, Config, Pallet, Pallet as BuyBack, *}; +use crate::{BalanceOf, Call, Config, Pallet as BuyBack, *}; use bifrost_primitives::VDOT; -use frame_benchmarking::v1::{account, benchmarks, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::{ assert_ok, traits::{EnsureOrigin, Hooks}, @@ -31,21 +31,58 @@ use frame_system::RawOrigin; use orml_traits::MultiCurrency; use sp_runtime::traits::UniqueSaturatedFrom; -benchmarks! { - set_vtoken { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - }: _(origin,VDOT,1_000_000u32.into(),Permill::from_percent(2),1000u32.into(),1000u32.into(),true,Some(Permill::from_percent(2)),Permill::from_percent(2)) +#[benchmarks] +mod benchmarks { + use super::*; - charge { - let test_account: T::AccountId = account("seed",1,1); + #[benchmark] + fn set_vtoken() -> Result<(), BenchmarkError> { + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - T::MultiCurrency::deposit(VDOT, &test_account, BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128))?; - }: _(RawOrigin::Signed(test_account),VDOT,BalanceOf::::unique_saturated_from(9_000_000_000_000u128)) + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + VDOT, + 1_000_000u32.into(), + Permill::from_percent(2), + 1000u32.into(), + 1000u32.into(), + true, + Some(Permill::from_percent(2)), + Permill::from_percent(2), + ); + + Ok(()) + } + + #[benchmark] + fn charge() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); + + T::MultiCurrency::deposit( + VDOT, + &test_account, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + + #[extrinsic_call] + _( + RawOrigin::Signed(test_account), + VDOT, + BalanceOf::::unique_saturated_from(9_000_000_000_000u128), + ); + + Ok(()) + } + + #[benchmark] + fn remove_vtoken() -> Result<(), BenchmarkError> { + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - remove_vtoken { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; assert_ok!(BuyBack::::set_vtoken( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone() as ::RuntimeOrigin, VDOT, 1_000_000u32.into(), Permill::from_percent(2), @@ -53,15 +90,22 @@ benchmarks! { 1000u32.into(), true, Some(Permill::from_percent(2)), - Permill::from_percent(2) + Permill::from_percent(2), )); - }: _(origin,VDOT) + #[extrinsic_call] + _(origin as ::RuntimeOrigin, VDOT); + + Ok(()) + } + + #[benchmark] + fn on_initialize() -> Result<(), BenchmarkError> { + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - on_initialize { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; assert_ok!(BuyBack::::set_vtoken( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin as ::RuntimeOrigin, VDOT, 1_000_000u32.into(), Permill::from_percent(2), @@ -69,11 +113,28 @@ benchmarks! { 1000u32.into(), true, Some(Permill::from_percent(2)), - Permill::from_percent(2) + Permill::from_percent(2), )); - }: { - BuyBack::::on_initialize(BlockNumberFor::::from(0u32)); + + #[block] + { + BuyBack::::on_initialize(BlockNumberFor::::from(0u32)); + } + + Ok(()) } - impl_benchmark_test_suite!(BuyBack,crate::mock::ExtBuilder::default().build(),crate::mock::Runtime); + // This line generates test cases for benchmarking, and could be run by: + // `cargo test -p pallet-example-basic --all-features`, you will see one line per case: + // `test benchmarking::bench_sort_vector ... ok` + // `test benchmarking::bench_accumulate_dummy ... ok` + // `test benchmarking::bench_set_dummy_benchmark ... ok` in the result. + // + // The line generates three steps per benchmark, with repeat=1 and the three steps are + // [low, mid, high] of the range. + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/buy-back/src/lib.rs b/pallets/buy-back/src/lib.rs index f7c609fe73..4631c37332 100644 --- a/pallets/buy-back/src/lib.rs +++ b/pallets/buy-back/src/lib.rs @@ -36,7 +36,7 @@ use cumulus_primitives_core::ParaId; use frame_support::{ pallet_prelude::*, sp_runtime::{ - traits::{AccountIdConversion, One, Zero}, + traits::{AccountIdConversion, BlockNumberProvider, One, Zero}, Permill, SaturatedConversion, Saturating, }, transactional, PalletId, @@ -95,29 +95,57 @@ pub mod pallet { BalanceOf, BlockNumberFor, >; + + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A successful call of the `Charge` extrinsic will create this event. - Charged { who: AccountIdOf, currency_id: CurrencyIdOf, value: BalanceOf }, + Charged { + who: AccountIdOf, + currency_id: CurrencyIdOf, + value: BalanceOf, + }, /// A successful call of the `SetVtoken` extrinsic will create this event. - ConfigSet { currency_id: CurrencyIdOf, info: Info, BlockNumberFor> }, + ConfigSet { + currency_id: CurrencyIdOf, + info: Info, BlockNumberFor>, + }, /// A successful call of the `RemoveVtoken` extrinsic will create this event. Removed { currency_id: CurrencyIdOf }, /// A failed call of the `BuyBack` extrinsic will create this event. - BuyBackFailed { currency_id: CurrencyIdOf, block_number: BlockNumberFor }, + BuyBackFailed { + currency_id: CurrencyIdOf, + block_number: BlockNumberFor, + }, /// A successful call of the `BuyBack` extrinsic will create this event. - BuyBackSuccess { currency_id: CurrencyIdOf, block_number: BlockNumberFor }, + BuyBackSuccess { + currency_id: CurrencyIdOf, + block_number: BlockNumberFor, + }, /// A failed call of the `AddLiquidity` extrinsic will create this event. - AddLiquidityFailed { currency_id: CurrencyIdOf, block_number: BlockNumberFor }, + AddLiquidityFailed { + currency_id: CurrencyIdOf, + block_number: BlockNumberFor, + }, /// A successful call of the `AddLiquidity` extrinsic will create this event. - AddLiquiditySuccess { currency_id: CurrencyIdOf, block_number: BlockNumberFor }, + AddLiquiditySuccess { + currency_id: CurrencyIdOf, + block_number: BlockNumberFor, + }, /// A failed call of the `SetSwapOutMin` extrinsic will create this event. - SetSwapOutMinFailed { currency_id: CurrencyIdOf, block_number: BlockNumberFor }, + SetSwapOutMinFailed { + currency_id: CurrencyIdOf, + block_number: BlockNumberFor, + }, /// A successful call of the `SetSwapOutMin` extrinsic will create this event. - SetSwapOutMinSuccess { currency_id: CurrencyIdOf, block_number: BlockNumberFor }, + SetSwapOutMinSuccess { + currency_id: CurrencyIdOf, + block_number: BlockNumberFor, + }, } #[pallet::error] @@ -171,7 +199,8 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: BlockNumberFor) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { + let n: BlockNumberFor = T::BlockNumberProvider::current_block_number(); let buyback_address = T::BuyBackAccount::get().into_account_truncating(); let liquidity_address = T::LiquidityAccount::get().into_account_truncating(); for (currency_id, mut info) in Infos::::iter() { @@ -203,7 +232,7 @@ pub mod pallet { block_number: n, }); } - }, + } target_block if target_block == n => { if let Some(swap_out_min) = AddLiquiditySwapOutMin::::get(currency_id) { if let Some(e) = Self::add_liquidity( @@ -234,7 +263,7 @@ pub mod pallet { Infos::::insert(currency_id, info.clone()); AddLiquiditySwapOutMin::::remove(currency_id); } - }, + } _ => (), } @@ -244,8 +273,8 @@ pub mod pallet { } match Self::get_target_block(info.last_buyback, info.buyback_duration) { target_block - if target_block == - n.saturating_sub(info.last_buyback_cycle) + if target_block + == n.saturating_sub(info.last_buyback_cycle) .saturated_into::() => { if let Some(e) = Self::set_swap_out_min(currency_id, &info).err() { @@ -264,10 +293,10 @@ pub mod pallet { block_number: n, }); } - }, + } target_block - if target_block == - n.saturating_sub(info.last_buyback_cycle) + if target_block + == n.saturating_sub(info.last_buyback_cycle) .saturated_into::() .saturating_sub(One::one()) => { @@ -291,17 +320,18 @@ pub mod pallet { block_number: n, }); } - info.last_buyback_cycle = - info.last_buyback_cycle.saturating_add(info.buyback_duration); + info.last_buyback_cycle = info + .last_buyback_cycle + .saturating_add(info.buyback_duration); info.last_buyback = n; Infos::::insert(currency_id, info); SwapOutMin::::remove(currency_id); } - }, + } _ => (), } } - T::WeightInfo::on_idle() + T::WeightInfo::on_initialize() } } @@ -326,9 +356,12 @@ pub mod pallet { Self::check_currency_id(currency_id)?; ensure!(min_swap_value > Zero::zero(), Error::::ZeroMinSwapValue); ensure!(buyback_duration > Zero::zero(), Error::::ZeroDuration); - ensure!(add_liquidity_duration > Zero::zero(), Error::::ZeroDuration); + ensure!( + add_liquidity_duration > Zero::zero(), + Error::::ZeroDuration + ); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let info = Info { min_swap_value, @@ -367,7 +400,11 @@ pub mod pallet { value, )?; - Self::deposit_event(Event::Charged { who: exchanger, currency_id, value }); + Self::deposit_event(Event::Charged { + who: exchanger, + currency_id, + value, + }); Ok(()) } @@ -378,7 +415,10 @@ pub mod pallet { pub fn remove_vtoken(origin: OriginFor, currency_id: CurrencyIdOf) -> DispatchResult { T::ControlOrigin::ensure_origin(origin)?; - ensure!(Infos::::contains_key(currency_id), Error::::CurrencyIdNotExists); + ensure!( + Infos::::contains_key(currency_id), + Error::::CurrencyIdNotExists + ); Infos::::remove(currency_id); Self::deposit_event(Event::Removed { currency_id }); @@ -458,15 +498,16 @@ pub mod pallet { pub fn check_currency_id(currency_id: CurrencyId) -> Result<(), DispatchError> { match currency_id { - CurrencyId::VToken(token_symbol) => + CurrencyId::VToken(token_symbol) => { if !T::CurrencyIdRegister::check_vtoken_registered(token_symbol) { return Err(Error::::CurrencyIdNotExists.into()); - }, + } + } CurrencyId::VToken2(token_id) => { if !T::CurrencyIdRegister::check_vtoken2_registered(token_id) { return Err(Error::::CurrencyIdNotExists.into()); } - }, + } _ => return Err(Error::::CurrencyIdError.into()), }; Ok(()) diff --git a/pallets/buy-back/src/mock.rs b/pallets/buy-back/src/mock.rs index c11aa3872e..5873683215 100644 --- a/pallets/buy-back/src/mock.rs +++ b/pallets/buy-back/src/mock.rs @@ -178,6 +178,7 @@ impl bifrost_buy_back::Config for Runtime { type ParachainId = ParaInfo; type CurrencyIdRegister = AssetIdMaps; type BbBNC = BbBNC; + type BlockNumberProvider = System; } pub struct ParaInfo; @@ -245,6 +246,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = (); type AssetIdMaps = AssetIdMaps; type TreasuryAccount = TreasuryAccount; + type BlockNumberProvider = System; } parameter_type_with_key! { @@ -303,6 +305,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } parameter_types! { @@ -355,7 +358,12 @@ where amount: AssetBalance, ) -> DispatchResult { let currency_id: CurrencyId = asset_id.try_into().unwrap(); - Local::transfer(currency_id, &origin, &target, amount.unique_saturated_into())?; + Local::transfer( + currency_id, + &origin, + &target, + amount.unique_saturated_into(), + )?; Ok(()) } @@ -456,6 +464,7 @@ impl pallet_xcm::Config for Runtime { parameter_types! { pub const BbBNCTokenType: CurrencyId = VBNC; pub const Week: BlockNumber = 50400; // a week + pub const OneYear: BlockNumber = 2620800; // one year pub const MaxBlock: BlockNumber = 10512000; // four years pub const Multiplier: Balance = 10_u128.pow(12); pub const VoteWeightMultiplier: Balance = 1; @@ -478,6 +487,11 @@ impl bb_bnc::Config for Runtime { type VoteWeightMultiplier = VoteWeightMultiplier; type MaxPositions = MaxPositions; type MarkupRefreshLimit = MarkupRefreshLimit; + type VtokenMinting = VtokenMinting; + type FarmingInfo = (); + type FourYears = MaxBlock; + type OneYear = OneYear; + type BlockNumberProvider = System; } pub struct ExtBuilder { @@ -486,7 +500,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -510,7 +526,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); env_logger::try_init().unwrap_or(()); pallet_balances::GenesisConfig:: { @@ -547,3 +565,8 @@ impl ExtBuilder { t.into() } } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/buy-back/src/tests.rs b/pallets/buy-back/src/tests.rs index 462542f05d..917fd03e28 100644 --- a/pallets/buy-back/src/tests.rs +++ b/pallets/buy-back/src/tests.rs @@ -33,13 +33,72 @@ const LIQUID_PROPORTION: Permill = Permill::from_percent(2); #[test] fn set_vtoken_should_not_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let destruction_ratio = Some(Permill::from_percent(2)); - let bias: Permill = Permill::from_percent(10); - assert_noop!( - BuyBack::set_vtoken( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let destruction_ratio = Some(Permill::from_percent(2)); + let bias: Permill = Permill::from_percent(10); + assert_noop!( + BuyBack::set_vtoken( + RuntimeOrigin::signed(ALICE), + KSM, + VALUE, + LIQUID_PROPORTION, + BUYBACK_DURATION, + LIQUID_DURATION, + true, + destruction_ratio, + bias + ), + Error::::CurrencyIdError + ); + + assert_noop!( + BuyBack::set_vtoken( + RuntimeOrigin::signed(ALICE), + VKSM, + VALUE, + LIQUID_PROPORTION, + 0, + LIQUID_DURATION, + true, + destruction_ratio, + bias + ), + Error::::ZeroDuration + ); + + assert_noop!( + BuyBack::set_vtoken( + RuntimeOrigin::signed(ALICE), + VKSM, + 0, + LIQUID_PROPORTION, + BUYBACK_DURATION, + LIQUID_DURATION, + true, + destruction_ratio, + bias + ), + Error::::ZeroMinSwapValue + ); + }); +} + +#[test] +fn buy_back_with_burn_should_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let zenlink_pair_account_id = init_zenlink(PARAID); + let destruction_ratio = Some(Permill::from_percent(2)); + let bias: Permill = Permill::from_percent(10); + + assert_ok!(BuyBack::set_vtoken( RuntimeOrigin::signed(ALICE), - KSM, + VKSM, VALUE, LIQUID_PROPORTION, BUYBACK_DURATION, @@ -47,317 +106,365 @@ fn set_vtoken_should_not_work() { true, destruction_ratio, bias - ), - Error::::CurrencyIdError - ); + )); + let buyback_account = + ::BuyBackAccount::get().into_account_truncating(); + let incentive_account = IncentivePalletId::get().into_account_truncating(); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 2000 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + BbBNC::set_incentive( + BB_BNC_SYSTEM_POOL_ID, + Some(7 * 86400 / 12), + Some(buyback_account.clone()), + ); + assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); + let infos = Infos::::get(VKSM).unwrap(); + assert_ok!(BuyBack::buy_back(&buyback_account, VKSM, &infos, 0)); + System::set_block_number(System::block_number() + 1); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 3200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 1377 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 611); + }); +} - assert_noop!( - BuyBack::set_vtoken( +#[test] +fn buy_back_no_burn_should_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let zenlink_pair_account_id = init_zenlink(PARAID); + let destruction_ratio = Some(Permill::from_percent(0)); + let bias: Permill = Permill::from_percent(10); + + assert_ok!(BuyBack::set_vtoken( RuntimeOrigin::signed(ALICE), VKSM, VALUE, LIQUID_PROPORTION, - 0, + BUYBACK_DURATION, LIQUID_DURATION, true, destruction_ratio, bias - ), - Error::::ZeroDuration - ); + )); + let buyback_account = + ::BuyBackAccount::get().into_account_truncating(); + let incentive_account = IncentivePalletId::get().into_account_truncating(); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 2000 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + BbBNC::set_incentive( + BB_BNC_SYSTEM_POOL_ID, + Some(7 * 86400 / 12), + Some(buyback_account.clone()), + ); + assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); + let infos = Infos::::get(VKSM).unwrap(); + assert_ok!(BuyBack::buy_back(&buyback_account, VKSM, &infos, 0)); + System::set_block_number(System::block_number() + 1); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 3200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 1377 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 623); + }); +} - assert_noop!( - BuyBack::set_vtoken( +#[test] +fn on_initialize_no_burn_should_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let zenlink_pair_account_id = init_zenlink(PARAID); + let destruction_ratio = None; + let bias: Permill = Permill::from_percent(10); + + assert_ok!(BuyBack::set_vtoken( RuntimeOrigin::signed(ALICE), VKSM, - 0, + VALUE, LIQUID_PROPORTION, BUYBACK_DURATION, LIQUID_DURATION, true, destruction_ratio, bias - ), - Error::::ZeroMinSwapValue - ); - }); -} - -#[test] -fn buy_back_with_burn_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let zenlink_pair_account_id = init_zenlink(PARAID); - let destruction_ratio = Some(Permill::from_percent(2)); - let bias: Permill = Permill::from_percent(10); - - assert_ok!(BuyBack::set_vtoken( - RuntimeOrigin::signed(ALICE), - VKSM, - VALUE, - LIQUID_PROPORTION, - BUYBACK_DURATION, - LIQUID_DURATION, - true, - destruction_ratio, - bias - )); - let buyback_account = ::BuyBackAccount::get().into_account_truncating(); - let incentive_account = IncentivePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 2000); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - BbBNC::set_incentive( - BB_BNC_SYSTEM_POOL_ID, - Some(7 * 86400 / 12), - Some(buyback_account.clone()), - ); - assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); - let infos = Infos::::get(VKSM).unwrap(); - assert_ok!(BuyBack::buy_back(&buyback_account, VKSM, &infos, 0)); - System::set_block_number(System::block_number() + 1); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 3200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 1377); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 611); - }); -} - -#[test] -fn buy_back_no_burn_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let zenlink_pair_account_id = init_zenlink(PARAID); - let destruction_ratio = Some(Permill::from_percent(0)); - let bias: Permill = Permill::from_percent(10); - - assert_ok!(BuyBack::set_vtoken( - RuntimeOrigin::signed(ALICE), - VKSM, - VALUE, - LIQUID_PROPORTION, - BUYBACK_DURATION, - LIQUID_DURATION, - true, - destruction_ratio, - bias - )); - let buyback_account = ::BuyBackAccount::get().into_account_truncating(); - let incentive_account = IncentivePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 2000); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - BbBNC::set_incentive( - BB_BNC_SYSTEM_POOL_ID, - Some(7 * 86400 / 12), - Some(buyback_account.clone()), - ); - assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); - let infos = Infos::::get(VKSM).unwrap(); - assert_ok!(BuyBack::buy_back(&buyback_account, VKSM, &infos, 0)); - System::set_block_number(System::block_number() + 1); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 3200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 1377); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 623); - }); -} - -#[test] -fn on_initialize_no_burn_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let zenlink_pair_account_id = init_zenlink(PARAID); - let destruction_ratio = None; - let bias: Permill = Permill::from_percent(10); - - assert_ok!(BuyBack::set_vtoken( - RuntimeOrigin::signed(ALICE), - VKSM, - VALUE, - LIQUID_PROPORTION, - BUYBACK_DURATION, - LIQUID_DURATION, - true, - destruction_ratio, - bias - )); - let buyback_account = ::BuyBackAccount::get().into_account_truncating(); - let incentive_account = IncentivePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 2000); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - BbBNC::set_incentive( - BB_BNC_SYSTEM_POOL_ID, - Some(7 * 86400 / 12), - Some(buyback_account.clone()), - ); - assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); - BuyBack::on_initialize(1); - BuyBack::on_initialize(2); - BuyBack::on_initialize(3); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 3200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 1377); // 362 - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 623); - }); + )); + let buyback_account = + ::BuyBackAccount::get().into_account_truncating(); + let incentive_account = IncentivePalletId::get().into_account_truncating(); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 2000 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + BbBNC::set_incentive( + BB_BNC_SYSTEM_POOL_ID, + Some(7 * 86400 / 12), + Some(buyback_account.clone()), + ); + assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); + System::set_block_number(1); + BuyBack::on_initialize(1); + System::set_block_number(2); + BuyBack::on_initialize(2); + System::set_block_number(3); + BuyBack::on_initialize(3); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 3200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 1377 + ); // 362 + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 623); + }); } #[test] fn on_initialize_with_burn_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let zenlink_pair_account_id = init_zenlink(PARAID); - let destruction_ratio = Some(Permill::from_percent(10)); - let bias: Permill = Permill::from_percent(10); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let zenlink_pair_account_id = init_zenlink(PARAID); + let destruction_ratio = Some(Permill::from_percent(10)); + let bias: Permill = Permill::from_percent(10); - assert_ok!(BuyBack::set_vtoken( - RuntimeOrigin::signed(ALICE), - VKSM, - VALUE, - LIQUID_PROPORTION, - BUYBACK_DURATION, - LIQUID_DURATION, - true, - destruction_ratio, - bias - )); - let buyback_account = ::BuyBackAccount::get().into_account_truncating(); - let incentive_account = IncentivePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 2000); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - BbBNC::set_incentive( - BB_BNC_SYSTEM_POOL_ID, - Some(7 * 86400 / 12), - Some(buyback_account.clone()), - ); - assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); - BuyBack::on_initialize(>::block_number() + 1); - System::set_block_number(System::block_number() + 1); - BuyBack::on_initialize(>::block_number() + 1); - System::set_block_number(System::block_number() + 1); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 3200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 1377); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 561); // 623 - 62 - }); + assert_ok!(BuyBack::set_vtoken( + RuntimeOrigin::signed(ALICE), + VKSM, + VALUE, + LIQUID_PROPORTION, + BUYBACK_DURATION, + LIQUID_DURATION, + true, + destruction_ratio, + bias + )); + let buyback_account = + ::BuyBackAccount::get().into_account_truncating(); + let incentive_account = IncentivePalletId::get().into_account_truncating(); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 2000 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + BbBNC::set_incentive( + BB_BNC_SYSTEM_POOL_ID, + Some(7 * 86400 / 12), + Some(buyback_account.clone()), + ); + assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); + System::set_block_number(System::block_number() + 1); + BuyBack::on_initialize(0); + System::set_block_number(System::block_number() + 1); + BuyBack::on_initialize(0); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 3200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 1377 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 561); // 623 - 62 + }); } #[test] fn on_initialize_with_bias_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let zenlink_pair_account_id = init_zenlink(PARAID); - let destruction_ratio = None; - let bias: Permill = Permill::from_percent(10); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let zenlink_pair_account_id = init_zenlink(PARAID); + let destruction_ratio = None; + let bias: Permill = Permill::from_percent(10); - assert_ok!(BuyBack::set_vtoken( - RuntimeOrigin::signed(ALICE), - VKSM, - VALUE, - LIQUID_PROPORTION, - BUYBACK_DURATION, - LIQUID_DURATION, - true, - destruction_ratio, - bias - )); - let buyback_account = ::BuyBackAccount::get().into_account_truncating(); - let incentive_account = IncentivePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 2000); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - BbBNC::set_incentive( - BB_BNC_SYSTEM_POOL_ID, - Some(7 * 86400 / 12), - Some(buyback_account.clone()), - ); - assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); - BuyBack::on_initialize(1); - let path = vec![ - AssetId::try_convert_from(VKSM, PARAID).unwrap(), - AssetId::try_convert_from(BNC, PARAID).unwrap(), - ]; - assert_ok!(ZenlinkProtocol::swap_exact_assets_for_assets( - RuntimeOrigin::signed(ALICE), - 100, - 0, - path, - ALICE, - >::block_number() + BlockNumberFor::::from(1u32) - )); - BuyBack::on_initialize(2); - BuyBack::on_initialize(3); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 3300); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 1336); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 578); - }); + assert_ok!(BuyBack::set_vtoken( + RuntimeOrigin::signed(ALICE), + VKSM, + VALUE, + LIQUID_PROPORTION, + BUYBACK_DURATION, + LIQUID_DURATION, + true, + destruction_ratio, + bias + )); + let buyback_account = + ::BuyBackAccount::get().into_account_truncating(); + let incentive_account = IncentivePalletId::get().into_account_truncating(); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 2000 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + BbBNC::set_incentive( + BB_BNC_SYSTEM_POOL_ID, + Some(7 * 86400 / 12), + Some(buyback_account.clone()), + ); + assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); + System::set_block_number(1); + BuyBack::on_initialize(1); + let path = vec![ + AssetId::try_convert_from(VKSM, PARAID).unwrap(), + AssetId::try_convert_from(BNC, PARAID).unwrap(), + ]; + assert_ok!(ZenlinkProtocol::swap_exact_assets_for_assets( + RuntimeOrigin::signed(ALICE), + 100, + 0, + path, + ALICE, + >::block_number() + + BlockNumberFor::::from(1u32) + )); + System::set_block_number(2); + BuyBack::on_initialize(2); + System::set_block_number(3); + BuyBack::on_initialize(3); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 3300 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 1336 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 578); + }); } #[test] fn on_initialize_with_bias_should_not_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let zenlink_pair_account_id = init_zenlink(PARAID); - let destruction_ratio = None; - let bias: Permill = Permill::from_percent(5); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let zenlink_pair_account_id = init_zenlink(PARAID); + let destruction_ratio = None; + let bias: Permill = Permill::from_percent(5); - assert_ok!(BuyBack::set_vtoken( - RuntimeOrigin::signed(ALICE), - VKSM, - VALUE, - LIQUID_PROPORTION, - BUYBACK_DURATION, - LIQUID_DURATION, - true, - destruction_ratio, - bias - )); - let buyback_account = ::BuyBackAccount::get().into_account_truncating(); - let incentive_account = IncentivePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2200); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 2000); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - BbBNC::set_incentive( - BB_BNC_SYSTEM_POOL_ID, - Some(7 * 86400 / 12), - Some(buyback_account.clone()), - ); - assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); - BuyBack::on_initialize(1); - let path = vec![ - AssetId::try_convert_from(VKSM, PARAID).unwrap(), - AssetId::try_convert_from(BNC, PARAID).unwrap(), - ]; - assert_ok!(ZenlinkProtocol::swap_exact_assets_for_assets( - RuntimeOrigin::signed(ALICE), - 100, - 0, - path, - ALICE, - >::block_number() + BlockNumberFor::::from(1u32) - )); - BuyBack::on_initialize(2); - BuyBack::on_initialize(3); - assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 10000); - assert_eq!(Currencies::free_balance(VKSM, &zenlink_pair_account_id), 2300); - assert_eq!(Currencies::free_balance(BNC, &zenlink_pair_account_id), 1914); - assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); - assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); - }); + assert_ok!(BuyBack::set_vtoken( + RuntimeOrigin::signed(ALICE), + VKSM, + VALUE, + LIQUID_PROPORTION, + BUYBACK_DURATION, + LIQUID_DURATION, + true, + destruction_ratio, + bias + )); + let buyback_account = + ::BuyBackAccount::get().into_account_truncating(); + let incentive_account = IncentivePalletId::get().into_account_truncating(); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 9000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2200 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 2000 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + BbBNC::set_incentive( + BB_BNC_SYSTEM_POOL_ID, + Some(7 * 86400 / 12), + Some(buyback_account.clone()), + ); + assert_ok!(BuyBack::charge(RuntimeOrigin::signed(ALICE), VKSM, 1000)); + BuyBack::on_initialize(1); + let path = vec![ + AssetId::try_convert_from(VKSM, PARAID).unwrap(), + AssetId::try_convert_from(BNC, PARAID).unwrap(), + ]; + assert_ok!(ZenlinkProtocol::swap_exact_assets_for_assets( + RuntimeOrigin::signed(ALICE), + 100, + 0, + path, + ALICE, + >::block_number() + + BlockNumberFor::::from(1u32) + )); + BuyBack::on_initialize(2); + BuyBack::on_initialize(3); + assert_eq!(Currencies::free_balance(VKSM, &buyback_account), 10000); + assert_eq!( + Currencies::free_balance(VKSM, &zenlink_pair_account_id), + 2300 + ); + assert_eq!( + Currencies::free_balance(BNC, &zenlink_pair_account_id), + 1914 + ); + assert_eq!(Currencies::free_balance(BNC, &buyback_account), 0); + assert_eq!(Currencies::free_balance(BNC, &incentive_account), 0); + }); } fn init_zenlink(_para_id: u32) -> AccountIdOf { diff --git a/pallets/buy-back/src/weights.rs b/pallets/buy-back/src/weights.rs index 2776509fd7..5bf56cc8f3 100644 --- a/pallets/buy-back/src/weights.rs +++ b/pallets/buy-back/src/weights.rs @@ -15,39 +15,54 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. -//! Autogenerated weights for `bifrost_buy_back` +//! Autogenerated weights for bifrost_buy_back //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `yml`, CPU: `AMD Ryzen 9 3950X 16-Core Processor` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bifrost-polkadot-local")`, DB CACHE: 1024 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.1 +//! DATE: 2024-12-04, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-polkadot-local"), DB CACHE: 1024 // Executed Command: -// ./target/release/bifrost +// target/release/bifrost // benchmark // pallet // --chain=bifrost-polkadot-local -// --pallet=bifrost-buy-back -// --extrinsic=* // --steps=50 // --repeat=20 +// --pallet=bifrost_buy-back +// --extrinsic=* +// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --header=./HEADER-GPL3 -// --output=./bifrost-buy-back.rs +// --output=./pallets/buy-back/src/weights.rs +// --template=./weight-template/pallet-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(missing_docs)] -use frame_support::{traits::Get, weights::{constants::RocksDbWeight, Weight}}; -use core::marker::PhantomData; +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; -/// Weight functions for `bifrost_buy_back`. +/// Weight functions needed for bifrost_buy_back. +pub trait WeightInfo { + fn set_vtoken() -> Weight; + fn charge() -> Weight; + fn remove_vtoken() -> Weight; + fn on_initialize() -> Weight; +} + +// For backwards compatibility and tests impl WeightInfo for () { + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `System::Number` (r:1 w:0) /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `System::ExecutionPhase` (r:1 w:0) @@ -60,14 +75,15 @@ impl WeightInfo for () { /// Proof: `BuyBack::Infos` (`max_values`: None, `max_size`: None, mode: `Measured`) fn set_vtoken() -> Weight { // Proof Size summary in bytes: - // Measured: `25` - // Estimated: `1510` - // Minimum execution time: 11_582_000 picoseconds. - Weight::from_parts(11_753_000, 0) - .saturating_add(Weight::from_parts(0, 1510)) - .saturating_add(RocksDbWeight::get().reads(4)) - .saturating_add(RocksDbWeight::get().writes(3)) + // Measured: `667` + // Estimated: `4132` + // Minimum execution time: 10_542_000 picoseconds. + Weight::from_parts(11_314_000, 4132) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `Tokens::Accounts` (r:2 w:2) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) @@ -82,14 +98,15 @@ impl WeightInfo for () { /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn charge() -> Weight { // Proof Size summary in bytes: - // Measured: `508` + // Measured: `1441` // Estimated: `6196` - // Minimum execution time: 43_842_000 picoseconds. - Weight::from_parts(44_144_000, 0) - .saturating_add(Weight::from_parts(0, 6196)) - .saturating_add(RocksDbWeight::get().reads(8)) - .saturating_add(RocksDbWeight::get().writes(5)) + // Minimum execution time: 32_777_000 picoseconds. + Weight::from_parts(33_824_000, 6196) + .saturating_add(RocksDbWeight::get().reads(9_u64)) + .saturating_add(RocksDbWeight::get().writes(5_u64)) } + /// Storage: `BuyBack::Infos` (r:1 w:1) + /// Proof: `BuyBack::Infos` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `System::Number` (r:1 w:0) /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `System::ExecutionPhase` (r:1 w:0) @@ -98,41 +115,23 @@ impl WeightInfo for () { /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `System::Events` (r:1 w:1) /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BuyBack::Infos` (r:0 w:1) - /// Proof: `BuyBack::Infos` (`max_values`: None, `max_size`: None, mode: `Measured`) fn remove_vtoken() -> Weight { // Proof Size summary in bytes: - // Measured: `25` - // Estimated: `1510` - // Minimum execution time: 10_931_000 picoseconds. - Weight::from_parts(11_161_000, 0) - .saturating_add(Weight::from_parts(0, 1510)) - .saturating_add(RocksDbWeight::get().reads(4)) - .saturating_add(RocksDbWeight::get().writes(3)) + // Measured: `266` + // Estimated: `3731` + // Minimum execution time: 8_183_000 picoseconds. + Weight::from_parts(8_648_000, 3731) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } - /// Storage: `BuyBack::Infos` (r:2 w:1) + /// Storage: `BuyBack::Infos` (r:2 w:0) /// Proof: `BuyBack::Infos` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:2 w:0) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) - fn on_idle() -> Weight { + fn on_initialize() -> Weight { // Proof Size summary in bytes: - // Measured: `502` - // Estimated: `6442` - // Minimum execution time: 32_792_000 picoseconds. - Weight::from_parts(33_293_000, 0) - .saturating_add(Weight::from_parts(0, 6442)) - .saturating_add(RocksDbWeight::get().reads(5)) - .saturating_add(RocksDbWeight::get().writes(1)) + // Measured: `303` + // Estimated: `6243` + // Minimum execution time: 5_610_000 picoseconds. + Weight::from_parts(5_932_000, 6243) + .saturating_add(RocksDbWeight::get().reads(2_u64)) } } - - -/// Weight functions needed for bifrost_buy_back. -pub trait WeightInfo { - fn set_vtoken() -> Weight; - fn charge() -> Weight; - fn remove_vtoken() -> Weight; - fn on_idle() -> Weight; -} diff --git a/pallets/channel-commission/Cargo.toml b/pallets/channel-commission/Cargo.toml index f6f0353045..a14e658261 100644 --- a/pallets/channel-commission/Cargo.toml +++ b/pallets/channel-commission/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-channel-commission" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/channel-commission/src/lib.rs b/pallets/channel-commission/src/lib.rs index d2343f2baf..12a5688fc8 100644 --- a/pallets/channel-commission/src/lib.rs +++ b/pallets/channel-commission/src/lib.rs @@ -31,13 +31,17 @@ use orml_traits::MultiCurrency; use sp_io::MultiRemovalResults; use sp_runtime::{ helpers_128bit::multiply_by_rational_with_rounding, - traits::{AccountIdConversion, CheckedAdd, UniqueSaturatedFrom, UniqueSaturatedInto, Zero}, + traits::{ + AccountIdConversion, BlockNumberProvider, CheckedAdd, UniqueSaturatedFrom, + UniqueSaturatedInto, Zero, + }, PerThing, Percent, Permill, Rounding, SaturatedConversion, Saturating, }; pub use weights::WeightInfo; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; +pub mod migrations; mod mock; mod tests; pub mod weights; @@ -82,6 +86,8 @@ pub mod pallet { // The maximum bytes length of channel name #[pallet::constant] type NameLengthLimit: Get; + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::error] @@ -289,29 +295,37 @@ pub mod pallet { ValueQuery, >; + const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + #[pallet::pallet] #[pallet::without_storage_info] + #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(PhantomData); #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: BlockNumberFor) -> Weight { + fn on_initialize(_: BlockNumberFor) -> Weight { let channel_count: u32 = ChannelNextId::::get().into(); + let current_block_number = T::BlockNumberProvider::current_block_number(); // get the commission token count let commission_token_count = CommissionTokens::::iter().count() as u32; // If the current block number is the first block of a new clearing period, we need to // prepare data for clearing. - if (n % T::ClearingDuration::get()).is_zero() { + if (current_block_number % T::ClearingDuration::get()).is_zero() { Self::set_clearing_environment(); - } else if (n % T::ClearingDuration::get()) < (channel_count + 1).into() { - let channel_index = n % T::ClearingDuration::get() - 1u32.into(); + } else if (current_block_number % T::ClearingDuration::get()) + < (channel_count + 1).into() + { + let channel_index = current_block_number % T::ClearingDuration::get() - 1u32.into(); let channel_id: ChannelId = BlockNumberFor::::unique_saturated_into(channel_index); Self::clear_channel_commissions(channel_id); Self::update_channel_vtoken_shares(channel_id); - } else if (n % T::ClearingDuration::get()) == (channel_count + 1).into() { + } else if (current_block_number % T::ClearingDuration::get()) + == (channel_count + 1).into() + { Self::clear_bifrost_commissions(); } @@ -368,7 +382,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; // check if the channel exists - ensure!(Channels::::contains_key(channel_id), Error::::ChannelNotExist); + ensure!( + Channels::::contains_key(channel_id), + Error::::ChannelNotExist + ); Self::settle_channel_commission(channel_id)?; @@ -447,7 +464,10 @@ pub mod pallet { ensure!(vtoken.is_vtoken(), Error::::InvalidVtoken); // check if the channel exists - ensure!(Channels::::contains_key(channel_id), Error::::ChannelNotExist); + ensure!( + Channels::::contains_key(channel_id), + Error::::ChannelNotExist + ); // check if the vtoken exists ensure!( CommissionTokens::::contains_key(vtoken), @@ -462,7 +482,11 @@ pub mod pallet { ChannelCommissionTokenRates::::insert(channel_id, vtoken, rate); } - Self::deposit_event(Event::ChannelCommissionSet { channel_id, vtoken, rate }); + Self::deposit_event(Event::ChannelCommissionSet { + channel_id, + vtoken, + rate, + }); Ok(()) } @@ -485,6 +509,7 @@ pub mod pallet { if let Some(commission_token) = commission_token_op { // set the commission token CommissionTokens::::insert(vtoken, commission_token); + PeriodClearedCommissions::::insert(vtoken, BalanceOf::::zero()); // set VtokenIssuanceSnapshots for the vtoken let issuance = T::MultiCurrency::total_issuance(vtoken); @@ -527,7 +552,10 @@ pub mod pallet { // only ChannelClaimableCommissions not removed. Channel can still claim the // previous commission - Self::deposit_event(Event::CommissionTokenSet { vtoken, commission_token: None }); + Self::deposit_event(Event::CommissionTokenSet { + vtoken, + commission_token: None, + }); } Ok(()) @@ -553,7 +581,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; // check if the channel exists - ensure!(Channels::::contains_key(channel_id), Error::::ChannelNotExist); + ensure!( + Channels::::contains_key(channel_id), + Error::::ChannelNotExist + ); // check if the vtoken exists ensure!( @@ -825,6 +856,9 @@ impl Pallet { // get the cleared amount from the PeriodClearedCommissions storage let cleared_commission = PeriodClearedCommissions::::get(commission_token); + // Reset the PeriodClearedCommissions of commission_token to 0. + PeriodClearedCommissions::::insert(commission_token, BalanceOf::::zero()); + // calculate the bifrost commission amount let bifrost_commission = total_commission.saturating_sub(cleared_commission); @@ -852,18 +886,6 @@ impl Pallet { }); } }); - - // clear PeriodClearedCommissions - let res = PeriodClearedCommissions::::clear(REMOVE_TOKEN_LIMIT, None); - let executed_num = res.backend; - if let Err(_) = Self::check_removed_all(res) { - log::error!("The removal process was not complete; cursor is still present."); - Self::deposit_event(Event::RemovalNotCompleteError { - target_num: PeriodClearedCommissions::::iter().count() as u32, - limit: REMOVE_TOKEN_LIMIT, - executed_num, - }); - } } pub(crate) fn calculate_mul_div_result( @@ -916,7 +938,11 @@ impl Pallet { // Remove the collected tokens from ChannelClaimableCommissions storage for (commission_token, amount) in tokens_to_remove { ChannelClaimableCommissions::::remove(channel_id, commission_token); - Self::deposit_event(Event::CommissionClaimed { channel_id, commission_token, amount }); + Self::deposit_event(Event::CommissionClaimed { + channel_id, + commission_token, + amount, + }); } Ok(()) @@ -941,7 +967,10 @@ impl VTokenMintRedeemProvider> for Pallet // Retrieve and update total mint for the given vtoken in a single step. PeriodVtokenTotalMint::::mutate(vtoken, |total_mint| -> Result<(), Error> { // Safely add the new amount to the existing total. - total_mint.1 = total_mint.1.checked_add(&amount).ok_or(Error::::Overflow)?; + total_mint.1 = total_mint + .1 + .checked_add(&amount) + .ok_or(Error::::Overflow)?; Ok(()) })?; @@ -951,8 +980,10 @@ impl VTokenMintRedeemProvider> for Pallet channel_id, vtoken, |channel_vtoken_mint| -> Result<(), Error> { - let sum_up_amount = - channel_vtoken_mint.1.checked_add(&amount).ok_or(Error::::Overflow)?; + let sum_up_amount = channel_vtoken_mint + .1 + .checked_add(&amount) + .ok_or(Error::::Overflow)?; channel_vtoken_mint.1 = sum_up_amount; Ok(()) @@ -970,7 +1001,10 @@ impl VTokenMintRedeemProvider> for Pallet // First, add to PeriodVtokenTotalRedeem. PeriodVtokenTotalRedeem::::mutate(vtoken, |total_redeem| -> Result<(), Error> { - total_redeem.1 = total_redeem.1.checked_add(&amount).ok_or(Error::::Overflow)?; + total_redeem.1 = total_redeem + .1 + .checked_add(&amount) + .ok_or(Error::::Overflow)?; Ok(()) })?; @@ -989,15 +1023,19 @@ impl SlpHostingFeeProvider, AccountIdOf> } // get the commission token of the staking token - let vtoken = staking_token.to_vtoken().map_err(|_| Error::::ConversionError)?; + let vtoken = staking_token + .to_vtoken() + .map_err(|_| Error::::ConversionError)?; // If the vtoken is configured for commission, record the hosting fee if let Some(commission_token) = CommissionTokens::::get(vtoken) { PeriodTotalCommissions::::mutate( commission_token, |total_commission| -> Result<(), Error> { - let sum_up_amount = - total_commission.1.checked_add(&amount).ok_or(Error::::Overflow)?; + let sum_up_amount = total_commission + .1 + .checked_add(&amount) + .ok_or(Error::::Overflow)?; total_commission.1 = sum_up_amount; Ok(()) diff --git a/pallets/channel-commission/src/migrations/mod.rs b/pallets/channel-commission/src/migrations/mod.rs new file mode 100644 index 0000000000..379d174c5a --- /dev/null +++ b/pallets/channel-commission/src/migrations/mod.rs @@ -0,0 +1,19 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +pub mod v1; diff --git a/pallets/channel-commission/src/migrations/v1.rs b/pallets/channel-commission/src/migrations/v1.rs new file mode 100644 index 0000000000..3b2815657e --- /dev/null +++ b/pallets/channel-commission/src/migrations/v1.rs @@ -0,0 +1,84 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use crate::*; +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +use frame_support::traits::OnRuntimeUpgrade; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; + +const LOG_TARGET: &str = "channel-commission::migration"; + +pub struct MigrateToV1(sp_std::marker::PhantomData); +impl OnRuntimeUpgrade for MigrateToV1 { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + // Check the storage version + let onchain_version = Pallet::::on_chain_storage_version(); + if onchain_version < 1 { + // Transform storage values + // We transform the storage values from the old into the new format. + log::info!(target: LOG_TARGET, "Start to migrate PeriodClearedCommissions storage..."); + CommissionTokens::::iter_values().for_each(|commission_token| { + log::info!(target: LOG_TARGET, "Init PeriodClearedCommissions for {:?}...", commission_token); + // Init the PeriodClearedCommissions of commission_token to 0. + PeriodClearedCommissions::::insert(commission_token, BalanceOf::::zero()); + }); + + // Update the storage version + StorageVersion::new(1).put::>(); + + // Return the consumed weight + let count = CommissionTokens::::iter().count(); + Weight::from( + T::DbWeight::get().reads_writes(count as u64 + count as u64 + 1, count as u64 + 1), + ) + } else { + // We don't do anything here. + Weight::zero() + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, TryRuntimeError> { + let cnt = PeriodClearedCommissions::::iter().count(); + // print out the pre-migrate storage count + log::info!(target: LOG_TARGET, "PeriodClearedCommissions pre-migrate storage count: {:?}", cnt); + Ok((cnt as u64).encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_cnt: Vec) -> Result<(), TryRuntimeError> { + let new_count = PeriodClearedCommissions::::iter().count(); + let should_count = CommissionTokens::::iter().count(); + + // print out the post-migrate storage count + log::info!( + target: LOG_TARGET, + "PeriodClearedCommissions post-migrate storage count: {:?}", + new_count + ); + + ensure!( + new_count as u64 == should_count as u64, + "Post-migration storage count does not match pre-migration count" + ); + + Ok(()) + } +} diff --git a/pallets/channel-commission/src/mock.rs b/pallets/channel-commission/src/mock.rs index aa9c70ae68..09616e4a77 100644 --- a/pallets/channel-commission/src/mock.rs +++ b/pallets/channel-commission/src/mock.rs @@ -141,6 +141,7 @@ impl bifrost_channel_commission::Config for Runtime { type WeightInfo = (); type ClearingDuration = ClearingDuration; type NameLengthLimit = NameLengthLimit; + type BlockNumberProvider = System; } pub struct ExtBuilder { @@ -149,7 +150,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -175,7 +178,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/channel-commission/src/tests.rs b/pallets/channel-commission/src/tests.rs index 597d81654c..cd02b91979 100644 --- a/pallets/channel-commission/src/tests.rs +++ b/pallets/channel-commission/src/tests.rs @@ -62,873 +62,1083 @@ fn setup() { #[test] fn set_commission_tokens_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(ChannelCommission::set_commission_tokens( - RuntimeOrigin::signed(ALICE), - VKSM, - Some(KSM), - )); - - // Channel A is registered - assert_eq!(CommissionTokens::::get(VKSM), Some(KSM)); - - assert_ok!(ChannelCommission::set_commission_tokens( - RuntimeOrigin::signed(ALICE), - VKSM, - None, - )); - - assert_eq!(CommissionTokens::::get(VKSM), None); - assert_eq!(VtokenIssuanceSnapshots::::get(VKSM), Default::default()); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(KSM), + )); + + // Channel A is registered + assert_eq!(CommissionTokens::::get(VKSM), Some(KSM)); + + assert_ok!(ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VKSM, + None, + )); + + assert_eq!(CommissionTokens::::get(VKSM), None); + assert_eq!( + VtokenIssuanceSnapshots::::get(VKSM), + Default::default() + ); + }); } #[test] fn set_commission_tokens_should_fail_with_invalid_vtoken() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_noop!( - ChannelCommission::set_commission_tokens(RuntimeOrigin::signed(ALICE), KSM, Some(KSM)), - Error::::InvalidVtoken - ); - - assert_noop!( - ChannelCommission::set_commission_tokens(RuntimeOrigin::signed(ALICE), KSM, None), - Error::::InvalidVtoken - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_noop!( + ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + KSM, + Some(KSM) + ), + Error::::InvalidVtoken + ); + + assert_noop!( + ChannelCommission::set_commission_tokens(RuntimeOrigin::signed(ALICE), KSM, None), + Error::::InvalidVtoken + ); + }); } #[test] fn set_commission_tokens_should_fail_with_no_change() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(ChannelCommission::set_commission_tokens( - RuntimeOrigin::signed(ALICE), - VKSM, - Some(KSM), - )); - - assert_noop!( - ChannelCommission::set_commission_tokens(RuntimeOrigin::signed(ALICE), VKSM, Some(KSM)), - Error::::NoChangesMade - ); - - assert_ok!(ChannelCommission::set_commission_tokens( - RuntimeOrigin::signed(ALICE), - VKSM, - None, - )); - - assert_noop!( - ChannelCommission::set_commission_tokens(RuntimeOrigin::signed(ALICE), VKSM, None), - Error::::NoChangesMade - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(KSM), + )); + + assert_noop!( + ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(KSM) + ), + Error::::NoChangesMade + ); + + assert_ok!(ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VKSM, + None, + )); + + assert_noop!( + ChannelCommission::set_commission_tokens(RuntimeOrigin::signed(ALICE), VKSM, None), + Error::::NoChangesMade + ); + }); } #[test] fn register_channel_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - // set commission tokens: VKSM -> KSM - assert_ok!(ChannelCommission::set_commission_tokens( - RuntimeOrigin::signed(ALICE), - VKSM, - Some(KSM), - )); - - // set commission tokens: VBNC -> BNC - assert_ok!(ChannelCommission::set_commission_tokens( - RuntimeOrigin::signed(ALICE), - VBNC, - Some(BNC), - )); - - assert_ok!(ChannelCommission::register_channel( - RuntimeOrigin::signed(ALICE), - CHANNEL_A_NAME.to_vec(), - CHANNEL_A_RECEIVER.clone(), - )); - - // Channel A is registered - assert_eq!( - Channels::::get(0), - Some((CHANNEL_A_RECEIVER, BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap())) - ); - - // next channel id has been increased - assert_eq!(ChannelNextId::::get(), 1); - - // ChannelCommissionTokenRates have been set for Channel A in both VKSM and VBNC - assert_eq!(ChannelCommissionTokenRates::::get(0, VKSM), DEFAULT_COMMISSION_RATE); - assert_eq!(ChannelCommissionTokenRates::::get(0, VBNC), DEFAULT_COMMISSION_RATE); - - // ChannelVtokenShares has been initialized for Channel A in both VKSM and VBNC - assert_eq!(ChannelVtokenShares::::get(0, VKSM), Permill::from_percent(0)); - - assert_eq!(ChannelVtokenShares::::get(0, VBNC), Permill::from_percent(0)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + // set commission tokens: VKSM -> KSM + assert_ok!(ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(KSM), + )); + + // set commission tokens: VBNC -> BNC + assert_ok!(ChannelCommission::set_commission_tokens( + RuntimeOrigin::signed(ALICE), + VBNC, + Some(BNC), + )); + + assert_ok!(ChannelCommission::register_channel( + RuntimeOrigin::signed(ALICE), + CHANNEL_A_NAME.to_vec(), + CHANNEL_A_RECEIVER.clone(), + )); + + // Channel A is registered + assert_eq!( + Channels::::get(0), + Some(( + CHANNEL_A_RECEIVER, + BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() + )) + ); + + // next channel id has been increased + assert_eq!(ChannelNextId::::get(), 1); + + // ChannelCommissionTokenRates have been set for Channel A in both VKSM and VBNC + assert_eq!( + ChannelCommissionTokenRates::::get(0, VKSM), + DEFAULT_COMMISSION_RATE + ); + assert_eq!( + ChannelCommissionTokenRates::::get(0, VBNC), + DEFAULT_COMMISSION_RATE + ); + + // ChannelVtokenShares has been initialized for Channel A in both VKSM and VBNC + assert_eq!( + ChannelVtokenShares::::get(0, VKSM), + Permill::from_percent(0) + ); + + assert_eq!( + ChannelVtokenShares::::get(0, VBNC), + Permill::from_percent(0) + ); + }); } #[test] fn remove_channel_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - // assure Channel A is registered - assert_eq!( - Channels::::get(0), - Some((CHANNEL_A_RECEIVER, BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap())) - ); - - // assure Channel A has records in ChannelCommissionTokenRates in both VKSM and VBNC - assert_eq!(ChannelCommissionTokenRates::::get(0, VKSM), DEFAULT_COMMISSION_RATE); - - assert_eq!(ChannelCommissionTokenRates::::get(0, VBNC), DEFAULT_COMMISSION_RATE); - - // successfully remove Channel A - assert_ok!(ChannelCommission::remove_channel(RuntimeOrigin::signed(ALICE), 0)); - - // Channel A is removed - assert_eq!(Channels::::get(0), None); - - // Channel A has no records in ChannelCommissionTokenRates in both VKSM and VBNC - assert_eq!(ChannelCommissionTokenRates::::get(0, VKSM), Zero::zero()); - - assert_eq!(ChannelCommissionTokenRates::::get(0, VBNC), Zero::zero()); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); + + // assure Channel A is registered + assert_eq!( + Channels::::get(0), + Some(( + CHANNEL_A_RECEIVER, + BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() + )) + ); + + // assure Channel A has records in ChannelCommissionTokenRates in both VKSM and VBNC + assert_eq!( + ChannelCommissionTokenRates::::get(0, VKSM), + DEFAULT_COMMISSION_RATE + ); + + assert_eq!( + ChannelCommissionTokenRates::::get(0, VBNC), + DEFAULT_COMMISSION_RATE + ); + + // successfully remove Channel A + assert_ok!(ChannelCommission::remove_channel( + RuntimeOrigin::signed(ALICE), + 0 + )); + + // Channel A is removed + assert_eq!(Channels::::get(0), None); + + // Channel A has no records in ChannelCommissionTokenRates in both VKSM and VBNC + assert_eq!( + ChannelCommissionTokenRates::::get(0, VKSM), + Zero::zero() + ); + + assert_eq!( + ChannelCommissionTokenRates::::get(0, VBNC), + Zero::zero() + ); + }); } #[test] fn remove_channel_should_fail_with_channel_not_exist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(Channels::::get(0), None); - assert_noop!( - ChannelCommission::remove_channel(RuntimeOrigin::signed(ALICE), 0), - Error::::ChannelNotExist - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(Channels::::get(0), None); + assert_noop!( + ChannelCommission::remove_channel(RuntimeOrigin::signed(ALICE), 0), + Error::::ChannelNotExist + ); + }); } #[test] fn update_channel_receive_account_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - // Channel A is registered - assert_eq!( - Channels::::get(0), - Some((CHANNEL_A_RECEIVER, BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap())) - ); - - // update Channel A's receive account - assert_ok!(ChannelCommission::update_channel_receive_account( - RuntimeOrigin::signed(ALICE), - 0, - CHANNEL_A_BACKUP_RECEIVER.clone(), - )); - - // Channel A's receive account is updated - assert_eq!( - Channels::::get(0), - Some(( - CHANNEL_A_BACKUP_RECEIVER, - BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() - )) - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); + + // Channel A is registered + assert_eq!( + Channels::::get(0), + Some(( + CHANNEL_A_RECEIVER, + BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() + )) + ); + + // update Channel A's receive account + assert_ok!(ChannelCommission::update_channel_receive_account( + RuntimeOrigin::signed(ALICE), + 0, + CHANNEL_A_BACKUP_RECEIVER.clone(), + )); + + // Channel A's receive account is updated + assert_eq!( + Channels::::get(0), + Some(( + CHANNEL_A_BACKUP_RECEIVER, + BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() + )) + ); + }); } #[test] fn update_channel_receive_account_should_fail_with_channel_not_exist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(Channels::::get(0), None); - assert_noop!( - ChannelCommission::update_channel_receive_account( - RuntimeOrigin::signed(ALICE), - 0, - CHANNEL_A_RECEIVER, - ), - Error::::ChannelNotExist - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(Channels::::get(0), None); + assert_noop!( + ChannelCommission::update_channel_receive_account( + RuntimeOrigin::signed(ALICE), + 0, + CHANNEL_A_RECEIVER, + ), + Error::::ChannelNotExist + ); + }); } #[test] fn update_channel_receive_account_should_fail_with_no_changes() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - // Channel A is registered - assert_eq!( - Channels::::get(0), - Some((CHANNEL_A_RECEIVER, BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap())) - ); - - assert_noop!( - ChannelCommission::update_channel_receive_account( - RuntimeOrigin::signed(ALICE), - 0, - CHANNEL_A_RECEIVER, - ), - Error::::NoChangesMade - ); - - // Channel A's receive account is updated - assert_eq!( - Channels::::get(0), - Some((CHANNEL_A_RECEIVER, BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap())) - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); + + // Channel A is registered + assert_eq!( + Channels::::get(0), + Some(( + CHANNEL_A_RECEIVER, + BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() + )) + ); + + assert_noop!( + ChannelCommission::update_channel_receive_account( + RuntimeOrigin::signed(ALICE), + 0, + CHANNEL_A_RECEIVER, + ), + Error::::NoChangesMade + ); + + // Channel A's receive account is updated + assert_eq!( + Channels::::get(0), + Some(( + CHANNEL_A_RECEIVER, + BoundedVec::try_from(CHANNEL_A_NAME.to_vec()).unwrap() + )) + ); + }); } #[test] fn set_channel_commission_token_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - // assure Channel A has records in ChannelCommissionTokenRates in both VKSM and VBNC - assert_eq!(ChannelCommissionTokenRates::::get(0, VKSM), DEFAULT_COMMISSION_RATE); - - assert_eq!(ChannelCommissionTokenRates::::get(0, VBNC), DEFAULT_COMMISSION_RATE); - - let new_rate = Percent::from_percent(50); - // set commission token VKSM to 50% - assert_ok!(ChannelCommission::set_channel_commission_token( - RuntimeOrigin::signed(ALICE), - 0, - VKSM, - Percent::from_percent(50), - )); - - assert_eq!(ChannelCommissionTokenRates::::get(0, VKSM), new_rate); - - // set commission token VBNC to None, which means removing it - assert_ok!(ChannelCommission::set_channel_commission_token( - RuntimeOrigin::signed(ALICE), - 0, - VBNC, - Zero::zero(), - )); - - assert_eq!(ChannelCommissionTokenRates::::get(0, VBNC), Zero::zero()); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); + + // assure Channel A has records in ChannelCommissionTokenRates in both VKSM and VBNC + assert_eq!( + ChannelCommissionTokenRates::::get(0, VKSM), + DEFAULT_COMMISSION_RATE + ); + + assert_eq!( + ChannelCommissionTokenRates::::get(0, VBNC), + DEFAULT_COMMISSION_RATE + ); + + let new_rate = Percent::from_percent(50); + // set commission token VKSM to 50% + assert_ok!(ChannelCommission::set_channel_commission_token( + RuntimeOrigin::signed(ALICE), + 0, + VKSM, + Percent::from_percent(50), + )); + + assert_eq!( + ChannelCommissionTokenRates::::get(0, VKSM), + new_rate + ); + + // set commission token VBNC to None, which means removing it + assert_ok!(ChannelCommission::set_channel_commission_token( + RuntimeOrigin::signed(ALICE), + 0, + VBNC, + Zero::zero(), + )); + + assert_eq!( + ChannelCommissionTokenRates::::get(0, VBNC), + Zero::zero() + ); + }); } #[test] fn set_channel_commission_token_should_fail_with_invalid_vtoken() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_noop!( - ChannelCommission::set_channel_commission_token( - RuntimeOrigin::signed(ALICE), - 0, - KSM, - Percent::from_percent(50), - ), - Error::::InvalidVtoken - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_noop!( + ChannelCommission::set_channel_commission_token( + RuntimeOrigin::signed(ALICE), + 0, + KSM, + Percent::from_percent(50), + ), + Error::::InvalidVtoken + ); + }); } #[test] fn set_channel_commission_token_should_fail_with_channel_not_exist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(Channels::::get(0), None); - assert_noop!( - ChannelCommission::set_channel_commission_token( - RuntimeOrigin::signed(ALICE), - 0, - VKSM, - Percent::from_percent(50), - ), - Error::::ChannelNotExist - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(Channels::::get(0), None); + assert_noop!( + ChannelCommission::set_channel_commission_token( + RuntimeOrigin::signed(ALICE), + 0, + VKSM, + Percent::from_percent(50), + ), + Error::::ChannelNotExist + ); + }); } #[test] fn set_channel_commission_token_should_fail_with_not_configure_commission() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(ChannelCommission::register_channel( - RuntimeOrigin::signed(ALICE), - CHANNEL_A_NAME.to_vec(), - CHANNEL_A_RECEIVER.clone(), - )); - - assert_noop!( - ChannelCommission::set_channel_commission_token( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(ChannelCommission::register_channel( RuntimeOrigin::signed(ALICE), - 0, - VKSM, - Percent::from_percent(50), - ), - Error::::VtokenNotConfiguredForCommission - ); - }); + CHANNEL_A_NAME.to_vec(), + CHANNEL_A_RECEIVER.clone(), + )); + + assert_noop!( + ChannelCommission::set_channel_commission_token( + RuntimeOrigin::signed(ALICE), + 0, + VKSM, + Percent::from_percent(50), + ), + Error::::VtokenNotConfiguredForCommission + ); + }); } #[test] fn claim_commissions_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - let commission_account: AccountId = - ::CommissionPalletId::get().into_account_truncating(); - // endow CommissionPalletId account with 1000 KSM and 1000 BNC - assert_ok!(Currencies::deposit(KSM, &commission_account, 1000)); - assert_ok!(Currencies::deposit(BNC, &commission_account, 1000)); - - // set channel A's claimable KSM amount to 100 - ChannelClaimableCommissions::::insert(0, KSM, 100); - - // set channel A's claimable BNC amount to 120 - ChannelClaimableCommissions::::insert(0, BNC, 120); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); - // assure channel A's claimable KSM amount is 100 - assert_eq!(ChannelClaimableCommissions::::get(0, KSM), 100); + let commission_account: AccountId = + ::CommissionPalletId::get().into_account_truncating(); + // endow CommissionPalletId account with 1000 KSM and 1000 BNC + assert_ok!(Currencies::deposit(KSM, &commission_account, 1000)); + assert_ok!(Currencies::deposit(BNC, &commission_account, 1000)); - // assure channel A's claimable BNC amount is 120 - assert_eq!(ChannelClaimableCommissions::::get(0, BNC), 120); + // set channel A's claimable KSM amount to 100 + ChannelClaimableCommissions::::insert(0, KSM, 100); - let receiver_ksm_before = Currencies::free_balance(KSM, &CHANNEL_A_RECEIVER); - let receiver_bnc_before = Currencies::free_balance(BNC, &CHANNEL_A_RECEIVER); + // set channel A's claimable BNC amount to 120 + ChannelClaimableCommissions::::insert(0, BNC, 120); - // claim 50 KSM from channel A - assert_ok!(ChannelCommission::claim_commissions( - RuntimeOrigin::signed(CHANNEL_A_RECEIVER.clone()), - 0, - )); + // assure channel A's claimable KSM amount is 100 + assert_eq!(ChannelClaimableCommissions::::get(0, KSM), 100); - // assure channel A's claimable KSM amount is None - assert_eq!(ChannelClaimableCommissions::::get(0, KSM), 0); + // assure channel A's claimable BNC amount is 120 + assert_eq!(ChannelClaimableCommissions::::get(0, BNC), 120); - // assure channel A's claimable BNC amount is None - assert_eq!(ChannelClaimableCommissions::::get(0, BNC), 0); + let receiver_ksm_before = Currencies::free_balance(KSM, &CHANNEL_A_RECEIVER); + let receiver_bnc_before = Currencies::free_balance(BNC, &CHANNEL_A_RECEIVER); - // assure channel A's receiver's KSM balance is increased by 100 - assert_eq!(Currencies::free_balance(KSM, &CHANNEL_A_RECEIVER), receiver_ksm_before + 100); - - // assure channel A's receiver's BNC balance is increased by 120 - assert_eq!(Currencies::free_balance(BNC, &CHANNEL_A_RECEIVER), receiver_bnc_before + 120); - }); + // claim 50 KSM from channel A + assert_ok!(ChannelCommission::claim_commissions( + RuntimeOrigin::signed(CHANNEL_A_RECEIVER.clone()), + 0, + )); + + // assure channel A's claimable KSM amount is None + assert_eq!(ChannelClaimableCommissions::::get(0, KSM), 0); + + // assure channel A's claimable BNC amount is None + assert_eq!(ChannelClaimableCommissions::::get(0, BNC), 0); + + // assure channel A's receiver's KSM balance is increased by 100 + assert_eq!( + Currencies::free_balance(KSM, &CHANNEL_A_RECEIVER), + receiver_ksm_before + 100 + ); + + // assure channel A's receiver's BNC balance is increased by 120 + assert_eq!( + Currencies::free_balance(BNC, &CHANNEL_A_RECEIVER), + receiver_bnc_before + 120 + ); + }); } #[test] fn claim_commissions_should_fail_with_channel_not_exist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_noop!( - ChannelCommission::claim_commissions( - RuntimeOrigin::signed(CHANNEL_A_RECEIVER.clone()), - 0, - ), - Error::::ChannelNotExist - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_noop!( + ChannelCommission::claim_commissions( + RuntimeOrigin::signed(CHANNEL_A_RECEIVER.clone()), + 0, + ), + Error::::ChannelNotExist + ); + }); } #[test] fn claim_commissions_should_fail_with_transfer_error() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - ChannelClaimableCommissions::::insert(0, KSM, 100); - assert_noop!( - ChannelCommission::claim_commissions( - RuntimeOrigin::signed(CHANNEL_A_RECEIVER.clone()), - 0, - ), - Error::::TransferError - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); + + ChannelClaimableCommissions::::insert(0, KSM, 100); + assert_noop!( + ChannelCommission::claim_commissions( + RuntimeOrigin::signed(CHANNEL_A_RECEIVER.clone()), + 0, + ), + Error::::TransferError + ); + }); } #[test] fn channel_commission_distribution_with_net_mint_positive_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let commission_account: AccountId = - ::CommissionPalletId::get().into_account_truncating(); - - // set the block number to 35 - System::set_block_number(35); - - setup(); - - // test case 1: net mint is positive.(VKSM) - - // first, set storages for test case 1 - // The first round, set channel A has a share of 20%, channel B has a share of 10%. Channel - // C has not participated yet. - let channel_a_share = Permill::from_percent(20); - ChannelVtokenShares::::insert(0, VKSM, channel_a_share); - - let channel_b_share = Permill::from_percent(10); - ChannelVtokenShares::::insert(1, VKSM, channel_b_share); - - // VtokenIssuanceSnapshots, set both VKSM and VBNC old total issuance to 10000. newly minted - // VKSM is 1000, VBNC is 1000. - VtokenIssuanceSnapshots::::insert(VKSM, (9000, 10000)); - - // PeriodVtokenTotalMint - PeriodVtokenTotalMint::::insert(VKSM, (10000, 2000)); - - // PeriodVtokenTotalRedeem - PeriodVtokenTotalRedeem::::insert(VKSM, (0, 1000)); - - // PeriodChannelVtokenMint. Channel A mint 1000 VKSM, Channel B mint 1000 VKSM. - PeriodChannelVtokenMint::::insert(0, VKSM, (2000, 500)); - PeriodChannelVtokenMint::::insert(1, VKSM, (2000, 100)); - - // PeriodTotalCommissions - PeriodTotalCommissions::::insert(KSM, (0, 100)); - - // set vksm token issuance to 11000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - VKSM, - 11000, - ); - - // set ksm token issuance to 11000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - KSM, - 11000, - ); - - // check balance of commission account - assert_eq!(Currencies::free_balance(VKSM, &commission_account), 11000); - - // set block number to 100 - run_to_block(100); - // set_clearing_environment already been called in block 100 - // check whether the clearing environment is set correctly for block 100 - assert_eq!(VtokenIssuanceSnapshots::::get(VKSM), (10000, 11000)); - assert_eq!(PeriodVtokenTotalMint::::get(VKSM), (2000, 0)); - assert_eq!(PeriodVtokenTotalRedeem::::get(VKSM), (1000, 0)); - assert_eq!(PeriodChannelVtokenMint::::get(0, VKSM), (500, 0)); - assert_eq!(PeriodChannelVtokenMint::::get(1, VKSM), (100, 0)); - assert_eq!(PeriodTotalCommissions::::get(KSM), (100, 0)); - - // get channel B's vtoken share before being cleared - let channel_b_vtoken_share_before = ChannelVtokenShares::::get(1, VKSM); - - run_to_block(101); - - let channel_a_commission = 4; - // check channel A claimable KSM amount after being cleared - assert_eq!(ChannelClaimableCommissions::::get(0, KSM), channel_a_commission); - - let channel_a_new_percentage = - Permill::from_rational_with_rounding(2250u32, 11000u32, Rounding::Down).unwrap(); - // check channel A vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(0, VKSM), channel_a_new_percentage); - - // check channel B has not been cleared yet - assert_eq!(ChannelClaimableCommissions::::get(1, KSM), 0); - assert_eq!(ChannelVtokenShares::::get(1, VKSM), channel_b_vtoken_share_before); - - run_to_block(102); - - let channel_b_commission = 2; - // check channel B claimable KSM amount after being cleared - assert_eq!(ChannelClaimableCommissions::::get(1, KSM), channel_b_commission); - - let channel_b_new_percentage = - Permill::from_rational_with_rounding(1050u32, 11000u32, Rounding::Down).unwrap(); - // check channel B vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(1, VKSM), channel_b_new_percentage); - - // check PeriodClearedCommissions, should be channel a commission + channel b commission - assert_eq!(PeriodClearedCommissions::::get(KSM), 6); - - let bifrost_commission_receiver: AccountId32 = - ::BifrostCommissionReceiver::get(); - // check Bifrost commission balance before being cleared - let bifrost_account_balance_before = - Currencies::free_balance(KSM, &bifrost_commission_receiver); - assert_eq!(bifrost_account_balance_before, 0); - - run_to_block(103); - // cleared commissions should be none - assert_eq!(PeriodClearedCommissions::::get(KSM), 0); - - // check Bifrost commission balance after being cleared - let bifrost_commission_balance_after = - Currencies::free_balance(KSM, &bifrost_commission_receiver); - assert_eq!(bifrost_commission_balance_after, 100 - 6); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let commission_account: AccountId = + ::CommissionPalletId::get().into_account_truncating(); + + // set the block number to 35 + System::set_block_number(35); + + setup(); + + // test case 1: net mint is positive.(VKSM) + + // first, set storages for test case 1 + // The first round, set channel A has a share of 20%, channel B has a share of 10%. Channel + // C has not participated yet. + let channel_a_share = Permill::from_percent(20); + ChannelVtokenShares::::insert(0, VKSM, channel_a_share); + + let channel_b_share = Permill::from_percent(10); + ChannelVtokenShares::::insert(1, VKSM, channel_b_share); + + // VtokenIssuanceSnapshots, set both VKSM and VBNC old total issuance to 10000. newly minted + // VKSM is 1000, VBNC is 1000. + VtokenIssuanceSnapshots::::insert(VKSM, (9000, 10000)); + + // PeriodVtokenTotalMint + PeriodVtokenTotalMint::::insert(VKSM, (10000, 2000)); + + // PeriodVtokenTotalRedeem + PeriodVtokenTotalRedeem::::insert(VKSM, (0, 1000)); + + // PeriodChannelVtokenMint. Channel A mint 1000 VKSM, Channel B mint 1000 VKSM. + PeriodChannelVtokenMint::::insert(0, VKSM, (2000, 500)); + PeriodChannelVtokenMint::::insert(1, VKSM, (2000, 100)); + + // PeriodTotalCommissions + PeriodTotalCommissions::::insert(KSM, (0, 100)); + + // set vksm token issuance to 11000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + VKSM, + 11000, + ); + + // set ksm token issuance to 11000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + KSM, + 11000, + ); + + // check balance of commission account + assert_eq!(Currencies::free_balance(VKSM, &commission_account), 11000); + + // set block number to 100 + run_to_block(100); + // set_clearing_environment already been called in block 100 + // check whether the clearing environment is set correctly for block 100 + assert_eq!( + VtokenIssuanceSnapshots::::get(VKSM), + (10000, 11000) + ); + assert_eq!(PeriodVtokenTotalMint::::get(VKSM), (2000, 0)); + assert_eq!(PeriodVtokenTotalRedeem::::get(VKSM), (1000, 0)); + assert_eq!(PeriodChannelVtokenMint::::get(0, VKSM), (500, 0)); + assert_eq!(PeriodChannelVtokenMint::::get(1, VKSM), (100, 0)); + assert_eq!(PeriodTotalCommissions::::get(KSM), (100, 0)); + + // get channel B's vtoken share before being cleared + let channel_b_vtoken_share_before = ChannelVtokenShares::::get(1, VKSM); + + run_to_block(101); + + let channel_a_commission = 4; + // check channel A claimable KSM amount after being cleared + assert_eq!( + ChannelClaimableCommissions::::get(0, KSM), + channel_a_commission + ); + + let channel_a_new_percentage = + Permill::from_rational_with_rounding(2250u32, 11000u32, Rounding::Down).unwrap(); + // check channel A vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(0, VKSM), + channel_a_new_percentage + ); + + // check channel B has not been cleared yet + assert_eq!(ChannelClaimableCommissions::::get(1, KSM), 0); + assert_eq!( + ChannelVtokenShares::::get(1, VKSM), + channel_b_vtoken_share_before + ); + + run_to_block(102); + + let channel_b_commission = 2; + // check channel B claimable KSM amount after being cleared + assert_eq!( + ChannelClaimableCommissions::::get(1, KSM), + channel_b_commission + ); + + let channel_b_new_percentage = + Permill::from_rational_with_rounding(1050u32, 11000u32, Rounding::Down).unwrap(); + // check channel B vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(1, VKSM), + channel_b_new_percentage + ); + + // check PeriodClearedCommissions, should be channel a commission + channel b commission + assert_eq!(PeriodClearedCommissions::::get(KSM), 6); + + let bifrost_commission_receiver: AccountId32 = + ::BifrostCommissionReceiver::get(); + // check Bifrost commission balance before being cleared + let bifrost_account_balance_before = + Currencies::free_balance(KSM, &bifrost_commission_receiver); + assert_eq!(bifrost_account_balance_before, 0); + + run_to_block(103); + // cleared commissions should be none + assert_eq!(PeriodClearedCommissions::::get(KSM), 0); + + // check Bifrost commission balance after being cleared + let bifrost_commission_balance_after = + Currencies::free_balance(KSM, &bifrost_commission_receiver); + assert_eq!(bifrost_commission_balance_after, 100 - 6); + }); } // test case 2: net mint is negative.(VBNC) #[test] fn channel_commission_distribution_with_net_mint_negative_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let commission_account: AccountId = - ::CommissionPalletId::get().into_account_truncating(); - - // set the block number to 35 - System::set_block_number(35); - - setup(); - - // first, set storages for test case 1 - // The first round, set channel A has a share of 20%, channel B has a share of 10%. Channel - // C has not participated yet. - let channel_a_share = Permill::from_percent(20); - ChannelVtokenShares::::insert(0, VBNC, channel_a_share); - - let channel_b_share = Permill::from_percent(10); - ChannelVtokenShares::::insert(1, VBNC, channel_b_share); - - // VtokenIssuanceSnapshots, set both VBNC old total issuance to 10000. newly minted - // VBNC is 1000. - VtokenIssuanceSnapshots::::insert(VBNC, (9000, 10000)); - - // PeriodVtokenTotalMint - PeriodVtokenTotalMint::::insert(VBNC, (10000, 1000)); - - // PeriodVtokenTotalRedeem - PeriodVtokenTotalRedeem::::insert(VBNC, (0, 2000)); - - // PeriodChannelVtokenMint. Channel A mint 200 VBNC, Channel B mint 100 VBNC. - PeriodChannelVtokenMint::::insert(0, VBNC, (2000, 200)); - PeriodChannelVtokenMint::::insert(1, VBNC, (1000, 100)); - - // PeriodTotalCommissions - PeriodTotalCommissions::::insert(BNC, (0, 100)); - - // set vbnc token issuance to 9000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - VBNC, - 9000, - ); - - // set bnc token issuance to 9000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - BNC, - 9000, - ); - // check balance of commission account - assert_eq!(Currencies::free_balance(VBNC, &commission_account), 9000); - - // set block number to 100 - run_to_block(100); - // set_clearing_environment already been called in block 100 - // check whether the clearing environment is set correctly for block 100 - assert_eq!(VtokenIssuanceSnapshots::::get(VBNC), (10000, 9000)); - assert_eq!(PeriodVtokenTotalMint::::get(VBNC), (1000, 0)); - assert_eq!(PeriodVtokenTotalRedeem::::get(VBNC), (2000, 0)); - assert_eq!(PeriodChannelVtokenMint::::get(0, VBNC), (200, 0)); - assert_eq!(PeriodChannelVtokenMint::::get(1, VBNC), (100, 0)); - assert_eq!(PeriodTotalCommissions::::get(BNC), (100, 0)); - - // get channel A's vtoken share before being cleared - let channel_a_vtoken_share_before = ChannelVtokenShares::::get(0, VBNC); - - // get channel B's vtoken share before being cleared - let channel_b_vtoken_share_before = ChannelVtokenShares::::get(1, VBNC); - - run_to_block(101); - - // Since the net mint is negative, the share of channels should not be changed. - let channel_a_commission = 4; - // check channel A claimable BNC amount after being cleared - assert_eq!(ChannelClaimableCommissions::::get(0, BNC), channel_a_commission); - - // check channel A vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(0, VBNC), channel_a_vtoken_share_before); - - // check channel B has not been cleared yet - assert_eq!(ChannelClaimableCommissions::::get(1, BNC), 0); - assert_eq!(ChannelVtokenShares::::get(1, VBNC), channel_b_vtoken_share_before); - - run_to_block(102); - - // Since the net mint is negative, the share of channels should not be changed. - let channel_b_commission = 2; - // check channel B claimable BNC amount after being cleared - assert_eq!(ChannelClaimableCommissions::::get(1, BNC), channel_b_commission); - - // check channel B vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(1, VBNC), channel_b_vtoken_share_before); - - // check PeriodClearedCommissions, should be channel a commission + channel b commission - assert_eq!(PeriodClearedCommissions::::get(BNC), 6); - - let bifrost_commission_receiver: AccountId32 = - ::BifrostCommissionReceiver::get(); - // check Bifrost commission balance before being cleared - let bifrost_account_balance_before = - Currencies::free_balance(BNC, &bifrost_commission_receiver); - assert_eq!(bifrost_account_balance_before, 0); - - run_to_block(103); - // cleared commissions should be none - assert_eq!(PeriodClearedCommissions::::get(BNC), 0); - - // check Bifrost commission balance after being cleared - let bifrost_commission_balance_after = - Currencies::free_balance(BNC, &bifrost_commission_receiver); - assert_eq!(bifrost_commission_balance_after, 100 - 6); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let commission_account: AccountId = + ::CommissionPalletId::get().into_account_truncating(); + + // set the block number to 35 + System::set_block_number(35); + + setup(); + + // first, set storages for test case 1 + // The first round, set channel A has a share of 20%, channel B has a share of 10%. Channel + // C has not participated yet. + let channel_a_share = Permill::from_percent(20); + ChannelVtokenShares::::insert(0, VBNC, channel_a_share); + + let channel_b_share = Permill::from_percent(10); + ChannelVtokenShares::::insert(1, VBNC, channel_b_share); + + // VtokenIssuanceSnapshots, set both VBNC old total issuance to 10000. newly minted + // VBNC is 1000. + VtokenIssuanceSnapshots::::insert(VBNC, (9000, 10000)); + + // PeriodVtokenTotalMint + PeriodVtokenTotalMint::::insert(VBNC, (10000, 1000)); + + // PeriodVtokenTotalRedeem + PeriodVtokenTotalRedeem::::insert(VBNC, (0, 2000)); + + // PeriodChannelVtokenMint. Channel A mint 200 VBNC, Channel B mint 100 VBNC. + PeriodChannelVtokenMint::::insert(0, VBNC, (2000, 200)); + PeriodChannelVtokenMint::::insert(1, VBNC, (1000, 100)); + + // PeriodTotalCommissions + PeriodTotalCommissions::::insert(BNC, (0, 100)); + + // set vbnc token issuance to 9000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + VBNC, + 9000, + ); + + // set bnc token issuance to 9000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + BNC, + 9000, + ); + // check balance of commission account + assert_eq!(Currencies::free_balance(VBNC, &commission_account), 9000); + + // set block number to 100 + run_to_block(100); + // set_clearing_environment already been called in block 100 + // check whether the clearing environment is set correctly for block 100 + assert_eq!(VtokenIssuanceSnapshots::::get(VBNC), (10000, 9000)); + assert_eq!(PeriodVtokenTotalMint::::get(VBNC), (1000, 0)); + assert_eq!(PeriodVtokenTotalRedeem::::get(VBNC), (2000, 0)); + assert_eq!(PeriodChannelVtokenMint::::get(0, VBNC), (200, 0)); + assert_eq!(PeriodChannelVtokenMint::::get(1, VBNC), (100, 0)); + assert_eq!(PeriodTotalCommissions::::get(BNC), (100, 0)); + + // get channel A's vtoken share before being cleared + let channel_a_vtoken_share_before = ChannelVtokenShares::::get(0, VBNC); + + // get channel B's vtoken share before being cleared + let channel_b_vtoken_share_before = ChannelVtokenShares::::get(1, VBNC); + + run_to_block(101); + + // Since the net mint is negative, the share of channels should not be changed. + let channel_a_commission = 4; + // check channel A claimable BNC amount after being cleared + assert_eq!( + ChannelClaimableCommissions::::get(0, BNC), + channel_a_commission + ); + + // check channel A vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(0, VBNC), + channel_a_vtoken_share_before + ); + + // check channel B has not been cleared yet + assert_eq!(ChannelClaimableCommissions::::get(1, BNC), 0); + assert_eq!( + ChannelVtokenShares::::get(1, VBNC), + channel_b_vtoken_share_before + ); + + run_to_block(102); + + // Since the net mint is negative, the share of channels should not be changed. + let channel_b_commission = 2; + // check channel B claimable BNC amount after being cleared + assert_eq!( + ChannelClaimableCommissions::::get(1, BNC), + channel_b_commission + ); + + // check channel B vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(1, VBNC), + channel_b_vtoken_share_before + ); + + // check PeriodClearedCommissions, should be channel a commission + channel b commission + assert_eq!(PeriodClearedCommissions::::get(BNC), 6); + + let bifrost_commission_receiver: AccountId32 = + ::BifrostCommissionReceiver::get(); + // check Bifrost commission balance before being cleared + let bifrost_account_balance_before = + Currencies::free_balance(BNC, &bifrost_commission_receiver); + assert_eq!(bifrost_account_balance_before, 0); + + run_to_block(103); + // cleared commissions should be none + assert_eq!(PeriodClearedCommissions::::get(BNC), 0); + + // check Bifrost commission balance after being cleared + let bifrost_commission_balance_after = + Currencies::free_balance(BNC, &bifrost_commission_receiver); + assert_eq!(bifrost_commission_balance_after, 100 - 6); + }); } #[test] fn set_channel_vtoken_shares_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - setup(); - - // assure Channel A has no 0 percent in ChannelVtokenShares in VKSM - assert_eq!(ChannelVtokenShares::::get(0, VKSM), Permill::from_percent(0)); - - // set channel A's vtoken share in VKSM to 50% - assert_ok!(ChannelCommission::set_channel_vtoken_shares( - RuntimeOrigin::signed(ALICE), - 0, - VKSM, - Permill::from_percent(50), - )); - - assert_eq!(ChannelVtokenShares::::get(0, VKSM), Permill::from_percent(50)); - - // set channel B's vtoken share in VKSM to 90%, it should fail because the sum of all shares - // should be less than or equal to 100% - assert_noop!( - ChannelCommission::set_channel_vtoken_shares( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + setup(); + + // assure Channel A has no 0 percent in ChannelVtokenShares in VKSM + assert_eq!( + ChannelVtokenShares::::get(0, VKSM), + Permill::from_percent(0) + ); + + // set channel A's vtoken share in VKSM to 50% + assert_ok!(ChannelCommission::set_channel_vtoken_shares( + RuntimeOrigin::signed(ALICE), + 0, + VKSM, + Permill::from_percent(50), + )); + + assert_eq!( + ChannelVtokenShares::::get(0, VKSM), + Permill::from_percent(50) + ); + + // set channel B's vtoken share in VKSM to 90%, it should fail because the sum of all shares + // should be less than or equal to 100% + assert_noop!( + ChannelCommission::set_channel_vtoken_shares( + RuntimeOrigin::signed(ALICE), + 1, + VKSM, + Permill::from_percent(90), + ), + Error::::InvalidCommissionRate + ); + + // set channel B's vtoken share in VKSM to 30%, it should be ok now + assert_ok!(ChannelCommission::set_channel_vtoken_shares( RuntimeOrigin::signed(ALICE), 1, VKSM, - Permill::from_percent(90), - ), - Error::::InvalidCommissionRate - ); - - // set channel B's vtoken share in VKSM to 30%, it should be ok now - assert_ok!(ChannelCommission::set_channel_vtoken_shares( - RuntimeOrigin::signed(ALICE), - 1, - VKSM, - Permill::from_percent(30), - )); - - assert_eq!(ChannelVtokenShares::::get(1, VKSM), Permill::from_percent(30)); - }); + Permill::from_percent(30), + )); + + assert_eq!( + ChannelVtokenShares::::get(1, VKSM), + Permill::from_percent(30) + ); + }); } #[test] fn set_channel_vtoken_shares_should_fail_with_channel_not_exist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_noop!( - ChannelCommission::set_channel_vtoken_shares( - RuntimeOrigin::signed(ALICE), - 0, - VKSM, - Permill::from_percent(90), - ), - Error::::ChannelNotExist - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_noop!( + ChannelCommission::set_channel_vtoken_shares( + RuntimeOrigin::signed(ALICE), + 0, + VKSM, + Permill::from_percent(90), + ), + Error::::ChannelNotExist + ); + }); } #[test] fn set_channel_vtoken_shares_should_fail_with_vtoken_not_configured() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(ChannelCommission::register_channel( - RuntimeOrigin::signed(ALICE), - CHANNEL_A_NAME.to_vec(), - CHANNEL_A_RECEIVER.clone(), - )); - - assert_noop!( - ChannelCommission::set_channel_vtoken_shares( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(ChannelCommission::register_channel( RuntimeOrigin::signed(ALICE), - 0, - VKSM, - Permill::from_percent(90), - ), - Error::::VtokenNotConfiguredForCommission - ); - }); + CHANNEL_A_NAME.to_vec(), + CHANNEL_A_RECEIVER.clone(), + )); + + assert_noop!( + ChannelCommission::set_channel_vtoken_shares( + RuntimeOrigin::signed(ALICE), + 0, + VKSM, + Permill::from_percent(90), + ), + Error::::VtokenNotConfiguredForCommission + ); + }); } // register a new channel base on some existing channels, and mint some tokens to see whether the // shares of existing channels are updated correctly.s #[test] fn register_a_new_channel_and_mint_should_update_shares_and_get_claimable_tokens() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let commission_account: AccountId = - ::CommissionPalletId::get().into_account_truncating(); - - // set the block number to 35 - System::set_block_number(35); - - // we have registered channel A and channel B for 0 shares for VKSM - setup(); - - // VtokenIssuanceSnapshots, set VKSM old total issuance to 10000. newly minted - // VKSM is 1000 - VtokenIssuanceSnapshots::::insert(VKSM, (9000, 10000)); - - // PeriodVtokenTotalMint - PeriodVtokenTotalMint::::insert(VKSM, (10000, 2000)); - - // PeriodVtokenTotalRedeem - PeriodVtokenTotalRedeem::::insert(VKSM, (0, 1000)); - - // PeriodChannelVtokenMint. Channel A mint 1000 VKSM, Channel B mint 1000 VKSM. - PeriodChannelVtokenMint::::insert(0, VKSM, (2000, 500)); - PeriodChannelVtokenMint::::insert(1, VKSM, (2000, 100)); - - // set vksm token issuance to 11000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - VKSM, - 11000, - ); - - // set ksm token issuance to 11000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - KSM, - 11000, - ); - - // set block number to 100 - run_to_block(100); - run_to_block(101); - - let channel_a_new_net_mint: u32 = 500 * 1000 / 2000; - - let channel_a_new_percentage = - Permill::from_rational_with_rounding(channel_a_new_net_mint, 11000u32, Rounding::Down) - .unwrap(); - // check channel A vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(0, VKSM), channel_a_new_percentage); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let commission_account: AccountId = + ::CommissionPalletId::get().into_account_truncating(); + + // set the block number to 35 + System::set_block_number(35); + + // we have registered channel A and channel B for 0 shares for VKSM + setup(); + + // VtokenIssuanceSnapshots, set VKSM old total issuance to 10000. newly minted + // VKSM is 1000 + VtokenIssuanceSnapshots::::insert(VKSM, (9000, 10000)); + + // PeriodVtokenTotalMint + PeriodVtokenTotalMint::::insert(VKSM, (10000, 2000)); + + // PeriodVtokenTotalRedeem + PeriodVtokenTotalRedeem::::insert(VKSM, (0, 1000)); + + // PeriodChannelVtokenMint. Channel A mint 1000 VKSM, Channel B mint 1000 VKSM. + PeriodChannelVtokenMint::::insert(0, VKSM, (2000, 500)); + PeriodChannelVtokenMint::::insert(1, VKSM, (2000, 100)); + + // set vksm token issuance to 11000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + VKSM, + 11000, + ); + + // set ksm token issuance to 11000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + KSM, + 11000, + ); + + // set block number to 100 + run_to_block(100); + run_to_block(101); + + let channel_a_new_net_mint: u32 = 500 * 1000 / 2000; + + let channel_a_new_percentage = Permill::from_rational_with_rounding( + channel_a_new_net_mint, + 11000u32, + Rounding::Down, + ) + .unwrap(); + // check channel A vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(0, VKSM), + channel_a_new_percentage + ); + }); } #[test] fn on_initialize_hook_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let commission_account: AccountId = - ::CommissionPalletId::get().into_account_truncating(); - - // set the block number to 35 - System::set_block_number(35); - - setup(); - - // test case 1: net mint is positive.(VKSM) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let commission_account: AccountId = + ::CommissionPalletId::get().into_account_truncating(); - // first, set storages for test case 1 - // The first round, set channel A has a share of 20%, channel B has a share of 10%. Channel - // C has not participated yet. - let channel_a_share = Permill::from_percent(20); - ChannelVtokenShares::::insert(0, VKSM, channel_a_share); - - let channel_b_share = Permill::from_percent(10); - ChannelVtokenShares::::insert(1, VKSM, channel_b_share); - - // VtokenIssuanceSnapshots, set both VKSM and VBNC old total issuance to 10000. newly minted - // VKSM is 1000, VBNC is 1000. - VtokenIssuanceSnapshots::::insert(VKSM, (9000, 10000)); - - // PeriodVtokenTotalMint - PeriodVtokenTotalMint::::insert(VKSM, (10000, 2000)); - - // PeriodVtokenTotalRedeem - PeriodVtokenTotalRedeem::::insert(VKSM, (0, 1000)); - - // PeriodChannelVtokenMint. Channel A mint 1000 VKSM, Channel B mint 1000 VKSM. - PeriodChannelVtokenMint::::insert(0, VKSM, (2000, 500)); - PeriodChannelVtokenMint::::insert(1, VKSM, (2000, 100)); - - // PeriodTotalCommissions - PeriodTotalCommissions::::insert(KSM, (0, 100)); - - // set vksm token issuance to 11000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - VKSM, - 11000, - ); - - // set ksm token issuance to 11000 - let _ = Currencies::update_balance( - RuntimeOrigin::root(), - commission_account.clone(), - KSM, - 11000, - ); - - // check balance of commission account - assert_eq!(Currencies::free_balance(VKSM, &commission_account), 11000); - - // set block number to 100 - ChannelCommission::on_initialize(100); - // set_clearing_environment already been called in block 100 - // check whether the clearing environment is set correctly for block 100 - assert_eq!(VtokenIssuanceSnapshots::::get(VKSM), (10000, 11000)); - assert_eq!(PeriodVtokenTotalMint::::get(VKSM), (2000, 0)); - assert_eq!(PeriodVtokenTotalRedeem::::get(VKSM), (1000, 0)); - assert_eq!(PeriodChannelVtokenMint::::get(0, VKSM), (500, 0)); - assert_eq!(PeriodChannelVtokenMint::::get(1, VKSM), (100, 0)); - assert_eq!(PeriodTotalCommissions::::get(KSM), (100, 0)); - - // get channel B's vtoken share before being cleared - let channel_b_vtoken_share_before = ChannelVtokenShares::::get(1, VKSM); - - ChannelCommission::on_initialize(101); - - let channel_a_commission = 4; - // check channel A claimable KSM amount after being cleared - assert_eq!(ChannelClaimableCommissions::::get(0, KSM), channel_a_commission); - - let channel_a_new_percentage = - Permill::from_rational_with_rounding(2250u32, 11000u32, Rounding::Down).unwrap(); - // check channel A vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(0, VKSM), channel_a_new_percentage); - - // check channel B has not been cleared yet - assert_eq!(ChannelClaimableCommissions::::get(1, KSM), 0); - assert_eq!(ChannelVtokenShares::::get(1, VKSM), channel_b_vtoken_share_before); - - ChannelCommission::on_initialize(102); - - let channel_b_commission = 2; - // check channel B claimable KSM amount after being cleared - assert_eq!(ChannelClaimableCommissions::::get(1, KSM), channel_b_commission); - - let channel_b_new_percentage = - Permill::from_rational_with_rounding(1050u32, 11000u32, Rounding::Down).unwrap(); - // check channel B vtoken share after being cleared - assert_eq!(ChannelVtokenShares::::get(1, VKSM), channel_b_new_percentage); - - // check PeriodClearedCommissions, should be channel a commission + channel b commission - assert_eq!(PeriodClearedCommissions::::get(KSM), 6); - - let bifrost_commission_receiver: AccountId32 = - ::BifrostCommissionReceiver::get(); - // check Bifrost commission balance before being cleared - let bifrost_account_balance_before = - Currencies::free_balance(KSM, &bifrost_commission_receiver); - assert_eq!(bifrost_account_balance_before, 0); - - ChannelCommission::on_initialize(103); - - // cleared commissions should be none - assert_eq!(PeriodClearedCommissions::::get(KSM), 0); - - // check Bifrost commission balance after being cleared - let bifrost_commission_balance_after = - Currencies::free_balance(KSM, &bifrost_commission_receiver); - assert_eq!(bifrost_commission_balance_after, 100 - 6); - }); + // set the block number to 35 + System::set_block_number(35); + + setup(); + + // test case 1: net mint is positive.(VKSM) + + // first, set storages for test case 1 + // The first round, set channel A has a share of 20%, channel B has a share of 10%. Channel + // C has not participated yet. + let channel_a_share = Permill::from_percent(20); + ChannelVtokenShares::::insert(0, VKSM, channel_a_share); + + let channel_b_share = Permill::from_percent(10); + ChannelVtokenShares::::insert(1, VKSM, channel_b_share); + + // VtokenIssuanceSnapshots, set both VKSM and VBNC old total issuance to 10000. newly minted + // VKSM is 1000, VBNC is 1000. + VtokenIssuanceSnapshots::::insert(VKSM, (9000, 10000)); + + // PeriodVtokenTotalMint + PeriodVtokenTotalMint::::insert(VKSM, (10000, 2000)); + + // PeriodVtokenTotalRedeem + PeriodVtokenTotalRedeem::::insert(VKSM, (0, 1000)); + + // PeriodChannelVtokenMint. Channel A mint 1000 VKSM, Channel B mint 1000 VKSM. + PeriodChannelVtokenMint::::insert(0, VKSM, (2000, 500)); + PeriodChannelVtokenMint::::insert(1, VKSM, (2000, 100)); + + // PeriodTotalCommissions + PeriodTotalCommissions::::insert(KSM, (0, 100)); + + // set vksm token issuance to 11000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + VKSM, + 11000, + ); + + // set ksm token issuance to 11000 + let _ = Currencies::update_balance( + RuntimeOrigin::root(), + commission_account.clone(), + KSM, + 11000, + ); + + // check balance of commission account + assert_eq!(Currencies::free_balance(VKSM, &commission_account), 11000); + + // set block number to 100 + System::set_block_number(100); + ChannelCommission::on_initialize(100); + // set_clearing_environment already been called in block 100 + // check whether the clearing environment is set correctly for block 100 + assert_eq!( + VtokenIssuanceSnapshots::::get(VKSM), + (10000, 11000) + ); + assert_eq!(PeriodVtokenTotalMint::::get(VKSM), (2000, 0)); + assert_eq!(PeriodVtokenTotalRedeem::::get(VKSM), (1000, 0)); + assert_eq!(PeriodChannelVtokenMint::::get(0, VKSM), (500, 0)); + assert_eq!(PeriodChannelVtokenMint::::get(1, VKSM), (100, 0)); + assert_eq!(PeriodTotalCommissions::::get(KSM), (100, 0)); + + // get channel B's vtoken share before being cleared + let channel_b_vtoken_share_before = ChannelVtokenShares::::get(1, VKSM); + + System::set_block_number(101); + ChannelCommission::on_initialize(101); + + let channel_a_commission = 4; + // check channel A claimable KSM amount after being cleared + assert_eq!( + ChannelClaimableCommissions::::get(0, KSM), + channel_a_commission + ); + + let channel_a_new_percentage = + Permill::from_rational_with_rounding(2250u32, 11000u32, Rounding::Down).unwrap(); + // check channel A vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(0, VKSM), + channel_a_new_percentage + ); + + // check channel B has not been cleared yet + assert_eq!(ChannelClaimableCommissions::::get(1, KSM), 0); + assert_eq!( + ChannelVtokenShares::::get(1, VKSM), + channel_b_vtoken_share_before + ); + + System::set_block_number(102); + ChannelCommission::on_initialize(102); + + let channel_b_commission = 2; + // check channel B claimable KSM amount after being cleared + assert_eq!( + ChannelClaimableCommissions::::get(1, KSM), + channel_b_commission + ); + + let channel_b_new_percentage = + Permill::from_rational_with_rounding(1050u32, 11000u32, Rounding::Down).unwrap(); + // check channel B vtoken share after being cleared + assert_eq!( + ChannelVtokenShares::::get(1, VKSM), + channel_b_new_percentage + ); + + // check PeriodClearedCommissions, should be channel a commission + channel b commission + assert_eq!(PeriodClearedCommissions::::get(KSM), 6); + + let bifrost_commission_receiver: AccountId32 = + ::BifrostCommissionReceiver::get(); + // check Bifrost commission balance before being cleared + let bifrost_account_balance_before = + Currencies::free_balance(KSM, &bifrost_commission_receiver); + assert_eq!(bifrost_account_balance_before, 0); + + System::set_block_number(103); + ChannelCommission::on_initialize(103); + + // cleared commissions should be none + assert_eq!(PeriodClearedCommissions::::get(KSM), 0); + + // check Bifrost commission balance after being cleared + let bifrost_commission_balance_after = + Currencies::free_balance(KSM, &bifrost_commission_receiver); + assert_eq!(bifrost_commission_balance_after, 100 - 6); + }); } diff --git a/pallets/clouds-convert/Cargo.toml b/pallets/clouds-convert/Cargo.toml index 8a843fb444..edff120b70 100644 --- a/pallets/clouds-convert/Cargo.toml +++ b/pallets/clouds-convert/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-clouds-convert" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/clouds-convert/src/benchmarking.rs b/pallets/clouds-convert/src/benchmarking.rs index f87a500ad1..f72d587037 100644 --- a/pallets/clouds-convert/src/benchmarking.rs +++ b/pallets/clouds-convert/src/benchmarking.rs @@ -20,28 +20,64 @@ #![cfg(feature = "runtime-benchmarks")] use bifrost_primitives::{currency::CLOUD, VBNC}; -use frame_benchmarking::{account, benchmarks}; +use frame_benchmarking::v2::*; use frame_system::RawOrigin; use sp_runtime::traits::{UniqueSaturatedFrom, Zero}; use crate::{BalanceOf, Call, Config, Pallet as CloudsConvert, Pallet}; use orml_traits::MultiCurrency; -benchmarks! { -clouds_to_vebnc { - let test_account: T::AccountId = account("seed",1,1); +#[benchmarks] +mod benchmarks { + use super::*; - T::MultiCurrency::deposit(CLOUD, &test_account, BalanceOf::::unique_saturated_from(100_000_000_000_000u128))?; - T::MultiCurrency::deposit(VBNC, &CloudsConvert::::clouds_pool_account(), BalanceOf::::unique_saturated_from(100_000_000_000_000_000_000u128))?; + #[benchmark] + fn clouds_to_vebnc() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); -}: _(RawOrigin::Signed(test_account), BalanceOf::::unique_saturated_from(10_000_000_000_000u128), Zero::zero()) + T::MultiCurrency::deposit( + CLOUD, + &test_account, + BalanceOf::::unique_saturated_from(100_000_000_000_000u128), + )?; + T::MultiCurrency::deposit( + VBNC, + &CloudsConvert::::clouds_pool_account(), + BalanceOf::::unique_saturated_from(100_000_000_000_000_000_000u128), + )?; -charge_vbnc { - let test_account: T::AccountId = account("seed",1,1); + #[extrinsic_call] + _( + RawOrigin::Signed(test_account), + BalanceOf::::unique_saturated_from(10_000_000_000_000u128), + Zero::zero(), + ); - T::MultiCurrency::deposit(VBNC, &test_account, BalanceOf::::unique_saturated_from(100_000_000_000_000u128))?; + Ok(()) + } -}: _(RawOrigin::Signed(test_account),BalanceOf::::unique_saturated_from(50_000_000_000u128)) + #[benchmark] + fn charge_vbnc() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); - impl_benchmark_test_suite!(CloudsConvert,crate::mock::ExtBuilder::default().build(),crate::mock::Runtime); + T::MultiCurrency::deposit( + VBNC, + &test_account, + BalanceOf::::unique_saturated_from(100_000_000_000_000u128), + )?; + + #[extrinsic_call] + _( + RawOrigin::Signed(test_account), + BalanceOf::::unique_saturated_from(50_000_000_000u128), + ); + + Ok(()) + } + + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/clouds-convert/src/lib.rs b/pallets/clouds-convert/src/lib.rs index 100d27baf2..ea65ec8901 100644 --- a/pallets/clouds-convert/src/lib.rs +++ b/pallets/clouds-convert/src/lib.rs @@ -97,9 +97,14 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - CloudsConverted { clouds: BalanceOf, vebnc: BalanceOf }, - - VbncCharged { vbnc: BalanceOf }, + CloudsConverted { + clouds: BalanceOf, + vebnc: BalanceOf, + }, + + VbncCharged { + vbnc: BalanceOf, + }, } #[pallet::pallet] @@ -125,10 +130,16 @@ pub mod pallet { .map_err(|_| Error::::NotEnoughBalance)?; let can_get_vbnc = Self::calculate_can_get_vbnc(value)?; - ensure!(can_get_vbnc >= expected_min_vebnc, Error::::LessThanExpected); + ensure!( + can_get_vbnc >= expected_min_vebnc, + Error::::LessThanExpected + ); // ensure can_get_vbnc greater than existential deposit let existential_deposit = T::MultiCurrency::minimum_balance(VBNC); - ensure!(can_get_vbnc >= existential_deposit, Error::::LessThanExistentialDeposit); + ensure!( + can_get_vbnc >= existential_deposit, + Error::::LessThanExistentialDeposit + ); // burn clouds T::MultiCurrency::withdraw(CLOUD, &who, value)?; @@ -141,7 +152,10 @@ pub mod pallet { T::BbBNC::create_lock_inner(&who, can_get_vbnc, T::LockedBlocks::get())?; // deposit event - Self::deposit_event(Event::CloudsConverted { clouds: value, vebnc: can_get_vbnc }); + Self::deposit_event(Event::CloudsConverted { + clouds: value, + vebnc: can_get_vbnc, + }); Ok(()) } diff --git a/pallets/clouds-convert/src/mock.rs b/pallets/clouds-convert/src/mock.rs index b4b455135b..79add8da4c 100644 --- a/pallets/clouds-convert/src/mock.rs +++ b/pallets/clouds-convert/src/mock.rs @@ -178,6 +178,7 @@ impl bifrost_clouds_convert::Config for Runtime { parameter_types! { pub const BbBNCTokenType: CurrencyId = VBNC; pub const Week: BlockNumber = 50400; // a week + pub const OneYear: BlockNumber = 2620800; // one year pub const MaxBlock: BlockNumber = 10512000; // four years pub const Multiplier: Balance = 10_u128.pow(12); pub const VoteWeightMultiplier: Balance = 1; @@ -200,6 +201,11 @@ impl bb_bnc::Config for Runtime { type VoteWeightMultiplier = VoteWeightMultiplier; type MaxPositions = MaxPositions; type MarkupRefreshLimit = MarkupRefreshLimit; + type VtokenMinting = (); + type FarmingInfo = (); + type FourYears = MaxBlock; + type OneYear = OneYear; + type BlockNumberProvider = System; } pub struct ExtBuilder { @@ -208,7 +214,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -228,7 +236,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self @@ -276,3 +286,8 @@ pub fn _run_to_block(n: BlockNumber) { CloudsConvert::on_initialize(System::block_number()); } } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/clouds-convert/src/tests.rs b/pallets/clouds-convert/src/tests.rs index c325395bf8..30fa14a1ae 100644 --- a/pallets/clouds-convert/src/tests.rs +++ b/pallets/clouds-convert/src/tests.rs @@ -26,93 +26,107 @@ use frame_support::{assert_noop, assert_ok}; #[test] fn clouds_to_vebnc_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - // Bob convert 100 clouds to vebnc - assert_noop!( - CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 0), - Error::::NotEnoughBalance - ); - - // deposit 500 clouds to Bob - assert_ok!(Tokens::deposit(CLOUD, &BOB, 500)); - - // expect too much vBNC - assert_noop!( - CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 100000), - Error::::LessThanExpected - ); - // convert too little clouds - assert_noop!( - CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 1, 0), - Error::::LessThanExistentialDeposit - ); - - // pool does not have enough vBNC - assert_noop!( - CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 1), - Error::::LessThanExpected - ); - // deposit some vBNC to Pool - assert_ok!(Tokens::deposit(VBNC, &CloudsConvert::clouds_pool_account(), 100000000000)); - - // check the veBNC balance of Bob - let bob_old_vebnc_balance = - ::BbBNC::balance_of(&BOB, None).unwrap(); - - // check the old pool balance - let old_pool_balance = ::MultiCurrency::free_balance( - VBNC, - &CloudsConvert::clouds_pool_account(), - ); - - // Bob convert 100 clouds to vebnc - assert_ok!(CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 1)); - - // check the veBNC balance of Bob - assert_eq!( - ::BbBNC::balance_of(&BOB, None).unwrap(), - bob_old_vebnc_balance + 20034907200 - ); - - // check the new pool balance - assert_eq!( - ::MultiCurrency::free_balance( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + // Bob convert 100 clouds to vebnc + assert_noop!( + CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 0), + Error::::NotEnoughBalance + ); + + // deposit 500 clouds to Bob + assert_ok!(Tokens::deposit(CLOUD, &BOB, 500)); + + // expect too much vBNC + assert_noop!( + CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 100000), + Error::::LessThanExpected + ); + // convert too little clouds + assert_noop!( + CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 1, 0), + Error::::LessThanExistentialDeposit + ); + + // pool does not have enough vBNC + assert_noop!( + CloudsConvert::clouds_to_vebnc(RuntimeOrigin::signed(BOB), 100, 1), + Error::::LessThanExpected + ); + // deposit some vBNC to Pool + assert_ok!(Tokens::deposit( VBNC, - &CloudsConvert::clouds_pool_account() - ), - old_pool_balance - 20000000000 - ); - }); + &CloudsConvert::clouds_pool_account(), + 100000000000 + )); + + // check the veBNC balance of Bob + let bob_old_vebnc_balance = + ::BbBNC::balance_of(&BOB, None).unwrap(); + + // check the old pool balance + let old_pool_balance = ::MultiCurrency::free_balance( + VBNC, + &CloudsConvert::clouds_pool_account(), + ); + + // Bob convert 100 clouds to vebnc + assert_ok!(CloudsConvert::clouds_to_vebnc( + RuntimeOrigin::signed(BOB), + 100, + 1 + )); + + // check the veBNC balance of Bob + assert_eq!( + ::BbBNC::balance_of(&BOB, None).unwrap(), + bob_old_vebnc_balance + 20034907200 + ); + + // check the new pool balance + assert_eq!( + ::MultiCurrency::free_balance( + VBNC, + &CloudsConvert::clouds_pool_account() + ), + old_pool_balance - 20000000000 + ); + }); } #[test] fn charge_vbnc_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - // check the vbnc balance of the pool - let old_pool_balance = ::MultiCurrency::free_balance( - VBNC, - &CloudsConvert::clouds_pool_account(), - ); - - // Bob charge 100 vbnc to the pool - assert_noop!( - CloudsConvert::charge_vbnc(RuntimeOrigin::signed(BOB), 100), - Error::::NotEnoughBalance - ); - - // deposit 100 vbnc to Bob - assert_ok!(Tokens::deposit(VBNC, &BOB, 500)); - - // Bob charge 100 vbnc to the pool - assert_ok!(CloudsConvert::charge_vbnc(RuntimeOrigin::signed(BOB), 100)); - - // check the new pool balance - assert_eq!( - ::MultiCurrency::free_balance( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + // check the vbnc balance of the pool + let old_pool_balance = ::MultiCurrency::free_balance( VBNC, - &CloudsConvert::clouds_pool_account() - ), - old_pool_balance + 100 - ); - }); + &CloudsConvert::clouds_pool_account(), + ); + + // Bob charge 100 vbnc to the pool + assert_noop!( + CloudsConvert::charge_vbnc(RuntimeOrigin::signed(BOB), 100), + Error::::NotEnoughBalance + ); + + // deposit 100 vbnc to Bob + assert_ok!(Tokens::deposit(VBNC, &BOB, 500)); + + // Bob charge 100 vbnc to the pool + assert_ok!(CloudsConvert::charge_vbnc(RuntimeOrigin::signed(BOB), 100)); + + // check the new pool balance + assert_eq!( + ::MultiCurrency::free_balance( + VBNC, + &CloudsConvert::clouds_pool_account() + ), + old_pool_balance + 100 + ); + }); } diff --git a/pallets/clouds-convert/src/weights.rs b/pallets/clouds-convert/src/weights.rs index 85793244b3..2dcb8d83db 100644 --- a/pallets/clouds-convert/src/weights.rs +++ b/pallets/clouds-convert/src/weights.rs @@ -22,6 +22,28 @@ // See the License for the specific language governing permissions and // limitations under the License. +//! Autogenerated weights for bifrost_clouds_convert +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.1 +//! DATE: 2024-12-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-polkadot-local"), DB CACHE: 1024 + +// Executed Command: +// target/release/bifrost +// benchmark +// pallet +// --chain=bifrost-polkadot-local +// --steps=50 +// --repeat=20 +// --pallet=bifrost-clouds-convert +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./pallets/clouds-convert/src/weights.rs +// --template=./weight-template/pallet-weight-template.hbs + #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -29,7 +51,7 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; -/// Weight functions needed for bifrost_cross_in_out. +/// Weight functions needed for bifrost_clouds_convert. pub trait WeightInfo { fn clouds_to_vebnc() -> Weight; fn charge_vbnc() -> Weight; @@ -37,15 +59,84 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { + /// Storage: `Tokens::Accounts` (r:3 w:3) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:2 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `BbBNC::Position` (r:1 w:1) + /// Proof: `BbBNC::Position` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserPositions` (r:1 w:1) + /// Proof: `BbBNC::UserPositions` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::BbConfigs` (r:1 w:0) + /// Proof: `BbBNC::BbConfigs` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::Locked` (r:1 w:1) + /// Proof: `BbBNC::Locked` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::Supply` (r:1 w:1) + /// Proof: `BbBNC::Supply` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserLocked` (r:1 w:1) + /// Proof: `BbBNC::UserLocked` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Locks` (r:1 w:1) + /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1271), added: 3746, mode: `MaxEncodedLen`) + /// Storage: `BbBNC::UserMarkupInfos` (r:1 w:0) + /// Proof: `BbBNC::UserMarkupInfos` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::IncentiveConfigs` (r:1 w:1) + /// Proof: `BbBNC::IncentiveConfigs` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::Epoch` (r:1 w:1) + /// Proof: `BbBNC::Epoch` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::PointHistory` (r:1 w:1) + /// Proof: `BbBNC::PointHistory` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserPointEpoch` (r:1 w:1) + /// Proof: `BbBNC::UserPointEpoch` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::Rewards` (r:1 w:0) + /// Proof: `BbBNC::Rewards` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::SlopeChanges` (r:2 w:1) + /// Proof: `BbBNC::SlopeChanges` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserPointHistory` (r:0 w:1) + /// Proof: `BbBNC::UserPointHistory` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserRewardPerTokenPaid` (r:0 w:1) + /// Proof: `BbBNC::UserRewardPerTokenPaid` (`max_values`: None, `max_size`: None, mode: `Measured`) fn clouds_to_vebnc() -> Weight { - Weight::from_parts(150_867_000, 5223) - .saturating_add(RocksDbWeight::get().reads(7_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Proof Size summary in bytes: + // Measured: `1657` + // Estimated: `8769` + // Minimum execution time: 104_956_000 picoseconds. + Weight::from_parts(108_318_000, 8769) + .saturating_add(RocksDbWeight::get().reads(27_u64)) + .saturating_add(RocksDbWeight::get().writes(20_u64)) } - + /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn charge_vbnc() -> Weight { - Weight::from_parts(150_867_000, 5223) - .saturating_add(RocksDbWeight::get().reads(7_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Proof Size summary in bytes: + // Measured: `1291` + // Estimated: `6196` + // Minimum execution time: 29_437_000 picoseconds. + Weight::from_parts(30_162_000, 6196) + .saturating_add(RocksDbWeight::get().reads(9_u64)) + .saturating_add(RocksDbWeight::get().writes(5_u64)) } } diff --git a/pallets/cross-in-out/Cargo.toml b/pallets/cross-in-out/Cargo.toml index fa54f13472..3433fb358d 100644 --- a/pallets/cross-in-out/Cargo.toml +++ b/pallets/cross-in-out/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-cross-in-out" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/cross-in-out/src/benchmarking.rs b/pallets/cross-in-out/src/benchmarking.rs index 584e0988fc..aa07c46ba4 100644 --- a/pallets/cross-in-out/src/benchmarking.rs +++ b/pallets/cross-in-out/src/benchmarking.rs @@ -22,7 +22,7 @@ #![allow(deprecated)] use bifrost_primitives::{CurrencyId, TokenSymbol}; -use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::assert_ok; use frame_system::RawOrigin; use sp_runtime::traits::{AccountIdConversion, UniqueSaturatedFrom}; @@ -31,81 +31,150 @@ use xcm::v2::prelude::*; use super::*; use crate::Pallet as CrossInOut; -benchmarks! { - deregister_currency_for_cross_in_out { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn deregister_currency_for_cross_in_out() -> Result<(), BenchmarkError> { + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + assert_ok!(CrossInOut::::register_currency_for_cross_in_out( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT) )); - }: _(origin,CurrencyId::Token(TokenSymbol::DOT)) - set_crossing_minimum_amount { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - }: _(origin,CurrencyId::Token(TokenSymbol::DOT),100u32.into(),100u32.into()) + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + CurrencyId::Token(TokenSymbol::DOT), + ); + + Ok(()) + } + + #[benchmark] + fn set_crossing_minimum_amount() -> Result<(), BenchmarkError> { + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + CurrencyId::Token(TokenSymbol::DOT), + 100u32.into(), + 100u32.into(), + ); + + Ok(()) + } - add_to_register_whitelist { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + #[benchmark] + fn add_to_register_whitelist() -> Result<(), BenchmarkError> { + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let caller = whitelisted_caller(); - }: _(origin,CurrencyId::Token(TokenSymbol::DOT),caller) - remove_from_register_whitelist { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let test_account: T::AccountId = account("seed",1,1); + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + CurrencyId::Token(TokenSymbol::DOT), + caller, + ); + + Ok(()) + } + + #[benchmark] + fn remove_from_register_whitelist() -> Result<(), BenchmarkError> { + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let test_account: T::AccountId = account("seed", 1, 1); + assert_ok!(CrossInOut::::add_to_register_whitelist( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT), test_account.clone() )); - }: _(origin,CurrencyId::Token(TokenSymbol::DOT),test_account) - register_linked_account { - let test_account: T::AccountId = account("seed",1,1); + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + CurrencyId::Token(TokenSymbol::DOT), + test_account, + ); + + Ok(()) + } + + #[benchmark] + fn register_linked_account() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + assert_ok!(CrossInOut::::add_to_register_whitelist( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT), test_account.clone() )); assert_ok!(CrossInOut::::register_currency_for_cross_in_out( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin, CurrencyId::Token(TokenSymbol::DOT) )); let location = Box::new(MultiLocation { - parents: 0, - interior: X1(AccountId32 { - network: Any, - id: T::EntrancePalletId::get().into_account_truncating(), - }), - }); - }: _(RawOrigin::Signed(test_account.clone()),CurrencyId::Token(TokenSymbol::DOT),account("seed",1,1),location) - - cross_out { - let test_account: T::AccountId = account("seed",1,1); + parents: 0, + interior: X1(AccountId32 { + network: Any, + id: T::EntrancePalletId::get().into_account_truncating(), + }), + }); + + #[extrinsic_call] + _( + RawOrigin::Signed(test_account.clone()), + CurrencyId::Token(TokenSymbol::DOT), + account("seed", 1, 1), + location, + ); + + Ok(()) + } + + #[benchmark] + fn cross_out() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + assert_ok!(CrossInOut::::register_currency_for_cross_in_out( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT) )); assert_ok!(CrossInOut::::set_crossing_minimum_amount( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - CurrencyId::Token(TokenSymbol::DOT),100u32.into(),100u32.into() + origin.clone(), + CurrencyId::Token(TokenSymbol::DOT), + 100u32.into(), + 100u32.into(), )); assert_ok!(CrossInOut::::add_to_register_whitelist( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT), test_account.clone() )); let location = Box::new(MultiLocation { - parents: 0, - interior: X1(AccountId32 { - network: Any, - id: T::EntrancePalletId::get().into_account_truncating(), - }), - }); + parents: 0, + interior: X1(AccountId32 { + network: Any, + id: T::EntrancePalletId::get().into_account_truncating(), + }), + }); assert_ok!(CrossInOut::::register_linked_account( RawOrigin::Signed(test_account.clone()).into(), @@ -114,31 +183,46 @@ benchmarks! { location )); - T::MultiCurrency::deposit(CurrencyId::Token(TokenSymbol::DOT), &test_account, BalanceOf::::unique_saturated_from(1000000000000u128))?; + T::MultiCurrency::deposit( + CurrencyId::Token(TokenSymbol::DOT), + &test_account, + BalanceOf::::unique_saturated_from(1_000_000_000_000u128), + )?; + + #[extrinsic_call] + _( + RawOrigin::Signed(test_account), + CurrencyId::Token(TokenSymbol::DOT), + BalanceOf::::unique_saturated_from(100_000_000_000u128), + ); - }: _(RawOrigin::Signed(test_account),CurrencyId::Token(TokenSymbol::DOT),BalanceOf::::unique_saturated_from(100000000000u128)) + Ok(()) + } + + #[benchmark] + fn change_outer_linked_account() -> Result<(), BenchmarkError> { + let origin: T::RuntimeOrigin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let test_account: T::AccountId = account("seed", 1, 1); - change_outer_linked_account { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let test_account: T::AccountId = account("seed",1,1); assert_ok!(CrossInOut::::register_currency_for_cross_in_out( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT) )); assert_ok!(CrossInOut::::add_to_register_whitelist( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, + origin.clone(), CurrencyId::Token(TokenSymbol::DOT), test_account.clone() )); let location1 = Box::new(MultiLocation { - parents: 0, - interior: X1(AccountId32 { - network: Any, - id: T::EntrancePalletId::get().into_account_truncating(), - }), - }); + parents: 0, + interior: X1(AccountId32 { + network: Any, + id: T::EntrancePalletId::get().into_account_truncating(), + }), + }); assert_ok!(CrossInOut::::register_linked_account( RawOrigin::Signed(test_account.clone()).into(), @@ -148,14 +232,27 @@ benchmarks! { )); let location2 = Box::new(MultiLocation { - parents: 1, - interior: X1(AccountId32 { - network: Any, - id: T::EntrancePalletId::get().into_account_truncating(), - }), - }); + parents: 1, + interior: X1(AccountId32 { + network: Any, + id: T::EntrancePalletId::get().into_account_truncating(), + }), + }); + + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + CurrencyId::Token(TokenSymbol::DOT), + location2, + test_account, + ); - }: _(origin,CurrencyId::Token(TokenSymbol::DOT),location2,test_account) + Ok(()) + } - impl_benchmark_test_suite!(CrossInOut,crate::mock::ExtBuilder::default().build(),crate::mock::Runtime); + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/cross-in-out/src/lib.rs b/pallets/cross-in-out/src/lib.rs index f416534674..a968d907a5 100644 --- a/pallets/cross-in-out/src/lib.rs +++ b/pallets/cross-in-out/src/lib.rs @@ -110,9 +110,15 @@ pub mod pallet { foreign_location: MultiLocation, }, /// Event emitted when an account is added to the register list. - AddedToRegisterList { account: AccountIdOf, currency_id: CurrencyId }, + AddedToRegisterList { + account: AccountIdOf, + currency_id: CurrencyId, + }, /// Event emitted when an account is removed from the register list. - RemovedFromRegisterList { account: AccountIdOf, currency_id: CurrencyId }, + RemovedFromRegisterList { + account: AccountIdOf, + currency_id: CurrencyId, + }, /// Event emitted when the crossing minimum amounts are set for a currency. CrossingMinimumAmountSet { currency_id: CurrencyId, @@ -195,7 +201,10 @@ pub mod pallet { let crossing_minimum_amount = CrossingMinimumAmount::::get(currency_id) .ok_or(Error::::NoCrossingMinimumSet)?; - ensure!(amount >= crossing_minimum_amount.1, Error::::AmountLowerThanMinimum); + ensure!( + amount >= crossing_minimum_amount.1, + Error::::AmountLowerThanMinimum + ); let balance = T::MultiCurrency::free_balance(currency_id, &crosser); ensure!(balance >= amount, Error::::NotEnoughBalance); @@ -205,7 +214,12 @@ pub mod pallet { T::MultiCurrency::withdraw(currency_id, &crosser, amount)?; - Self::deposit_event(Event::CrossedOut { currency_id, crosser, location, amount }); + Self::deposit_event(Event::CrossedOut { + currency_id, + crosser, + location, + amount, + }); Ok(()) } @@ -222,7 +236,10 @@ pub mod pallet { let register_whitelist = RegisterWhiteList::::get(currency_id).ok_or(Error::::NotAllowed)?; - ensure!(register_whitelist.contains(®isterer), Error::::NotAllowed); + ensure!( + register_whitelist.contains(®isterer), + Error::::NotAllowed + ); ensure!( CrossCurrencyRegistry::::contains_key(currency_id), @@ -273,7 +290,10 @@ pub mod pallet { let original_location = AccountToOuterMultilocation::::get(currency_id, account.clone()) .ok_or(Error::::NotExist)?; - ensure!(original_location != *foreign_location.clone(), Error::::AlreadyExist); + ensure!( + original_location != *foreign_location.clone(), + Error::::AlreadyExist + ); AccountToOuterMultilocation::::insert( currency_id, @@ -336,7 +356,7 @@ pub mod pallet { currency_id, }); Ok(()) - }, + } _ => Err(Error::::NotAllowed), } }, @@ -365,7 +385,7 @@ pub mod pallet { currency_id, }); Ok(()) - }, + } _ => Err(Error::::NotExist), } }, diff --git a/pallets/cross-in-out/src/mock.rs b/pallets/cross-in-out/src/mock.rs index 043bf05f49..036a7ce92e 100644 --- a/pallets/cross-in-out/src/mock.rs +++ b/pallets/cross-in-out/src/mock.rs @@ -144,7 +144,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -168,7 +170,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self @@ -195,3 +199,8 @@ impl ExtBuilder { t.into() } } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/cross-in-out/src/tests.rs b/pallets/cross-in-out/src/tests.rs index dd549ff6bc..8220866678 100644 --- a/pallets/cross-in-out/src/tests.rs +++ b/pallets/cross-in-out/src/tests.rs @@ -28,191 +28,216 @@ use xcm::opaque::v2::{Junction, Junctions::X1}; #[allow(deprecated)] #[test] fn cross_in_and_cross_out_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let location = MultiLocation { - parents: 100, - interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), - }; - CrossCurrencyRegistry::::insert(KSM, ()); - CrossingMinimumAmount::::insert(KSM, (1, 1)); - AccountToOuterMultilocation::::insert(KSM, ALICE, location.clone()); - OuterMultilocationToAccount::::insert(KSM, location.clone(), ALICE); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 100); - - assert_ok!(CrossInOut::cross_out(RuntimeOrigin::signed(ALICE), KSM, 50)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 50); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let location = MultiLocation { + parents: 100, + interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), + }; + CrossCurrencyRegistry::::insert(KSM, ()); + CrossingMinimumAmount::::insert(KSM, (1, 1)); + AccountToOuterMultilocation::::insert(KSM, ALICE, location.clone()); + OuterMultilocationToAccount::::insert(KSM, location.clone(), ALICE); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 100); + + assert_ok!(CrossInOut::cross_out(RuntimeOrigin::signed(ALICE), KSM, 50)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 50); + }); } #[test] fn add_to_and_remove_from_register_whitelist_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(RegisterWhiteList::::get(KSM), None); - - assert_ok!(CrossInOut::add_to_register_whitelist(RuntimeOrigin::signed(ALICE), KSM, ALICE)); - assert_eq!( - RegisterWhiteList::::get(KSM), - Some(BoundedVec::try_from(vec![ALICE]).unwrap()) - ); - - assert_noop!( - CrossInOut::remove_from_register_whitelist(RuntimeOrigin::signed(ALICE), KSM, BOB), - Error::::NotExist - ); - - assert_ok!(CrossInOut::remove_from_register_whitelist( - RuntimeOrigin::signed(ALICE), - KSM, - ALICE - )); - assert_eq!(RegisterWhiteList::::get(KSM), Some(BoundedVec::default())); - }); -} + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(RegisterWhiteList::::get(KSM), None); -#[allow(deprecated)] -#[test] -fn register_linked_account_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let location = MultiLocation { - parents: 100, - interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), - }; - - let location2 = MultiLocation { - parents: 111, - interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), - }; - - assert_noop!( - CrossInOut::register_linked_account( + assert_ok!(CrossInOut::add_to_register_whitelist( RuntimeOrigin::signed(ALICE), KSM, - BOB, - Box::new(location.clone()) - ), - Error::::NotAllowed - ); - - RegisterWhiteList::::insert(KSM, BoundedVec::try_from(vec![ALICE]).unwrap()); - - assert_noop!( - CrossInOut::register_linked_account( + ALICE + )); + assert_eq!( + RegisterWhiteList::::get(KSM), + Some(BoundedVec::try_from(vec![ALICE]).unwrap()) + ); + + assert_noop!( + CrossInOut::remove_from_register_whitelist(RuntimeOrigin::signed(ALICE), KSM, BOB), + Error::::NotExist + ); + + assert_ok!(CrossInOut::remove_from_register_whitelist( RuntimeOrigin::signed(ALICE), KSM, - BOB, - Box::new(location.clone()) - ), - Error::::CurrencyNotSupportCrossInAndOut - ); - - CrossCurrencyRegistry::::insert(KSM, ()); - - assert_ok!(CrossInOut::register_linked_account( - RuntimeOrigin::signed(ALICE), - KSM, - ALICE, - Box::new(location.clone()) - )); + ALICE + )); + assert_eq!( + RegisterWhiteList::::get(KSM), + Some(BoundedVec::default()) + ); + }); +} - assert_noop!( - CrossInOut::register_linked_account( +#[allow(deprecated)] +#[test] +fn register_linked_account_should_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let location = MultiLocation { + parents: 100, + interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), + }; + + let location2 = MultiLocation { + parents: 111, + interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), + }; + + assert_noop!( + CrossInOut::register_linked_account( + RuntimeOrigin::signed(ALICE), + KSM, + BOB, + Box::new(location.clone()) + ), + Error::::NotAllowed + ); + + RegisterWhiteList::::insert(KSM, BoundedVec::try_from(vec![ALICE]).unwrap()); + + assert_noop!( + CrossInOut::register_linked_account( + RuntimeOrigin::signed(ALICE), + KSM, + BOB, + Box::new(location.clone()) + ), + Error::::CurrencyNotSupportCrossInAndOut + ); + + CrossCurrencyRegistry::::insert(KSM, ()); + + assert_ok!(CrossInOut::register_linked_account( RuntimeOrigin::signed(ALICE), KSM, ALICE, - Box::new(location2) - ), - Error::::AlreadyExist - ); - }); + Box::new(location.clone()) + )); + + assert_noop!( + CrossInOut::register_linked_account( + RuntimeOrigin::signed(ALICE), + KSM, + ALICE, + Box::new(location2) + ), + Error::::AlreadyExist + ); + }); } #[test] fn register_and_deregister_currency_for_cross_in_out_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - CrossCurrencyRegistry::::insert(KSM, ()); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + CrossCurrencyRegistry::::insert(KSM, ()); - assert_ok!(CrossInOut::deregister_currency_for_cross_in_out( - RuntimeOrigin::signed(ALICE), - KSM, - )); + assert_ok!(CrossInOut::deregister_currency_for_cross_in_out( + RuntimeOrigin::signed(ALICE), + KSM, + )); - assert_eq!(CrossCurrencyRegistry::::get(KSM), None); - }); + assert_eq!(CrossCurrencyRegistry::::get(KSM), None); + }); } #[allow(deprecated)] #[test] fn change_outer_linked_account_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let location = MultiLocation { - parents: 100, - interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), - }; - - let location2 = MultiLocation { - parents: 111, - interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), - }; - - AccountToOuterMultilocation::::insert(KSM, BOB, location.clone()); - OuterMultilocationToAccount::::insert(KSM, location.clone(), BOB); - - assert_noop!( - CrossInOut::change_outer_linked_account( - RuntimeOrigin::signed(BOB), - KSM, - Box::new(location2.clone()), - BOB - ), - BadOrigin - ); - - assert_noop!( - CrossInOut::change_outer_linked_account( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let location = MultiLocation { + parents: 100, + interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), + }; + + let location2 = MultiLocation { + parents: 111, + interior: X1(Junction::GeneralKey(WeakBoundedVec::default())), + }; + + AccountToOuterMultilocation::::insert(KSM, BOB, location.clone()); + OuterMultilocationToAccount::::insert(KSM, location.clone(), BOB); + + assert_noop!( + CrossInOut::change_outer_linked_account( + RuntimeOrigin::signed(BOB), + KSM, + Box::new(location2.clone()), + BOB + ), + BadOrigin + ); + + assert_noop!( + CrossInOut::change_outer_linked_account( + RuntimeOrigin::signed(ALICE), + KSM, + Box::new(location.clone()), + BOB + ), + Error::::CurrencyNotSupportCrossInAndOut + ); + + CrossCurrencyRegistry::::insert(KSM, ()); + + assert_noop!( + CrossInOut::change_outer_linked_account( + RuntimeOrigin::signed(ALICE), + KSM, + Box::new(location.clone()), + BOB + ), + Error::::AlreadyExist + ); + + assert_ok!(CrossInOut::change_outer_linked_account( RuntimeOrigin::signed(ALICE), KSM, - Box::new(location.clone()), - BOB - ), - Error::::CurrencyNotSupportCrossInAndOut - ); - - CrossCurrencyRegistry::::insert(KSM, ()); - - assert_noop!( - CrossInOut::change_outer_linked_account( - RuntimeOrigin::signed(ALICE), - KSM, - Box::new(location.clone()), + Box::new(location2.clone()), BOB - ), - Error::::AlreadyExist - ); - - assert_ok!(CrossInOut::change_outer_linked_account( - RuntimeOrigin::signed(ALICE), - KSM, - Box::new(location2.clone()), - BOB - )); - }); + )); + }); } #[test] fn set_crossing_minimum_amount_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_noop!( - CrossInOut::set_crossing_minimum_amount(RuntimeOrigin::signed(BOB), KSM, 100, 100), - BadOrigin - ); - - assert_ok!(CrossInOut::set_crossing_minimum_amount( - RuntimeOrigin::signed(ALICE), - KSM, - 100, - 100 - )); - - assert_eq!(CrossingMinimumAmount::::get(KSM), Some((100, 100))); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_noop!( + CrossInOut::set_crossing_minimum_amount(RuntimeOrigin::signed(BOB), KSM, 100, 100), + BadOrigin + ); + + assert_ok!(CrossInOut::set_crossing_minimum_amount( + RuntimeOrigin::signed(ALICE), + KSM, + 100, + 100 + )); + + assert_eq!(CrossingMinimumAmount::::get(KSM), Some((100, 100))); + }); } diff --git a/pallets/cross-in-out/src/weights.rs b/pallets/cross-in-out/src/weights.rs index d75f2deea4..e81772c5fd 100644 --- a/pallets/cross-in-out/src/weights.rs +++ b/pallets/cross-in-out/src/weights.rs @@ -24,9 +24,9 @@ //! Autogenerated weights for bifrost_cross_in_out //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-11-26, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` //! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 // Executed Command: @@ -64,99 +64,99 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { - /// Storage: CrossInOut CrossCurrencyRegistry (r:1 w:1) - /// Proof Skipped: CrossInOut CrossCurrencyRegistry (max_values: None, max_size: None, mode: Measured) + /// Storage: `CrossInOut::CrossCurrencyRegistry` (r:1 w:1) + /// Proof: `CrossInOut::CrossCurrencyRegistry` (`max_values`: None, `max_size`: None, mode: `Measured`) fn deregister_currency_for_cross_in_out() -> Weight { // Proof Size summary in bytes: - // Measured: `119` - // Estimated: `3584` - // Minimum execution time: 32_833_000 picoseconds. - Weight::from_parts(34_234_000, 3584) + // Measured: `152` + // Estimated: `3617` + // Minimum execution time: 12_600_000 picoseconds. + Weight::from_parts(13_724_000, 3617) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: CrossInOut CrossingMinimumAmount (r:0 w:1) - /// Proof Skipped: CrossInOut CrossingMinimumAmount (max_values: None, max_size: None, mode: Measured) + /// Storage: `CrossInOut::CrossingMinimumAmount` (r:0 w:1) + /// Proof: `CrossInOut::CrossingMinimumAmount` (`max_values`: None, `max_size`: None, mode: `Measured`) fn set_crossing_minimum_amount() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 23_847_000 picoseconds. - Weight::from_parts(24_439_000, 0) + // Minimum execution time: 8_367_000 picoseconds. + Weight::from_parts(9_335_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: CrossInOut RegisterWhiteList (r:1 w:1) - /// Proof Skipped: CrossInOut RegisterWhiteList (max_values: None, max_size: None, mode: Measured) + /// Storage: `CrossInOut::RegisterWhiteList` (r:1 w:1) + /// Proof: `CrossInOut::RegisterWhiteList` (`max_values`: None, `max_size`: None, mode: `Measured`) fn add_to_register_whitelist() -> Weight { // Proof Size summary in bytes: - // Measured: `76` - // Estimated: `3541` - // Minimum execution time: 37_554_000 picoseconds. - Weight::from_parts(38_949_000, 3541) + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 16_483_000 picoseconds. + Weight::from_parts(18_335_000, 3574) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: CrossInOut RegisterWhiteList (r:1 w:1) - /// Proof Skipped: CrossInOut RegisterWhiteList (max_values: None, max_size: None, mode: Measured) + /// Storage: `CrossInOut::RegisterWhiteList` (r:1 w:1) + /// Proof: `CrossInOut::RegisterWhiteList` (`max_values`: None, `max_size`: None, mode: `Measured`) fn remove_from_register_whitelist() -> Weight { // Proof Size summary in bytes: - // Measured: `154` - // Estimated: `3619` - // Minimum execution time: 35_639_000 picoseconds. - Weight::from_parts(36_505_000, 3619) + // Measured: `187` + // Estimated: `3652` + // Minimum execution time: 13_204_000 picoseconds. + Weight::from_parts(14_958_000, 3652) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: CrossInOut RegisterWhiteList (r:1 w:0) - /// Proof Skipped: CrossInOut RegisterWhiteList (max_values: None, max_size: None, mode: Measured) - /// Storage: CrossInOut CrossCurrencyRegistry (r:1 w:0) - /// Proof Skipped: CrossInOut CrossCurrencyRegistry (max_values: None, max_size: None, mode: Measured) - /// Storage: CrossInOut AccountToOuterMultilocation (r:1 w:1) - /// Proof Skipped: CrossInOut AccountToOuterMultilocation (max_values: None, max_size: None, mode: Measured) - /// Storage: CrossInOut OuterMultilocationToAccount (r:0 w:1) - /// Proof Skipped: CrossInOut OuterMultilocationToAccount (max_values: None, max_size: None, mode: Measured) + /// Storage: `CrossInOut::RegisterWhiteList` (r:1 w:0) + /// Proof: `CrossInOut::RegisterWhiteList` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CrossInOut::CrossCurrencyRegistry` (r:1 w:0) + /// Proof: `CrossInOut::CrossCurrencyRegistry` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CrossInOut::AccountToOuterMultilocation` (r:1 w:1) + /// Proof: `CrossInOut::AccountToOuterMultilocation` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CrossInOut::OuterMultilocationToAccount` (r:0 w:1) + /// Proof: `CrossInOut::OuterMultilocationToAccount` (`max_values`: None, `max_size`: None, mode: `Measured`) fn register_linked_account() -> Weight { // Proof Size summary in bytes: - // Measured: `193` - // Estimated: `3658` - // Minimum execution time: 58_046_000 picoseconds. - Weight::from_parts(60_005_000, 3658) + // Measured: `226` + // Estimated: `3691` + // Minimum execution time: 24_918_000 picoseconds. + Weight::from_parts(28_149_000, 3691) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: CrossInOut CrossCurrencyRegistry (r:1 w:0) - /// Proof Skipped: CrossInOut CrossCurrencyRegistry (max_values: None, max_size: None, mode: Measured) - /// Storage: CrossInOut CrossingMinimumAmount (r:1 w:0) - /// Proof Skipped: CrossInOut CrossingMinimumAmount (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:1 w:1) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: CrossInOut AccountToOuterMultilocation (r:1 w:0) - /// Proof Skipped: CrossInOut AccountToOuterMultilocation (max_values: None, max_size: None, mode: Measured) - /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `CrossInOut::CrossCurrencyRegistry` (r:1 w:0) + /// Proof: `CrossInOut::CrossCurrencyRegistry` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CrossInOut::CrossingMinimumAmount` (r:1 w:0) + /// Proof: `CrossInOut::CrossingMinimumAmount` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `CrossInOut::AccountToOuterMultilocation` (r:1 w:0) + /// Proof: `CrossInOut::AccountToOuterMultilocation` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn cross_out() -> Weight { // Proof Size summary in bytes: - // Measured: `1781` - // Estimated: `5246` - // Minimum execution time: 121_998_000 picoseconds. - Weight::from_parts(125_151_000, 5246) + // Measured: `1010` + // Estimated: `4475` + // Minimum execution time: 37_734_000 picoseconds. + Weight::from_parts(61_399_000, 4475) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: CrossInOut CrossCurrencyRegistry (r:1 w:0) - /// Proof Skipped: CrossInOut CrossCurrencyRegistry (max_values: None, max_size: None, mode: Measured) - /// Storage: CrossInOut AccountToOuterMultilocation (r:1 w:1) - /// Proof Skipped: CrossInOut AccountToOuterMultilocation (max_values: None, max_size: None, mode: Measured) - /// Storage: CrossInOut OuterMultilocationToAccount (r:0 w:1) - /// Proof Skipped: CrossInOut OuterMultilocationToAccount (max_values: None, max_size: None, mode: Measured) + /// Storage: `CrossInOut::CrossCurrencyRegistry` (r:1 w:0) + /// Proof: `CrossInOut::CrossCurrencyRegistry` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CrossInOut::AccountToOuterMultilocation` (r:1 w:1) + /// Proof: `CrossInOut::AccountToOuterMultilocation` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CrossInOut::OuterMultilocationToAccount` (r:0 w:1) + /// Proof: `CrossInOut::OuterMultilocationToAccount` (`max_values`: None, `max_size`: None, mode: `Measured`) fn change_outer_linked_account() -> Weight { // Proof Size summary in bytes: - // Measured: `312` - // Estimated: `3777` - // Minimum execution time: 56_481_000 picoseconds. - Weight::from_parts(57_253_000, 3777) + // Measured: `345` + // Estimated: `3810` + // Minimum execution time: 21_855_000 picoseconds. + Weight::from_parts(26_017_000, 3810) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/pallets/currencies/Cargo.toml b/pallets/currencies/Cargo.toml index 4761ae6512..607918a8a1 100644 --- a/pallets/currencies/Cargo.toml +++ b/pallets/currencies/Cargo.toml @@ -4,7 +4,7 @@ description = "Provide `MultiCurrency` implementation using `pallet-balances` an repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/currencies" license = "Apache-2.0" version = "0.4.1-dev" -authors = ["Laminar Developers ", "Sora Yu "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/currencies/src/lib.rs b/pallets/currencies/src/lib.rs index 5c6b448bce..4dc4136a42 100644 --- a/pallets/currencies/src/lib.rs +++ b/pallets/currencies/src/lib.rs @@ -532,32 +532,36 @@ impl fungibles::Inspect for Pallet { fn total_issuance(asset_id: Self::AssetId) -> Self::Balance { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::total_issuance(), + id if id == T::GetNativeCurrencyId::get() => { + >::total_issuance() + } _ => >::total_issuance(asset_id), } } fn minimum_balance(asset_id: Self::AssetId) -> Self::Balance { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::minimum_balance(), + id if id == T::GetNativeCurrencyId::get() => { + >::minimum_balance() + } _ => >::minimum_balance(asset_id), } } fn balance(asset_id: Self::AssetId, who: &T::AccountId) -> Self::Balance { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::balance(who), + id if id == T::GetNativeCurrencyId::get() => { + >::balance(who) + } _ => >::balance(asset_id, who), } } fn total_balance(asset_id: Self::AssetId, who: &T::AccountId) -> Self::Balance { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::total_balance(who), + id if id == T::GetNativeCurrencyId::get() => { + >::total_balance(who) + } _ => >::total_balance(asset_id, who), } } @@ -590,8 +594,9 @@ impl fungibles::Inspect for Pallet { provenance: Provenance, ) -> DepositConsequence { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::can_deposit(who, amount, provenance), + id if id == T::GetNativeCurrencyId::get() => { + >::can_deposit(who, amount, provenance) + } _ => >::can_deposit( asset_id, who, amount, provenance, ), @@ -604,8 +609,9 @@ impl fungibles::Inspect for Pallet { amount: Self::Balance, ) -> WithdrawConsequence { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::can_withdraw(who, amount), + id if id == T::GetNativeCurrencyId::get() => { + >::can_withdraw(who, amount) + } _ => >::can_withdraw(asset_id, who, amount), } } @@ -639,19 +645,23 @@ impl fungibles::Unbalanced for Pallet { amount: Self::Balance, ) -> Result, DispatchError> { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::write_balance(who, amount), - _ => - >::write_balance(asset_id, who, amount), + id if id == T::GetNativeCurrencyId::get() => { + >::write_balance(who, amount) + } + _ => { + >::write_balance(asset_id, who, amount) + } } } fn set_total_issuance(asset_id: Self::AssetId, amount: Self::Balance) { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::set_total_issuance(amount), - _ => - >::set_total_issuance(asset_id, amount), + id if id == T::GetNativeCurrencyId::get() => { + >::set_total_issuance(amount) + } + _ => { + >::set_total_issuance(asset_id, amount) + } } } } @@ -663,8 +673,9 @@ impl fungibles::Mutate for Pallet { amount: Self::Balance, ) -> Result { match asset_id { - id if id == T::GetNativeCurrencyId::get() => - >::mint_into(who, amount), + id if id == T::GetNativeCurrencyId::get() => { + >::mint_into(who, amount) + } _ => >::mint_into(asset_id, who, amount), } } @@ -678,14 +689,15 @@ impl fungibles::Mutate for Pallet { fortitude: Fortitude, ) -> Result { match asset_id { - id if id == T::GetNativeCurrencyId::get() => + id if id == T::GetNativeCurrencyId::get() => { >::burn_from( who, amount, preservation, precision, fortitude, - ), + ) + } _ => >::burn_from( asset_id, who, @@ -995,8 +1007,9 @@ where } fn ensure_can_withdraw(who: &AccountId, amount: Self::Balance) -> DispatchResult { - let new_balance = - Self::free_balance(who).checked_sub(&amount).ok_or(Error::::BalanceTooLow)?; + let new_balance = Self::free_balance(who) + .checked_sub(&amount) + .ok_or(Error::::BalanceTooLow)?; Currency::ensure_can_withdraw(who, amount, WithdrawReasons::all(), new_balance) } @@ -1015,8 +1028,13 @@ where } fn withdraw(who: &AccountId, amount: Self::Balance) -> DispatchResult { - Currency::withdraw(who, amount, WithdrawReasons::all(), ExistenceRequirement::AllowDeath) - .map(|_| ()) + Currency::withdraw( + who, + amount, + WithdrawReasons::all(), + ExistenceRequirement::AllowDeath, + ) + .map(|_| ()) } fn can_slash(who: &AccountId, amount: Self::Balance) -> bool { @@ -1049,8 +1067,10 @@ where type Amount = Amount; fn update_balance(who: &AccountId, by_amount: Self::Amount) -> DispatchResult { - let by_balance = - by_amount.abs().try_into().map_err(|_| Error::::AmountIntoBalanceFailed)?; + let by_balance = by_amount + .abs() + .try_into() + .map_err(|_| Error::::AmountIntoBalanceFailed)?; if by_amount.is_positive() { Self::deposit(who, by_balance) } else { diff --git a/pallets/currencies/src/mock.rs b/pallets/currencies/src/mock.rs index 66005251b2..a3e29e2415 100644 --- a/pallets/currencies/src/mock.rs +++ b/pallets/currencies/src/mock.rs @@ -142,7 +142,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/currencies/src/tests.rs b/pallets/currencies/src/tests.rs index 5cd1102adc..88bc49819b 100644 --- a/pallets/currencies/src/tests.rs +++ b/pallets/currencies/src/tests.rs @@ -9,267 +9,400 @@ use sp_runtime::traits::BadOrigin; #[test] fn multi_lockable_currency_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(Currencies::set_lock(ID_1, X_TOKEN_ID, &ALICE, 50)); - assert_eq!(Tokens::locks(&ALICE, X_TOKEN_ID).len(), 1); - assert_ok!(Currencies::set_lock(ID_1, NATIVE_CURRENCY_ID, &ALICE, 50)); - assert_eq!(PalletBalances::locks(&ALICE).len(), 1); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(Currencies::set_lock(ID_1, X_TOKEN_ID, &ALICE, 50)); + assert_eq!(Tokens::locks(&ALICE, X_TOKEN_ID).len(), 1); + assert_ok!(Currencies::set_lock(ID_1, NATIVE_CURRENCY_ID, &ALICE, 50)); + assert_eq!(PalletBalances::locks(&ALICE).len(), 1); + }); } #[test] fn multi_reservable_currency_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(Currencies::total_issuance(NATIVE_CURRENCY_ID), 200); - assert_eq!(Currencies::total_issuance(X_TOKEN_ID), 200); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 100); - assert_eq!(NativeCurrency::free_balance(&ALICE), 100); - - assert_ok!(Currencies::reserve(X_TOKEN_ID, &ALICE, 30)); - assert_ok!(Currencies::reserve(NATIVE_CURRENCY_ID, &ALICE, 40)); - assert_eq!(Currencies::reserved_balance(X_TOKEN_ID, &ALICE), 30); - assert_eq!(Currencies::reserved_balance(NATIVE_CURRENCY_ID, &ALICE), 40); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(Currencies::total_issuance(NATIVE_CURRENCY_ID), 200); + assert_eq!(Currencies::total_issuance(X_TOKEN_ID), 200); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 100); + assert_eq!(NativeCurrency::free_balance(&ALICE), 100); + + assert_ok!(Currencies::reserve(X_TOKEN_ID, &ALICE, 30)); + assert_ok!(Currencies::reserve(NATIVE_CURRENCY_ID, &ALICE, 40)); + assert_eq!(Currencies::reserved_balance(X_TOKEN_ID, &ALICE), 30); + assert_eq!(Currencies::reserved_balance(NATIVE_CURRENCY_ID, &ALICE), 40); + }); } #[test] fn named_multi_reservable_currency_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(Currencies::total_issuance(NATIVE_CURRENCY_ID), 200); - assert_eq!(Currencies::total_issuance(X_TOKEN_ID), 200); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 100); - assert_eq!(NativeCurrency::free_balance(&ALICE), 100); - - assert_ok!(Currencies::reserve_named(&RID_1, X_TOKEN_ID, &ALICE, 30)); - assert_ok!(Currencies::reserve_named(&RID_2, X_TOKEN_ID, &ALICE, 50)); - assert_ok!(Currencies::reserve_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE, 20)); - assert_ok!(Currencies::reserve_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE, 60)); - let r1x_before = 30; - assert_eq!(Currencies::reserved_balance_named(&RID_1, X_TOKEN_ID, &ALICE), r1x_before); - let r2x_before = 50; - assert_eq!(Currencies::reserved_balance_named(&RID_2, X_TOKEN_ID, &ALICE), r2x_before); - let r1n_before = 20; - assert_eq!( - Currencies::reserved_balance_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE), - r1n_before - ); - let r2n_before = 60; - assert_eq!( - Currencies::reserved_balance_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE), - r2n_before - ); - - let n_free_before = 20; - assert_eq!(NativeCurrency::free_balance(&ALICE), n_free_before); - let x_free_before = 20; - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), x_free_before); - - assert_eq!(Currencies::unreserve_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE, 100), 80); - assert_eq!(NativeCurrency::free_balance(&ALICE), n_free_before + 20); - assert_eq!(Currencies::reserved_balance_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE), 0); - - assert_eq!( - Currencies::reserved_balance_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE), - r2n_before - ); - assert_eq!(Currencies::reserved_balance_named(&RID_1, X_TOKEN_ID, &ALICE), r1x_before); - assert_eq!(Currencies::reserved_balance_named(&RID_2, X_TOKEN_ID, &ALICE), r2x_before); - - assert_eq!(Currencies::unreserve_named(&RID_1, X_TOKEN_ID, &ALICE, 100), 70); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), x_free_before + 30); - assert_eq!(Currencies::reserved_balance_named(&RID_1, X_TOKEN_ID, &ALICE), 0); - - assert_eq!(Currencies::reserved_balance_named(&RID_2, X_TOKEN_ID, &ALICE), r2x_before); - assert_eq!( - Currencies::reserved_balance_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE), - r2n_before - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(Currencies::total_issuance(NATIVE_CURRENCY_ID), 200); + assert_eq!(Currencies::total_issuance(X_TOKEN_ID), 200); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 100); + assert_eq!(NativeCurrency::free_balance(&ALICE), 100); + + assert_ok!(Currencies::reserve_named(&RID_1, X_TOKEN_ID, &ALICE, 30)); + assert_ok!(Currencies::reserve_named(&RID_2, X_TOKEN_ID, &ALICE, 50)); + assert_ok!(Currencies::reserve_named( + &RID_1, + NATIVE_CURRENCY_ID, + &ALICE, + 20 + )); + assert_ok!(Currencies::reserve_named( + &RID_2, + NATIVE_CURRENCY_ID, + &ALICE, + 60 + )); + let r1x_before = 30; + assert_eq!( + Currencies::reserved_balance_named(&RID_1, X_TOKEN_ID, &ALICE), + r1x_before + ); + let r2x_before = 50; + assert_eq!( + Currencies::reserved_balance_named(&RID_2, X_TOKEN_ID, &ALICE), + r2x_before + ); + let r1n_before = 20; + assert_eq!( + Currencies::reserved_balance_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE), + r1n_before + ); + let r2n_before = 60; + assert_eq!( + Currencies::reserved_balance_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE), + r2n_before + ); + + let n_free_before = 20; + assert_eq!(NativeCurrency::free_balance(&ALICE), n_free_before); + let x_free_before = 20; + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), x_free_before); + + assert_eq!( + Currencies::unreserve_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE, 100), + 80 + ); + assert_eq!(NativeCurrency::free_balance(&ALICE), n_free_before + 20); + assert_eq!( + Currencies::reserved_balance_named(&RID_1, NATIVE_CURRENCY_ID, &ALICE), + 0 + ); + + assert_eq!( + Currencies::reserved_balance_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE), + r2n_before + ); + assert_eq!( + Currencies::reserved_balance_named(&RID_1, X_TOKEN_ID, &ALICE), + r1x_before + ); + assert_eq!( + Currencies::reserved_balance_named(&RID_2, X_TOKEN_ID, &ALICE), + r2x_before + ); + + assert_eq!( + Currencies::unreserve_named(&RID_1, X_TOKEN_ID, &ALICE, 100), + 70 + ); + assert_eq!( + Currencies::free_balance(X_TOKEN_ID, &ALICE), + x_free_before + 30 + ); + assert_eq!( + Currencies::reserved_balance_named(&RID_1, X_TOKEN_ID, &ALICE), + 0 + ); + + assert_eq!( + Currencies::reserved_balance_named(&RID_2, X_TOKEN_ID, &ALICE), + r2x_before + ); + assert_eq!( + Currencies::reserved_balance_named(&RID_2, NATIVE_CURRENCY_ID, &ALICE), + r2n_before + ); + }); } #[test] fn native_currency_lockable_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(NativeCurrency::set_lock(ID_1, &ALICE, 10)); - assert_eq!(PalletBalances::locks(&ALICE).len(), 1); - assert_ok!(NativeCurrency::remove_lock(ID_1, &ALICE)); - assert_eq!(PalletBalances::locks(&ALICE).len(), 0); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(NativeCurrency::set_lock(ID_1, &ALICE, 10)); + assert_eq!(PalletBalances::locks(&ALICE).len(), 1); + assert_ok!(NativeCurrency::remove_lock(ID_1, &ALICE)); + assert_eq!(PalletBalances::locks(&ALICE).len(), 0); + }); } #[test] fn native_currency_reservable_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(NativeCurrency::reserve(&ALICE, 50)); - assert_eq!(NativeCurrency::reserved_balance(&ALICE), 50); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(NativeCurrency::reserve(&ALICE, 50)); + assert_eq!(NativeCurrency::reserved_balance(&ALICE), 50); + }); } #[test] fn basic_currency_adapting_pallet_balances_lockable() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::set_lock(ID_1, &ALICE, 10)); - assert_eq!(PalletBalances::locks(&ALICE).len(), 1); - assert_ok!(AdaptedBasicCurrency::remove_lock(ID_1, &ALICE)); - assert_eq!(PalletBalances::locks(&ALICE).len(), 0); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::set_lock(ID_1, &ALICE, 10)); + assert_eq!(PalletBalances::locks(&ALICE).len(), 1); + assert_ok!(AdaptedBasicCurrency::remove_lock(ID_1, &ALICE)); + assert_eq!(PalletBalances::locks(&ALICE).len(), 0); + }); } #[test] fn basic_currency_adapting_pallet_balances_reservable() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::reserve(&ALICE, 50)); - assert_eq!(AdaptedBasicCurrency::reserved_balance(&ALICE), 50); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::reserve(&ALICE, 50)); + assert_eq!(AdaptedBasicCurrency::reserved_balance(&ALICE), 50); + }); } #[test] fn named_basic_currency_adapting_pallet_balances_reservable() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::reserve_named(&RID_1, &ALICE, 50)); - assert_ok!(AdaptedBasicCurrency::reserve_named(&RID_2, &ALICE, 30)); - assert_eq!(AdaptedBasicCurrency::reserved_balance_named(&RID_1, &ALICE), 50); - assert_eq!(AdaptedBasicCurrency::reserved_balance_named(&RID_2, &ALICE), 30); - assert_eq!(AdaptedBasicCurrency::free_balance(&ALICE), 20); - - assert_eq!(AdaptedBasicCurrency::unreserve_named(&RID_1, &ALICE, 80), 30); - assert_eq!(AdaptedBasicCurrency::free_balance(&ALICE), 70); - assert_eq!(AdaptedBasicCurrency::reserved_balance_named(&RID_1, &ALICE), 0); - - assert_eq!(AdaptedBasicCurrency::reserved_balance_named(&RID_2, &ALICE), 30); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::reserve_named(&RID_1, &ALICE, 50)); + assert_ok!(AdaptedBasicCurrency::reserve_named(&RID_2, &ALICE, 30)); + assert_eq!( + AdaptedBasicCurrency::reserved_balance_named(&RID_1, &ALICE), + 50 + ); + assert_eq!( + AdaptedBasicCurrency::reserved_balance_named(&RID_2, &ALICE), + 30 + ); + assert_eq!(AdaptedBasicCurrency::free_balance(&ALICE), 20); + + assert_eq!( + AdaptedBasicCurrency::unreserve_named(&RID_1, &ALICE, 80), + 30 + ); + assert_eq!(AdaptedBasicCurrency::free_balance(&ALICE), 70); + assert_eq!( + AdaptedBasicCurrency::reserved_balance_named(&RID_1, &ALICE), + 0 + ); + + assert_eq!( + AdaptedBasicCurrency::reserved_balance_named(&RID_2, &ALICE), + 30 + ); + }); } #[test] fn multi_currency_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(Currencies::transfer(Some(ALICE).into(), BOB, X_TOKEN_ID, 50)); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 50); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &BOB), 150); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(Currencies::transfer( + Some(ALICE).into(), + BOB, + X_TOKEN_ID, + 50 + )); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 50); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &BOB), 150); + }); } #[test] fn multi_currency_extended_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(>::update_balance( - X_TOKEN_ID, &ALICE, 50 - )); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 150); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!( + >::update_balance( + X_TOKEN_ID, &ALICE, 50 + ) + ); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 150); + }); } #[test] fn native_currency_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(Currencies::transfer_native_currency(Some(ALICE).into(), BOB, 50)); - assert_eq!(NativeCurrency::free_balance(&ALICE), 50); - assert_eq!(NativeCurrency::free_balance(&BOB), 150); - - assert_ok!(NativeCurrency::transfer(&ALICE, &BOB, 10)); - assert_eq!(NativeCurrency::free_balance(&ALICE), 40); - assert_eq!(NativeCurrency::free_balance(&BOB), 160); - - assert_eq!(Currencies::slash(NATIVE_CURRENCY_ID, &ALICE, 10), 0); - assert_eq!(NativeCurrency::free_balance(&ALICE), 30); - assert_eq!(NativeCurrency::total_issuance(), 190); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(Currencies::transfer_native_currency( + Some(ALICE).into(), + BOB, + 50 + )); + assert_eq!(NativeCurrency::free_balance(&ALICE), 50); + assert_eq!(NativeCurrency::free_balance(&BOB), 150); + + assert_ok!(NativeCurrency::transfer(&ALICE, &BOB, 10)); + assert_eq!(NativeCurrency::free_balance(&ALICE), 40); + assert_eq!(NativeCurrency::free_balance(&BOB), 160); + + assert_eq!(Currencies::slash(NATIVE_CURRENCY_ID, &ALICE, 10), 0); + assert_eq!(NativeCurrency::free_balance(&ALICE), 30); + assert_eq!(NativeCurrency::total_issuance(), 190); + }); } #[test] fn native_currency_extended_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(NativeCurrency::update_balance(&ALICE, 10)); - assert_eq!(NativeCurrency::free_balance(&ALICE), 110); - - assert_ok!(>::update_balance( - NATIVE_CURRENCY_ID, - &ALICE, - 10 - )); - assert_eq!(NativeCurrency::free_balance(&ALICE), 120); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(NativeCurrency::update_balance(&ALICE, 10)); + assert_eq!(NativeCurrency::free_balance(&ALICE), 110); + + assert_ok!( + >::update_balance( + NATIVE_CURRENCY_ID, + &ALICE, + 10 + ) + ); + assert_eq!(NativeCurrency::free_balance(&ALICE), 120); + }); } #[test] fn basic_currency_adapting_pallet_balances_transfer() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::transfer(&ALICE, &BOB, 50)); - assert_eq!(PalletBalances::total_balance(&ALICE), 50); - assert_eq!(PalletBalances::total_balance(&BOB), 150); - - // creation fee - assert_ok!(AdaptedBasicCurrency::transfer(&ALICE, &EVA, 10)); - assert_eq!(PalletBalances::total_balance(&ALICE), 40); - assert_eq!(PalletBalances::total_balance(&EVA), 10); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::transfer(&ALICE, &BOB, 50)); + assert_eq!(PalletBalances::total_balance(&ALICE), 50); + assert_eq!(PalletBalances::total_balance(&BOB), 150); + + // creation fee + assert_ok!(AdaptedBasicCurrency::transfer(&ALICE, &EVA, 10)); + assert_eq!(PalletBalances::total_balance(&ALICE), 40); + assert_eq!(PalletBalances::total_balance(&EVA), 10); + }); } #[test] fn basic_currency_adapting_pallet_balances_deposit() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::deposit(&EVA, 50)); - assert_eq!(PalletBalances::total_balance(&EVA), 50); - assert_eq!(PalletBalances::total_issuance(), 250); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::deposit(&EVA, 50)); + assert_eq!(PalletBalances::total_balance(&EVA), 50); + assert_eq!(PalletBalances::total_issuance(), 250); + }); } #[test] fn basic_currency_adapting_pallet_balances_deposit_throw_error_when_actual_deposit_is_not_expected() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(PalletBalances::total_balance(&EVA), 0); - assert_eq!(PalletBalances::total_issuance(), 200); - assert_noop!(AdaptedBasicCurrency::deposit(&EVA, 1), Error::::DepositFailed); - assert_eq!(PalletBalances::total_balance(&EVA), 0); - assert_eq!(PalletBalances::total_issuance(), 200); - assert_ok!(AdaptedBasicCurrency::deposit(&EVA, 2)); - assert_eq!(PalletBalances::total_balance(&EVA), 2); - assert_eq!(PalletBalances::total_issuance(), 202); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(PalletBalances::total_balance(&EVA), 0); + assert_eq!(PalletBalances::total_issuance(), 200); + assert_noop!( + AdaptedBasicCurrency::deposit(&EVA, 1), + Error::::DepositFailed + ); + assert_eq!(PalletBalances::total_balance(&EVA), 0); + assert_eq!(PalletBalances::total_issuance(), 200); + assert_ok!(AdaptedBasicCurrency::deposit(&EVA, 2)); + assert_eq!(PalletBalances::total_balance(&EVA), 2); + assert_eq!(PalletBalances::total_issuance(), 202); + }); } #[test] fn basic_currency_adapting_pallet_balances_withdraw() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::withdraw(&ALICE, 100)); - assert_eq!(PalletBalances::total_balance(&ALICE), 0); - assert_eq!(PalletBalances::total_issuance(), 100); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::withdraw(&ALICE, 100)); + assert_eq!(PalletBalances::total_balance(&ALICE), 0); + assert_eq!(PalletBalances::total_issuance(), 100); + }); } #[test] fn basic_currency_adapting_pallet_balances_slash() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(AdaptedBasicCurrency::slash(&ALICE, 101), 1); - assert_eq!(PalletBalances::total_balance(&ALICE), 0); - assert_eq!(PalletBalances::total_issuance(), 100); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(AdaptedBasicCurrency::slash(&ALICE, 101), 1); + assert_eq!(PalletBalances::total_balance(&ALICE), 0); + assert_eq!(PalletBalances::total_issuance(), 100); + }); } #[test] fn basic_currency_adapting_pallet_balances_update_balance() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(AdaptedBasicCurrency::update_balance(&ALICE, -10)); - assert_eq!(PalletBalances::total_balance(&ALICE), 90); - assert_eq!(PalletBalances::total_issuance(), 190); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(AdaptedBasicCurrency::update_balance(&ALICE, -10)); + assert_eq!(PalletBalances::total_balance(&ALICE), 90); + assert_eq!(PalletBalances::total_issuance(), 190); + }); } #[test] fn update_balance_call_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE, - NATIVE_CURRENCY_ID, - -10 - )); - assert_eq!(NativeCurrency::free_balance(&ALICE), 90); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 100); - assert_ok!(Currencies::update_balance(RuntimeOrigin::root(), ALICE, X_TOKEN_ID, 10)); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 110); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE, + NATIVE_CURRENCY_ID, + -10 + )); + assert_eq!(NativeCurrency::free_balance(&ALICE), 90); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 100); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE, + X_TOKEN_ID, + 10 + )); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 110); + }); } #[test] @@ -284,45 +417,57 @@ fn update_balance_call_fails_if_not_root_origin() { #[test] fn call_event_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - System::set_block_number(1); - - assert_ok!(Currencies::transfer(Some(ALICE).into(), BOB, X_TOKEN_ID, 50)); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 50); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &BOB), 150); - System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Transfer { - currency_id: X_TOKEN_ID, - from: ALICE, - to: BOB, - amount: 50, - })); - - assert_ok!(>::transfer( - X_TOKEN_ID, &ALICE, &BOB, 10 - )); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 40); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &BOB), 160); - System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Transfer { - currency_id: X_TOKEN_ID, - from: ALICE, - to: BOB, - amount: 10, - })); - - assert_ok!(>::deposit(X_TOKEN_ID, &ALICE, 100)); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 140); - System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Deposited { - currency_id: X_TOKEN_ID, - who: ALICE, - amount: 100, - })); - - assert_ok!(>::withdraw(X_TOKEN_ID, &ALICE, 20)); - assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 120); - System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Withdrawn { - currency_id: X_TOKEN_ID, - who: ALICE, - amount: 20, - })); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + System::set_block_number(1); + + assert_ok!(Currencies::transfer( + Some(ALICE).into(), + BOB, + X_TOKEN_ID, + 50 + )); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 50); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &BOB), 150); + System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Transfer { + currency_id: X_TOKEN_ID, + from: ALICE, + to: BOB, + amount: 50, + })); + + assert_ok!(>::transfer( + X_TOKEN_ID, &ALICE, &BOB, 10 + )); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 40); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &BOB), 160); + System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Transfer { + currency_id: X_TOKEN_ID, + from: ALICE, + to: BOB, + amount: 10, + })); + + assert_ok!(>::deposit( + X_TOKEN_ID, &ALICE, 100 + )); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 140); + System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Deposited { + currency_id: X_TOKEN_ID, + who: ALICE, + amount: 100, + })); + + assert_ok!(>::withdraw( + X_TOKEN_ID, &ALICE, 20 + )); + assert_eq!(Currencies::free_balance(X_TOKEN_ID, &ALICE), 120); + System::assert_last_event(RuntimeEvent::Tokens(orml_tokens::Event::Withdrawn { + currency_id: X_TOKEN_ID, + who: ALICE, + amount: 20, + })); + }); } diff --git a/pallets/deprecated/asset-registry/Cargo.toml b/pallets/deprecated/asset-registry/Cargo.toml index c6e22cd689..bc394a9e7f 100644 --- a/pallets/deprecated/asset-registry/Cargo.toml +++ b/pallets/deprecated/asset-registry/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-asset-registry" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/call-switchgear/Cargo.toml b/pallets/deprecated/call-switchgear/Cargo.toml index 491d475fb3..125c61be11 100644 --- a/pallets/deprecated/call-switchgear/Cargo.toml +++ b/pallets/deprecated/call-switchgear/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-call-switchgear" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/lightening-redeem/Cargo.toml b/pallets/deprecated/lightening-redeem/Cargo.toml index d9b93cb127..30e1062548 100644 --- a/pallets/deprecated/lightening-redeem/Cargo.toml +++ b/pallets/deprecated/lightening-redeem/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-lightening-redeem" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/pallets/deprecated/liquidity-mining/Cargo.toml b/pallets/deprecated/liquidity-mining/Cargo.toml index c7044fbc46..8df47f8438 100644 --- a/pallets/deprecated/liquidity-mining/Cargo.toml +++ b/pallets/deprecated/liquidity-mining/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-liquidity-mining" version = "0.8.0" -authors = ["Allen Pocket "] +authors = ["Liebi Technologies "] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/pallets/deprecated/liquidity-mining/rpc/Cargo.toml b/pallets/deprecated/liquidity-mining/rpc/Cargo.toml index 6b6712bc57..e60e01be67 100644 --- a/pallets/deprecated/liquidity-mining/rpc/Cargo.toml +++ b/pallets/deprecated/liquidity-mining/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-liquidity-mining-rpc-api" version = "0.8.0" -authors = ["Allen Pocket "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/liquidity-mining/rpc/runtime-api/Cargo.toml b/pallets/deprecated/liquidity-mining/rpc/runtime-api/Cargo.toml index fa40d03793..1adcf4a1fd 100644 --- a/pallets/deprecated/liquidity-mining/rpc/runtime-api/Cargo.toml +++ b/pallets/deprecated/liquidity-mining/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-liquidity-mining-rpc-runtime-api" version = "0.8.0" -authors = ["Allen Pocket "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/salp-lite/Cargo.toml b/pallets/deprecated/salp-lite/Cargo.toml index 78c05ac97c..a757df5d6c 100644 --- a/pallets/deprecated/salp-lite/Cargo.toml +++ b/pallets/deprecated/salp-lite/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp-lite" version = "0.8.0" -authors = ["Ron Yang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/salp/Cargo.toml b/pallets/deprecated/salp/Cargo.toml index ae26cb32ef..ffd9bd12f8 100644 --- a/pallets/deprecated/salp/Cargo.toml +++ b/pallets/deprecated/salp/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp" version = "0.8.0" -authors = ["Edwin Wang ", "Ron yang"] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/salp/rpc/Cargo.toml b/pallets/deprecated/salp/rpc/Cargo.toml index 1015d62ab0..89f9f40ea8 100644 --- a/pallets/deprecated/salp/rpc/Cargo.toml +++ b/pallets/deprecated/salp/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp-rpc" version = "0.8.0" -authors = ["Ron Yang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/salp/rpc/runtime-api/Cargo.toml b/pallets/deprecated/salp/rpc/runtime-api/Cargo.toml index 4d40d9b248..bceea138d5 100644 --- a/pallets/deprecated/salp/rpc/runtime-api/Cargo.toml +++ b/pallets/deprecated/salp/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp-rpc-runtime-api" version = "0.8.0" -authors = ["Ron Yang"] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/deprecated/system-maker/Cargo.toml b/pallets/deprecated/system-maker/Cargo.toml index 2173b235b9..7fb0aa69bb 100644 --- a/pallets/deprecated/system-maker/Cargo.toml +++ b/pallets/deprecated/system-maker/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-system-maker" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/deprecated/system-maker/src/lib.rs b/pallets/deprecated/system-maker/src/lib.rs index 31760408e5..5ce536f3ff 100644 --- a/pallets/deprecated/system-maker/src/lib.rs +++ b/pallets/deprecated/system-maker/src/lib.rs @@ -99,11 +99,26 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - Charged { who: AccountIdOf, currency_id: CurrencyIdOf, value: BalanceOf }, - ConfigSet { currency_id: CurrencyIdOf, info: Info> }, - Closed { currency_id: CurrencyIdOf }, - Paid { currency_id: CurrencyIdOf, value: BalanceOf }, - RedeemFailed { vcurrency_id: CurrencyIdOf, amount: BalanceOf }, + Charged { + who: AccountIdOf, + currency_id: CurrencyIdOf, + value: BalanceOf, + }, + ConfigSet { + currency_id: CurrencyIdOf, + info: Info>, + }, + Closed { + currency_id: CurrencyIdOf, + }, + Paid { + currency_id: CurrencyIdOf, + value: BalanceOf, + }, + RedeemFailed { + vcurrency_id: CurrencyIdOf, + amount: BalanceOf, + }, } #[pallet::error] @@ -160,7 +175,10 @@ pub mod pallet { let vcurrency_id = T::CurrencyIdConversion::convert_to_vtoken(currency_id) .map_err(|_| Error::::NotSupportTokenType)?; - ensure!(vcurrency_id == info.vcurrency_id, Error::::NotSupportTokenType); + ensure!( + vcurrency_id == info.vcurrency_id, + Error::::NotSupportTokenType + ); Infos::::mutate(currency_id, |old_info| { *old_info = Some(info.clone()); }); @@ -186,7 +204,11 @@ pub mod pallet { value, )?; - Self::deposit_event(Event::Charged { who: exchanger, currency_id, value }); + Self::deposit_event(Event::Charged { + who: exchanger, + currency_id, + value, + }); Ok(()) } diff --git a/pallets/deprecated/system-maker/src/mock.rs b/pallets/deprecated/system-maker/src/mock.rs index 7a309d1ae2..dcc350fd33 100644 --- a/pallets/deprecated/system-maker/src/mock.rs +++ b/pallets/deprecated/system-maker/src/mock.rs @@ -354,7 +354,12 @@ where amount: AssetBalance, ) -> DispatchResult { let currency_id: CurrencyId = asset_id.try_into().unwrap(); - Local::transfer(currency_id, &origin, &target, amount.unique_saturated_into())?; + Local::transfer( + currency_id, + &origin, + &target, + amount.unique_saturated_into(), + )?; Ok(()) } @@ -458,7 +463,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -476,13 +483,23 @@ impl ExtBuilder { (ALICE, RelayCurrencyId::get(), 10000), (ALICE, VKSM, 10000), (BOB, KSM, 100), - (SystemMakerPalletId::get().into_account_truncating(), VKSM, 10000), - (SystemMakerPalletId::get().into_account_truncating(), KSM, 10000), + ( + SystemMakerPalletId::get().into_account_truncating(), + VKSM, + 10000, + ), + ( + SystemMakerPalletId::get().into_account_truncating(), + KSM, + 10000, + ), ]) } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/deprecated/system-maker/src/tests.rs b/pallets/deprecated/system-maker/src/tests.rs index 00c57ec38e..bbb5fb846e 100644 --- a/pallets/deprecated/system-maker/src/tests.rs +++ b/pallets/deprecated/system-maker/src/tests.rs @@ -27,47 +27,56 @@ use sp_arithmetic::per_things::Permill; #[test] fn on_idle() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let para_id = 2001u32; - let zenlink_pair_account_id = init_zenlink(para_id); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let para_id = 2001u32; + let zenlink_pair_account_id = init_zenlink(para_id); - assert_ok!(SystemMaker::set_config( - RuntimeOrigin::signed(ALICE), - RelayCurrencyId::get(), - Info { - vcurrency_id: VKSM, - annualization: 600_000u32, - granularity: 1000, - minimum_redeem: 20000 - }, - )); - let system_maker = - ::SystemMakerPalletId::get().into_account_truncating(); - assert_eq!(Tokens::free_balance(KSM, &system_maker), 10000); - SystemMaker::on_idle( - >::block_number(), - Weight::from_parts(100000000, 0), - ); - System::set_block_number(System::block_number() + 1); - assert_eq!(Tokens::free_balance(VKSM, &system_maker), 10731); - assert_eq!(Tokens::free_balance(KSM, &zenlink_pair_account_id), 3000); - assert_eq!(Tokens::free_balance(VKSM, &zenlink_pair_account_id), 1469); - init_vtoken_minting(); - SystemMaker::on_idle(>::block_number(), Weight::zero()); - assert_eq!(Tokens::free_balance(VKSM, &system_maker), 10731); - assert_ok!(SystemMaker::set_config( - RuntimeOrigin::signed(ALICE), - RelayCurrencyId::get(), - Info { - vcurrency_id: VKSM, - annualization: 600_000u32, - granularity: 1000, - minimum_redeem: 2000 - }, - )); - SystemMaker::on_idle(>::block_number(), Weight::zero()); - assert_eq!(Tokens::free_balance(VKSM, &system_maker), 0); - }); + assert_ok!(SystemMaker::set_config( + RuntimeOrigin::signed(ALICE), + RelayCurrencyId::get(), + Info { + vcurrency_id: VKSM, + annualization: 600_000u32, + granularity: 1000, + minimum_redeem: 20000 + }, + )); + let system_maker = + ::SystemMakerPalletId::get().into_account_truncating(); + assert_eq!(Tokens::free_balance(KSM, &system_maker), 10000); + SystemMaker::on_idle( + >::block_number(), + Weight::from_parts(100000000, 0), + ); + System::set_block_number(System::block_number() + 1); + assert_eq!(Tokens::free_balance(VKSM, &system_maker), 10731); + assert_eq!(Tokens::free_balance(KSM, &zenlink_pair_account_id), 3000); + assert_eq!(Tokens::free_balance(VKSM, &zenlink_pair_account_id), 1469); + init_vtoken_minting(); + SystemMaker::on_idle( + >::block_number(), + Weight::zero(), + ); + assert_eq!(Tokens::free_balance(VKSM, &system_maker), 10731); + assert_ok!(SystemMaker::set_config( + RuntimeOrigin::signed(ALICE), + RelayCurrencyId::get(), + Info { + vcurrency_id: VKSM, + annualization: 600_000u32, + granularity: 1000, + minimum_redeem: 2000 + }, + )); + SystemMaker::on_idle( + >::block_number(), + Weight::zero(), + ); + assert_eq!(Tokens::free_balance(VKSM, &system_maker), 0); + }); } fn init_zenlink(para_id: u32) -> AccountIdOf { @@ -105,6 +114,13 @@ fn init_vtoken_minting() { TimeUnit::Era(1) )); assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - assert_ok!(VtokenMinting::set_minimum_redeem(RuntimeOrigin::signed(ALICE), VKSM, 90)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::set_minimum_redeem( + RuntimeOrigin::signed(ALICE), + VKSM, + 90 + )); } diff --git a/pallets/deprecated/vsbond-auction/Cargo.toml b/pallets/deprecated/vsbond-auction/Cargo.toml index bbfa38c547..c024aac0ba 100644 --- a/pallets/deprecated/vsbond-auction/Cargo.toml +++ b/pallets/deprecated/vsbond-auction/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vsbond-auction" version = "0.8.0" -authors = ["Allen Pocket "] +authors = ["Liebi Technologies "] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/pallets/evm-accounts/Cargo.toml b/pallets/evm-accounts/Cargo.toml index 65366645cb..23c61345b5 100644 --- a/pallets/evm-accounts/Cargo.toml +++ b/pallets/evm-accounts/Cargo.toml @@ -51,6 +51,9 @@ std = [ "frame-benchmarking/std", ] runtime-benchmarks = [ + "frame-benchmarking", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", "frame-benchmarking/runtime-benchmarks", "sp-io", ] diff --git a/pallets/evm-accounts/src/benchmarking.rs b/pallets/evm-accounts/src/benchmarking.rs index 9214eab696..1e13a5287e 100644 --- a/pallets/evm-accounts/src/benchmarking.rs +++ b/pallets/evm-accounts/src/benchmarking.rs @@ -16,63 +16,75 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; -use crate::Pallet as EVMAccounts; - -use frame_benchmarking::{account, benchmarks}; +use frame_benchmarking::v2::*; use frame_system::RawOrigin; use sp_std::prelude::*; -benchmarks! { - where_clause { - where T::AccountId: AsRef<[u8; 32]> + frame_support::pallet_prelude::IsType, - } +#[benchmarks(where T::AccountId: AsRef<[u8; 32]> + frame_support::pallet_prelude::IsType)] +mod benchmarks { + use super::*; - bind_evm_address { + #[benchmark] + fn bind_evm_address() -> Result<(), BenchmarkError> { let user: T::AccountId = account("user", 0, 1); let evm_address = Pallet::::evm_address(&user); assert!(!AccountExtension::::contains_key(evm_address)); - }: _(RawOrigin::Signed(user.clone())) - verify { + #[extrinsic_call] + _(RawOrigin::Signed(user.clone())); + assert!(AccountExtension::::contains_key(evm_address)); + Ok(()) } - add_contract_deployer { + #[benchmark] + fn add_contract_deployer() -> Result<(), BenchmarkError> { let user: T::AccountId = account("user", 0, 1); let evm_address = Pallet::::evm_address(&user); assert!(!ContractDeployer::::contains_key(evm_address)); - }: _(RawOrigin::Root, evm_address) - verify { + #[extrinsic_call] + _(RawOrigin::Root, evm_address); + assert!(ContractDeployer::::contains_key(evm_address)); + Ok(()) } - remove_contract_deployer { + #[benchmark] + fn remove_contract_deployer() -> Result<(), BenchmarkError> { let user: T::AccountId = account("user", 0, 1); let evm_address = Pallet::::evm_address(&user); - EVMAccounts::::add_contract_deployer(RawOrigin::Root.into(), evm_address)?; - + Pallet::::add_contract_deployer(RawOrigin::Root.into(), evm_address)?; assert!(ContractDeployer::::contains_key(evm_address)); - }: _(RawOrigin::Root, evm_address) - verify { + #[extrinsic_call] + _(RawOrigin::Root, evm_address); + assert!(!ContractDeployer::::contains_key(evm_address)); + Ok(()) } - renounce_contract_deployer { + #[benchmark] + fn renounce_contract_deployer() -> Result<(), BenchmarkError> { let user: T::AccountId = account("user", 0, 1); let evm_address = Pallet::::evm_address(&user); - EVMAccounts::::add_contract_deployer(RawOrigin::Root.into(), evm_address)?; - EVMAccounts::::bind_evm_address(RawOrigin::Signed(user.clone()).into())?; + Pallet::::add_contract_deployer(RawOrigin::Root.into(), evm_address)?; + Pallet::::bind_evm_address(RawOrigin::Signed(user.clone()).into())?; assert!(ContractDeployer::::contains_key(evm_address)); - }: _(RawOrigin::Signed(user)) - verify { + #[extrinsic_call] + _(RawOrigin::Signed(user)); + assert!(!ContractDeployer::::contains_key(evm_address)); + Ok(()) } - impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Test + ); } diff --git a/pallets/evm-accounts/src/lib.rs b/pallets/evm-accounts/src/lib.rs index e77dba36a5..2fee5bdbf3 100644 --- a/pallets/evm-accounts/src/lib.rs +++ b/pallets/evm-accounts/src/lib.rs @@ -70,6 +70,7 @@ mod mock; #[cfg(test)] mod tests; +#[cfg(feature = "runtime-benchmarks")] mod benchmarking; pub mod weights; @@ -126,7 +127,10 @@ pub mod pallet { #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { /// Binding was created. - Bound { account: T::AccountId, address: EvmAddress }, + Bound { + account: T::AccountId, + address: EvmAddress, + }, /// Deployer was added. DeployerAdded { who: EvmAddress }, /// Deployer was removed. @@ -154,8 +158,16 @@ pub mod pallet { fn integrity_test() { // implementation of this pallet expects that EvmAddress is 20 bytes and AccountId is 32 // bytes long. If this is not true, `copy_from_slice` might panic. - assert_eq!(EvmAddress::len_bytes(), 20, "EVM Address is expected to be 20 bytes long."); - assert_eq!(AccountId32::LEN, 32, "AccountId is expected to be 32 bytes long."); + assert_eq!( + EvmAddress::len_bytes(), + 20, + "EVM Address is expected to be 20 bytes long." + ); + assert_eq!( + AccountId32::LEN, + 32, + "AccountId is expected to be 32 bytes long." + ); } } @@ -199,7 +211,10 @@ pub mod pallet { >::insert(evm_address, last_12_bytes); - Self::deposit_event(Event::Bound { account: who, address: evm_address }); + Self::deposit_event(Event::Bound { + account: who, + address: evm_address, + }); Ok(()) } diff --git a/pallets/evm-accounts/src/mock.rs b/pallets/evm-accounts/src/mock.rs index 25d6514ace..86e997950a 100644 --- a/pallets/evm-accounts/src/mock.rs +++ b/pallets/evm-accounts/src/mock.rs @@ -51,7 +51,9 @@ parameter_types! { pub struct EvmNonceProviderMock; impl EvmNonceProvider for EvmNonceProviderMock { fn get_nonce(evm_address: H160) -> U256 { - NONCE.with(|v| v.borrow().get(&evm_address).copied()).unwrap_or_default() + NONCE + .with(|v| v.borrow().get(&evm_address).copied()) + .unwrap_or_default() } } @@ -100,18 +102,24 @@ impl Default for ExtBuilder { v.borrow_mut().clear(); }); - Self { endowed_accounts: vec![(ALICE, HDX, INITIAL_BALANCE)] } + Self { + endowed_accounts: vec![(ALICE, HDX, INITIAL_BALANCE)], + } } } impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - - orml_tokens::GenesisConfig:: { balances: self.endowed_accounts } - .assimilate_storage(&mut t) + let mut t = frame_system::GenesisConfig::::default() + .build_storage() .unwrap(); + orml_tokens::GenesisConfig:: { + balances: self.endowed_accounts, + } + .assimilate_storage(&mut t) + .unwrap(); + let mut r: sp_io::TestExternalities = t.into(); r.execute_with(|| System::set_block_number(1)); r @@ -126,3 +134,8 @@ impl ExtBuilder { self } } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/evm-accounts/src/tests.rs b/pallets/evm-accounts/src/tests.rs index 376a66fa6d..180f907153 100644 --- a/pallets/evm-accounts/src/tests.rs +++ b/pallets/evm-accounts/src/tests.rs @@ -30,7 +30,10 @@ fn eth_address_should_convert_to_truncated_address_when_not_bound() { "d2efb4a4ab6b9c7dff8d8e1aa76dc53a0aab3a0d93747eb25db1bb7b08a76a09" ]); - assert_eq!(EVMAccounts::convert_account_id(evm_address), truncated_address.clone()); + assert_eq!( + EVMAccounts::convert_account_id(evm_address), + truncated_address.clone() + ); // Act & Assert assert_eq!(EVMAccounts::bound_account_id(evm_address), None); @@ -55,12 +58,15 @@ fn eth_address_should_convert_to_full_address_when_bound() { #[test] fn bind_address_should_fail_when_nonce_is_not_zero() { - ExtBuilder::default().with_non_zero_nonce(ALICE).build().execute_with(|| { - assert_noop!( - EVMAccounts::bind_evm_address(RuntimeOrigin::signed(ALICE)), - Error::::TruncatedAccountAlreadyUsed - ); - }); + ExtBuilder::default() + .with_non_zero_nonce(ALICE) + .build() + .execute_with(|| { + assert_noop!( + EVMAccounts::bind_evm_address(RuntimeOrigin::signed(ALICE)), + Error::::TruncatedAccountAlreadyUsed + ); + }); } #[test] @@ -82,13 +88,19 @@ fn add_contract_deployer_should_store_address_in_the_storage() { assert!(!EVMAccounts::can_deploy_contracts(evm_address)); // Act - assert_ok!(EVMAccounts::add_contract_deployer(RuntimeOrigin::root(), evm_address)); + assert_ok!(EVMAccounts::add_contract_deployer( + RuntimeOrigin::root(), + evm_address + )); // Assert assert!(EVMAccounts::can_deploy_contracts(evm_address)); // adding the address again should be ok - assert_ok!(EVMAccounts::add_contract_deployer(RuntimeOrigin::root(), evm_address)); + assert_ok!(EVMAccounts::add_contract_deployer( + RuntimeOrigin::root(), + evm_address + )); }); } @@ -97,17 +109,26 @@ fn remove_contract_deployer_should_remove_address_from_the_storage() { ExtBuilder::default().build().execute_with(|| { // Arrange let evm_address = EVMAccounts::evm_address(&ALICE); - assert_ok!(EVMAccounts::add_contract_deployer(RuntimeOrigin::root(), evm_address)); + assert_ok!(EVMAccounts::add_contract_deployer( + RuntimeOrigin::root(), + evm_address + )); assert!(EVMAccounts::can_deploy_contracts(evm_address)); // Act - assert_ok!(EVMAccounts::remove_contract_deployer(RuntimeOrigin::root(), evm_address)); + assert_ok!(EVMAccounts::remove_contract_deployer( + RuntimeOrigin::root(), + evm_address + )); // Assert assert!(!EVMAccounts::can_deploy_contracts(evm_address)); // removing the address again should be ok - assert_ok!(EVMAccounts::remove_contract_deployer(RuntimeOrigin::root(), evm_address)); + assert_ok!(EVMAccounts::remove_contract_deployer( + RuntimeOrigin::root(), + evm_address + )); }); } @@ -116,16 +137,23 @@ fn renounce_contract_deployer_should_remove_address_from_the_storage() { ExtBuilder::default().build().execute_with(|| { // Arrange let evm_address = EVMAccounts::evm_address(&ALICE); - assert_ok!(EVMAccounts::add_contract_deployer(RuntimeOrigin::root(), evm_address)); + assert_ok!(EVMAccounts::add_contract_deployer( + RuntimeOrigin::root(), + evm_address + )); assert!(EVMAccounts::can_deploy_contracts(evm_address)); // Act - assert_ok!(EVMAccounts::renounce_contract_deployer(RuntimeOrigin::signed(ALICE))); + assert_ok!(EVMAccounts::renounce_contract_deployer( + RuntimeOrigin::signed(ALICE) + )); // Assert assert!(!EVMAccounts::can_deploy_contracts(evm_address)); // ronouncing the address again should be ok - assert_ok!(EVMAccounts::renounce_contract_deployer(RuntimeOrigin::signed(ALICE))); + assert_ok!(EVMAccounts::renounce_contract_deployer( + RuntimeOrigin::signed(ALICE) + )); }); } diff --git a/pallets/evm-accounts/src/weights.rs b/pallets/evm-accounts/src/weights.rs index 9421d1a0f0..c2817d0200 100644 --- a/pallets/evm-accounts/src/weights.rs +++ b/pallets/evm-accounts/src/weights.rs @@ -1,13 +1,20 @@ -// This file is part of HydraDX. +// This file is part of Bifrost. -// Copyright (C) 2020-2024 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,38 +22,36 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Autogenerated weights for `pallet_evm_accounts` +//! Autogenerated weights for pallet_evm_accounts //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2024-02-21, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.1 +//! DATE: 2024-12-24, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-polkadot-local"), DB CACHE: 1024 // Executed Command: -// target/release/hydradx +// target/release/bifrost // benchmark // pallet -// --chain=dev -// --steps=10 -// --repeat=30 -// --wasm-execution=compiled -// --heap-pages=4096 -// --template=.maintain/pallet-weight-template-no-back.hbs +// --chain=bifrost-polkadot-local +// --steps=50 +// --repeat=20 // --pallet=pallet-evm-accounts -// --output=weights-1.1.0/evm-accounts.rs // --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./pallets/evm-accounts/src/weights.rs +// --template=./weight-template/pallet-weight-template.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; +/// Weight functions needed for pallet_evm_accounts. pub trait WeightInfo { fn bind_evm_address() -> Weight; fn add_contract_deployer() -> Weight; @@ -54,111 +59,86 @@ pub trait WeightInfo { fn renounce_contract_deployer() -> Weight; } -pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { - /// Storage: `EVMAccounts::AccountExtension` (r:1 w:1) - /// Proof: `EVMAccounts::AccountExtension` (`max_values`: None, `max_size`: Some(48), added: - /// 2523, mode: `MaxEncodedLen`) Storage: `System::Account` (r:1 w:0) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: - /// `MaxEncodedLen`) Storage: `AssetRegistry::NextAssetId` (r:1 w:0) - /// Proof: `AssetRegistry::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, - /// mode: `MaxEncodedLen`) Storage: `AssetRegistry::LocationAssets` (r:1 w:0) - /// Proof: `AssetRegistry::LocationAssets` (`max_values`: None, `max_size`: Some(622), added: - /// 3097, mode: `MaxEncodedLen`) Storage: `Tokens::Accounts` (r:1 w:0) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: - /// `MaxEncodedLen`) - fn bind_evm_address() -> Weight { - // Proof Size summary in bytes: - // Measured: `479` - // Estimated: `4087` - // Minimum execution time: 36_357_000 picoseconds. - Weight::from_parts(36_601_000, 4087) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `EVMAccounts::ContractDeployer` (r:0 w:1) - /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: - /// 2511, mode: `MaxEncodedLen`) - fn add_contract_deployer() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 13_157_000 picoseconds. - Weight::from_parts(13_481_000, 0).saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `EVMAccounts::ContractDeployer` (r:0 w:1) - /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: - /// 2511, mode: `MaxEncodedLen`) - fn remove_contract_deployer() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 13_196_000 picoseconds. - Weight::from_parts(13_517_000, 0).saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `EVMAccounts::ContractDeployer` (r:0 w:1) - /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: - /// 2511, mode: `MaxEncodedLen`) - fn renounce_contract_deployer() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 13_153_000 picoseconds. - Weight::from_parts(13_380_000, 0).saturating_add(T::DbWeight::get().writes(1)) - } -} - // For backwards compatibility and tests impl WeightInfo for () { /// Storage: `EVMAccounts::AccountExtension` (r:1 w:1) - /// Proof: `EVMAccounts::AccountExtension` (`max_values`: None, `max_size`: Some(48), added: - /// 2523, mode: `MaxEncodedLen`) Storage: `System::Account` (r:1 w:0) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: - /// `MaxEncodedLen`) Storage: `AssetRegistry::NextAssetId` (r:1 w:0) - /// Proof: `AssetRegistry::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, - /// mode: `MaxEncodedLen`) Storage: `AssetRegistry::LocationAssets` (r:1 w:0) - /// Proof: `AssetRegistry::LocationAssets` (`max_values`: None, `max_size`: Some(622), added: - /// 3097, mode: `MaxEncodedLen`) Storage: `Tokens::Accounts` (r:1 w:0) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: - /// `MaxEncodedLen`) + /// Proof: `EVMAccounts::AccountExtension` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:1 w:0) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn bind_evm_address() -> Weight { // Proof Size summary in bytes: - // Measured: `479` - // Estimated: `4087` - // Minimum execution time: 36_357_000 picoseconds. - Weight::from_parts(36_601_000, 4087) - .saturating_add(RocksDbWeight::get().reads(5)) - .saturating_add(RocksDbWeight::get().writes(1)) + // Measured: `435` + // Estimated: `3593` + // Minimum execution time: 15_784_000 picoseconds. + Weight::from_parts(16_421_000, 3593) + .saturating_add(RocksDbWeight::get().reads(7_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `EVMAccounts::ContractDeployer` (r:0 w:1) - /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: - /// 2511, mode: `MaxEncodedLen`) + /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) fn add_contract_deployer() -> Weight { // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 13_157_000 picoseconds. - Weight::from_parts(13_481_000, 0).saturating_add(RocksDbWeight::get().writes(1)) + // Measured: `25` + // Estimated: `1510` + // Minimum execution time: 6_039_000 picoseconds. + Weight::from_parts(6_327_000, 1510) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `EVMAccounts::ContractDeployer` (r:0 w:1) - /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: - /// 2511, mode: `MaxEncodedLen`) + /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) fn remove_contract_deployer() -> Weight { // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 13_196_000 picoseconds. - Weight::from_parts(13_517_000, 0).saturating_add(RocksDbWeight::get().writes(1)) + // Measured: `25` + // Estimated: `1510` + // Minimum execution time: 6_099_000 picoseconds. + Weight::from_parts(6_709_000, 1510) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `EVMAccounts::ContractDeployer` (r:0 w:1) - /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: - /// 2511, mode: `MaxEncodedLen`) + /// Proof: `EVMAccounts::ContractDeployer` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) fn renounce_contract_deployer() -> Weight { // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 13_153_000 picoseconds. - Weight::from_parts(13_380_000, 0).saturating_add(RocksDbWeight::get().writes(1)) + // Measured: `25` + // Estimated: `1510` + // Minimum execution time: 6_116_000 picoseconds. + Weight::from_parts(6_412_000, 1510) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } } diff --git a/pallets/farming/Cargo.toml b/pallets/farming/Cargo.toml index 50853b0645..ecc6ea15c1 100644 --- a/pallets/farming/Cargo.toml +++ b/pallets/farming/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-farming" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/farming/rpc/Cargo.toml b/pallets/farming/rpc/Cargo.toml index f82d994a3d..d4cb683ac6 100644 --- a/pallets/farming/rpc/Cargo.toml +++ b/pallets/farming/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-farming-rpc" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/farming/rpc/runtime-api/Cargo.toml b/pallets/farming/rpc/runtime-api/Cargo.toml index 6fd4f7ba04..358e433928 100644 --- a/pallets/farming/rpc/runtime-api/Cargo.toml +++ b/pallets/farming/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-farming-rpc-runtime-api" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/farming/rpc/src/lib.rs b/pallets/farming/rpc/src/lib.rs index 9a926babda..cdbfef36dd 100644 --- a/pallets/farming/rpc/src/lib.rs +++ b/pallets/farming/rpc/src/lib.rs @@ -60,13 +60,17 @@ pub struct FarmingRpc { impl FarmingRpc { pub fn new(client: Arc) -> Self { - Self { client, _marker: PhantomData } + Self { + client, + _marker: PhantomData, + } } } #[async_trait] impl - FarmingRpcApiServer<::Hash, AccountId, PoolId, CurrencyId> for FarmingRpc + FarmingRpcApiServer<::Hash, AccountId, PoolId, CurrencyId> + for FarmingRpc where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, diff --git a/pallets/farming/src/benchmarking.rs b/pallets/farming/src/benchmarking.rs index c743e1dd31..8635bcd178 100644 --- a/pallets/farming/src/benchmarking.rs +++ b/pallets/farming/src/benchmarking.rs @@ -19,58 +19,91 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg(feature = "runtime-benchmarks")] -use frame_benchmarking::{benchmarks, whitelisted_caller}; +use crate::{Config, Pallet as Farming, *}; +use bifrost_primitives::DOT; +use frame_benchmarking::v2::*; use frame_support::{assert_ok, sp_runtime::traits::UniqueSaturatedFrom}; use frame_system::{Pallet as System, RawOrigin}; +use orml_traits::MultiCurrency; use sp_std::vec; -use crate::{Pallet as Farming, *}; +#[benchmarks(where T: Config + bb_bnc::Config)] +mod benchmarks { + use super::*; -benchmarks! { - on_initialize {}:{Farming::::on_initialize(BlockNumberFor::::from(10u32));} - create_farming_pool { - let caller: T::AccountId = whitelisted_caller(); + #[benchmark] + fn on_initialize() -> Result<(), BenchmarkError> { + #[block] + { + Farming::::on_initialize(BlockNumberFor::::from(10u32)); + } + + Ok(()) + } + + #[benchmark] + fn create_farming_pool() -> Result<(), BenchmarkError> { + let _caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; - }: _(RawOrigin::Root, - tokens_proportion.clone(), - basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), - BalanceOf::::unique_saturated_from(0u128), - BlockNumberFor::::from(0u32), - BlockNumberFor::::from(7u32), - BlockNumberFor::::from(6u32), - 5) - - deposit { + #[extrinsic_call] + _( + RawOrigin::Root, + tokens_proportion.clone(), + basic_rewards.clone(), + Some(gauge_basic_rewards), + BalanceOf::::unique_saturated_from(0u128), + BlockNumberFor::::from(0u32), + BlockNumberFor::::from(7u32), + BlockNumberFor::::from(6u32), + 5, + ); + + Ok(()) + } + #[benchmark] + fn charge() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id: CurrencyIdOf = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; - let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; + let _gauge_basic_rewards = vec![(default_currency_id, token_amount)]; assert_ok!(Farming::::create_farming_pool( RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + None, BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - }: _(RawOrigin::Signed(caller.clone()), 0, token_amount) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(10u128), + )]; - withdraw { + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 0, charge_rewards); + + Ok(()) + } + + #[benchmark] + fn deposit() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); - let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let token_amount = BalanceOf::::unique_saturated_from(0u128); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; @@ -78,22 +111,37 @@ benchmarks! { RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - assert_ok!(Farming::::deposit(RawOrigin::Signed(caller.clone()).into(), 0, token_amount)); - }: _(RawOrigin::Signed(caller.clone()), 0, None) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(10u128), + )]; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 0, token_amount); - claim { + Ok(()) + } + #[benchmark] + fn withdraw() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; @@ -101,24 +149,43 @@ benchmarks! { RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - assert_ok!(Farming::::deposit(RawOrigin::Signed(caller.clone()).into(), 0, token_amount)); - System::::set_block_number(System::::block_number() + BlockNumberFor::::from(10u32)); - Farming::::on_initialize(BlockNumberFor::::from(0u32)); - }: _(RawOrigin::Signed(caller.clone()), 0) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards + )); + assert_ok!(Farming::::deposit( + RawOrigin::Signed(caller.clone()).into(), + 0, + token_amount + )); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 0, None); + + Ok(()) + } - gauge_withdraw { + #[benchmark] + fn claim() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; @@ -126,23 +193,47 @@ benchmarks! { RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - assert_ok!(Farming::::deposit(RawOrigin::Signed(caller.clone()).into(), 0, token_amount)); - // System::::set_block_number(System::::block_number() + BlockNumberFor::::from(10u32)); - }: _(RawOrigin::Signed(caller.clone()), 0) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + assert_ok!(Farming::::deposit( + RawOrigin::Signed(caller.clone()).into(), + 0, + token_amount + )); + System::::set_block_number( + System::::block_number() + BlockNumberFor::::from(10u32), + ); + Farming::::on_initialize(BlockNumberFor::::from(0u32)); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 0); + + Ok(()) + } - withdraw_claim { + #[benchmark] + fn withdraw_claim() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; @@ -150,154 +241,247 @@ benchmarks! { RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - assert_ok!(Farming::::deposit(RawOrigin::Signed(caller.clone()).into(), 0, token_amount)); - }: _(RawOrigin::Signed(caller.clone()), 0) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + assert_ok!(Farming::::deposit( + RawOrigin::Signed(caller.clone()).into(), + 0, + token_amount + )); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 0); + + Ok(()) + } - reset_pool { + #[benchmark] + fn reset_pool() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; let pid = 0; - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; assert_ok!(Farming::::create_farming_pool( RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards.clone())), + Some(gauge_basic_rewards.clone()), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - System::::set_block_number(System::::block_number() + BlockNumberFor::::from(10u32)); + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + System::::set_block_number( + System::::block_number() + BlockNumberFor::::from(10u32), + ); Farming::::on_initialize(BlockNumberFor::::from(0u32)); assert_ok!(Farming::::close_pool(RawOrigin::Root.into(), pid)); assert_ok!(Farming::::set_retire_limit(RawOrigin::Root.into(), 10)); assert_ok!(Farming::::force_retire_pool(RawOrigin::Root.into(), pid)); - }: _(RawOrigin::Root, - pid, - Some(basic_rewards.clone()), - Some(BalanceOf::::unique_saturated_from(0u128)), - Some(BlockNumberFor::::from(0u32)), - Some(BlockNumberFor::::from(7u32)), - Some(BlockNumberFor::::from(6u32)), - Some(5), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)) - ) - - force_retire_pool { + + #[extrinsic_call] + _( + RawOrigin::Root, + pid, + Some(basic_rewards.clone()), + Some(BalanceOf::::unique_saturated_from(0u128)), + Some(BlockNumberFor::::from(0u32)), + Some(BlockNumberFor::::from(7u32)), + Some(BlockNumberFor::::from(6u32)), + Some(5), + Some(gauge_basic_rewards), + ); + + Ok(()) + } + + #[benchmark] + fn force_retire_pool() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; let pid = 0; - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; assert_ok!(Farming::::create_farming_pool( RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards.clone())), + Some(gauge_basic_rewards.clone()), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - System::::set_block_number(System::::block_number() + BlockNumberFor::::from(10u32)); + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + System::::set_block_number( + System::::block_number() + BlockNumberFor::::from(10u32), + ); Farming::::on_initialize(BlockNumberFor::::from(0u32)); assert_ok!(Farming::::close_pool(RawOrigin::Root.into(), pid)); assert_ok!(Farming::::set_retire_limit(RawOrigin::Root.into(), 10)); - }: _(RawOrigin::Root, pid) + #[extrinsic_call] + _(RawOrigin::Root, pid); - kill_pool { - let caller: T::AccountId = whitelisted_caller(); + Ok(()) + } + #[benchmark] + fn kill_pool() -> Result<(), BenchmarkError> { + let _caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; let pid = 0; - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; + let _charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; assert_ok!(Farming::::create_farming_pool( RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards.clone())), + Some(gauge_basic_rewards.clone()), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - }: _(RawOrigin::Root,pid) + #[extrinsic_call] + _(RawOrigin::Root, pid); - edit_pool { - let caller: T::AccountId = whitelisted_caller(); + Ok(()) + } + + #[benchmark] + fn edit_pool() -> Result<(), BenchmarkError> { + let _caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; - assert_ok!(Farming::::create_farming_pool(RawOrigin::Root.into(), + assert_ok!(Farming::::create_farming_pool( + RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards.clone())), + Some(gauge_basic_rewards.clone()), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), - 5)); - }: _(RawOrigin::Root, - 0, - Some(basic_rewards.clone()), - Some(BlockNumberFor::::from(7u32)), - Some(BlockNumberFor::::from(6u32)), - Some(gauge_basic_rewards), - Some(5)) - - close_pool { + 5 + )); + #[extrinsic_call] + _( + RawOrigin::Root, + 0, + Some(basic_rewards.clone()), + Some(BlockNumberFor::::from(7u32)), + Some(BlockNumberFor::::from(6u32)), + Some(gauge_basic_rewards), + Some(5), + ); + + Ok(()) + } + + #[benchmark] + fn close_pool() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::create_farming_pool(RawOrigin::Root.into(), + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; + assert_ok!(Farming::::create_farming_pool( + RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), - 5)); - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - System::::set_block_number(System::::block_number() + BlockNumberFor::::from(10u32)); + 5 + )); + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + System::::set_block_number( + System::::block_number() + BlockNumberFor::::from(10u32), + ); Farming::::on_initialize(BlockNumberFor::::from(0u32)); - }: _(RawOrigin::Root, 0) + #[extrinsic_call] + _(RawOrigin::Root, 0); + + Ok(()) + } - charge { + #[benchmark] + fn force_gauge_claim() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; @@ -305,20 +489,136 @@ benchmarks! { RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - }: _(RawOrigin::Signed(caller.clone()), 0, charge_rewards, false) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + assert_ok!(Farming::::deposit( + RawOrigin::Signed(caller.clone()).into(), + 0, + token_amount + )); + assert_ok!(Farming::::set_retire_limit(RawOrigin::Root.into(), 10)); + #[extrinsic_call] + _(RawOrigin::Root, 0); + + Ok(()) + } + + #[benchmark] + fn set_retire_limit() -> Result<(), BenchmarkError> { + #[extrinsic_call] + _(RawOrigin::Root, 10); + + Ok(()) + } + + #[benchmark] + fn add_boost_pool_whitelist() -> Result<(), BenchmarkError> { + #[extrinsic_call] + _(RawOrigin::Root, vec![0]); + + Ok(()) + } - force_gauge_claim { + #[benchmark] + fn set_next_round_whitelist() -> Result<(), BenchmarkError> { + assert_ok!(Farming::::add_boost_pool_whitelist( + RawOrigin::Root.into(), + vec![0] + )); + #[extrinsic_call] + _(RawOrigin::Root, vec![0]); + + Ok(()) + } + + #[benchmark] + fn vote() -> Result<(), BenchmarkError> { + let caller: T::AccountId = whitelisted_caller(); + let vote_list: Vec<(u32, Percent)> = vec![(0, Percent::from_percent(100))]; + assert_ok!(Farming::::add_boost_pool_whitelist( + RawOrigin::Root.into(), + vec![0] + )); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), vote_list); + + Ok(()) + } + + #[benchmark] + fn start_boost_round() -> Result<(), BenchmarkError> { + assert_ok!(Farming::::add_boost_pool_whitelist( + RawOrigin::Root.into(), + vec![0] + )); + #[extrinsic_call] + _(RawOrigin::Root, BlockNumberFor::::from(100000u32)); + + Ok(()) + } + + #[benchmark] + fn end_boost_round() -> Result<(), BenchmarkError> { + assert_ok!(Farming::::add_boost_pool_whitelist( + RawOrigin::Root.into(), + vec![0] + )); + assert_ok!(Farming::::start_boost_round( + RawOrigin::Root.into(), + BlockNumberFor::::from(100000u32) + )); + #[extrinsic_call] + _(RawOrigin::Root); + + Ok(()) + } + + #[benchmark] + fn charge_boost() -> Result<(), BenchmarkError> { + let caller: T::AccountId = whitelisted_caller(); + let default_currency_id = DOT.into(); + let charge_list = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(1_000_0000_000_000u128), + )]; + assert_ok!(Farming::::add_boost_pool_whitelist( + RawOrigin::Root.into(), + vec![0] + )); + assert_ok!(Farming::::start_boost_round( + RawOrigin::Root.into(), + BlockNumberFor::::from(100000u32) + )); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), charge_list); + + Ok(()) + } + + #[benchmark] + fn refresh() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - let default_currency_id = CurrencyIdOf::::default(); + let default_currency_id = DOT.into(); let tokens_proportion = vec![(default_currency_id, Perbill::from_percent(100))]; let basic_rewards = vec![(default_currency_id, token_amount)]; let gauge_basic_rewards = vec![(default_currency_id, token_amount)]; @@ -326,47 +626,40 @@ benchmarks! { RawOrigin::Root.into(), tokens_proportion.clone(), basic_rewards.clone(), - Some((BlockNumberFor::::from(1000u32), gauge_basic_rewards)), + Some(gauge_basic_rewards), BalanceOf::::unique_saturated_from(0u128), BlockNumberFor::::from(0u32), BlockNumberFor::::from(7u32), BlockNumberFor::::from(6u32), 5, )); - let charge_rewards = vec![(default_currency_id,BalanceOf::::unique_saturated_from(300000u128))]; - assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards, false)); - assert_ok!(Farming::::deposit(RawOrigin::Signed(caller.clone()).into(), 0, token_amount)); - assert_ok!(Farming::::set_retire_limit(RawOrigin::Root.into(), 10)); - }: _(RawOrigin::Root, 0) - - set_retire_limit {}: _(RawOrigin::Root, 10) - - add_boost_pool_whitelist {}: _(RawOrigin::Root, vec![0]) - - set_next_round_whitelist { - assert_ok!(Farming::::add_boost_pool_whitelist(RawOrigin::Root.into(), vec![0])); - }: _(RawOrigin::Root, vec![0]) - - vote { - let caller: T::AccountId = whitelisted_caller(); - let vote_list: Vec<(u32, Percent)> = vec![(0, Percent::from_percent(100))]; - assert_ok!(Farming::::add_boost_pool_whitelist(RawOrigin::Root.into(), vec![0])); - }: _(RawOrigin::Signed(caller.clone()), vote_list) - - start_boost_round { - assert_ok!(Farming::::add_boost_pool_whitelist(RawOrigin::Root.into(), vec![0])); - }: _(RawOrigin::Root, BlockNumberFor::::from(100000u32)) - - end_boost_round { - assert_ok!(Farming::::add_boost_pool_whitelist(RawOrigin::Root.into(), vec![0])); - assert_ok!(Farming::::start_boost_round(RawOrigin::Root.into(), BlockNumberFor::::from(100000u32))); - }: _(RawOrigin::Root) + ::MultiCurrency::deposit( + default_currency_id, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128), + )?; + let charge_rewards = vec![( + default_currency_id, + BalanceOf::::unique_saturated_from(300000u128), + )]; + assert_ok!(Farming::::charge( + RawOrigin::Signed(caller.clone()).into(), + 0, + charge_rewards, + )); + assert_ok!(Farming::::deposit( + RawOrigin::Signed(caller.clone()).into(), + 0, + token_amount + )); + assert_ok!(bb_bnc::Pallet::::set_config( + RawOrigin::Root.into(), + Some((4 * 365 * 86400 / 12u32).into()), + Some((7 * 86400 / 12u32).into()) + )); + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone())); - charge_boost { - let caller: T::AccountId = whitelisted_caller(); - let default_currency_id = CurrencyIdOf::::default(); - let charge_list = vec![(default_currency_id, BalanceOf::::unique_saturated_from(1_000_0000_000_000u128))]; - assert_ok!(Farming::::add_boost_pool_whitelist(RawOrigin::Root.into(), vec![0])); - assert_ok!(Farming::::start_boost_round(RawOrigin::Root.into(), BlockNumberFor::::from(100000u32))); - }: _(RawOrigin::Signed(caller.clone()), charge_list) + Ok(()) + } } diff --git a/pallets/farming/src/boost.rs b/pallets/farming/src/boost.rs index 4d85616ace..517b8ff210 100644 --- a/pallets/farming/src/boost.rs +++ b/pallets/farming/src/boost.rs @@ -90,7 +90,10 @@ impl Pallet { pub(crate) fn start_boost_round_inner(round_length: BlockNumberFor) -> DispatchResult { ensure!(round_length != Zero::zero(), Error::::RoundLengthNotSet); let mut boost_pool_info = BoostPoolInfos::::get(); - ensure!(boost_pool_info.end_round == Zero::zero(), Error::::RoundNotOver); + ensure!( + boost_pool_info.end_round == Zero::zero(), + Error::::RoundNotOver + ); // Update whitelist if BoostNextRoundWhitelist::::iter_keys().count() != 0 { @@ -100,10 +103,14 @@ impl Pallet { }); let _ = BoostNextRoundWhitelist::::clear(u32::max_value(), None); } else { - ensure!(BoostWhitelist::::iter_keys().count() != 0, Error::::WhitelistEmpty); + ensure!( + BoostWhitelist::::iter_keys().count() != 0, + Error::::WhitelistEmpty + ); } - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); boost_pool_info.start_round = current_block_number; boost_pool_info.end_round = current_block_number.saturating_add(round_length); boost_pool_info.total_votes = Zero::zero(); @@ -150,12 +157,15 @@ impl Pallet { Self::deposit_event(Event::RoundStartError { info: e }); }) .ok(); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); boost_pool_info.start_round = current_block_number; boost_pool_info.end_round = current_block_number.saturating_add(boost_pool_info.round_length); boost_pool_info.total_votes = Zero::zero(); - Self::deposit_event(Event::RoundStart { round_length: boost_pool_info.round_length }); + Self::deposit_event(Event::RoundStart { + round_length: boost_pool_info.round_length, + }); BoostPoolInfos::::set(boost_pool_info); let _ = BoostVotingPools::::clear(u32::max_value(), None); } @@ -170,27 +180,30 @@ impl Pallet { }) .try_for_each(|(pid, value, pool_info)| -> DispatchResult { let proportion = Percent::from_rational(value, boost_pool_info.total_votes); - pool_info.basic_rewards.keys().try_for_each(|currency| -> DispatchResult { - // proportion * free_balance - let transfer_balance: BalanceOf = - proportion.mul_floor(T::MultiCurrency::free_balance( + pool_info + .basic_rewards + .keys() + .try_for_each(|currency| -> DispatchResult { + // proportion * free_balance + let transfer_balance: BalanceOf = + proportion.mul_floor(T::MultiCurrency::free_balance( + *currency, + &T::FarmingBoost::get().into_account_truncating(), + )); + + BoostBasicRewards::::mutate_exists(pid, currency, |value| { + // Store None if overflow + *value = transfer_balance.checked_div( + &T::BlockNumberToBalance::convert(boost_pool_info.round_length), + ); + }); + T::MultiCurrency::transfer( *currency, &T::FarmingBoost::get().into_account_truncating(), - )); - - BoostBasicRewards::::mutate_exists(pid, currency, |value| { - // Store None if overflow - *value = transfer_balance.checked_div(&T::BlockNumberToBalance::convert( - boost_pool_info.round_length, - )); - }); - T::MultiCurrency::transfer( - *currency, - &T::FarmingBoost::get().into_account_truncating(), - &T::RewardIssuer::get().into_sub_account_truncating(pid), - transfer_balance, - ) - })?; + &T::RewardIssuer::get().into_sub_account_truncating(pid), + transfer_balance, + ) + })?; Ok(()) }) @@ -200,7 +213,7 @@ impl Pallet { who: &AccountIdOf, vote_list: Vec<(PoolId, Percent)>, ) -> DispatchResult { - let current_block_number = frame_system::Pallet::::block_number(); + let current_block_number = T::BlockNumberProvider::current_block_number(); let mut boost_pool_info = BoostPoolInfos::::get(); if let Some(user_boost_info) = UserBoostInfos::::get(who) { @@ -229,26 +242,34 @@ impl Pallet { let new_vote_amount = T::BbBNC::balance_of(who, None)?; let mut percent_check = Percent::from_percent(0); - vote_list.iter().try_for_each(|(pid, proportion)| -> DispatchResult { - ensure!(BoostWhitelist::::get(pid) != None, Error::::NotInWhitelist); - let increace = *proportion * new_vote_amount; - percent_check = - percent_check.checked_add(proportion).ok_or(Error::::PercentOverflow)?; - BoostVotingPools::::mutate(pid, |maybe_total_votes| -> DispatchResult { - match maybe_total_votes.as_mut() { - Some(total_votes) => - *total_votes = - total_votes.checked_add(&increace).ok_or(ArithmeticError::Overflow)?, - None => *maybe_total_votes = Some(increace), - } + vote_list + .iter() + .try_for_each(|(pid, proportion)| -> DispatchResult { + ensure!( + BoostWhitelist::::get(pid) != None, + Error::::NotInWhitelist + ); + let increace = *proportion * new_vote_amount; + percent_check = percent_check + .checked_add(proportion) + .ok_or(Error::::PercentOverflow)?; + BoostVotingPools::::mutate(pid, |maybe_total_votes| -> DispatchResult { + match maybe_total_votes.as_mut() { + Some(total_votes) => { + *total_votes = total_votes + .checked_add(&increace) + .ok_or(ArithmeticError::Overflow)? + } + None => *maybe_total_votes = Some(increace), + } + Ok(()) + })?; + boost_pool_info.total_votes = boost_pool_info + .total_votes + .checked_add(&new_vote_amount) + .ok_or(ArithmeticError::Overflow)?; Ok(()) })?; - boost_pool_info.total_votes = boost_pool_info - .total_votes - .checked_add(&new_vote_amount) - .ok_or(ArithmeticError::Overflow)?; - Ok(()) - })?; BoostPoolInfos::::set(boost_pool_info); let vote_list_bound = diff --git a/pallets/farming/src/gauge.rs b/pallets/farming/src/gauge.rs index 7062935e87..ee79c7d6f8 100644 --- a/pallets/farming/src/gauge.rs +++ b/pallets/farming/src/gauge.rs @@ -112,27 +112,25 @@ where pid: PoolId, pool_info: &mut PoolInfo, CurrencyIdOf, AccountIdOf, BlockNumberFor>, gauge_basic_rewards: BTreeMap, BalanceOf>, - max_block: BlockNumberFor, ) -> DispatchResult { - pool_info.gauge = Some(pid); - let current_block_number = frame_system::Pallet::::block_number(); - let gauge_pool_info = GaugePoolInfo::new( - pid, + let gid: u32 = pid + GAUGE_BASE_ID; + pool_info.gauge = Some(gid); + let gauge_reward_issuer: AccountIdOf = + T::RewardIssuer::get().into_sub_account_truncating(gid); + let gauge_pool_info = PoolInfo::new_gauge( pool_info.keeper.clone(), - pool_info.reward_issuer.clone(), + gauge_reward_issuer, + pool_info.tokens_proportion.clone(), + pool_info.basic_token, gauge_basic_rewards, - max_block, - current_block_number, + None, + Zero::zero(), // min_deposit_to_start, + Default::default(), + Default::default(), + Default::default(), + Default::default(), ); - - GaugePoolInfos::::insert(pid, &gauge_pool_info); - GaugePoolNextId::::mutate(|id| -> DispatchResult { - *id = id.checked_add(1).ok_or(ArithmeticError::Overflow)?; - Ok(()) - })?; - - let controller = T::GaugeRewardIssuer::get().into_sub_account_truncating(pid); - T::BbBNC::set_incentive(pid, Some(max_block), Some(controller)); + PoolInfos::::insert(gid, &gauge_pool_info); Ok(()) } @@ -148,8 +146,11 @@ where pool_info.rewards.iter().try_for_each( |(reward_currency, (total_reward, total_withdrawn_reward))| -> DispatchResult { - let withdrawn_reward = - share_info.withdrawn_rewards.get(reward_currency).copied().unwrap_or_default(); + let withdrawn_reward = share_info + .withdrawn_rewards + .get(reward_currency) + .copied() + .unwrap_or_default(); let total_reward_proportion: BalanceOf = u128::try_from( U256::from(share_info.share.to_owned().saturated_into::()) @@ -188,7 +189,7 @@ where None => (), Some(gid) => { let current_block_number: BlockNumberFor = - frame_system::Pallet::::block_number(); + T::BlockNumberProvider::current_block_number(); let gauge_pool_info = GaugePoolInfos::::get(gid).ok_or(Error::::GaugePoolNotExist)?; let gauge_info = @@ -199,8 +200,8 @@ where current_block_number }; - let latest_claimed_time_factor = gauge_info.latest_time_factor + - gauge_info + let latest_claimed_time_factor = gauge_info.latest_time_factor + + gauge_info .gauge_amount .saturated_into::() .checked_mul( @@ -248,19 +249,8 @@ where Ok(()) }, )?; - }, + } }; Ok(result_vec) } - - pub fn update_reward(who: &AccountIdOf, pid: PoolId) -> Result<(), DispatchError> { - let pool_info = PoolInfos::::get(pid).ok_or(Error::::PoolDoesNotExist)?; - let share_info = - SharesAndWithdrawnRewards::::get(pid, who).ok_or(Error::::ShareInfoNotExists)?; - if T::BbBNC::balance_of(who, None)? == BalanceOf::::zero() { - return Ok(()); - } - T::BbBNC::update_reward(pid, Some(who), Some((share_info.share, pool_info.total_shares)))?; - Ok(()) - } } diff --git a/pallets/farming/src/lib.rs b/pallets/farming/src/lib.rs index e3f9f0a2a7..c2a1f04025 100644 --- a/pallets/farming/src/lib.rs +++ b/pallets/farming/src/lib.rs @@ -34,13 +34,13 @@ pub mod weights; pub use weights::WeightInfo; use crate::boost::*; -use bifrost_primitives::{FarmingInfo, PoolId}; +use bifrost_primitives::{CurrencyId, FarmingInfo, PoolId}; use frame_support::{ pallet_prelude::*, sp_runtime::{ traits::{ - AccountIdConversion, AtLeast32BitUnsigned, CheckedAdd, CheckedDiv, CheckedSub, Convert, - Saturating, Zero, + AccountIdConversion, AtLeast32BitUnsigned, BlockNumberProvider, CheckedAdd, CheckedDiv, + CheckedMul, CheckedSub, Convert, Saturating, Zero, }, ArithmeticError, Perbill, Percent, }, @@ -52,7 +52,7 @@ use orml_traits::MultiCurrency; pub use pallet::*; pub use rewards::*; use sp_runtime::SaturatedConversion; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; +use sp_std::{cmp::Ordering, collections::btree_map::BTreeMap, vec::Vec}; pub type AccountIdOf = ::AccountId; @@ -66,6 +66,7 @@ use bb_bnc::BbBNCInterface; use parity_scale_codec::FullCodec; use sp_std::fmt::Debug; +const GAUGE_BASE_ID: u32 = 10000000; #[frame_support::pallet] pub mod pallet { use super::*; @@ -87,7 +88,9 @@ pub mod pallet { + scale_info::TypeInfo + MaxEncodedLen + Ord - + Default; + + Default + + From + + Into; type MultiCurrency: MultiCurrency, CurrencyId = Self::CurrencyId>; @@ -123,6 +126,9 @@ pub mod pallet { #[pallet::constant] type GaugeRewardIssuer: Get; + + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::event] @@ -161,8 +167,6 @@ pub mod pallet { pid: PoolId, /// Charged rewards. rewards: Vec<(CurrencyIdOf, BalanceOf)>, - /// Returns true if the reward is for gauge pool, false otherwise. - if_gauge: bool, }, /// The pool is deposited. Deposited { @@ -305,6 +309,8 @@ pub mod pallet { PoolNotCleared, /// Invalid remove amount InvalidRemoveAmount, + /// User farming pool overflow + UserFarmingPoolOverflow, } /// Record the id of the new pool. @@ -393,9 +399,20 @@ pub mod pallet { pub type BoostBasicRewards = StorageDoubleMap<_, Twox64Concat, PoolId, Twox64Concat, CurrencyIdOf, BalanceOf>; + /// The pool ID of the user participating in the farming pool. + #[pallet::storage] + pub type UserFarmingPool = StorageMap< + _, + Blake2_128Concat, + AccountIdOf, + BoundedVec>, + ValueQuery, + >; + #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: BlockNumberFor) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { + let n: BlockNumberFor = T::BlockNumberProvider::current_block_number(); PoolInfos::::iter().for_each(|(pid, mut pool_info)| match pool_info.state { PoolState::Ongoing => { pool_info.basic_rewards.clone().iter_mut().for_each( @@ -415,27 +432,17 @@ pub mod pallet { }, ); PoolInfos::::insert(pid, &pool_info); - }, + } PoolState::Charged => { - if n >= pool_info.after_block_to_start && - pool_info.total_shares >= pool_info.min_deposit_to_start + if n >= pool_info.after_block_to_start + && pool_info.total_shares >= pool_info.min_deposit_to_start { pool_info.block_startup = Some(n); pool_info.state = PoolState::Ongoing; PoolInfos::::insert(pid, &pool_info); } - }, - _ => (), - }); - - GaugePoolInfos::::iter().for_each(|(gid, gauge_pool_info)| { - match gauge_pool_info.gauge_state { - GaugeState::Bonded => { - let rewards = gauge_pool_info.gauge_basic_rewards.into_keys().collect(); - T::BbBNC::auto_notify_reward(gid, n, rewards).unwrap_or_default(); - }, - _ => (), } + _ => (), }); if n == BoostPoolInfos::::get().end_round { @@ -473,7 +480,7 @@ pub mod pallet { origin: OriginFor, tokens_proportion: Vec<(CurrencyIdOf, Perbill)>, basic_rewards: Vec<(CurrencyIdOf, BalanceOf)>, - gauge_init: Option<(BlockNumberFor, Vec<(CurrencyIdOf, BalanceOf)>)>, + gauge_init: Option, BalanceOf)>>, min_deposit_to_start: BalanceOf, #[pallet::compact] after_block_to_start: BlockNumberFor, #[pallet::compact] withdraw_limit_time: BlockNumberFor, @@ -483,8 +490,9 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; let pid = PoolNextId::::get(); - let keeper = T::Keeper::get().into_sub_account_truncating(pid); - let reward_issuer = T::RewardIssuer::get().into_sub_account_truncating(pid); + let keeper: AccountIdOf = T::Keeper::get().into_sub_account_truncating(pid); + let reward_issuer: AccountIdOf = + T::RewardIssuer::get().into_sub_account_truncating(pid); let basic_token = *tokens_proportion.get(0).ok_or(Error::::NotNullable)?; let tokens_proportion_map: BTreeMap, Perbill> = tokens_proportion.into_iter().collect(); @@ -492,11 +500,11 @@ pub mod pallet { basic_rewards.into_iter().collect(); let mut pool_info = PoolInfo::new( - keeper, + keeper.clone(), reward_issuer, - tokens_proportion_map, + tokens_proportion_map.clone(), basic_token, - basic_rewards_map, + basic_rewards_map.clone(), None, min_deposit_to_start, after_block_to_start, @@ -505,11 +513,11 @@ pub mod pallet { withdraw_limit_count, ); - if let Some((max_block, gauge_basic_rewards)) = gauge_init { + if let Some(gauge_basic_rewards) = gauge_init { let gauge_basic_rewards_map: BTreeMap, BalanceOf> = gauge_basic_rewards.into_iter().collect(); - Self::create_gauge_pool(pid, &mut pool_info, gauge_basic_rewards_map, max_block)?; + Self::create_gauge_pool(pid, &mut pool_info, gauge_basic_rewards_map.clone())?; }; PoolInfos::::insert(pid, &pool_info); @@ -537,47 +545,35 @@ pub mod pallet { origin: OriginFor, pid: PoolId, rewards: Vec<(CurrencyIdOf, BalanceOf)>, - if_gauge: bool, ) -> DispatchResult { let exchanger = ensure_signed(origin)?; let mut pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; - match if_gauge { - true => { - let gauge_reward_issuer = - T::GaugeRewardIssuer::get().into_sub_account_truncating(pid); - rewards.iter().try_for_each(|(reward_currency, reward)| -> DispatchResult { - T::MultiCurrency::transfer( - *reward_currency, - &exchanger, - &gauge_reward_issuer, - *reward, - ) - })?; - }, - false => { - ensure!( - pool_info.state == PoolState::UnCharged || - pool_info.state == PoolState::Ongoing, - Error::::InvalidPoolState - ); - rewards.iter().try_for_each(|(reward_currency, reward)| -> DispatchResult { - T::MultiCurrency::transfer( - *reward_currency, - &exchanger, - &pool_info.reward_issuer, - *reward, - ) - })?; - if pool_info.state == PoolState::UnCharged { - pool_info.state = PoolState::Charged - } - PoolInfos::::insert(&pid, pool_info); - }, - }; + ensure!( + pool_info.state == PoolState::UnCharged || pool_info.state == PoolState::Ongoing, + Error::::InvalidPoolState + ); + rewards + .iter() + .try_for_each(|(reward_currency, reward)| -> DispatchResult { + T::MultiCurrency::transfer( + *reward_currency, + &exchanger, + &pool_info.reward_issuer, + *reward, + ) + })?; + if pool_info.state == PoolState::UnCharged { + pool_info.state = PoolState::Charged + } + PoolInfos::::insert(&pid, pool_info); - Self::deposit_event(Event::Charged { who: exchanger, pid, rewards, if_gauge }); + Self::deposit_event(Event::Charged { + who: exchanger, + pid, + rewards, + }); Ok(()) } @@ -607,7 +603,7 @@ pub mod pallet { if let PoolState::Charged = pool_info.state { let current_block_number: BlockNumberFor = - frame_system::Pallet::::block_number(); + T::BlockNumberProvider::current_block_number(); ensure!( current_block_number >= pool_info.after_block_to_start, Error::::CanNotDeposit @@ -626,9 +622,40 @@ pub mod pallet { }, )?; Self::add_share(&exchanger, pid, &mut pool_info, add_value); - Self::update_reward(&exchanger, pid)?; + let gauge_pid = pid + GAUGE_BASE_ID; + if let Some(mut gauge_pool_info) = PoolInfos::::get(gauge_pid) { + let gauge_new_value = T::BbBNC::balance_of(&exchanger, None)? + .checked_mul(&add_value) + .ok_or(ArithmeticError::Overflow)?; + if let Some(share_info) = SharesAndWithdrawnRewards::::get(gauge_pid, &exchanger) + { + Self::update_gauge_share( + &exchanger, + gauge_pid, + gauge_new_value, + share_info.share, + &mut gauge_pool_info, + )?; + } else { + Self::add_share(&exchanger, gauge_pid, &mut gauge_pool_info, gauge_new_value); + } + } + UserFarmingPool::::try_mutate(&exchanger, |pools| -> DispatchResult { + if pools.contains(&pid) { + return Ok(()); + } else { + pools + .try_push(pid) + .map_err(|_| Error::::UserFarmingPoolOverflow)?; + } + Ok(()) + })?; - Self::deposit_event(Event::Deposited { who: exchanger, pid, add_value }); + Self::deposit_event(Event::Deposited { + who: exchanger, + pid, + add_value, + }); Ok(()) } @@ -653,9 +680,9 @@ pub mod pallet { let pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; ensure!( - pool_info.state == PoolState::Ongoing || - pool_info.state == PoolState::Charged || - pool_info.state == PoolState::Dead, + pool_info.state == PoolState::Ongoing + || pool_info.state == PoolState::Charged + || pool_info.state == PoolState::Dead, Error::::InvalidPoolState ); let share_info = SharesAndWithdrawnRewards::::get(&pid, &exchanger) @@ -666,9 +693,30 @@ pub mod pallet { ); Self::remove_share(&exchanger, pid, remove_value, pool_info.withdraw_limit_time)?; - Self::update_reward(&exchanger, pid)?; + let gauge_pid = pid + GAUGE_BASE_ID; + if let Some(mut gauge_pool_info) = PoolInfos::::get(gauge_pid) { + let native_remove_value = remove_value.unwrap_or(share_info.share); + let gauge_new_value = T::BbBNC::balance_of(&exchanger, None)? + .checked_mul(&share_info.share.saturating_sub(native_remove_value)) + .ok_or(ArithmeticError::Overflow)?; + if let Some(gauge_share_info) = + SharesAndWithdrawnRewards::::get(gauge_pid, &exchanger) + { + Self::update_gauge_share( + &exchanger, + gauge_pid, + gauge_new_value, + gauge_share_info.share, + &mut gauge_pool_info, + )?; + } + } - Self::deposit_event(Event::Withdrawn { who: exchanger, pid, remove_value }); + Self::deposit_event(Event::Withdrawn { + who: exchanger, + pid, + remove_value, + }); Ok(()) } @@ -691,19 +739,27 @@ pub mod pallet { Error::::InvalidPoolState ); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let share_info = SharesAndWithdrawnRewards::::get(&pid, &exchanger) .ok_or(Error::::ShareInfoNotExists)?; ensure!( - share_info.claim_last_block.saturating_add(pool_info.claim_limit_time) <= - current_block_number, + share_info + .claim_last_block + .saturating_add(pool_info.claim_limit_time) + <= current_block_number, Error::::CanNotClaim ); Self::claim_rewards(&exchanger, pid)?; + Self::claim_rewards(&exchanger, pid + GAUGE_BASE_ID)?; Self::process_withdraw_list(&exchanger, pid, &pool_info, true)?; + Self::refresh_inner(&exchanger, pid)?; - Self::deposit_event(Event::Claimed { who: exchanger, pid }); + Self::deposit_event(Event::Claimed { + who: exchanger, + pid, + }); Ok(()) } @@ -720,8 +776,12 @@ pub mod pallet { let pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; Self::process_withdraw_list(&exchanger, pid, &pool_info, false)?; + Self::refresh_inner(&exchanger, pid)?; - Self::deposit_event(Event::WithdrawClaimed { who: exchanger, pid }); + Self::deposit_event(Event::WithdrawClaimed { + who: exchanger, + pid, + }); Ok(()) } @@ -737,7 +797,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; let mut pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; - ensure!(pool_info.state == PoolState::Dead, Error::::InvalidPoolState); + ensure!( + pool_info.state == PoolState::Dead, + Error::::InvalidPoolState + ); let withdraw_limit_time = BlockNumberFor::::default(); let retire_limit = RetireLimit::::get(); let mut all_retired = true; @@ -753,12 +816,6 @@ pub mod pallet { } if all_retired { - if let Some(ref gid) = pool_info.gauge { - let mut gauge_pool_info = - GaugePoolInfos::::get(gid).ok_or(Error::::GaugePoolNotExist)?; - gauge_pool_info.gauge_state = GaugeState::Unbond; - GaugePoolInfos::::insert(&gid, gauge_pool_info); - } pool_info.state = PoolState::Retired; pool_info.gauge = None; PoolInfos::::insert(&pid, pool_info); @@ -796,7 +853,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; let mut pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; - ensure!(pool_info.state == PoolState::Ongoing, Error::::InvalidPoolState); + ensure!( + pool_info.state == PoolState::Ongoing, + Error::::InvalidPoolState + ); pool_info.state = PoolState::Dead; PoolInfos::::insert(&pid, pool_info); @@ -825,12 +885,15 @@ pub mod pallet { withdraw_limit_time: Option>, claim_limit_time: Option>, withdraw_limit_count: Option, - gauge_init: Option<(BlockNumberFor, Vec<(CurrencyIdOf, BalanceOf)>)>, + gauge_init: Option, BalanceOf)>>, ) -> DispatchResult { T::ControlOrigin::ensure_origin(origin)?; let mut pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; - ensure!(pool_info.state == PoolState::Retired, Error::::InvalidPoolState); + ensure!( + pool_info.state == PoolState::Retired, + Error::::InvalidPoolState + ); if let Some(basic_rewards) = basic_rewards { let basic_rewards_map: BTreeMap, BalanceOf> = basic_rewards.into_iter().collect(); @@ -851,11 +914,11 @@ pub mod pallet { if let Some(withdraw_limit_count) = withdraw_limit_count { pool_info.withdraw_limit_count = withdraw_limit_count; }; - if let Some((max_block, gauge_basic_rewards)) = gauge_init { + if let Some(gauge_basic_rewards) = gauge_init { let gauge_basic_rewards_map: BTreeMap, BalanceOf> = gauge_basic_rewards.into_iter().collect(); - Self::create_gauge_pool(pid, &mut pool_info, gauge_basic_rewards_map, max_block)?; + Self::create_gauge_pool(pid, &mut pool_info, gauge_basic_rewards_map)?; }; pool_info.total_shares = Default::default(); pool_info.rewards = BTreeMap::new(); @@ -904,10 +967,10 @@ pub mod pallet { let mut pool_info = PoolInfos::::get(&pid).ok_or(Error::::PoolDoesNotExist)?; ensure!( - pool_info.state == PoolState::Retired || - pool_info.state == PoolState::Ongoing || - pool_info.state == PoolState::Charged || - pool_info.state == PoolState::UnCharged, + pool_info.state == PoolState::Retired + || pool_info.state == PoolState::Ongoing + || pool_info.state == PoolState::Charged + || pool_info.state == PoolState::UnCharged, Error::::InvalidPoolState ); if let Some(basic_rewards) = basic_rewards { @@ -943,24 +1006,6 @@ pub mod pallet { Ok(()) } - /// Withdraw the rewards from the gauge pool. - /// - /// - `gid`: The gauge pool id. - #[pallet::call_index(12)] - #[pallet::weight(T::WeightInfo::gauge_withdraw())] - pub fn gauge_withdraw(origin: OriginFor, gid: PoolId) -> DispatchResult { - // Check origin - let who = ensure_signed(origin)?; - - let pool_info = PoolInfos::::get(gid).ok_or(Error::::PoolDoesNotExist)?; - let share_info = SharesAndWithdrawnRewards::::get(gid, &who) - .ok_or(Error::::ShareInfoNotExists)?; - T::BbBNC::get_rewards(gid, &who, Some((share_info.share, pool_info.total_shares)))?; - - Self::deposit_event(Event::GaugeWithdrawn { who, gid }); - Ok(()) - } - /// Force claim the rewards from the gauge pool. /// /// Control origin can force claim the rewards from the gauge pool to the users. @@ -1041,11 +1086,14 @@ pub mod pallet { /// /// - `vote_list`: The vote list for the pool #[pallet::call_index(16)] - #[pallet::weight(T::WeightInfo::claim())] + #[pallet::weight(T::WeightInfo::vote())] pub fn vote(origin: OriginFor, vote_list: Vec<(PoolId, Percent)>) -> DispatchResult { let exchanger = ensure_signed(origin)?; Self::vote_inner(&exchanger, vote_list.clone())?; - Self::deposit_event(Event::Voted { who: exchanger, vote_list }); + Self::deposit_event(Event::Voted { + who: exchanger, + vote_list, + }); Ok(()) } @@ -1053,7 +1101,7 @@ pub mod pallet { /// /// - `round_length`: The length of the round #[pallet::call_index(17)] - #[pallet::weight(T::WeightInfo::claim())] + #[pallet::weight(T::WeightInfo::start_boost_round())] pub fn start_boost_round( origin: OriginFor, round_length: BlockNumberFor, @@ -1065,7 +1113,7 @@ pub mod pallet { /// Force end of boost round #[pallet::call_index(18)] - #[pallet::weight(T::WeightInfo::claim())] + #[pallet::weight(T::WeightInfo::end_boost_round())] pub fn end_boost_round(origin: OriginFor) -> DispatchResult { T::ControlOrigin::ensure_origin(origin)?; Self::end_boost_round_inner(); @@ -1076,35 +1124,88 @@ pub mod pallet { /// /// - `rewards`: The rewards to charge #[pallet::call_index(19)] - #[pallet::weight(T::WeightInfo::claim())] + #[pallet::weight(T::WeightInfo::charge_boost())] pub fn charge_boost( origin: OriginFor, rewards: Vec<(CurrencyIdOf, BalanceOf)>, ) -> DispatchResult { let exchanger = ensure_signed(origin)?; - rewards.iter().try_for_each(|(currency, reward)| -> DispatchResult { - T::MultiCurrency::transfer( - *currency, - &exchanger, - &T::FarmingBoost::get().into_account_truncating(), - *reward, - ) - })?; - Self::deposit_event(Event::BoostCharged { who: exchanger, rewards }); + rewards + .iter() + .try_for_each(|(currency, reward)| -> DispatchResult { + T::MultiCurrency::transfer( + *currency, + &exchanger, + &T::FarmingBoost::get().into_account_truncating(), + *reward, + ) + })?; + Self::deposit_event(Event::BoostCharged { + who: exchanger, + rewards, + }); Ok(()) } + + #[pallet::call_index(20)] + #[pallet::weight(T::WeightInfo::refresh())] + pub fn refresh(origin: OriginFor) -> DispatchResult { + let exchanger = ensure_signed(origin)?; + Self::refresh_gauge_pool(&exchanger) + } } } -impl FarmingInfo, CurrencyIdOf> for Pallet { +impl FarmingInfo, CurrencyIdOf, T::AccountId> for Pallet { fn get_token_shares(pool_id: PoolId, currency_id: CurrencyIdOf) -> BalanceOf { if let Some(pool_info) = PoolInfos::::get(&pool_id) { if let Some(token_proportion_value) = pool_info.tokens_proportion.get(¤cy_id) { - let native_amount = - pool_info.basic_token.1.saturating_reciprocal_mul(pool_info.total_shares); + let native_amount = pool_info + .basic_token + .1 + .saturating_reciprocal_mul(pool_info.total_shares); return *token_proportion_value * native_amount; } } Zero::zero() } + + fn refresh_gauge_pool(exchanger: &T::AccountId) -> DispatchResult { + let mut pids = UserFarmingPool::::get(&exchanger); + for pid in pids.clone() { + let gauge_pid = pid + GAUGE_BASE_ID; + if let Some(share_info) = SharesAndWithdrawnRewards::::get(&pid, &exchanger) { + if let Some(mut gauge_pool_info) = PoolInfos::::get(gauge_pid) { + let gauge_new_value = T::BbBNC::balance_of(&exchanger, None)? + .checked_mul(&share_info.share) + .ok_or(ArithmeticError::Overflow)?; + if let Some(share_info) = + SharesAndWithdrawnRewards::::get(gauge_pid, &exchanger) + { + Self::update_gauge_share( + &exchanger, + gauge_pid, + gauge_new_value, + share_info.share, + &mut gauge_pool_info, + )?; + } else { + Self::add_share( + &exchanger, + gauge_pid, + &mut gauge_pool_info, + gauge_new_value, + ); + } + } + } else { + // If `SharesAndWithdrawnRewards` returns `None`, remove the `pid` from `UserFarmingPool`. + pids.retain(|&x| x != pid); + SharesAndWithdrawnRewards::::remove(gauge_pid, &exchanger); + } + } + UserFarmingPool::::insert(&exchanger, pids); + + Ok(()) + } } diff --git a/pallets/farming/src/mock.rs b/pallets/farming/src/mock.rs index 848b5af192..824d97e4b5 100644 --- a/pallets/farming/src/mock.rs +++ b/pallets/farming/src/mock.rs @@ -150,11 +150,13 @@ impl bifrost_farming::Config for Runtime { type BlockNumberToBalance = ConvertInto; type WhitelistMaximumLimit = WhitelistMaximumLimit; type GaugeRewardIssuer = FarmingGaugeRewardIssuerPalletId; + type BlockNumberProvider = System; } parameter_types! { pub const BbBNCTokenType: CurrencyId = VBNC; pub const Week: BlockNumber = 50400; // a week + pub const OneYear: BlockNumber = 2620800; // one year pub const MaxBlock: BlockNumber = 10512000; // four years pub const Multiplier: Balance = 10_u128.pow(12); pub const VoteWeightMultiplier: Balance = 1; @@ -177,6 +179,11 @@ impl bb_bnc::Config for Runtime { type VoteWeightMultiplier = VoteWeightMultiplier; type MaxPositions = MaxPositions; type MarkupRefreshLimit = MarkupRefreshLimit; + type VtokenMinting = (); + type FarmingInfo = Farming; + type FourYears = MaxBlock; + type OneYear = OneYear; + type BlockNumberProvider = System; } ord_parameter_types! { @@ -195,7 +202,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -223,7 +232,9 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { env_logger::try_init().unwrap_or(()); - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/farming/src/rewards.rs b/pallets/farming/src/rewards.rs index 7fb23d95cd..617686047d 100644 --- a/pallets/farming/src/rewards.rs +++ b/pallets/farming/src/rewards.rs @@ -113,6 +113,37 @@ where withdraw_limit_count, } } + pub fn new_gauge( + keeper: AccountIdOf, + reward_issuer: AccountIdOf, + tokens_proportion: BTreeMap, + basic_token: (CurrencyIdOf, Perbill), + basic_rewards: BTreeMap, + gauge: Option, + min_deposit_to_start: BalanceOf, + after_block_to_start: BlockNumberFor, + withdraw_limit_time: BlockNumberFor, + claim_limit_time: BlockNumberFor, + withdraw_limit_count: u8, + ) -> Self { + Self { + tokens_proportion, + basic_token, + total_shares: Default::default(), + basic_rewards, + rewards: BTreeMap::new(), + state: PoolState::Ongoing, + keeper, + reward_issuer, + gauge, + block_startup: None, + min_deposit_to_start, + after_block_to_start, + withdraw_limit_time, + claim_limit_time, + withdraw_limit_count, + } + } } #[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] @@ -134,7 +165,9 @@ impl Pallet { return Ok(()); } PoolInfos::::mutate_exists(pool, |maybe_pool_info| -> DispatchResult { - let pool_info = maybe_pool_info.as_mut().ok_or(Error::::PoolDoesNotExist)?; + let pool_info = maybe_pool_info + .as_mut() + .ok_or(Error::::PoolDoesNotExist)?; pool_info .rewards @@ -174,7 +207,10 @@ impl Pallet { U256::from(add_amount.to_owned().saturated_into::()) .saturating_mul(total_reward.to_owned().saturated_into::().into()) .checked_div( - initial_total_shares.to_owned().saturated_into::().into(), + initial_total_shares + .to_owned() + .saturated_into::() + .into(), ) .unwrap_or_default(), ) @@ -189,21 +225,24 @@ impl Pallet { }, ); - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); let mut share_info = SharesAndWithdrawnRewards::::get(pid, who) .unwrap_or_else(|| ShareInfo::new(who.clone(), current_block_number)); share_info.share = share_info.share.saturating_add(add_amount); // update withdrawn inflation for each reward currency - withdrawn_inflation.into_iter().for_each(|(reward_currency, reward_inflation)| { - share_info - .withdrawn_rewards - .entry(reward_currency) - .and_modify(|withdrawn_reward| { - *withdrawn_reward = withdrawn_reward.saturating_add(reward_inflation); - }) - .or_insert(reward_inflation); - }); + withdrawn_inflation + .into_iter() + .for_each(|(reward_currency, reward_inflation)| { + share_info + .withdrawn_rewards + .entry(reward_currency) + .and_modify(|withdrawn_reward| { + *withdrawn_reward = withdrawn_reward.saturating_add(reward_inflation); + }) + .or_insert(reward_inflation); + }); SharesAndWithdrawnRewards::::insert(pid, who, share_info); PoolInfos::::insert(&pid, pool_info); } @@ -224,7 +263,8 @@ impl Pallet { Self::claim_rewards(who, pool)?; SharesAndWithdrawnRewards::::mutate(pool, who, |share_info_old| -> DispatchResult { - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); if let Some(mut share_info) = share_info_old.take() { let remove_amount; if let Some(remove_amount_input) = remove_amount_input { @@ -242,7 +282,9 @@ impl Pallet { } PoolInfos::::mutate(pool, |maybe_pool_info| -> DispatchResult { - let pool_info = maybe_pool_info.as_mut().ok_or(Error::::PoolDoesNotExist)?; + let pool_info = maybe_pool_info + .as_mut() + .ok_or(Error::::PoolDoesNotExist)?; share_info .withdraw_list @@ -295,26 +337,21 @@ impl Pallet { } pub fn claim_rewards(who: &T::AccountId, pool: PoolId) -> DispatchResult { - if let Some(_) = GaugePoolInfos::::get(pool) { - let pool_info = PoolInfos::::get(pool).ok_or(Error::::PoolDoesNotExist)?; - let share_info = SharesAndWithdrawnRewards::::get(pool, who) - .ok_or(Error::::ShareInfoNotExists)?; - T::BbBNC::get_rewards(pool, who, Some((share_info.share, pool_info.total_shares)))?; - } SharesAndWithdrawnRewards::::mutate_exists( pool, who, |maybe_share_withdrawn| -> DispatchResult { let current_block_number: BlockNumberFor = - frame_system::Pallet::::block_number(); + T::BlockNumberProvider::current_block_number(); if let Some(share_info) = maybe_share_withdrawn { if share_info.share.is_zero() { return Ok(()); } PoolInfos::::mutate(pool, |maybe_pool_info| -> DispatchResult { - let pool_info = - maybe_pool_info.as_mut().ok_or(Error::::PoolDoesNotExist)?; + let pool_info = maybe_pool_info + .as_mut() + .ok_or(Error::::PoolDoesNotExist)?; let total_shares = U256::from(pool_info.total_shares.to_owned().saturated_into::()); @@ -364,6 +401,7 @@ impl Pallet { account_to_send = T::TreasuryAccount::get(); } } + // pay reward to `who` T::MultiCurrency::transfer( *reward_currency, @@ -395,7 +433,7 @@ impl Pallet { |share_info_old| -> DispatchResult { if let Some(mut share_info) = share_info_old.take() { let current_block_number: BlockNumberFor = - frame_system::Pallet::::block_number(); + T::BlockNumberProvider::current_block_number(); let mut tmp: Vec<(BlockNumberFor, BalanceOf)> = Default::default(); share_info.withdraw_list.iter().try_for_each( |(dest_block, remove_value)| -> DispatchResult { @@ -438,10 +476,10 @@ impl Pallet { share_info.withdraw_list = tmp; // if withdraw_list and share both are empty, and if_remove is true, remove it. - if share_info.withdraw_list != - Vec::<(BlockNumberFor, BalanceOf)>::default() || - !share_info.share.is_zero() || - !if_remove + if share_info.withdraw_list + != Vec::<(BlockNumberFor, BalanceOf)>::default() + || !share_info.share.is_zero() + || !if_remove { *share_info_old = Some(share_info); }; @@ -450,4 +488,65 @@ impl Pallet { }, ) } + + pub fn refresh_inner(exchanger: &T::AccountId, pid: PoolId) -> DispatchResult { + let gauge_pid = pid + GAUGE_BASE_ID; + if let Some(share_info) = SharesAndWithdrawnRewards::::get(&pid, &exchanger) { + if let Some(mut gauge_pool_info) = PoolInfos::::get(gauge_pid) { + let gauge_new_value = T::BbBNC::balance_of(&exchanger, None)? + .checked_mul(&share_info.share) + .ok_or(ArithmeticError::Overflow)?; + if let Some(share_info) = SharesAndWithdrawnRewards::::get(gauge_pid, &exchanger) + { + Self::update_gauge_share( + &exchanger, + gauge_pid, + gauge_new_value, + share_info.share, + &mut gauge_pool_info, + )?; + } else { + Self::add_share(&exchanger, gauge_pid, &mut gauge_pool_info, gauge_new_value); + } + } + } else { + // If `SharesAndWithdrawnRewards` returns `None`, remove the `pid` from `UserFarmingPool`. + UserFarmingPool::::mutate(&exchanger, |pids| { + pids.retain(|&x| x != pid); + }); + SharesAndWithdrawnRewards::::remove(gauge_pid, &exchanger); + } + + Ok(()) + } + + pub fn update_gauge_share( + exchanger: &T::AccountId, + gauge_pid: PoolId, + gauge_new_value: BalanceOf, + share: BalanceOf, + gauge_pool_info: &mut PoolInfo< + BalanceOf, + CurrencyIdOf, + AccountIdOf, + BlockNumberFor, + >, + ) -> DispatchResult { + match gauge_new_value.cmp(&share) { + Ordering::Less => { + let gauge_remove_value = share.saturating_sub(gauge_new_value); + Self::remove_share( + exchanger, + gauge_pid, + Some(gauge_remove_value), + gauge_pool_info.withdraw_limit_time, + )?; + } + Ordering::Equal | Ordering::Greater => { + let gauge_add_value = gauge_new_value.saturating_sub(share); + Self::add_share(exchanger, gauge_pid, gauge_pool_info, gauge_add_value); + } + }; + Ok(()) + } } diff --git a/pallets/farming/src/tests.rs b/pallets/farming/src/tests.rs index 1218c3ba8d..1326f23879 100644 --- a/pallets/farming/src/tests.rs +++ b/pallets/farming/src/tests.rs @@ -26,256 +26,305 @@ use frame_support::{assert_err, assert_ok}; #[test] fn claim() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_no_gauge(); - // assert_eq!(SharesAndWithdrawnRewards::::get(pid, &ALICE), ShareInfo::default()); - assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); - assert_err!( - Farming::claim(RuntimeOrigin::signed(ALICE), pid), - Error::::InvalidPoolState - ); - System::set_block_number(System::block_number() + 100); - Farming::on_initialize(0); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); - Farming::on_initialize(0); - assert_ok!(Farming::withdraw_claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - Farming::on_initialize(0); - assert_ok!(Farming::close_pool(RuntimeOrigin::signed(ALICE), pid)); - assert_ok!(Farming::force_retire_pool(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 5000); // 3000 + 1000 + 1000 - Farming::on_initialize(0); - assert_err!( - Farming::force_retire_pool(RuntimeOrigin::signed(ALICE), pid), - Error::::InvalidPoolState - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, _tokens) = init_no_gauge(); + // assert_eq!(SharesAndWithdrawnRewards::::get(pid, &ALICE), ShareInfo::default()); + assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); + assert_err!( + Farming::claim(RuntimeOrigin::signed(ALICE), pid), + Error::::InvalidPoolState + ); + System::set_block_number(System::block_number() + 100); + Farming::on_initialize(0); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); + Farming::on_initialize(0); + assert_ok!(Farming::withdraw_claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + Farming::on_initialize(0); + assert_ok!(Farming::close_pool(RuntimeOrigin::signed(ALICE), pid)); + assert_ok!(Farming::force_retire_pool( + RuntimeOrigin::signed(ALICE), + pid + )); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 5000); // 3000 + 1000 + 1000 + Farming::on_initialize(0); + assert_err!( + Farming::force_retire_pool(RuntimeOrigin::signed(ALICE), pid), + Error::::InvalidPoolState + ); + }); } #[test] fn deposit() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, tokens) = init_gauge(); - System::set_block_number(System::block_number() + 1); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); - System::set_block_number(System::block_number() + 1); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 0)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 1000); - let keeper: AccountId = ::Keeper::get().into_sub_account_truncating(pid); - let reward_issuer: AccountId = - ::RewardIssuer::get().into_sub_account_truncating(pid); - let mut gauge_basic_rewards = BTreeMap::, BalanceOf>::new(); - gauge_basic_rewards.entry(KSM).or_insert(990_000); - let gauge_pool_info2 = GaugePoolInfo { - pid, - token: Default::default(), - keeper, - reward_issuer, - rewards: BTreeMap::< - CurrencyIdOf, - (BalanceOf, BalanceOf, BalanceOf), - >::new(), - gauge_basic_rewards, - max_block: 7 * 86400 / 12, - gauge_amount: 0, - total_time_factor: 0, - gauge_last_block: 0, - gauge_state: GaugeState::Bonded, - }; - assert_eq!(GaugePoolInfos::::get(0), Some(gauge_pool_info2)); - Farming::on_initialize(1); - Farming::on_initialize(1); - System::set_block_number(System::block_number() + 1000); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, tokens) = init_gauge(); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 0)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 1000); + let keeper: AccountId = + ::Keeper::get().into_sub_account_truncating(pid); + let mut gauge_basic_rewards = + BTreeMap::, BalanceOf>::new(); + gauge_basic_rewards.entry(KSM).or_insert(990_000); + let gauge_reward_issuer: AccountId = ::RewardIssuer::get() + .into_sub_account_truncating(pid + GAUGE_BASE_ID); + let mut basic_rewards_map = + BTreeMap::, BalanceOf>::new(); + basic_rewards_map.entry(KSM).or_insert(990); + let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); + let gauge_pool_info2 = PoolInfo { + tokens_proportion: tokens_proportion_map, + total_shares: Default::default(), + basic_token: (KSM, Perbill::from_percent(100)), + basic_rewards: basic_rewards_map.clone(), + rewards: BTreeMap::new(), + state: PoolState::Ongoing, + keeper: keeper.clone(), + reward_issuer: gauge_reward_issuer.clone(), + gauge: None, + block_startup: None, + min_deposit_to_start: Default::default(), + after_block_to_start: Default::default(), + withdraw_limit_time: Default::default(), + claim_limit_time: Default::default(), + withdraw_limit_count: Default::default(), + }; + assert_eq!( + PoolInfos::::get(pid + GAUGE_BASE_ID), + Some(gauge_pool_info2) + ); + Farming::on_initialize(1); + Farming::on_initialize(1); + System::set_block_number(System::block_number() + 1000); + }) } #[test] fn withdraw() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, tokens) = init_no_gauge(); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); - Farming::on_initialize(0); - Farming::on_initialize(0); - System::set_block_number(System::block_number() + 1); - assert_ok!(Farming::withdraw(RuntimeOrigin::signed(ALICE), pid, Some(800))); - assert_err!( - Farming::withdraw(RuntimeOrigin::signed(ALICE), pid, Some(100)), - Error::::WithdrawLimitCountExceeded - ); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - System::set_block_number(System::block_number() + 100); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(BOB), pid, tokens)); - Farming::on_initialize(0); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3966); - assert_ok!(Farming::withdraw(RuntimeOrigin::signed(ALICE), pid, Some(200))); - System::set_block_number(System::block_number() + 100); - assert_ok!(Farming::withdraw_claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 4166); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(SharesAndWithdrawnRewards::::get(pid, &ALICE), None); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 4166); - let ed = ::MultiCurrency::minimum_balance(KSM); - assert_eq!(Tokens::free_balance(KSM, &TREASURY_ACCOUNT), ed); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, tokens) = init_no_gauge(); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); + Farming::on_initialize(0); + Farming::on_initialize(0); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::withdraw( + RuntimeOrigin::signed(ALICE), + pid, + Some(800) + )); + assert_err!( + Farming::withdraw(RuntimeOrigin::signed(ALICE), pid, Some(100)), + Error::::WithdrawLimitCountExceeded + ); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + System::set_block_number(System::block_number() + 100); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(BOB), pid, tokens)); + Farming::on_initialize(0); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3966); + assert_ok!(Farming::withdraw( + RuntimeOrigin::signed(ALICE), + pid, + Some(200) + )); + System::set_block_number(System::block_number() + 100); + assert_ok!(Farming::withdraw_claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 4166); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(SharesAndWithdrawnRewards::::get(pid, &ALICE), None); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 4166); + let ed = ::MultiCurrency::minimum_balance(KSM); + assert_eq!(Tokens::free_balance(KSM, &TREASURY_ACCOUNT), ed); + }) } #[test] fn gauge() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, tokens) = init_gauge(); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); - if let Some(gauge_pool_infos) = GaugePoolInfos::::get(0) { - assert_eq!( - gauge_pool_infos.rewards, - BTreeMap::< - CurrencyIdOf, - (BalanceOf, BalanceOf, BalanceOf), - >::new() - ) - }; - Farming::on_initialize(0); - System::set_block_number(System::block_number() + 1); - Farming::on_initialize(0); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3018); - Farming::on_initialize(0); - System::set_block_number(System::block_number() + 10); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2018); - System::set_block_number(System::block_number() + 20); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3586); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(BOB), pid, 10)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 9699990); - System::set_block_number(System::block_number() + 200); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 7366); - assert_eq!(Tokens::free_balance(KSM, &BOB), 9699990); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(BOB), pid, 0)); - System::set_block_number(System::block_number() + 200); - assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); - assert_ok!(Farming::force_gauge_claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 9699990); - }) -} - -#[test] -fn gauge_withdraw() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_gauge(); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); - if let Some(gauge_pool_infos) = GaugePoolInfos::::get(0) { - assert_eq!(gauge_pool_infos.gauge_amount, 0) - }; - Farming::on_initialize(1); - System::set_block_number(System::block_number() + 1); - Farming::on_initialize(1); - assert_ok!(Farming::gauge_withdraw(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2018); - System::set_block_number(System::block_number() + 1000); - assert_ok!(Farming::gauge_withdraw(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 21017); - if let Some(gauge_pool_infos) = GaugePoolInfos::::get(0) { - assert_eq!(gauge_pool_infos.gauge_amount, 0) - }; - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, tokens) = init_gauge(); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); + if let Some(gauge_pool_infos) = GaugePoolInfos::::get(0) { + assert_eq!( + gauge_pool_infos.rewards, + BTreeMap::< + CurrencyIdOf, + (BalanceOf, BalanceOf, BalanceOf), + >::new() + ) + }; + Farming::on_initialize(0); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2990); + Farming::on_initialize(0); + System::set_block_number(System::block_number() + 10); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2980); // 1990 + 990 + System::set_block_number(System::block_number() + 20); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3980); // 2980 + 1000 + assert_ok!(Farming::deposit(RuntimeOrigin::signed(BOB), pid, 10)); + assert_eq!(Tokens::free_balance(KSM, &BOB), 9699990); + Farming::on_initialize(0); + System::set_block_number(System::block_number() + 200); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + // BOB doesn't have bbBNC + assert_eq!(Tokens::free_balance(KSM, &ALICE), 5965); // 2980 + 995 + 990 + assert_eq!(Tokens::free_balance(KSM, &BOB), 9699990); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(BOB), pid, 0)); + System::set_block_number(System::block_number() + 200); + assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); + assert_ok!(Farming::force_gauge_claim( + RuntimeOrigin::signed(ALICE), + pid + )); + assert_eq!(Tokens::free_balance(KSM, &BOB), 9699990); + }) } #[test] fn retire() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, tokens) = init_no_gauge(); - Farming::on_initialize(0); - System::set_block_number(System::block_number() + 1); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); - System::set_block_number(System::block_number() + 1); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 0)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 1000); - assert_ok!(Farming::close_pool(RuntimeOrigin::signed(ALICE), pid)); - assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); - System::set_block_number(System::block_number() + 1000); - assert_ok!(Farming::force_retire_pool(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - assert_eq!(SharesAndWithdrawnRewards::::get(pid, &ALICE), None); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, tokens) = init_no_gauge(); + Farming::on_initialize(0); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 0)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 1000); + assert_ok!(Farming::close_pool(RuntimeOrigin::signed(ALICE), pid)); + assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); + System::set_block_number(System::block_number() + 1000); + assert_ok!(Farming::force_retire_pool( + RuntimeOrigin::signed(ALICE), + pid + )); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + assert_eq!(SharesAndWithdrawnRewards::::get(pid, &ALICE), None); + }) } #[test] fn reset() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_gauge(); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); - Farming::on_initialize(0); - System::set_block_number(System::block_number() + 1); - Farming::on_initialize(0); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3018); - assert_ok!(Farming::close_pool(RuntimeOrigin::signed(ALICE), pid)); - assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); - assert_ok!(Farming::force_retire_pool(RuntimeOrigin::signed(ALICE), pid)); - let basic_rewards = vec![(KSM, 1000)]; - assert_ok!(Farming::reset_pool( - RuntimeOrigin::signed(ALICE), - pid, - None, - None, - None, - None, - None, - None, - Some((1000, basic_rewards)), - )); - let keeper: AccountId = ::Keeper::get().into_sub_account_truncating(pid); - let reward_issuer: AccountId = - ::RewardIssuer::get().into_sub_account_truncating(pid); - let mut basic_rewards_map = BTreeMap::, BalanceOf>::new(); - basic_rewards_map.entry(KSM).or_insert(1000); - let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); - tokens_proportion_map.entry(KSM).or_insert(Perbill::from_percent(100)); - let pool_infos = PoolInfo { - tokens_proportion: tokens_proportion_map, - total_shares: Default::default(), - basic_token: (KSM, Perbill::from_percent(100)), - basic_rewards: basic_rewards_map.clone(), - rewards: BTreeMap::new(), - state: PoolState::UnCharged, - keeper: keeper.clone(), - reward_issuer: reward_issuer.clone(), - gauge: Some(0), - block_startup: None, - min_deposit_to_start: Default::default(), - after_block_to_start: Default::default(), - withdraw_limit_time: Default::default(), - claim_limit_time: Default::default(), - withdraw_limit_count: 5, - }; - assert_eq!(PoolInfos::::get(0), Some(pool_infos)); - assert_eq!(GaugePoolInfos::::get(1), None); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 4018); - let charge_rewards = vec![(KSM, 300000)]; - assert_ok!(Farming::charge(RuntimeOrigin::signed(BOB), pid, charge_rewards, false)); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 1)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 4017); - Farming::on_initialize(1); - System::set_block_number(System::block_number() + 20); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 4396); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, _tokens) = init_gauge(); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2000); + Farming::on_initialize(0); + System::set_block_number(System::block_number() + 1); + assert_eq!(BbBNC::balance_of(&ALICE, None), Ok(99716188888)); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(BbBNC::balance_of(&ALICE, None), Ok(99716188888)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 2990); + assert_ok!(Farming::close_pool(RuntimeOrigin::signed(ALICE), pid)); + assert_ok!(Farming::set_retire_limit(RuntimeOrigin::signed(ALICE), 10)); + assert_ok!(Farming::force_retire_pool( + RuntimeOrigin::signed(ALICE), + pid + )); + let basic_rewards = vec![(KSM, 1000)]; + assert_ok!(Farming::reset_pool( + RuntimeOrigin::signed(ALICE), + pid, + None, + None, + None, + None, + None, + None, + Some(basic_rewards), + )); + let keeper: AccountId = + ::Keeper::get().into_sub_account_truncating(pid); + let reward_issuer: AccountId = + ::RewardIssuer::get().into_sub_account_truncating(pid); + let mut basic_rewards_map = + BTreeMap::, BalanceOf>::new(); + basic_rewards_map.entry(KSM).or_insert(1000); + let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); + let pool_infos = PoolInfo { + tokens_proportion: tokens_proportion_map, + total_shares: Default::default(), + basic_token: (KSM, Perbill::from_percent(100)), + basic_rewards: basic_rewards_map.clone(), + rewards: BTreeMap::new(), + state: PoolState::UnCharged, + keeper: keeper.clone(), + reward_issuer: reward_issuer.clone(), + gauge: Some(GAUGE_BASE_ID + pid), + block_startup: None, + min_deposit_to_start: Default::default(), + after_block_to_start: Default::default(), + withdraw_limit_time: Default::default(), + claim_limit_time: Default::default(), + withdraw_limit_count: 5, + }; + assert_eq!(PoolInfos::::get(0), Some(pool_infos)); + assert_eq!(GaugePoolInfos::::get(1), None); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3990); + let charge_rewards = vec![(KSM, 300000)]; + assert_ok!(Farming::charge( + RuntimeOrigin::signed(BOB), + pid, + charge_rewards, + )); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 1)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3989); + Farming::on_initialize(1); + Farming::on_initialize(2); + System::set_block_number(System::block_number() + 20); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 4989); + }) } fn init_gauge() -> (PoolId, BalanceOf) { let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); - tokens_proportion_map.entry(KSM).or_insert(Perbill::from_percent(100)); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); let tokens_proportion = vec![(KSM, Perbill::from_percent(100))]; let tokens = 1000; let basic_rewards = vec![(KSM, 1000)]; - let gauge_basic_rewards = vec![(KSM, 990_000)]; + let gauge_basic_rewards = vec![(KSM, 990)]; + + let pid = 0; + + let gauge_reward_issuer: AccountId = + ::RewardIssuer::get().into_sub_account_truncating(pid + GAUGE_BASE_ID); + assert_ok!(Tokens::deposit(KSM, &gauge_reward_issuer, 990_000)); + assert_eq!(Tokens::free_balance(KSM, &gauge_reward_issuer), 990_000); let pid = 0; @@ -288,7 +337,7 @@ fn init_gauge() -> (PoolId, BalanceOf) { RuntimeOrigin::signed(ALICE), tokens_proportion.clone(), basic_rewards.clone(), - Some((7 * 86400 / 12, gauge_basic_rewards.clone())), + Some(gauge_basic_rewards.clone()), 0, 0, 0, @@ -297,20 +346,30 @@ fn init_gauge() -> (PoolId, BalanceOf) { )); let charge_rewards = vec![(KSM, 300000)]; - assert_ok!(Farming::charge(RuntimeOrigin::signed(BOB), pid, charge_rewards, false)); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); - assert_ok!(BbBNC::set_config(RuntimeOrigin::signed(ALICE), Some(0), Some(7 * 86400 / 12))); + assert_ok!(Farming::charge( + RuntimeOrigin::signed(BOB), + pid, + charge_rewards, + )); + assert_ok!(BbBNC::set_config( + RuntimeOrigin::signed(ALICE), + Some(0), + Some(7 * 86400 / 12) + )); assert_ok!(BbBNC::create_lock_inner( &ALICE, 100_000_000_000, System::block_number() + (4 * 365 * 86400 - 7 * 86400) / 12 )); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); (pid, tokens) } fn init_no_gauge() -> (PoolId, BalanceOf) { let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); - tokens_proportion_map.entry(KSM).or_insert(Perbill::from_percent(100)); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); let tokens_proportion = vec![(KSM, Perbill::from_percent(100))]; let tokens = 1000; let basic_rewards = vec![(KSM, 1000)]; @@ -329,270 +388,436 @@ fn init_no_gauge() -> (PoolId, BalanceOf) { let pid = 0; let charge_rewards = vec![(KSM, 100000)]; - assert_ok!(Farming::charge(RuntimeOrigin::signed(BOB), pid, charge_rewards, false)); + assert_ok!(Farming::charge( + RuntimeOrigin::signed(BOB), + pid, + charge_rewards, + )); assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); (pid, tokens) } #[test] fn create_farming_pool() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); - tokens_proportion_map.entry(KSM).or_insert(Perbill::from_percent(100)); - let tokens_proportion = vec![(KSM, Perbill::from_percent(100))]; - let tokens_proportion2 = vec![]; - - let tokens = 1000; - let basic_rewards = vec![(KSM, 1000)]; - let gauge_basic_rewards = vec![(KSM, 900)]; - - assert_err!( - Farming::create_farming_pool( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); + let tokens_proportion = vec![(KSM, Perbill::from_percent(100))]; + let tokens_proportion2 = vec![]; + + let tokens = 1000; + let basic_rewards = vec![(KSM, 1000)]; + let gauge_basic_rewards = vec![(KSM, 900)]; + + assert_err!( + Farming::create_farming_pool( + RuntimeOrigin::signed(ALICE), + tokens_proportion2, + basic_rewards.clone(), + Some(gauge_basic_rewards.clone()), + 2, + 1, + 7, + 6, + 5 + ), + Error::::NotNullable + ); + assert_ok!(Farming::create_farming_pool( + RuntimeOrigin::signed(ALICE), + tokens_proportion.clone(), + basic_rewards.clone(), + Some(gauge_basic_rewards.clone()), + 2, + 1, + 7, + 6, + 5 + )); + assert_ok!(Farming::create_farming_pool( RuntimeOrigin::signed(ALICE), - tokens_proportion2, + tokens_proportion.clone(), basic_rewards.clone(), - Some((1000, gauge_basic_rewards.clone())), + Some(gauge_basic_rewards), 2, 1, 7, 6, 5 - ), - Error::::NotNullable - ); - assert_ok!(Farming::create_farming_pool( - RuntimeOrigin::signed(ALICE), - tokens_proportion.clone(), - basic_rewards.clone(), - Some((1000, gauge_basic_rewards.clone())), - 2, - 1, - 7, - 6, - 5 - )); - assert_ok!(Farming::create_farming_pool( - RuntimeOrigin::signed(ALICE), - tokens_proportion.clone(), - basic_rewards.clone(), - Some((1000, gauge_basic_rewards)), - 2, - 1, - 7, - 6, - 5 - )); - if let Some(pool_infos) = PoolInfos::::get(0) { - assert_eq!(pool_infos.state, PoolState::UnCharged) - }; - assert_ok!(Farming::kill_pool(RuntimeOrigin::signed(ALICE), 0)); - - let pid = 1; - let charge_rewards = vec![(KSM, 300000)]; - assert_ok!(Farming::charge(RuntimeOrigin::signed(BOB), pid, charge_rewards, false)); - if let Some(pool_infos) = PoolInfos::::get(0) { - assert_eq!(pool_infos.total_shares, 0); - assert_eq!(pool_infos.min_deposit_to_start, 2); - assert_eq!(pool_infos.state, PoolState::Charged) - }; - assert_err!( - Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens), - Error::::CanNotDeposit - ); - System::set_block_number(System::block_number() + 3); - assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); - Farming::on_initialize(System::block_number() + 3); - Farming::on_initialize(0); - if let Some(pool_infos) = PoolInfos::::get(0) { - assert_eq!(pool_infos.total_shares, 1000); - assert_eq!(pool_infos.min_deposit_to_start, 2); - assert_eq!(pool_infos.state, PoolState::Ongoing) - }; - assert_err!( - Farming::claim(RuntimeOrigin::signed(ALICE), pid), - Error::::CanNotClaim - ); - System::set_block_number(System::block_number() + 6); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - System::set_block_number(System::block_number() + 100); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - assert_ok!(Farming::withdraw(RuntimeOrigin::signed(ALICE), pid, Some(800))); - System::set_block_number(System::block_number() + 6); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_err!( - Farming::claim(RuntimeOrigin::signed(ALICE), pid), - Error::::CanNotClaim - ); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); - System::set_block_number(System::block_number() + 6); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 3800); - }) + )); + if let Some(pool_infos) = PoolInfos::::get(0) { + assert_eq!(pool_infos.state, PoolState::UnCharged) + }; + assert_ok!(Farming::kill_pool(RuntimeOrigin::signed(ALICE), 0)); + + let pid = 1; + let charge_rewards = vec![(KSM, 300000)]; + assert_ok!(Farming::charge( + RuntimeOrigin::signed(BOB), + pid, + charge_rewards, + )); + if let Some(pool_infos) = PoolInfos::::get(0) { + assert_eq!(pool_infos.total_shares, 0); + assert_eq!(pool_infos.min_deposit_to_start, 2); + assert_eq!(pool_infos.state, PoolState::Charged) + }; + assert_err!( + Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens), + Error::::CanNotDeposit + ); + System::set_block_number(System::block_number() + 3); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); + Farming::on_initialize(System::block_number() + 3); + Farming::on_initialize(0); + if let Some(pool_infos) = PoolInfos::::get(0) { + assert_eq!(pool_infos.total_shares, 1000); + assert_eq!(pool_infos.min_deposit_to_start, 2); + assert_eq!(pool_infos.state, PoolState::Ongoing) + }; + assert_err!( + Farming::claim(RuntimeOrigin::signed(ALICE), pid), + Error::::CanNotClaim + ); + System::set_block_number(System::block_number() + 6); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + System::set_block_number(System::block_number() + 100); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + assert_ok!(Farming::withdraw( + RuntimeOrigin::signed(ALICE), + pid, + Some(800) + )); + System::set_block_number(System::block_number() + 6); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_err!( + Farming::claim(RuntimeOrigin::signed(ALICE), pid), + Error::::CanNotClaim + ); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3000); + System::set_block_number(System::block_number() + 6); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 3800); + }) } #[test] fn add_boost_pool_whitelist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let mut whitelist = vec![0]; - assert_ok!(Farming::add_boost_pool_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_eq!(BoostWhitelist::::iter().count(), 1); - whitelist.push(1); - assert_ok!(Farming::add_boost_pool_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_eq!(BoostWhitelist::::iter().count(), 2); - assert_err!( - Farming::add_boost_pool_whitelist(RuntimeOrigin::signed(BOB), whitelist.clone()), - DispatchError::BadOrigin - ); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let mut whitelist = vec![0]; + assert_ok!(Farming::add_boost_pool_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_eq!(BoostWhitelist::::iter().count(), 1); + whitelist.push(1); + assert_ok!(Farming::add_boost_pool_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_eq!(BoostWhitelist::::iter().count(), 2); + assert_err!( + Farming::add_boost_pool_whitelist(RuntimeOrigin::signed(BOB), whitelist.clone()), + DispatchError::BadOrigin + ); + }) } #[test] fn set_next_round_whitelist() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let mut whitelist = vec![0]; - assert_ok!(Farming::set_next_round_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_eq!(BoostNextRoundWhitelist::::iter().count(), 1); - whitelist.push(1); - assert_ok!(Farming::set_next_round_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_eq!(BoostNextRoundWhitelist::::iter().count(), 2); - assert_err!( - Farming::set_next_round_whitelist(RuntimeOrigin::signed(BOB), whitelist.clone()), - DispatchError::BadOrigin - ); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let mut whitelist = vec![0]; + assert_ok!(Farming::set_next_round_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_eq!(BoostNextRoundWhitelist::::iter().count(), 1); + whitelist.push(1); + assert_ok!(Farming::set_next_round_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_eq!(BoostNextRoundWhitelist::::iter().count(), 2); + assert_err!( + Farming::set_next_round_whitelist(RuntimeOrigin::signed(BOB), whitelist.clone()), + DispatchError::BadOrigin + ); + }) } #[test] fn start_boost_round() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let vote_list = vec![(0u32, Percent::from_percent(100))]; - let whitelist = vec![0]; - assert_ok!(Farming::set_next_round_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_ok!(Farming::add_boost_pool_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_ok!(Farming::vote(RuntimeOrigin::signed(ALICE), vote_list.clone())); - assert_ok!(Farming::vote(RuntimeOrigin::signed(BOB), vote_list.clone())); - assert_ok!(Farming::vote(RuntimeOrigin::signed(CHARLIE), vote_list.clone())); - assert_ok!(Farming::start_boost_round(RuntimeOrigin::signed(ALICE), 100)); - assert_eq!(BoostVotingPools::::iter().count(), 0); - assert_eq!(UserBoostInfos::::iter().count(), 3); - assert_eq!(BoostWhitelist::::iter().count(), 1); - assert_eq!(BoostNextRoundWhitelist::::iter().count(), 0); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let vote_list = vec![(0u32, Percent::from_percent(100))]; + let whitelist = vec![0]; + assert_ok!(Farming::set_next_round_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_ok!(Farming::add_boost_pool_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_ok!(Farming::vote( + RuntimeOrigin::signed(ALICE), + vote_list.clone() + )); + assert_ok!(Farming::vote(RuntimeOrigin::signed(BOB), vote_list.clone())); + assert_ok!(Farming::vote( + RuntimeOrigin::signed(CHARLIE), + vote_list.clone() + )); + assert_ok!(Farming::start_boost_round( + RuntimeOrigin::signed(ALICE), + 100 + )); + assert_eq!(BoostVotingPools::::iter().count(), 0); + assert_eq!(UserBoostInfos::::iter().count(), 3); + assert_eq!(BoostWhitelist::::iter().count(), 1); + assert_eq!(BoostNextRoundWhitelist::::iter().count(), 0); + }) } #[test] fn vote() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - BbBNC::set_incentive(0, Some(7 * 86400 / 12), Some(ALICE.clone())); - - let (pid, _tokens) = init_gauge(); - let vote_list = vec![(pid, Percent::from_percent(100))]; - let whitelist = vec![pid]; - assert_ok!(Farming::set_next_round_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_ok!(Farming::add_boost_pool_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - - let charge_rewards = vec![(KSM, 300_000)]; - assert_ok!(Farming::charge_boost(RuntimeOrigin::signed(CHARLIE), charge_rewards)); - assert_eq!(BoostVotingPools::::iter().count(), 1); - assert_ok!(Farming::start_boost_round(RuntimeOrigin::signed(ALICE), 100)); - let boost_pool_info = - BoostPoolInfo { total_votes: 0, end_round: 100, start_round: 0, round_length: 100 }; - assert_eq!(BoostPoolInfos::::get(), boost_pool_info); - - assert_ok!(Farming::vote(RuntimeOrigin::signed(ALICE), vote_list.clone())); - assert_ok!(Farming::vote(RuntimeOrigin::signed(BOB), vote_list.clone())); - assert_ok!(Farming::vote(RuntimeOrigin::signed(CHARLIE), vote_list.clone())); - assert_eq!(BoostVotingPools::::iter().count(), 1); - assert_eq!(UserBoostInfos::::iter().count(), 3); - - assert_eq!(UserBoostInfos::::get(ALICE).unwrap().vote_amount, 99716198400); - let boost_pool_info = BoostPoolInfo { - total_votes: 99716198400, - end_round: 100, - start_round: 0, - round_length: 100, - }; - assert_eq!(BoostPoolInfos::::get(), boost_pool_info); - assert_ok!(BbBNC::create_lock_inner( - &CHARLIE, - 100_000_000_000, - (365 * 86400 - 7 * 86400) / 12 - )); - assert_eq!(BoostPoolInfos::::get().total_votes, 99716198400); - // vote again to refresh the vote amount of CHARLIE - assert_ok!(Farming::vote(RuntimeOrigin::signed(CHARLIE), vote_list.clone())); - assert_eq!(BoostPoolInfos::::get().total_votes, 124645248000); - - assert_eq!(BoostBasicRewards::::get(pid, KSM), Some(3000)); - Farming::on_initialize(0); - Farming::on_initialize(1); - Farming::on_initialize(2); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 10000); - System::set_block_number(System::block_number() + 100); - assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); - assert_eq!(Tokens::free_balance(KSM, &ALICE), 11519); - - assert_ok!(Farming::end_boost_round(RuntimeOrigin::signed(ALICE))); - assert_eq!(BoostPoolInfos::::get().end_round, 0); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + BbBNC::set_incentive(0, Some(7 * 86400 / 12), Some(ALICE.clone())); + + let (pid, _tokens) = init_gauge(); + let vote_list = vec![(pid, Percent::from_percent(100))]; + let whitelist = vec![pid]; + assert_ok!(Farming::set_next_round_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_ok!(Farming::add_boost_pool_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + + let charge_rewards = vec![(KSM, 300_000)]; + assert_ok!(Farming::charge_boost( + RuntimeOrigin::signed(CHARLIE), + charge_rewards + )); + assert_eq!(BoostVotingPools::::iter().count(), 1); + assert_ok!(Farming::start_boost_round( + RuntimeOrigin::signed(ALICE), + 100 + )); + let boost_pool_info = BoostPoolInfo { + total_votes: 0, + end_round: 100, + start_round: 0, + round_length: 100, + }; + assert_eq!(BoostPoolInfos::::get(), boost_pool_info); + + assert_ok!(Farming::vote( + RuntimeOrigin::signed(ALICE), + vote_list.clone() + )); + assert_ok!(Farming::vote(RuntimeOrigin::signed(BOB), vote_list.clone())); + assert_ok!(Farming::vote( + RuntimeOrigin::signed(CHARLIE), + vote_list.clone() + )); + assert_eq!(BoostVotingPools::::iter().count(), 1); + assert_eq!(UserBoostInfos::::iter().count(), 3); + + assert_eq!( + UserBoostInfos::::get(ALICE).unwrap().vote_amount, + 99716198400 + ); + let boost_pool_info = BoostPoolInfo { + total_votes: 99716198400, + end_round: 100, + start_round: 0, + round_length: 100, + }; + assert_eq!(BoostPoolInfos::::get(), boost_pool_info); + assert_ok!(BbBNC::create_lock_inner( + &CHARLIE, + 100_000_000_000, + (365 * 86400 - 7 * 86400) / 12 + )); + assert_eq!(BoostPoolInfos::::get().total_votes, 99716198400); + // vote again to refresh the vote amount of CHARLIE + assert_ok!(Farming::vote( + RuntimeOrigin::signed(CHARLIE), + vote_list.clone() + )); + assert_eq!(BoostPoolInfos::::get().total_votes, 124645248000); + + assert_eq!(BoostBasicRewards::::get(pid, KSM), Some(3000)); + Farming::on_initialize(0); + Farming::on_initialize(1); + Farming::on_initialize(2); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 12970); + System::set_block_number(System::block_number() + 100); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 12970); + + assert_ok!(Farming::end_boost_round(RuntimeOrigin::signed(ALICE))); + assert_eq!(BoostPoolInfos::::get().end_round, 0); + }) } #[test] fn charge_boost() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let vote_list = vec![(0u32, Percent::from_percent(100))]; - let whitelist = vec![0]; - assert_ok!(Farming::set_next_round_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_ok!(Farming::add_boost_pool_whitelist( - RuntimeOrigin::signed(ALICE), - whitelist.clone() - )); - assert_ok!(Farming::vote(RuntimeOrigin::signed(ALICE), vote_list.clone())); - assert_ok!(Farming::vote(RuntimeOrigin::signed(BOB), vote_list.clone())); - assert_ok!(Farming::vote(RuntimeOrigin::signed(CHARLIE), vote_list.clone())); - assert_ok!(Farming::start_boost_round(RuntimeOrigin::signed(ALICE), 100)); - assert_eq!(BoostVotingPools::::iter().count(), 0); - assert_eq!(UserBoostInfos::::iter().count(), 3); - assert_eq!(BoostWhitelist::::iter().count(), 1); - assert_eq!(BoostNextRoundWhitelist::::iter().count(), 0); - let charge_rewards = vec![(KSM, 300000)]; - assert_ok!(Farming::charge_boost(RuntimeOrigin::signed(BOB), charge_rewards)); - let boost_pool_info = - BoostPoolInfo { total_votes: 0, end_round: 100, start_round: 0, round_length: 100 }; - assert_eq!(BoostPoolInfos::::get(), boost_pool_info); - assert_eq!(BoostVotingPools::::iter().count(), 0); - assert_eq!(UserBoostInfos::::iter().count(), 3); - assert_eq!(BoostWhitelist::::iter().count(), 1); - assert_eq!(BoostNextRoundWhitelist::::iter().count(), 0); - }) + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let vote_list = vec![(0u32, Percent::from_percent(100))]; + let whitelist = vec![0]; + assert_ok!(Farming::set_next_round_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_ok!(Farming::add_boost_pool_whitelist( + RuntimeOrigin::signed(ALICE), + whitelist.clone() + )); + assert_ok!(Farming::vote( + RuntimeOrigin::signed(ALICE), + vote_list.clone() + )); + assert_ok!(Farming::vote(RuntimeOrigin::signed(BOB), vote_list.clone())); + assert_ok!(Farming::vote( + RuntimeOrigin::signed(CHARLIE), + vote_list.clone() + )); + assert_ok!(Farming::start_boost_round( + RuntimeOrigin::signed(ALICE), + 100 + )); + assert_eq!(BoostVotingPools::::iter().count(), 0); + assert_eq!(UserBoostInfos::::iter().count(), 3); + assert_eq!(BoostWhitelist::::iter().count(), 1); + assert_eq!(BoostNextRoundWhitelist::::iter().count(), 0); + let charge_rewards = vec![(KSM, 300000)]; + assert_ok!(Farming::charge_boost( + RuntimeOrigin::signed(BOB), + charge_rewards + )); + let boost_pool_info = BoostPoolInfo { + total_votes: 0, + end_round: 100, + start_round: 0, + round_length: 100, + }; + assert_eq!(BoostPoolInfos::::get(), boost_pool_info); + assert_eq!(BoostVotingPools::::iter().count(), 0); + assert_eq!(UserBoostInfos::::iter().count(), 3); + assert_eq!(BoostWhitelist::::iter().count(), 1); + assert_eq!(BoostNextRoundWhitelist::::iter().count(), 0); + }) +} + +#[test] +fn refresh_should_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, tokens) = init_gauge(); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); + System::set_block_number(System::block_number() + 1); + assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, 0)); + assert_eq!(Tokens::free_balance(KSM, &ALICE), 1000); + let keeper: AccountId = + ::Keeper::get().into_sub_account_truncating(pid); + let mut gauge_basic_rewards = + BTreeMap::, BalanceOf>::new(); + gauge_basic_rewards.entry(KSM).or_insert(990_000); + let gauge_reward_issuer: AccountId = ::RewardIssuer::get() + .into_sub_account_truncating(pid + GAUGE_BASE_ID); + let mut basic_rewards_map = + BTreeMap::, BalanceOf>::new(); + basic_rewards_map.entry(KSM).or_insert(990); + let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); + let gauge_pool_info2 = PoolInfo { + tokens_proportion: tokens_proportion_map, + total_shares: Default::default(), + basic_token: (KSM, Perbill::from_percent(100)), + basic_rewards: basic_rewards_map.clone(), + rewards: BTreeMap::new(), + state: PoolState::Ongoing, + keeper: keeper.clone(), + reward_issuer: gauge_reward_issuer.clone(), + gauge: None, + block_startup: None, + min_deposit_to_start: Default::default(), + after_block_to_start: Default::default(), + withdraw_limit_time: Default::default(), + claim_limit_time: Default::default(), + withdraw_limit_count: Default::default(), + }; + assert_eq!( + PoolInfos::::get(pid + GAUGE_BASE_ID), + Some(gauge_pool_info2) + ); + Farming::on_initialize(1); + Farming::on_initialize(1); + System::set_block_number(System::block_number() + 1000); + + assert_ok!(BbBNC::create_lock_inner( + &ALICE, + 100_000_000_000, + (365 * 86400 - 7 * 86400) / 12 + )); + + assert_eq!( + SharesAndWithdrawnRewards::::get(pid + GAUGE_BASE_ID, &CHARLIE), + None + ); + assert_ok!(Farming::refresh_inner(&CHARLIE, pid)); + assert_eq!( + SharesAndWithdrawnRewards::::get(pid + GAUGE_BASE_ID, &CHARLIE), + None + ); + assert_eq!( + SharesAndWithdrawnRewards::::get(pid + GAUGE_BASE_ID, &ALICE) + .unwrap() + .share, + 249252371904000 + ); + System::set_block_number(System::block_number() + 100); + assert_ok!(Farming::withdraw( + RuntimeOrigin::signed(ALICE), + pid, + Some(2000) + )); + assert_ok!(Farming::withdraw_claim(RuntimeOrigin::signed(ALICE), pid)); + assert_ok!(Farming::claim(RuntimeOrigin::signed(ALICE), pid)); + assert_eq!( + SharesAndWithdrawnRewards::::get(pid + GAUGE_BASE_ID, &ALICE), + None + ); + }) } diff --git a/pallets/farming/src/weights.rs b/pallets/farming/src/weights.rs index 383f21518d..d0901fea2c 100644 --- a/pallets/farming/src/weights.rs +++ b/pallets/farming/src/weights.rs @@ -58,7 +58,6 @@ pub trait WeightInfo { fn deposit() -> Weight; fn withdraw() -> Weight; fn claim() -> Weight; - fn gauge_withdraw() -> Weight; fn withdraw_claim() -> Weight; fn reset_pool() -> Weight; fn force_retire_pool() -> Weight; @@ -74,6 +73,7 @@ pub trait WeightInfo { fn start_boost_round() -> Weight; fn end_boost_round() -> Weight; fn charge_boost() -> Weight; + fn refresh() -> Weight; } // For backwards compatibility and tests @@ -156,23 +156,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: Farming GaugePoolInfos (r:1 w:1) - /// Proof Skipped: Farming GaugePoolInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: Farming GaugeInfos (r:1 w:1) - /// Proof Skipped: Farming GaugeInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: Farming PoolInfos (r:1 w:0) - /// Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: Farming SharesAndWithdrawnRewards (r:1 w:0) - /// Proof Skipped: Farming SharesAndWithdrawnRewards (max_values: None, max_size: None, mode: Measured) - fn gauge_withdraw() -> Weight { - // Proof Size summary in bytes: - // Measured: `832` - // Estimated: `4297` - // Minimum execution time: 82_741_000 picoseconds. - Weight::from_parts(83_538_000, 4297) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } /// Storage: Farming PoolInfos (r:1 w:0) /// Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) /// Storage: Farming SharesAndWithdrawnRewards (r:1 w:1) @@ -380,4 +363,20 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } + /// Storage: `Farming::UserFarmingPool` (r:1 w:0) + /// Proof: `Farming::UserFarmingPool` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::SharesAndWithdrawnRewards` (r:2 w:0) + /// Proof: `Farming::SharesAndWithdrawnRewards` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::PoolInfos` (r:1 w:0) + /// Proof: `Farming::PoolInfos` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserPositions` (r:1 w:0) + /// Proof: `BbBNC::UserPositions` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn refresh() -> Weight { + // Proof Size summary in bytes: + // Measured: `604` + // Estimated: `6544` + // Minimum execution time: 16_472_000 picoseconds. + Weight::from_parts(17_023_000, 6544) + .saturating_add(RocksDbWeight::get().reads(5)) + } } diff --git a/pallets/fee-share/Cargo.toml b/pallets/fee-share/Cargo.toml index 48bb407a44..b4177eb5fa 100644 --- a/pallets/fee-share/Cargo.toml +++ b/pallets/fee-share/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-fee-share" version = "0.8.0" -authors = ["yooml "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/fee-share/src/lib.rs b/pallets/fee-share/src/lib.rs index cc1b45fd1b..22f4634941 100644 --- a/pallets/fee-share/src/lib.rs +++ b/pallets/fee-share/src/lib.rs @@ -35,7 +35,8 @@ use frame_support::{ pallet_prelude::*, sp_runtime::{ traits::{ - AccountIdConversion, CheckedAdd, CheckedMul, SaturatedConversion, Saturating, Zero, + AccountIdConversion, BlockNumberProvider, CheckedAdd, CheckedMul, SaturatedConversion, + Saturating, Zero, }, ArithmeticError, FixedU128, Perbill, }, @@ -103,6 +104,8 @@ pub mod pallet { /// The oracle price feeder type OraclePriceProvider: OraclePriceProvider; + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::event] @@ -207,16 +210,17 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_idle(bn: BlockNumberFor, _remaining_weight: Weight) -> Weight { + fn on_idle(_: BlockNumberFor, _remaining_weight: Weight) -> Weight { + let current_block_number = T::BlockNumberProvider::current_block_number(); DollarStandardInfos::::iter().for_each(|(distribution_id, mut info)| { - if bn.eq(&info.target_block) { + if current_block_number.eq(&info.target_block) { info.target_block = info.target_block.saturating_add(info.interval); info.cumulative = Zero::zero(); DollarStandardInfos::::insert(distribution_id, info); } }); let (era_length, next_era) = AutoEra::::get(); - if bn.eq(&next_era) { + if current_block_number.eq(&next_era) { DistributionInfos::::iter().for_each(|(distribution_id, info)| { if info.if_auto { if let Some(e) = @@ -272,14 +276,21 @@ pub mod pallet { let fee_share_account_id = T::FeeSharePalletId::get().into_sub_account_truncating(distribution_id); - let info = Info { fee_share_account_id, token_type, if_auto }; + let info = Info { + fee_share_account_id, + token_type, + if_auto, + }; DistributionInfos::::insert(distribution_id, info.clone()); DistributionNextId::::mutate(|id| -> DispatchResult { *id = id.checked_add(1).ok_or(ArithmeticError::Overflow)?; Ok(()) })?; - Self::deposit_event(Event::Created { distribution_id, info }); + Self::deposit_event(Event::Created { + distribution_id, + info, + }); Ok(()) } @@ -306,7 +317,10 @@ pub mod pallet { // Clear the original proportion let res = TokensProportions::::clear_prefix(distribution_id, u32::max_value(), None); - ensure!(res.maybe_cursor.is_none(), Error::::TokensProportionsNotCleared); + ensure!( + res.maybe_cursor.is_none(), + Error::::TokensProportionsNotCleared + ); let mut total_proportion = Perbill::from_percent(0); tokens_proportion.into_iter().for_each(|(k, v)| { @@ -325,7 +339,10 @@ pub mod pallet { } DistributionInfos::::insert(distribution_id, info.clone()); - Self::deposit_event(Event::Edited { distribution_id, info }); + Self::deposit_event(Event::Edited { + distribution_id, + info, + }); Ok(()) } @@ -340,12 +357,16 @@ pub mod pallet { ) -> DispatchResult { T::ControlOrigin::ensure_origin(origin)?; - let current_block = frame_system::Pallet::::block_number(); - let next_era = - current_block.checked_add(&era_length).ok_or(ArithmeticError::Overflow)?; + let current_block = T::BlockNumberProvider::current_block_number(); + let next_era = current_block + .checked_add(&era_length) + .ok_or(ArithmeticError::Overflow)?; AutoEra::::put((era_length, next_era)); - Self::deposit_event(Event::EraLengthSet { era_length, next_era }); + Self::deposit_event(Event::EraLengthSet { + era_length, + next_era, + }); Ok(()) } @@ -413,7 +434,7 @@ pub mod pallet { ensure!(interval > Zero::zero(), Error::::IntervalIsZero); ensure!(target_value > 0, Error::::ValueIsZero); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let info = DollarStandardInfo { target_value, cumulative: Zero::zero(), @@ -423,7 +444,10 @@ pub mod pallet { }; DollarStandardInfos::::insert(distribution_id, info.clone()); - Self::deposit_event(Event::USDConfigSet { distribution_id, info }); + Self::deposit_event(Event::USDConfigSet { + distribution_id, + info, + }); Ok(()) } } @@ -435,13 +459,18 @@ pub mod pallet { ) -> DispatchResult { let mut usd_value: FixedU128 = Zero::zero(); // Calculate the total value based on the US dollar standard - infos.token_type.iter().try_for_each(|¤cy_id| -> DispatchResult { - let amount = - T::MultiCurrency::free_balance(currency_id, &infos.fee_share_account_id); - let value = Self::get_asset_value(currency_id, amount)?; - usd_value = usd_value.checked_add(&value).ok_or(ArithmeticError::Overflow)?; - Ok(()) - })?; + infos + .token_type + .iter() + .try_for_each(|¤cy_id| -> DispatchResult { + let amount = + T::MultiCurrency::free_balance(currency_id, &infos.fee_share_account_id); + let value = Self::get_asset_value(currency_id, amount)?; + usd_value = usd_value + .checked_add(&value) + .ok_or(ArithmeticError::Overflow)?; + Ok(()) + })?; if let Some(mut usd_infos) = DollarStandardInfos::::get(distribution_id) { match usd_infos.cumulative.cmp(&usd_infos.target_value) { // If the cumulative value is greater than or equal to the target value, the @@ -456,39 +485,42 @@ pub mod pallet { .ok_or(ArithmeticError::Overflow)?; DollarStandardInfos::::insert(distribution_id, &usd_infos); return Self::transfer_all(infos, usd_infos.target_account_id); - }, + } } } - infos.token_type.iter().try_for_each(|¤cy_id| -> DispatchResult { - let ed = T::MultiCurrency::minimum_balance(currency_id); - let amount = - T::MultiCurrency::free_balance(currency_id, &infos.fee_share_account_id); - TokensProportions::::iter_prefix(distribution_id).try_for_each( - |(account_to_send, proportion)| -> DispatchResult { - let withdraw_amount = proportion.mul_floor(amount); - if withdraw_amount < ed { - let receiver_balance = - T::MultiCurrency::total_balance(currency_id, &account_to_send); - - let receiver_balance_after = receiver_balance - .checked_add(&withdraw_amount) - .ok_or(ArithmeticError::Overflow)?; - if receiver_balance_after < ed { - // If the balance of the receiving account is less than the - // existential deposit, the balance is not transferred - return Ok(()); + infos + .token_type + .iter() + .try_for_each(|¤cy_id| -> DispatchResult { + let ed = T::MultiCurrency::minimum_balance(currency_id); + let amount = + T::MultiCurrency::free_balance(currency_id, &infos.fee_share_account_id); + TokensProportions::::iter_prefix(distribution_id).try_for_each( + |(account_to_send, proportion)| -> DispatchResult { + let withdraw_amount = proportion.mul_floor(amount); + if withdraw_amount < ed { + let receiver_balance = + T::MultiCurrency::total_balance(currency_id, &account_to_send); + + let receiver_balance_after = receiver_balance + .checked_add(&withdraw_amount) + .ok_or(ArithmeticError::Overflow)?; + if receiver_balance_after < ed { + // If the balance of the receiving account is less than the + // existential deposit, the balance is not transferred + return Ok(()); + } } - } - T::MultiCurrency::transfer( - currency_id, - &infos.fee_share_account_id, - &account_to_send, - withdraw_amount, - ) - }, - ) - }) + T::MultiCurrency::transfer( + currency_id, + &infos.fee_share_account_id, + &account_to_send, + withdraw_amount, + ) + }, + ) + }) } pub fn get_price(currency_id: CurrencyIdOf) -> Result { @@ -519,16 +551,19 @@ pub mod pallet { infos: &Info>, target_account_id: AccountIdOf, ) -> DispatchResult { - infos.token_type.iter().try_for_each(|¤cy_id| -> DispatchResult { - let amount = - T::MultiCurrency::free_balance(currency_id, &infos.fee_share_account_id); - T::MultiCurrency::transfer( - currency_id, - &infos.fee_share_account_id, - &target_account_id, - amount, - ) - }) + infos + .token_type + .iter() + .try_for_each(|¤cy_id| -> DispatchResult { + let amount = + T::MultiCurrency::free_balance(currency_id, &infos.fee_share_account_id); + T::MultiCurrency::transfer( + currency_id, + &infos.fee_share_account_id, + &target_account_id, + amount, + ) + }) } } } diff --git a/pallets/fee-share/src/mock.rs b/pallets/fee-share/src/mock.rs index f138d448fe..f699068147 100644 --- a/pallets/fee-share/src/mock.rs +++ b/pallets/fee-share/src/mock.rs @@ -182,6 +182,7 @@ impl bifrost_fee_share::Config for Runtime { type WeightInfo = (); type FeeSharePalletId = FeeSharePalletId; type OraclePriceProvider = MockOraclePriceProvider; + type BlockNumberProvider = System; } impl pallet_prices::Config for Runtime { @@ -200,7 +201,10 @@ pub type TimeStampedPrice = orml_oracle::TimestampedValue; pub struct MockDataProvider; impl DataProvider for MockDataProvider { fn get(_asset_id: &CurrencyId) -> Option { - Some(TimeStampedPrice { value: Price::saturating_from_integer(100), timestamp: 0 }) + Some(TimeStampedPrice { + value: Price::saturating_from_integer(100), + timestamp: 0, + }) } } @@ -255,7 +259,9 @@ impl MockOraclePriceProvider { pub fn set_price(asset_id: CurrencyId, price: Price) { Self::PRICES.with(|prices| { - prices.borrow_mut().insert(CurrencyIdWrap(asset_id), Some((price, 1u64))); + prices + .borrow_mut() + .insert(CurrencyIdWrap(asset_id), Some((price, 1u64))); }); } @@ -357,6 +363,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = (); type AssetIdMaps = AssetIdMaps; type TreasuryAccount = TreasuryAccount; + type BlockNumberProvider = System; } parameter_type_with_key! { @@ -415,6 +422,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } parameter_types! { @@ -467,7 +475,12 @@ where amount: AssetBalance, ) -> DispatchResult { let currency_id: CurrencyId = asset_id.try_into().unwrap(); - Local::transfer(currency_id, &origin, &target, amount.unique_saturated_into())?; + Local::transfer( + currency_id, + &origin, + &target, + amount.unique_saturated_into(), + )?; Ok(()) } @@ -571,7 +584,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -589,14 +604,24 @@ impl ExtBuilder { (ALICE, RelayCurrencyId::get(), 10000), (ALICE, VKSM, 10000), (BOB, KSM, 100), - (FeeSharePalletId::get().into_account_truncating(), VKSM, 10000), - (FeeSharePalletId::get().into_account_truncating(), KSM, 10000), + ( + FeeSharePalletId::get().into_account_truncating(), + VKSM, + 10000, + ), + ( + FeeSharePalletId::get().into_account_truncating(), + KSM, + 10000, + ), ]) } pub fn build(self) -> sp_io::TestExternalities { env_logger::try_init().unwrap_or(()); - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/fee-share/src/tests.rs b/pallets/fee-share/src/tests.rs index 677e88227b..a3d4a71251 100644 --- a/pallets/fee-share/src/tests.rs +++ b/pallets/fee-share/src/tests.rs @@ -26,148 +26,199 @@ use sp_arithmetic::per_things::Perbill; #[test] fn on_idle() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; - - assert_ok!(FeeShare::create_distribution( - RuntimeOrigin::signed(ALICE), - BoundedVec::try_from(vec![KSM]).unwrap(), - BoundedVec::try_from(tokens_proportion).unwrap(), - true, - )); - let keeper: AccountId = - ::FeeSharePalletId::get().into_sub_account_truncating(0); - - assert_ok!(FeeShare::set_era_length(RuntimeOrigin::signed(ALICE), 1)); - FeeShare::on_idle(>::block_number() + 1, Weight::zero()); - assert_ok!(>::transfer(KSM, &ALICE, &keeper, 100,)); - FeeShare::on_idle(>::block_number() + 2, Weight::zero()); - assert_eq!(Tokens::free_balance(KSM, &keeper), 0); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; + + assert_ok!(FeeShare::create_distribution( + RuntimeOrigin::signed(ALICE), + BoundedVec::try_from(vec![KSM]).unwrap(), + BoundedVec::try_from(tokens_proportion).unwrap(), + true, + )); + let keeper: AccountId = + ::FeeSharePalletId::get().into_sub_account_truncating(0); + + assert_ok!(FeeShare::set_era_length(RuntimeOrigin::signed(ALICE), 1)); + let current_block_number = System::block_number() + 1; + System::set_block_number(current_block_number); + FeeShare::on_idle(current_block_number, Weight::zero()); + assert_ok!(>::transfer( + KSM, &ALICE, &keeper, 100, + )); + let current_block_number = System::block_number() + 1; + System::set_block_number(current_block_number); + FeeShare::on_idle(current_block_number, Weight::zero()); + assert_eq!(Tokens::free_balance(KSM, &keeper), 0); + }); } #[test] fn edit_delete_distribution() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; - - assert_ok!(FeeShare::create_distribution( - RuntimeOrigin::signed(ALICE), - BoundedVec::try_from(vec![KSM]).unwrap(), - BoundedVec::try_from(tokens_proportion.clone()).unwrap(), - true, - )); - assert_ok!(FeeShare::edit_distribution( - RuntimeOrigin::signed(ALICE), - 0, - None, // Some(vec![KSM]), - Some(BoundedVec::try_from(tokens_proportion).unwrap()), - Some(false), - )); - let keeper: AccountId = - ::FeeSharePalletId::get().into_sub_account_truncating(0); - - assert_ok!(FeeShare::set_era_length(RuntimeOrigin::signed(ALICE), 1)); - FeeShare::on_idle(>::block_number() + 1, Weight::zero()); - assert_ok!(>::transfer(KSM, &ALICE, &keeper, 100,)); - FeeShare::on_idle(>::block_number() + 2, Weight::zero()); - assert_eq!(Tokens::free_balance(KSM, &keeper), 10100); - assert_ok!(FeeShare::execute_distribute(RuntimeOrigin::signed(ALICE), 0)); - assert_eq!(Tokens::free_balance(KSM, &keeper), 0); - - if let Some(infos) = DistributionInfos::::get(0) { - assert_eq!(infos.token_type, vec![KSM]) - } - assert_ok!(FeeShare::delete_distribution(RuntimeOrigin::signed(ALICE), 0)); - assert_eq!(DistributionInfos::::get(0), None); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; + + assert_ok!(FeeShare::create_distribution( + RuntimeOrigin::signed(ALICE), + BoundedVec::try_from(vec![KSM]).unwrap(), + BoundedVec::try_from(tokens_proportion.clone()).unwrap(), + true, + )); + assert_ok!(FeeShare::edit_distribution( + RuntimeOrigin::signed(ALICE), + 0, + None, // Some(vec![KSM]), + Some(BoundedVec::try_from(tokens_proportion).unwrap()), + Some(false), + )); + let keeper: AccountId = + ::FeeSharePalletId::get().into_sub_account_truncating(0); + + assert_ok!(FeeShare::set_era_length(RuntimeOrigin::signed(ALICE), 1)); + FeeShare::on_idle( + >::block_number() + 1, + Weight::zero(), + ); + assert_ok!(>::transfer( + KSM, &ALICE, &keeper, 100, + )); + FeeShare::on_idle( + >::block_number() + 2, + Weight::zero(), + ); + assert_eq!(Tokens::free_balance(KSM, &keeper), 10100); + assert_ok!(FeeShare::execute_distribute( + RuntimeOrigin::signed(ALICE), + 0 + )); + assert_eq!(Tokens::free_balance(KSM, &keeper), 0); + + if let Some(infos) = DistributionInfos::::get(0) { + assert_eq!(infos.token_type, vec![KSM]) + } + assert_ok!(FeeShare::delete_distribution( + RuntimeOrigin::signed(ALICE), + 0 + )); + assert_eq!(DistributionInfos::::get(0), None); + }); } #[test] fn set_usd_config_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; - - assert_ok!(FeeShare::create_distribution( - RuntimeOrigin::signed(ALICE), - BoundedVec::try_from(vec![KSM]).unwrap(), - BoundedVec::try_from(tokens_proportion.clone()).unwrap(), - true, - )); - - let distribution_id = 0; - let target_value = 100; - let interval = 10; - assert_ok!(FeeShare::set_usd_config( - RuntimeOrigin::signed(ALICE), - distribution_id, - target_value, - interval, - BOB, - )); - - let keeper: AccountId = - ::FeeSharePalletId::get().into_sub_account_truncating(0); - - assert_ok!(FeeShare::set_era_length(RuntimeOrigin::signed(ALICE), 1)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 100); - FeeShare::on_idle(>::block_number() + 1, Weight::zero()); - assert_ok!(>::transfer(KSM, &ALICE, &keeper, 100,)); - assert_eq!(Tokens::free_balance(KSM, &BOB), 10100); - assert_eq!(DollarStandardInfos::::get(0).unwrap().cumulative, 10000); - FeeShare::on_idle(>::block_number() + 2, Weight::zero()); - assert_eq!(Tokens::free_balance(KSM, &keeper), 0); - assert_eq!(Tokens::free_balance(KSM, &BOB), 10100); - assert_eq!(DollarStandardInfos::::get(0).unwrap().cumulative, 10000); - assert_ok!(>::transfer(KSM, &ALICE, &keeper, 100,)); - FeeShare::on_idle(>::block_number() + 10, Weight::zero()); - assert_eq!(DollarStandardInfos::::get(0).unwrap().cumulative, 0); - }); -} + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; -#[test] -fn set_usd_config_should_not_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; - let distribution_id = 0; - let target_value = 100; - let interval = 10; - - assert_err!( - FeeShare::set_usd_config( + assert_ok!(FeeShare::create_distribution( RuntimeOrigin::signed(ALICE), - distribution_id, - target_value, - interval, - BOB, - ), - Error::::DistributionNotExist - ); - assert_ok!(FeeShare::create_distribution( - RuntimeOrigin::signed(ALICE), - BoundedVec::try_from(vec![KSM]).unwrap(), - BoundedVec::try_from(tokens_proportion.clone()).unwrap(), - true, - )); - assert_err!( - FeeShare::set_usd_config( + BoundedVec::try_from(vec![KSM]).unwrap(), + BoundedVec::try_from(tokens_proportion.clone()).unwrap(), + true, + )); + + let distribution_id = 0; + let target_value = 100; + let interval = 10; + assert_ok!(FeeShare::set_usd_config( RuntimeOrigin::signed(ALICE), distribution_id, target_value, - 0, - BOB, - ), - Error::::IntervalIsZero - ); - assert_err!( - FeeShare::set_usd_config( - RuntimeOrigin::signed(ALICE), - distribution_id, - 0, interval, BOB, - ), - Error::::ValueIsZero - ); - }); + )); + + let keeper: AccountId = + ::FeeSharePalletId::get().into_sub_account_truncating(0); + + assert_ok!(FeeShare::set_era_length(RuntimeOrigin::signed(ALICE), 1)); + assert_eq!(Tokens::free_balance(KSM, &BOB), 100); + let current_block_number = System::block_number() + 1; + System::set_block_number(current_block_number); + FeeShare::on_idle(current_block_number, Weight::zero()); + assert_ok!(>::transfer( + KSM, &ALICE, &keeper, 100, + )); + assert_eq!(Tokens::free_balance(KSM, &BOB), 10100); + assert_eq!( + DollarStandardInfos::::get(0).unwrap().cumulative, + 10000 + ); + let current_block_number = System::block_number() + 1; + System::set_block_number(current_block_number); + FeeShare::on_idle(current_block_number, Weight::zero()); + assert_eq!(Tokens::free_balance(KSM, &keeper), 0); + assert_eq!(Tokens::free_balance(KSM, &BOB), 10100); + assert_eq!( + DollarStandardInfos::::get(0).unwrap().cumulative, + 10000 + ); + assert_ok!(>::transfer( + KSM, &ALICE, &keeper, 100, + )); + let current_block_number = System::block_number() + 8; + System::set_block_number(current_block_number); + FeeShare::on_idle(current_block_number, Weight::zero()); + assert_eq!( + DollarStandardInfos::::get(0).unwrap().cumulative, + 0 + ); + }); +} + +#[test] +fn set_usd_config_should_not_work() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let tokens_proportion = vec![(ALICE, Perbill::from_percent(100))]; + let distribution_id = 0; + let target_value = 100; + let interval = 10; + + assert_err!( + FeeShare::set_usd_config( + RuntimeOrigin::signed(ALICE), + distribution_id, + target_value, + interval, + BOB, + ), + Error::::DistributionNotExist + ); + assert_ok!(FeeShare::create_distribution( + RuntimeOrigin::signed(ALICE), + BoundedVec::try_from(vec![KSM]).unwrap(), + BoundedVec::try_from(tokens_proportion.clone()).unwrap(), + true, + )); + assert_err!( + FeeShare::set_usd_config( + RuntimeOrigin::signed(ALICE), + distribution_id, + target_value, + 0, + BOB, + ), + Error::::IntervalIsZero + ); + assert_err!( + FeeShare::set_usd_config( + RuntimeOrigin::signed(ALICE), + distribution_id, + 0, + interval, + BOB, + ), + Error::::ValueIsZero + ); + }); } diff --git a/pallets/flexible-fee/Cargo.toml b/pallets/flexible-fee/Cargo.toml index 523b91d006..aaede442df 100644 --- a/pallets/flexible-fee/Cargo.toml +++ b/pallets/flexible-fee/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-flexible-fee" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] @@ -25,9 +25,11 @@ polkadot-parachain-primitives = { workspace = true } log = { workspace = true } xcm = { workspace = true } sp-core = { workspace = true } +pallet-traits = { workspace = true } [dev-dependencies] orml-tokens = { workspace = true } +pallet-evm-accounts = { workspace = true } bifrost-currencies = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } @@ -42,6 +44,7 @@ pallet-xcm = { workspace = true } default = ["std"] std = [ "parity-scale-codec/std", + "pallet-traits/std", "scale-info/std", "frame-support/std", "frame-system/std", diff --git a/pallets/flexible-fee/rpc/Cargo.toml b/pallets/flexible-fee/rpc/Cargo.toml index 4249cf1581..5c1cdf9b94 100644 --- a/pallets/flexible-fee/rpc/Cargo.toml +++ b/pallets/flexible-fee/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-flexible-fee-rpc" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/flexible-fee/rpc/runtime-api/Cargo.toml b/pallets/flexible-fee/rpc/runtime-api/Cargo.toml index d3c9776e76..345976b95e 100644 --- a/pallets/flexible-fee/rpc/runtime-api/Cargo.toml +++ b/pallets/flexible-fee/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-flexible-fee-rpc-runtime-api" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/flexible-fee/rpc/src/lib.rs b/pallets/flexible-fee/rpc/src/lib.rs index c99fb3cdd8..c40d529281 100644 --- a/pallets/flexible-fee/rpc/src/lib.rs +++ b/pallets/flexible-fee/rpc/src/lib.rs @@ -40,7 +40,10 @@ pub struct FlexibleFeeRpc { impl FlexibleFeeRpc { pub fn new(client: Arc) -> Self { - Self { client, _marker: PhantomData } + Self { + client, + _marker: PhantomData, + } } } @@ -107,13 +110,15 @@ where ) })?; - let fee_details = api.query_fee_details(at, uxt.clone(), encoded_len).map_err(|e| { - ErrorObject::owned( - Error::RuntimeError.into(), - "Unable to query fee details.", - Some(format!("{:?}", e)), - ) - })?; + let fee_details = api + .query_fee_details(at, uxt.clone(), encoded_len) + .map_err(|e| { + ErrorObject::owned( + Error::RuntimeError.into(), + "Unable to query fee details.", + Some(format!("{:?}", e)), + ) + })?; let total_inclusion_fee: Balance = { if let Some(inclusion_fee) = fee_details.inclusion_fee { diff --git a/pallets/flexible-fee/src/benchmarking.rs b/pallets/flexible-fee/src/benchmarking.rs index cf1a947146..dd18e3b930 100644 --- a/pallets/flexible-fee/src/benchmarking.rs +++ b/pallets/flexible-fee/src/benchmarking.rs @@ -18,7 +18,7 @@ #![cfg(feature = "runtime-benchmarks")] -use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_support::BoundedVec; use bifrost_primitives::{CurrencyId, TokenSymbol}; @@ -27,17 +27,35 @@ use sp_std::vec; use crate::{Call, Config, Pallet}; -benchmarks! { - set_user_default_fee_currency { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn set_user_default_fee_currency() -> Result<(), BenchmarkError> { let caller = whitelisted_caller(); - }: _(RawOrigin::Signed(caller),Some(CurrencyId::Token(TokenSymbol::DOT))) - set_default_fee_currency_list { + #[extrinsic_call] + _( + RawOrigin::Signed(caller), + Some(CurrencyId::Token(TokenSymbol::DOT)), + ); + + Ok(()) + } + + #[benchmark] + fn set_default_fee_currency_list() -> Result<(), BenchmarkError> { let default_list = BoundedVec::try_from(vec![CurrencyId::Token(TokenSymbol::DOT)]).unwrap(); - }: _(RawOrigin::Root,default_list) + #[extrinsic_call] + _(RawOrigin::Root, default_list); + + Ok(()) + } impl_benchmark_test_suite!( - Pallet, - crate::mock::new_test_ext(), - crate::mock::Test) + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Test + ); } diff --git a/pallets/flexible-fee/src/impls/account_fee_currency.rs b/pallets/flexible-fee/src/impls/account_fee_currency.rs index 39e53df535..62620dab7c 100644 --- a/pallets/flexible-fee/src/impls/account_fee_currency.rs +++ b/pallets/flexible-fee/src/impls/account_fee_currency.rs @@ -84,7 +84,7 @@ impl AccountFeeCurrency for Pallet { _ => hopeless_currency, }; continue; - }, + } Ordering::Equal => return Ok(*maybe_currency), Ordering::Greater => return Ok(*maybe_currency), }; diff --git a/pallets/flexible-fee/src/impls/evm_permit.rs b/pallets/flexible-fee/src/impls/evm_permit.rs new file mode 100644 index 0000000000..3e6b69bd2c --- /dev/null +++ b/pallets/flexible-fee/src/impls/evm_permit.rs @@ -0,0 +1,69 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use crate::Error; +use bifrost_primitives::EvmPermit; +use frame_support::dispatch::{DispatchResult, DispatchResultWithPostInfo}; +use sp_core::{H160, H256, U256}; +use sp_std::{marker::PhantomData, vec::Vec}; +use xcm::prelude::Weight; + +pub struct DisabledEvmPermitHandler(PhantomData); +impl EvmPermit for DisabledEvmPermitHandler { + fn validate_permit( + _source: H160, + _target: H160, + _data: Vec, + _value: U256, + _gas_limit: u64, + _deadline: U256, + _v: u8, + _r: H256, + _s: H256, + ) -> DispatchResult { + Err(Error::::EvmPermitCallExecutionError.into()) + } + + fn dispatch_permit( + _source: H160, + _target: H160, + _data: Vec, + _value: U256, + _gas_limit: u64, + _max_fee_per_gas: U256, + _max_priority_fee_per_gas: Option, + _nonce: Option, + _access_list: Vec<(H160, Vec)>, + ) -> DispatchResultWithPostInfo { + Err(Error::::EvmPermitCallExecutionError.into()) + } + + fn gas_price() -> (U256, Weight) { + Default::default() + } + + fn dispatch_weight(_gas_limit: u64) -> Weight { + Weight::MAX + } + + fn permit_nonce(_account: H160) -> U256 { + U256::default() + } + + fn on_dispatch_permit_error() {} +} diff --git a/pallets/flexible-fee/src/impls/mod.rs b/pallets/flexible-fee/src/impls/mod.rs index d34b07c324..fab6b8a370 100644 --- a/pallets/flexible-fee/src/impls/mod.rs +++ b/pallets/flexible-fee/src/impls/mod.rs @@ -17,4 +17,5 @@ // along with this program. If not, see . pub mod account_fee_currency; +pub mod evm_permit; pub mod on_charge_transaction; diff --git a/pallets/flexible-fee/src/impls/on_charge_transaction.rs b/pallets/flexible-fee/src/impls/on_charge_transaction.rs index 3366058843..f50531cc30 100644 --- a/pallets/flexible-fee/src/impls/on_charge_transaction.rs +++ b/pallets/flexible-fee/src/impls/on_charge_transaction.rs @@ -77,12 +77,12 @@ where extra_fee_amount, &extra_fee_receiver, ) { - Ok(_) => {}, + Ok(_) => {} Err(_) => { return Err(TransactionValidityError::Invalid( InvalidTransaction::Payment, )); - }, + } } }; } @@ -131,7 +131,9 @@ where &fee_currency, fee_currency_price, ) - .ok_or(TransactionValidityError::Invalid(InvalidTransaction::Payment))?; + .ok_or(TransactionValidityError::Invalid( + InvalidTransaction::Payment, + ))?; let refund = paid_fee.saturating_sub(converted_corrected_fee); let converted_tip = T::OraclePriceProvider::get_amount_by_prices( &BNC, @@ -140,14 +142,16 @@ where &fee_currency, fee_currency_price, ) - .ok_or(TransactionValidityError::Invalid(InvalidTransaction::Payment))?; + .ok_or(TransactionValidityError::Invalid( + InvalidTransaction::Payment, + ))?; ( fee_currency, refund, converted_corrected_fee.saturating_sub(converted_tip), converted_tip, ) - }, + } }; // refund to the account that paid the fees T::MultiCurrency::deposit(currency, who, refund) diff --git a/pallets/flexible-fee/src/lib.rs b/pallets/flexible-fee/src/lib.rs index 074b0e18d0..e4bfaa9e3c 100644 --- a/pallets/flexible-fee/src/lib.rs +++ b/pallets/flexible-fee/src/lib.rs @@ -19,17 +19,18 @@ #![cfg_attr(not(feature = "std"), no_std)] pub use crate::pallet::*; +use bifrost_asset_registry::{AssetMetadata, CurrencyIdMapping, TokenInfo}; use bifrost_primitives::{ - currency::{VGLMR, VMANTA, WETH}, - traits::XcmDestWeightAndFeeHandler, - AssetHubChainId, Balance, BalanceCmp, CurrencyId, DerivativeIndex, OraclePriceProvider, Price, - TryConvertFrom, XcmOperationType, BNC, DOT, GLMR, MANTA, VBNC, VDOT, + traits::XcmDestWeightAndFeeHandler, AssetHubChainId, Balance, BalanceCmp, CurrencyId, + DerivativeIndex, OraclePriceProvider, Price, TryConvertFrom, XcmOperationType, BNC, VBNC, }; use bifrost_xcm_interface::calls::{PolkadotXcmCall, RelaychainCall}; use core::convert::Into; use cumulus_primitives_core::ParaId; use frame_support::{ - pallet_prelude::*, + dispatch::PostDispatchInfo, + pallet_prelude::{ValidateUnsigned, *}, + storage::with_transaction, traits::{ fungibles::Inspect, tokens::{Fortitude, Preservation}, @@ -41,11 +42,13 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; +use pallet_traits::evm::InspectEvmAccounts; use polkadot_parachain_primitives::primitives::Sibling; use sp_arithmetic::traits::UniqueSaturatedInto; +use sp_core::{H160, H256, U256}; use sp_runtime::{ traits::{AccountIdConversion, One}, - BoundedVec, + BoundedVec, ModuleError, TransactionOutcome, }; use sp_std::{boxed::Box, cmp::Ordering, vec, vec::Vec}; pub use weights::WeightInfo; @@ -63,6 +66,9 @@ pub mod weights; pub type AccountIdOf = ::AccountId; pub type BalanceOf = <::MultiCurrency as MultiCurrency>>::Balance; +pub type CurrencyIdOf = <::MultiCurrency as MultiCurrency< + ::AccountId, +>>::CurrencyId; pub type RawCallName = BoundedVec>; #[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] @@ -74,7 +80,7 @@ pub enum TargetChain { #[frame_support::pallet] pub mod pallet { use super::*; - use bifrost_primitives::{Balance, OraclePriceProvider}; + use bifrost_primitives::{Balance, EvmPermit, OraclePriceProvider}; use frame_support::traits::fungibles::Inspect; #[pallet::config] @@ -96,6 +102,9 @@ pub mod pallet { type ControlOrigin: EnsureOrigin; /// Get the weight and fee for executing Xcm. type XcmWeightAndFeeHandler: XcmDestWeightAndFeeHandler; + /// EVM Accounts info + type InspectEvmAccounts: InspectEvmAccounts; + type EvmPermit: EvmPermit; /// Get TreasuryAccount #[pallet::constant] type TreasuryAccount: Get; @@ -115,6 +124,8 @@ pub mod pallet { type ParachainId: Get; #[pallet::constant] type PalletId: Get; + // asset registry to get asset metadata + type AssetIdMaps: CurrencyIdMapping>>; } #[pallet::hooks] @@ -144,11 +155,20 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Transfer to another chain - TransferTo { from: T::AccountId, target_chain: TargetChain, amount: BalanceOf }, + TransferTo { + from: T::AccountId, + target_chain: TargetChain, + amount: BalanceOf, + }, /// Set user default fee currency - SetDefaultFeeCurrency { who: T::AccountId, currency_id: Option }, + SetDefaultFeeCurrency { + who: T::AccountId, + currency_id: Option, + }, /// Set universal fee currency order list - SetFeeCurrencyList { currency_list: BoundedVec }, + SetFeeCurrencyList { + currency_list: BoundedVec, + }, /// Set extra fee by call SetExtraFee { /// The raw call name to be set as the extra fee call. @@ -202,6 +222,14 @@ pub mod pallet { CurrencyNotSupport, /// The maximum number of currencies that can be handled has been reached. MaxCurrenciesReached, + /// EVM permit expired. + EvmPermitExpired, + /// EVM permit is invalid. + EvmPermitInvalid, + /// EVM permit call failed. + EvmPermitCallExecutionError, + /// EVM permit call failed. + EvmPermitRunnerError, } #[pallet::call] @@ -262,9 +290,155 @@ pub mod pallet { Some(fee_info) => ExtraFeeByCall::::insert(&raw_call_name, fee_info), None => ExtraFeeByCall::::remove(&raw_call_name), }; - Self::deposit_event(Event::::SetExtraFee { raw_call_name, fee_info }); + Self::deposit_event(Event::::SetExtraFee { + raw_call_name, + fee_info, + }); Ok(()) } + + /// Dispatch EVM permit. + /// The main purpose of this function is to allow EVM accounts to pay for the transaction + /// fee in non-native currency by allowing them to self-dispatch pre-signed permit. + /// The EVM fee is paid in the currency set for the account. + #[pallet::call_index(3)] + #[pallet::weight(::EvmPermit::dispatch_weight(*gas_limit))] + pub fn dispatch_permit( + origin: OriginFor, + from: H160, + to: H160, + value: U256, + data: Vec, + gas_limit: u64, + deadline: U256, + v: u8, + r: H256, + s: H256, + ) -> DispatchResultWithPostInfo { + ensure_none(origin)?; + + // dispatch permit should never return error. + // validate_unsigned should prevent the transaction getting to this point in case of + // invalid permit. In case of any error, we call error handler ( which should pause + // this transaction) and return ok. + if T::EvmPermit::validate_permit( + from, + to, + data.clone(), + value, + gas_limit, + deadline, + v, + r, + s, + ) + .is_err() + { + T::EvmPermit::on_dispatch_permit_error(); + return Ok(PostDispatchInfo::default()); + }; + + let (gas_price, _) = T::EvmPermit::gas_price(); + + let result = T::EvmPermit::dispatch_permit( + from, + to, + data, + value, + gas_limit, + gas_price, + None, + None, + vec![], + ) + .unwrap_or_else(|e| { + // In case of runner error, account has not been charged, so we need to call error + // handler to pause dispatch error + if e.error == Error::::EvmPermitRunnerError.into() { + T::EvmPermit::on_dispatch_permit_error(); + } + e.post_info + }); + + Ok(result) + } + } + + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + + fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { + match call { + Call::dispatch_permit { + from, + to, + value, + data, + gas_limit, + deadline, + v, + r, + s, + } => { + // We need to wrap this as separate tx, and since we also "dry-run" the + // dispatch, we need to rollback the changes if any + let result = with_transaction::<(), DispatchError, _>(|| { + // First verify signature + let result = T::EvmPermit::validate_permit( + *from, + *to, + data.clone(), + *value, + *gas_limit, + *deadline, + *v, + *r, + *s, + ); + if let Some(error_res) = result.err() { + return TransactionOutcome::Rollback(Err(error_res)); + } + + let (gas_price, _) = T::EvmPermit::gas_price(); + + let result = T::EvmPermit::dispatch_permit( + *from, + *to, + data.clone(), + *value, + *gas_limit, + gas_price, + None, + None, + vec![], + ); + match result { + Ok(_post_info) => TransactionOutcome::Rollback(Ok(())), + Err(e) => TransactionOutcome::Rollback(Err(e.error)), + } + }); + let nonce = T::EvmPermit::permit_nonce(*from); + match result { + Ok(()) => ValidTransaction::with_tag_prefix("EvmPermit") + .and_provides((nonce, from)) + .priority(0) + .longevity(64) + .propagate(true) + .build(), + Err(e) => { + let error_number = match e { + DispatchError::Module(ModuleError { error, .. }) => error[0], + _ => 0, /* this case should never happen because an Error is + * always converted to DispatchError::Module(ModuleError) */ + }; + InvalidTransaction::Custom(error_number).into() + } + } + } + _ => InvalidTransaction::Call.into(), + } + } } } @@ -314,11 +488,17 @@ impl Pallet { ) .ok_or(Error::::WeightAndFeeNotExist)?; - let fee: Asset = Asset { id: AssetId(Location::here()), fun: Fungible(xcm_fee) }; + let fee: Asset = Asset { + id: AssetId(Location::here()), + fun: Fungible(xcm_fee), + }; let remote_xcm = Xcm(vec![ WithdrawAsset(fee.clone().into()), - BuyExecution { fees: fee.clone(), weight_limit: Unlimited }, + BuyExecution { + fees: fee.clone(), + weight_limit: Unlimited, + }, Transact { origin_kind: OriginKind::SovereignAccount, require_weight_at_most, @@ -368,19 +548,27 @@ impl Pallet { /// Get user fee charge assets order fn get_fee_currency_list(account_id: &T::AccountId) -> Vec { // Get universal fee currency order list - let mut fee_currency_list: Vec = - UniversalFeeCurrencyOrderList::::get().into_iter().collect(); + let mut fee_currency_list: Vec = UniversalFeeCurrencyOrderList::::get() + .into_iter() + .collect(); // Get user default fee currency if let Some(default_fee_currency) = UserDefaultFeeCurrency::::get(&account_id) { - if let Some(index) = fee_currency_list.iter().position(|&c| c == default_fee_currency) { + if let Some(index) = fee_currency_list + .iter() + .position(|&c| c == default_fee_currency) + { fee_currency_list.remove(index); } let first_fee_currency_index = 0; fee_currency_list.insert(first_fee_currency_index, default_fee_currency); }; - fee_currency_list + if fee_currency_list.is_empty() { + vec![BNC] + } else { + fee_currency_list + } } fn get_fee_currency_and_fee_amount( @@ -439,14 +627,14 @@ impl Pallet { Ok(amount_in) => { fee_info = Some((currency_id, amount_in)); break; - }, - Err(_) => {}, + } + Err(_) => {} } } } match fee_info { - Some((fee_currency, fee_amount)) => + Some((fee_currency, fee_amount)) => { if fee_currency == extra_fee_currency { T::MultiCurrency::transfer(fee_currency, who, extra_fee_receiver, fee_amount) .map_err(|_| Error::::NotEnoughBalance)?; @@ -465,7 +653,8 @@ impl Pallet { ) .map_err(|_| Error::::NotEnoughBalance)?; Ok(()) - }, + } + } None => Err(Error::::ConversionError), } } @@ -508,7 +697,7 @@ impl Pallet { T::MultiCurrency::ensure_can_withdraw(from_currency, who, amount_in) .map_err(|_| Error::::NotEnoughBalance)?; Ok(amount_in) - }, + } Err(_) => Err(Error::::NotEnoughBalance)?, } } @@ -555,12 +744,14 @@ impl BalanceCmp for Pallet { let amount = amount.saturating_mul(adjust_precision); // Adjust the balance based on currency type. - let balance_precision_offset = match *currency { - WETH | GLMR | VGLMR | MANTA | VMANTA => standard_precision.saturating_sub(18), - BNC | VBNC => standard_precision.saturating_sub(12), - DOT | VDOT => standard_precision.saturating_sub(10), - _ => return Err(Error::::CurrencyNotSupport), - }; + let decimals = currency + .decimals() + .or_else(|| { + T::AssetIdMaps::get_currency_metadata(*currency) + .map(|metadata| metadata.decimals.into()) + }) + .ok_or(Error::::CurrencyNotSupport)?; + let balance_precision_offset = standard_precision.saturating_sub(decimals.into()); // Apply precision adjustment to balance. balance = balance.saturating_mul(10u128.pow(balance_precision_offset)); diff --git a/pallets/flexible-fee/src/mock.rs b/pallets/flexible-fee/src/mock.rs index 7e061dcb07..49981d83de 100644 --- a/pallets/flexible-fee/src/mock.rs +++ b/pallets/flexible-fee/src/mock.rs @@ -20,16 +20,20 @@ use super::*; use crate::{self as flexible_fee, mock_price::MockOraclePriceProvider}; +use bifrost_asset_registry::AssetIdMaps; use bifrost_currencies::BasicCurrencyAdapter; -use bifrost_primitives::{Balance, CurrencyId, FlexibleFeePalletId, TokenSymbol, ZenlinkPalletId}; +use bifrost_primitives::{ + Balance, CurrencyId, EvmPermit, FlexibleFeePalletId, TokenSymbol, ZenlinkPalletId, +}; use cumulus_primitives_core::ParaId as Pid; use frame_support::{ - derive_impl, parameter_types, + derive_impl, ord_parameter_types, parameter_types, sp_runtime::{DispatchError, DispatchResult}, traits::{ConstU128, Get, Nothing}, weights::{ConstantMultiplier, IdentityFee}, PalletId, }; +use frame_system::EnsureSignedBy; use frame_system::{self, EnsureRoot}; use orml_traits::MultiCurrency; use pallet_balances::Call as BalancesCall; @@ -38,7 +42,7 @@ use sp_runtime::{ AccountId32, BuildStorage, SaturatedConversion, }; use sp_std::marker::PhantomData; -use std::convert::TryInto; +use std::{cell::RefCell, convert::TryInto}; use zenlink_protocol::{ AssetBalance, AssetId as ZenlinkAssetId, LocalAssetHandler, PairLpGenerate, ZenlinkMultiAssets, }; @@ -62,16 +66,23 @@ frame_support::construct_runtime!( ZenlinkProtocol: zenlink_protocol, Currencies: bifrost_currencies, AssetRegistry: bifrost_asset_registry, + EVMAccounts: pallet_evm_accounts, } ); pub(crate) const BALANCE_TRANSFER_CALL: ::RuntimeCall = - RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: ALICE, value: 69 }); + RuntimeCall::Balances(BalancesCall::transfer_allow_death { + dest: ALICE, + value: 69, + }); +ord_parameter_types! { + pub const CouncilAccount: AccountId = AccountId::from([1u8; 32]); +} impl bifrost_asset_registry::Config for Test { type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type RegisterOrigin = EnsureRoot; + type RegisterOrigin = EnsureSignedBy; type WeightInfo = (); } @@ -146,6 +157,21 @@ impl orml_tokens::Config for Test { type CurrencyHooks = (); } +pub struct EvmNonceProvider; +impl pallet_evm_accounts::EvmNonceProvider for EvmNonceProvider { + fn get_nonce(_: sp_core::H160) -> sp_core::U256 { + sp_core::U256::zero() + } +} + +impl pallet_evm_accounts::Config for Test { + type RuntimeEvent = RuntimeEvent; + type EvmNonceProvider = EvmNonceProvider; + type FeeMultiplier = ConstU32<10>; + type ControllerOrigin = EnsureRoot; + type WeightInfo = (); +} + parameter_types! { pub const TreasuryAccount: AccountId32 = TREASURY_ACCOUNT; pub const MaxFeeCurrencyOrderListLen: u32 = 50; @@ -167,6 +193,9 @@ impl crate::Config for Test { type XcmRouter = (); type PalletId = FlexibleFeePalletId; type OraclePriceProvider = MockOraclePriceProvider; + type InspectEvmAccounts = EVMAccounts; + type EvmPermit = PermitDispatchHandler; + type AssetIdMaps = AssetIdMaps; } pub struct XcmDestWeightAndFee; @@ -255,7 +284,12 @@ where amount: AssetBalance, ) -> DispatchResult { let currency_id: CurrencyId = asset_id.try_into().unwrap(); - Local::transfer(currency_id, &origin, &target, amount.unique_saturated_into())?; + Local::transfer( + currency_id, + &origin, + &target, + amount.unique_saturated_into(), + )?; Ok(()) } @@ -284,7 +318,9 @@ where // Build genesis storage according to the mock runtime. pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); // We use default for brevity, but you can configure as desired if needed. pallet_balances::GenesisConfig::::default() .assimilate_storage(&mut t) @@ -310,3 +346,127 @@ impl BalanceCmp for Test { Pallet::::cmp_with_precision(account, currency, amount, amount_precision) } } + +#[derive(Clone, Debug, PartialEq)] +pub struct PermitDispatchData { + pub source: H160, + pub target: H160, + pub input: Vec, + pub value: U256, + pub gas_limit: u64, + pub max_fee_per_gas: U256, + pub max_priority_fee_per_gas: Option, + pub nonce: Option, + pub access_list: Vec<(H160, Vec)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ValidationData { + pub source: H160, + pub target: H160, + pub input: Vec, + pub value: U256, + pub gas_limit: u64, + pub deadline: U256, + pub v: u8, + pub r: H256, + pub s: H256, +} + +thread_local! { + static PERMIT_VALIDATION: RefCell> = const { RefCell::new(vec![]) }; + static PERMIT_DISPATCH: RefCell> = const { RefCell::new(vec![]) }; +} + +pub struct PermitDispatchHandler; + +impl PermitDispatchHandler { + pub fn last_validation_call_data() -> ValidationData { + PERMIT_VALIDATION.with(|v| v.borrow().last().unwrap().clone()) + } + + pub fn last_dispatch_call_data() -> PermitDispatchData { + PERMIT_DISPATCH.with(|v| v.borrow().last().unwrap().clone()) + } +} + +impl EvmPermit for PermitDispatchHandler { + fn validate_permit( + source: H160, + target: H160, + input: Vec, + value: U256, + gas_limit: u64, + deadline: U256, + v: u8, + r: H256, + s: H256, + ) -> DispatchResult { + let data = ValidationData { + source, + target, + input, + value, + gas_limit, + deadline, + v, + r, + s, + }; + PERMIT_VALIDATION.with(|v| v.borrow_mut().push(data)); + Ok(()) + } + + fn dispatch_permit( + source: H160, + target: H160, + input: Vec, + value: U256, + gas_limit: u64, + max_fee_per_gas: U256, + max_priority_fee_per_gas: Option, + nonce: Option, + access_list: Vec<(H160, Vec)>, + ) -> DispatchResultWithPostInfo { + let data = PermitDispatchData { + source, + target, + input, + value, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + nonce, + access_list, + }; + PERMIT_DISPATCH.with(|v| v.borrow_mut().push(data)); + Ok(PostDispatchInfo::default()) + } + + fn gas_price() -> (U256, Weight) { + (U256::from(222u128), Weight::zero()) + } + + fn dispatch_weight(_gas_limit: u64) -> Weight { + todo!() + } + + fn permit_nonce(_account: H160) -> U256 { + U256::default() + } + + fn on_dispatch_permit_error() {} +} + +pub struct ExtBuilder; + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + new_test_ext() + } +} + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder.build() +} diff --git a/pallets/flexible-fee/src/mock_price.rs b/pallets/flexible-fee/src/mock_price.rs index 18374e46e4..592650c0c8 100644 --- a/pallets/flexible-fee/src/mock_price.rs +++ b/pallets/flexible-fee/src/mock_price.rs @@ -46,10 +46,10 @@ impl MockOraclePriceProvider { match storage_price.get(¤cy_id) { Some((_, mantissa)) => { storage_price.insert(currency_id, (price, *mantissa)); - }, + } None => { storage_price.insert(currency_id, (price, 10u128.pow(12))); - }, + } }; StoragePrice::set(storage_price); } @@ -101,7 +101,11 @@ impl OraclePriceProvider for MockOraclePriceProvider { let amount_out = total_value .mul(FixedU128::from_inner(*currency_out_mantissa)) .div(*currency_out_price); - return Some((amount_out.into_inner(), *currency_in_price, *currency_out_price)); + return Some(( + amount_out.into_inner(), + *currency_in_price, + *currency_out_price, + )); } } None @@ -119,10 +123,16 @@ mod test { Some((FixedU128::from_inner(200_000_000_000_000_000), 0)) ); MockOraclePriceProvider::set_price(BNC, FixedU128::from(100)); - assert_eq!(MockOraclePriceProvider::get_price(&BNC), Some((FixedU128::from(100), 0))); + assert_eq!( + MockOraclePriceProvider::get_price(&BNC), + Some((FixedU128::from(100), 0)) + ); MockOraclePriceProvider::set_price(DOT, FixedU128::from(100)); - assert_eq!(MockOraclePriceProvider::get_price(&DOT), Some((FixedU128::from(100), 0))); + assert_eq!( + MockOraclePriceProvider::get_price(&DOT), + Some((FixedU128::from(100), 0)) + ); } #[test] @@ -136,19 +146,31 @@ mod test { MockOraclePriceProvider::get_oracle_amount_by_currency_and_amount_in( &BNC, bnc_amount, &DOT ), - Some((dot_amount, FixedU128::from_inner(200_000_000_000_000_000), FixedU128::from(5))) + Some(( + dot_amount, + FixedU128::from_inner(200_000_000_000_000_000), + FixedU128::from(5) + )) ); assert_eq!( MockOraclePriceProvider::get_oracle_amount_by_currency_and_amount_in( &BNC, bnc_amount, &DOT_U ), - Some((usdt_amount, FixedU128::from_inner(200_000_000_000_000_000), FixedU128::from(1))) + Some(( + usdt_amount, + FixedU128::from_inner(200_000_000_000_000_000), + FixedU128::from(1) + )) ); assert_eq!( MockOraclePriceProvider::get_oracle_amount_by_currency_and_amount_in( &BNC, bnc_amount, &KSM ), - Some((ksm_amount, FixedU128::from_inner(200_000_000_000_000_000), FixedU128::from(20))) + Some(( + ksm_amount, + FixedU128::from_inner(200_000_000_000_000_000), + FixedU128::from(20) + )) ); assert_eq!( MockOraclePriceProvider::get_oracle_amount_by_currency_and_amount_in( diff --git a/pallets/flexible-fee/src/tests.rs b/pallets/flexible-fee/src/tests.rs index e7ffb47f11..e8756eabd3 100644 --- a/pallets/flexible-fee/src/tests.rs +++ b/pallets/flexible-fee/src/tests.rs @@ -23,37 +23,228 @@ use crate::{ impls::on_charge_transaction::PaymentInfo, mock::*, BlockNumberFor, BoundedVec, Config, DispatchError::BadOrigin, Error, UserDefaultFeeCurrency, }; +use bifrost_asset_registry::AssetMetadata; +use bifrost_asset_registry::CurrencyMetadatas; use bifrost_primitives::{ AccountFeeCurrency, BalanceCmp, CurrencyId, TryConvertFrom, BNC, DOT, KSM, MANTA, VBNC, VDOT, WETH, }; use frame_support::{ - assert_noop, assert_ok, + assert_noop, assert_ok, assert_storage_noop, dispatch::{DispatchInfo, PostDispatchInfo}, + pallet_prelude::ValidateUnsigned, traits::fungibles::Mutate, weights::Weight, }; use orml_traits::MultiCurrency; +use pallet_traits::evm::InspectEvmAccounts; use pallet_transaction_payment::OnChargeTransaction; use sp_arithmetic::FixedU128; -use sp_runtime::AccountId32; +use sp_core::{H256, U256}; +use sp_runtime::{transaction_validity::TransactionSource, AccountId32}; use std::cmp::Ordering::{Greater, Less}; use zenlink_protocol::AssetId; // some common variables pub const CHARLIE: AccountId32 = AccountId32::new([0u8; 32]); -pub const ALICE: AccountId32 = AccountId32::new([2u8; 32]); +pub const ALICE: AccountId = AccountId::new([1; 32]); +pub const BOB: AccountId = AccountId::new([2; 32]); pub const DICK: AccountId32 = AccountId32::new([3u8; 32]); /// create a transaction info struct from weight. Handy to avoid building the whole struct. pub fn info() -> DispatchInfo { // pays_fee: Pays::Yes -- class: DispatchClass::Normal - DispatchInfo { weight: Weight::default(), ..Default::default() } + DispatchInfo { + weight: Weight::default(), + ..Default::default() + } } fn post_info() -> PostDispatchInfo { - PostDispatchInfo { actual_weight: Some(Weight::default()), pays_fee: Default::default() } + PostDispatchInfo { + actual_weight: Some(Weight::default()), + pays_fee: Default::default(), + } +} + +fn ini_meta_data() { + let metadata = AssetMetadata { + name: b"Polkadot DOT".to_vec(), + symbol: b"DOT".to_vec(), + decimals: 10, + minimal_balance: 1000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_ok!(AssetRegistry::register_vtoken_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 0 + )); + + assert_eq!(CurrencyMetadatas::::get(DOT), Some(metadata.clone())); + + let metadata = AssetMetadata { + name: b"Moonbeam Native Token".to_vec(), + symbol: b"GLMR".to_vec(), + decimals: 18, + minimal_balance: 1000000000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Tether USD".to_vec(), + symbol: b"USDT".to_vec(), + decimals: 6, + minimal_balance: 1000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Astar".to_vec(), + symbol: b"ASTR".to_vec(), + decimals: 18, + minimal_balance: 10000000000000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Filecoin Network Token".to_vec(), + symbol: b"FIL".to_vec(), + decimals: 18, + minimal_balance: 1000000000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"USD Coin".to_vec(), + symbol: b"USDC".to_vec(), + decimals: 6, + minimal_balance: 1000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"interBTC".to_vec(), + symbol: b"IBTC".to_vec(), + decimals: 8, + minimal_balance: 100, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Interlay".to_vec(), + symbol: b"INTR".to_vec(), + decimals: 10, + minimal_balance: 10000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Manta Network".to_vec(), + symbol: b"MANTA".to_vec(), + decimals: 18, + minimal_balance: 1000000000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"bncs-20 inscription token BNCS".to_vec(), + symbol: b"BNCS".to_vec(), + decimals: 12, + minimal_balance: 10000000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"PINK".to_vec(), + symbol: b"PINK".to_vec(), + decimals: 10, + minimal_balance: 100000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"DED".to_vec(), + symbol: b"DED".to_vec(), + decimals: 10, + minimal_balance: 1, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Pendulum".to_vec(), + symbol: b"PEN".to_vec(), + decimals: 12, + minimal_balance: 100000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + let metadata = AssetMetadata { + name: b"Wrapped ETH".to_vec(), + symbol: b"WETH".to_vec(), + decimals: 18, + minimal_balance: 15000000000000, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_eq!(CurrencyMetadatas::::get(WETH), Some(metadata.clone())); } fn basic_setup() { @@ -147,7 +338,10 @@ fn set_user_default_fee_currency_should_work() { let alice_default_currency = UserDefaultFeeCurrency::::get(ALICE).unwrap(); assert_eq!(alice_default_currency, BNC); - assert_ok!(FlexibleFee::set_user_default_fee_currency(origin_signed_alice.clone(), None)); + assert_ok!(FlexibleFee::set_user_default_fee_currency( + origin_signed_alice.clone(), + None + )); assert_eq!(UserDefaultFeeCurrency::::get(ALICE).is_none(), true); }); } @@ -185,7 +379,10 @@ fn set_default_fee_currency_list_should_work() { asset_order_list_vec.clone() )); - assert_eq!(crate::UniversalFeeCurrencyOrderList::::get(), asset_order_list_vec); + assert_eq!( + crate::UniversalFeeCurrencyOrderList::::get(), + asset_order_list_vec + ); }); } @@ -389,12 +586,20 @@ fn get_currency_asset_id_should_work() { new_test_ext().execute_with(|| { // BNC let asset_id = FlexibleFee::get_currency_asset_id(BNC).unwrap(); - let bnc_asset_id = AssetId { chain_id: 2001, asset_type: 0, asset_index: 0 }; + let bnc_asset_id = AssetId { + chain_id: 2001, + asset_type: 0, + asset_index: 0, + }; assert_eq!(asset_id, bnc_asset_id); // KSM let asset_id = FlexibleFee::get_currency_asset_id(KSM).unwrap(); - let ksm_asset_id = AssetId { chain_id: 2001, asset_type: 2, asset_index: 516 }; + let ksm_asset_id = AssetId { + chain_id: 2001, + asset_type: 2, + asset_index: 516, + }; assert_eq!(asset_id, ksm_asset_id); }); } @@ -402,6 +607,8 @@ fn get_currency_asset_id_should_work() { #[test] fn get_fee_currency_should_work_with_default_currency() { new_test_ext().execute_with(|| { + ini_meta_data(); + let origin_signed_alice = RuntimeOrigin::signed(ALICE); assert_ok!(FlexibleFee::set_user_default_fee_currency( origin_signed_alice.clone(), @@ -422,6 +629,8 @@ fn get_fee_currency_should_work_with_default_currency() { #[test] fn get_fee_currency_should_work_with_default_currency_poor() { new_test_ext().execute_with(|| { + ini_meta_data(); + let origin_signed_alice = RuntimeOrigin::signed(ALICE); assert_ok!(FlexibleFee::set_user_default_fee_currency( origin_signed_alice.clone(), @@ -442,6 +651,8 @@ fn get_fee_currency_should_work_with_default_currency_poor() { #[test] fn get_fee_currency_should_work_with_weth() { new_test_ext().execute_with(|| { + ini_meta_data(); + assert_ok!(Currencies::deposit(BNC, &ALICE, 100u128.pow(12))); // BNC assert_ok!(Currencies::deposit(DOT, &ALICE, 100u128.pow(10))); // DOT assert_ok!(Currencies::deposit(VDOT, &ALICE, 100u128.pow(10))); // vDOT @@ -456,6 +667,8 @@ fn get_fee_currency_should_work_with_weth() { #[test] fn get_fee_currency_should_work_with_weth_poor() { new_test_ext().execute_with(|| { + ini_meta_data(); + assert_ok!(Currencies::deposit(BNC, &ALICE, 100u128.pow(12))); // BNC assert_ok!(Currencies::deposit(DOT, &ALICE, 100u128.pow(10))); // DOT assert_ok!(Currencies::deposit(VDOT, &ALICE, 100u128.pow(10))); // vDOT @@ -480,6 +693,8 @@ fn get_fee_currency_should_work_with_weth_poor() { #[test] fn get_fee_currency_should_work_with_universal_fee_currency() { new_test_ext().execute_with(|| { + ini_meta_data(); + let origin_signed_alice = RuntimeOrigin::signed(ALICE); assert_ok!(FlexibleFee::set_user_default_fee_currency( origin_signed_alice.clone(), @@ -510,6 +725,8 @@ fn get_fee_currency_should_work_with_universal_fee_currency() { #[test] fn get_fee_currency_should_work_with_universal_fee_currency_poor() { new_test_ext().execute_with(|| { + ini_meta_data(); + assert_ok!(Currencies::deposit(BNC, &ALICE, 1u128.pow(12))); // BNC assert_ok!(Currencies::deposit(DOT, &ALICE, 100u128.pow(10))); // DOT assert_ok!(Currencies::deposit(VDOT, &ALICE, 1u128.pow(10))); // vDOT @@ -534,6 +751,8 @@ fn get_fee_currency_should_work_with_universal_fee_currency_poor() { #[test] fn get_fee_currency_should_work_with_all_currency_poor() { new_test_ext().execute_with(|| { + ini_meta_data(); + let origin_signed_alice = RuntimeOrigin::signed(ALICE); assert_ok!(FlexibleFee::set_user_default_fee_currency( origin_signed_alice.clone(), @@ -564,6 +783,8 @@ fn get_fee_currency_should_work_with_all_currency_poor() { #[test] fn cmp_with_precision_should_work_with_weth() { new_test_ext().execute_with(|| { + ini_meta_data(); + assert_ok!(Currencies::deposit(WETH, &ALICE, 10u128.pow(18) - 1)); // ETH let ordering = @@ -575,6 +796,8 @@ fn cmp_with_precision_should_work_with_weth() { #[test] fn cmp_with_precision_should_work_with_dot() { new_test_ext().execute_with(|| { + ini_meta_data(); + assert_ok!(Currencies::deposit(DOT, &ALICE, 10u128.pow(11) + 1)); // DOT let ordering = @@ -593,3 +816,139 @@ fn cmp_with_precision_should_work_with_bnc() { assert_eq!(ordering, Greater); }); } + +#[test] +fn validate_unsigned_should_correctly_call_validate_handler() { + let alice_evm_address = EVMAccounts::evm_address(&ALICE); + let other_evm_address = EVMAccounts::evm_address(&BOB); + + new_test_ext().execute_with(|| { + let r: [u8; 32] = [100; 32]; + let s: [u8; 32] = [200; 32]; + + let call = crate::Call::dispatch_permit { + from: alice_evm_address, + to: other_evm_address, + data: b"test".to_vec(), + value: U256::from(1234), + gas_limit: 123, + deadline: U256::from(99999), + v: 255, + r: H256::from(r), + s: H256::from(s), + }; + + assert_storage_noop!({ + let res = FlexibleFee::validate_unsigned(TransactionSource::Local, &call); + assert_ok!(res); + }); + + let expected = ValidationData { + source: alice_evm_address, + target: other_evm_address, + input: b"test".to_vec(), + value: U256::from(1234), + gas_limit: 123, + deadline: U256::from(99999), + v: 255, + r: H256::from(r), + s: H256::from(s), + }; + + assert_eq!(PermitDispatchHandler::last_validation_call_data(), expected); + }); +} + +#[test] +fn validate_unsigned_should_correctly_dry_run_dispatch() { + let alice_evm_address = EVMAccounts::evm_address(&ALICE); + let other_evm_address = EVMAccounts::evm_address(&BOB); + + new_test_ext().execute_with(|| { + let r: [u8; 32] = [100; 32]; + let s: [u8; 32] = [200; 32]; + + let call = crate::Call::dispatch_permit { + from: alice_evm_address, + to: other_evm_address, + data: b"test".to_vec(), + value: U256::from(1234), + gas_limit: 123, + deadline: U256::from(99999), + v: 255, + r: H256::from(r), + s: H256::from(s), + }; + + assert_storage_noop!({ + let res = FlexibleFee::validate_unsigned(TransactionSource::Local, &call); + assert_ok!(res); + }); + + let expected = PermitDispatchData { + source: alice_evm_address, + target: other_evm_address, + input: b"test".to_vec(), + value: U256::from(1234), + gas_limit: 123, + max_fee_per_gas: U256::from(222u128), + max_priority_fee_per_gas: None, + nonce: None, + access_list: vec![], + }; + + assert_eq!(PermitDispatchHandler::last_dispatch_call_data(), expected); + }); +} + +#[test] +fn dispatch_should_correctly_call_validate_and_dispatch() { + let alice_evm_address = EVMAccounts::evm_address(&ALICE); + let other_evm_address = EVMAccounts::evm_address(&BOB); + + new_test_ext().execute_with(|| { + let r: [u8; 32] = [50; 32]; + let s: [u8; 32] = [100; 32]; + + assert_ok!(FlexibleFee::dispatch_permit( + RuntimeOrigin::none(), + alice_evm_address, + other_evm_address, + U256::from(1234), + b"test".to_vec(), + 333, + U256::from(99999u128), + 128, + H256::from(r), + H256::from(s), + )); + + let expected = ValidationData { + source: alice_evm_address, + target: other_evm_address, + input: b"test".to_vec(), + value: U256::from(1234), + gas_limit: 333, + deadline: U256::from(99999u128), + v: 128, + r: H256::from(r), + s: H256::from(s), + }; + + assert_eq!(PermitDispatchHandler::last_validation_call_data(), expected); + + let expected = PermitDispatchData { + source: alice_evm_address, + target: other_evm_address, + input: b"test".to_vec(), + value: U256::from(1234), + gas_limit: 333, + max_fee_per_gas: U256::from(222u128), + max_priority_fee_per_gas: None, + nonce: None, + access_list: vec![], + }; + + assert_eq!(PermitDispatchHandler::last_dispatch_call_data(), expected); + }); +} diff --git a/pallets/flexible-fee/src/weights.rs b/pallets/flexible-fee/src/weights.rs index bcc1c4b985..aa4f85257d 100644 --- a/pallets/flexible-fee/src/weights.rs +++ b/pallets/flexible-fee/src/weights.rs @@ -24,9 +24,9 @@ //! Autogenerated weights for bifrost_flexible_fee //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-11-27, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` //! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 // Executed Command: @@ -36,7 +36,7 @@ // --chain=bifrost-kusama-local // --steps=50 // --repeat=20 -// --pallet=bifrost_flexible_fee +// --pallet=bifrost_flexible-fee // --extrinsic=* // --execution=wasm // --wasm-execution=compiled @@ -59,24 +59,24 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { - /// Storage: FlexibleFee UserDefaultFeeCurrency (r:0 w:1) - /// Proof Skipped: FlexibleFee UserDefaultFeeCurrency (max_values: None, max_size: None, mode: Measured) + /// Storage: `FlexibleFee::UserDefaultFeeCurrency` (r:0 w:1) + /// Proof: `FlexibleFee::UserDefaultFeeCurrency` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) fn set_user_default_fee_currency() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 11_322_000 picoseconds. - Weight::from_parts(11_925_000, 0) + // Minimum execution time: 3_734_000 picoseconds. + Weight::from_parts(3_996_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: FlexibleFee UniversalFeeCurrencyOrderList (r:0 w:1) - /// Proof Skipped: FlexibleFee UniversalFeeCurrencyOrderList (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: `FlexibleFee::UniversalFeeCurrencyOrderList` (r:0 w:1) + /// Proof: `FlexibleFee::UniversalFeeCurrencyOrderList` (`max_values`: Some(1), `max_size`: Some(701), added: 1196, mode: `MaxEncodedLen`) fn set_default_fee_currency_list() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 10_424_000 picoseconds. - Weight::from_parts(10_846_000, 0) + // Minimum execution time: 3_257_000 picoseconds. + Weight::from_parts(3_404_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/pallets/lend-market/Cargo.toml b/pallets/lend-market/Cargo.toml index fa38f07ba5..941adb6f7e 100644 --- a/pallets/lend-market/Cargo.toml +++ b/pallets/lend-market/Cargo.toml @@ -1,5 +1,5 @@ [package] -authors = ["Parallel Team", "Liebi Technologies "] +authors = ["Liebi Technologies "] edition = "2021" name = "lend-market" version = "0.8.0" diff --git a/pallets/lend-market/rpc/Cargo.toml b/pallets/lend-market/rpc/Cargo.toml index bf9d9e42d8..15f5b5f234 100644 --- a/pallets/lend-market/rpc/Cargo.toml +++ b/pallets/lend-market/rpc/Cargo.toml @@ -1,5 +1,5 @@ [package] -authors = ["Parallel Team", "Liebi Technologies "] +authors = ["Liebi Technologies "] edition = "2021" name = 'lend-market-rpc' version = "0.8.0" diff --git a/pallets/lend-market/rpc/runtime-api/Cargo.toml b/pallets/lend-market/rpc/runtime-api/Cargo.toml index 381688bc56..615d4e43ad 100644 --- a/pallets/lend-market/rpc/runtime-api/Cargo.toml +++ b/pallets/lend-market/rpc/runtime-api/Cargo.toml @@ -1,5 +1,5 @@ [package] -authors = ["Parallel Team", "Liebi Technologies "] +authors = ["Liebi Technologies "] edition = "2021" name = 'lend-market-rpc-runtime-api' version = "0.8.0" diff --git a/pallets/lend-market/rpc/runtime-api/src/lib.rs b/pallets/lend-market/rpc/runtime-api/src/lib.rs index 3410ec5190..48fd14b496 100644 --- a/pallets/lend-market/rpc/runtime-api/src/lib.rs +++ b/pallets/lend-market/rpc/runtime-api/src/lib.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . #![cfg_attr(not(feature = "std"), no_std)] diff --git a/pallets/lend-market/rpc/src/lib.rs b/pallets/lend-market/rpc/src/lib.rs index f995692876..88c65c78be 100644 --- a/pallets/lend-market/rpc/src/lib.rs +++ b/pallets/lend-market/rpc/src/lib.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . use std::sync::Arc; @@ -62,7 +66,10 @@ pub struct LendMarket { impl LendMarket { /// Create new `LendMarket` with the given reference to the client. pub fn new(client: Arc) -> Self { - Self { client, _marker: Default::default() } + Self { + client, + _marker: Default::default(), + } } } @@ -159,7 +166,11 @@ where /// Converts a runtime trap into an RPC error. fn runtime_error_into_rpc_error(err: impl std::fmt::Debug) -> ErrorObject<'static> { - ErrorObject::owned(Error::RuntimeError.into(), "Runtime trapped", Some(format!("{:?}", err))) + ErrorObject::owned( + Error::RuntimeError.into(), + "Runtime trapped", + Some(format!("{:?}", err)), + ) } /// Converts an account liquidity error into an RPC error. diff --git a/pallets/lend-market/src/benchmarking.rs b/pallets/lend-market/src/benchmarking.rs index dbbc991a4d..b6748310d7 100644 --- a/pallets/lend-market/src/benchmarking.rs +++ b/pallets/lend-market/src/benchmarking.rs @@ -85,7 +85,10 @@ fn set_account_borrows( AccountBorrows::::insert( asset_id, &who, - BorrowSnapshot { principal: borrow_balance, borrow_index: Rate::one() }, + BorrowSnapshot { + principal: borrow_balance, + borrow_index: Rate::one(), + }, ); TotalBorrows::::insert(asset_id, borrow_balance); T::Assets::burn_from( @@ -195,7 +198,7 @@ benchmarks! { assert_ok!(LendMarket::::mint(SystemOrigin::Signed(caller.clone()).into(), DOT_U, 100_000_000)); assert_ok!(LendMarket::::add_reward(SystemOrigin::Signed(caller.clone()).into(), 1_000_000_000_000_u128)); assert_ok!(LendMarket::::update_market_reward_speed(SystemOrigin::Root.into(), DOT_U, Some(1_000_000), Some(1_000_000))); - let target_height = frame_system::Pallet::::block_number().saturating_add(One::one()); + let target_height = T::BlockNumberProvider::current_block_number().saturating_add(One::one()); frame_system::Pallet::::set_block_number(target_height); }: _(SystemOrigin::Signed(caller.clone())) verify { @@ -210,7 +213,7 @@ benchmarks! { assert_ok!(LendMarket::::mint(SystemOrigin::Signed(caller.clone()).into(), DOT_U, 100_000_000)); assert_ok!(LendMarket::::add_reward(SystemOrigin::Signed(caller.clone()).into(), 1_000_000_000_000_u128)); assert_ok!(LendMarket::::update_market_reward_speed(SystemOrigin::Root.into(), DOT_U, Some(1_000_000), Some(1_000_000))); - let target_height = frame_system::Pallet::::block_number().saturating_add(One::one()); + let target_height = T::BlockNumberProvider::current_block_number().saturating_add(One::one()); frame_system::Pallet::::set_block_number(target_height); }: _(SystemOrigin::Signed(caller.clone()), DOT_U) verify { diff --git a/pallets/lend-market/src/farming.rs b/pallets/lend-market/src/farming.rs index 2b542d1d0a..90e51f1f6c 100644 --- a/pallets/lend-market/src/farming.rs +++ b/pallets/lend-market/src/farming.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . use sp_io::hashing::blake2_256; use sp_runtime::{traits::Zero, DispatchResult}; @@ -61,7 +65,7 @@ impl Pallet { } pub(crate) fn update_reward_supply_index(asset_id: AssetIdOf) -> DispatchResult { - let current_block_number = >::block_number(); + let current_block_number = T::BlockNumberProvider::current_block_number(); RewardSupplyState::::try_mutate(asset_id, |supply_state| -> DispatchResult { let delta_block = current_block_number.saturating_sub(supply_state.block); if delta_block.is_zero() { @@ -72,8 +76,10 @@ impl Pallet { let total_supply = TotalSupply::::get(asset_id); let delta_index = Self::calculate_reward_delta_index(delta_block, supply_speed, total_supply)?; - supply_state.index = - supply_state.index.checked_add(delta_index).ok_or(ArithmeticError::Overflow)?; + supply_state.index = supply_state + .index + .checked_add(delta_index) + .ok_or(ArithmeticError::Overflow)?; } supply_state.block = current_block_number; @@ -82,7 +88,7 @@ impl Pallet { } pub(crate) fn update_reward_borrow_index(asset_id: AssetIdOf) -> DispatchResult { - let current_block_number = >::block_number(); + let current_block_number = T::BlockNumberProvider::current_block_number(); RewardBorrowState::::try_mutate(asset_id, |borrow_state| -> DispatchResult { let delta_block = current_block_number.saturating_sub(borrow_state.block); if delta_block.is_zero() { @@ -101,8 +107,10 @@ impl Pallet { borrow_speed, base_borrow_amount, )?; - borrow_state.index = - borrow_state.index.checked_add(delta_index).ok_or(ArithmeticError::Overflow)?; + borrow_state.index = borrow_state + .index + .checked_add(delta_index) + .ok_or(ArithmeticError::Overflow)?; } borrow_state.block = current_block_number; @@ -129,8 +137,9 @@ impl Pallet { let supplier_account = AccountDeposits::::get(asset_id, supplier); let supplier_amount = supplier_account.voucher_balance; let reward_delta = Self::calculate_reward_delta(supplier_amount, delta_index)?; - *total_reward = - total_reward.checked_add(reward_delta).ok_or(ArithmeticError::Overflow)?; + *total_reward = total_reward + .checked_add(reward_delta) + .ok_or(ArithmeticError::Overflow)?; Self::deposit_event(Event::::DistributedSupplierReward( asset_id, supplier.clone(), @@ -168,8 +177,9 @@ impl Pallet { .ok_or(ArithmeticError::Overflow)?; let reward_delta = Self::calculate_reward_delta(base_borrow_amount, delta_index)?; - *total_reward = - total_reward.checked_add(reward_delta).ok_or(ArithmeticError::Overflow)?; + *total_reward = total_reward + .checked_add(reward_delta) + .ok_or(ArithmeticError::Overflow)?; Self::deposit_event(Event::::DistributedBorrowerReward( asset_id, borrower.clone(), diff --git a/pallets/lend-market/src/interest.rs b/pallets/lend-market/src/interest.rs index f09041a1dc..db257d80c6 100644 --- a/pallets/lend-market/src/interest.rs +++ b/pallets/lend-market/src/interest.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . use bifrost_primitives::{Timestamp, SECONDS_PER_YEAR}; use sp_runtime::{traits::Zero, DispatchResult}; @@ -57,7 +61,18 @@ impl Pallet { pub fn get_market_status( asset_id: AssetIdOf, - ) -> Result<(Rate, Rate, Rate, Ratio, BalanceOf, BalanceOf, FixedU128), DispatchError> { + ) -> Result< + ( + Rate, + Rate, + Rate, + Ratio, + BalanceOf, + BalanceOf, + FixedU128, + ), + DispatchError, + > { let market = Self::market(asset_id)?; let total_supply = TotalSupply::::get(asset_id); let total_cash = Self::get_total_cash(asset_id); @@ -66,8 +81,10 @@ impl Pallet { let mut borrow_index = BorrowIndex::::get(asset_id); let util = Self::calc_utilization_ratio(total_cash, total_borrows, total_reserves)?; - let borrow_rate = - market.rate_model.get_borrow_rate(util).ok_or(ArithmeticError::Overflow)?; + let borrow_rate = market + .rate_model + .get_borrow_rate(util) + .ok_or(ArithmeticError::Overflow)?; let supply_rate = InterestRateModel::get_supply_rate(borrow_rate, util, market.reserve_factor); @@ -141,8 +158,8 @@ impl Pallet { /// The exchange rate should be greater than 0.02 and less than 1 pub(crate) fn ensure_valid_exchange_rate(exchange_rate: Rate) -> DispatchResult { ensure!( - exchange_rate >= Rate::from_inner(MIN_EXCHANGE_RATE) && - exchange_rate < Rate::from_inner(MAX_EXCHANGE_RATE), + exchange_rate >= Rate::from_inner(MIN_EXCHANGE_RATE) + && exchange_rate < Rate::from_inner(MAX_EXCHANGE_RATE), Error::::InvalidExchangeRate ); diff --git a/pallets/lend-market/src/lend_token.rs b/pallets/lend-market/src/lend_token.rs index 284f103225..9cde2e7a84 100644 --- a/pallets/lend-market/src/lend_token.rs +++ b/pallets/lend-market/src/lend_token.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . use crate::{types::Deposits, AssetIdOf, BalanceOf, *}; use frame_support::{ @@ -77,7 +81,10 @@ impl Inspect for Pallet { return res; } - if TotalSupply::::get(underlying_id).checked_add(amount).is_none() { + if TotalSupply::::get(underlying_id) + .checked_add(amount) + .is_none() + { return DepositConsequence::Overflow; } @@ -141,8 +148,8 @@ impl Pallet { _keep_alive: bool, ) -> Result, DispatchError> { ensure!( - amount <= - Self::reducible_balance( + amount + <= Self::reducible_balance( lend_token_id, source, Preservation::Expendable, @@ -173,8 +180,10 @@ impl Pallet { source, |deposits| -> DispatchResult { let mut d = deposits.unwrap_or_default(); - d.voucher_balance = - d.voucher_balance.checked_sub(amount).ok_or(ArithmeticError::Underflow)?; + d.voucher_balance = d + .voucher_balance + .checked_sub(amount) + .ok_or(ArithmeticError::Underflow)?; if d.voucher_balance.is_zero() { // remove deposits storage if zero balance *deposits = None; @@ -186,8 +195,10 @@ impl Pallet { )?; AccountDeposits::::try_mutate(underlying_id, dest, |deposits| -> DispatchResult { - deposits.voucher_balance = - deposits.voucher_balance.checked_add(amount).ok_or(ArithmeticError::Overflow)?; + deposits.voucher_balance = deposits + .voucher_balance + .checked_add(amount) + .ok_or(ArithmeticError::Overflow)?; Ok(()) })?; @@ -199,8 +210,10 @@ impl Pallet { who: &T::AccountId, ) -> Result, DispatchError> { let underlying_id = Self::underlying_id(lend_token_id)?; - let Deposits { is_collateral, voucher_balance } = - AccountDeposits::::get(underlying_id, who); + let Deposits { + is_collateral, + voucher_balance, + } = AccountDeposits::::get(underlying_id, who); if !is_collateral { return Ok(voucher_balance); diff --git a/pallets/lend-market/src/lib.rs b/pallets/lend-market/src/lib.rs index f5ad462b26..d8eef85465 100644 --- a/pallets/lend-market/src/lib.rs +++ b/pallets/lend-market/src/lib.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . //! # LendMarket pallet //! @@ -48,8 +52,8 @@ use pallet_traits::{ use sp_core::bounded::BoundedVec; use sp_runtime::{ traits::{ - AccountIdConversion, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, - SaturatedConversion, Saturating, StaticLookup, Zero, + AccountIdConversion, BlockNumberProvider, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, + One, SaturatedConversion, Saturating, StaticLookup, Zero, }, ArithmeticError, FixedPointNumber, FixedU128, }; @@ -128,6 +132,9 @@ pub mod pallet { #[pallet::constant] type MaxLengthLimit: Get; + + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::error] @@ -467,20 +474,26 @@ pub mod pallet { market: Market>, ) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; - ensure!(!Markets::::contains_key(asset_id), Error::::MarketAlreadyExists); + ensure!( + !Markets::::contains_key(asset_id), + Error::::MarketAlreadyExists + ); ensure!( market.state == MarketState::Pending, Error::::NewMarketMustHavePendingState ); - ensure!(market.rate_model.check_model(), Error::::InvalidRateModelParam); ensure!( - market.collateral_factor >= Ratio::zero() && - market.collateral_factor < Ratio::one(), + market.rate_model.check_model(), + Error::::InvalidRateModelParam + ); + ensure!( + market.collateral_factor >= Ratio::zero() + && market.collateral_factor < Ratio::one(), Error::::InvalidFactor, ); ensure!( - market.liquidation_threshold < Ratio::one() && - market.liquidation_threshold >= market.collateral_factor, + market.liquidation_threshold < Ratio::one() + && market.liquidation_threshold >= market.collateral_factor, Error::::InvalidFactor ); ensure!( @@ -488,11 +501,14 @@ pub mod pallet { Error::::InvalidFactor, ); ensure!( - market.liquidate_incentive_reserved_factor > Ratio::zero() && - market.liquidate_incentive_reserved_factor < Ratio::one(), + market.liquidate_incentive_reserved_factor > Ratio::zero() + && market.liquidate_incentive_reserved_factor < Ratio::one(), Error::::InvalidFactor, ); - ensure!(market.supply_cap > Zero::zero(), Error::::InvalidSupplyCap,); + ensure!( + market.supply_cap > Zero::zero(), + Error::::InvalidSupplyCap, + ); // Ensures a given `lend_token_id` not exists on the `Market` and `UnderlyingAssetId`. Self::ensure_lend_token(market.lend_token_id)?; @@ -643,7 +659,10 @@ pub mod pallet { market: Market>, ) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; - ensure!(market.rate_model.check_model(), Error::::InvalidRateModelParam); + ensure!( + market.rate_model.check_model(), + Error::::InvalidRateModelParam + ); if UnderlyingAssetId::::contains_key(market.lend_token_id) { ensure!( Self::underlying_id(market.lend_token_id)? == asset_id, @@ -676,7 +695,13 @@ pub mod pallet { let reward_asset = T::RewardAssetId::get(); let pool_account = Self::reward_account_id()?; - T::Assets::transfer(reward_asset, &who, &pool_account, amount, Preservation::Preserve)?; + T::Assets::transfer( + reward_asset, + &who, + &pool_account, + amount, + Preservation::Preserve, + )?; Self::deposit_event(Event::::RewardAdded(who, amount)); @@ -923,7 +948,10 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; Self::ensure_active_market(asset_id)?; - ensure!(AccountDeposits::::contains_key(asset_id, &who), Error::::NoDeposit); + ensure!( + AccountDeposits::::contains_key(asset_id, &who), + Error::::NoDeposit + ); let deposits = AccountDeposits::::get(asset_id, &who); if deposits.is_collateral == enable { return Err(Error::::DuplicateOperation.into()); @@ -995,8 +1023,9 @@ pub mod pallet { Preservation::Expendable, )?; let total_reserves = TotalReserves::::get(asset_id); - let total_reserves_new = - total_reserves.checked_add(add_amount).ok_or(ArithmeticError::Overflow)?; + let total_reserves_new = total_reserves + .checked_add(add_amount) + .ok_or(ArithmeticError::Overflow)?; TotalReserves::::insert(asset_id, total_reserves_new); Self::deposit_event(Event::::ReservesAdded( @@ -1033,8 +1062,9 @@ pub mod pallet { if reduce_amount > total_reserves { return Err(Error::::InsufficientReserves.into()); } - let total_reserves_new = - total_reserves.checked_sub(reduce_amount).ok_or(ArithmeticError::Underflow)?; + let total_reserves_new = total_reserves + .checked_sub(reduce_amount) + .ok_or(ArithmeticError::Underflow)?; TotalReserves::::insert(asset_id, total_reserves_new); T::Assets::transfer( asset_id, @@ -1130,7 +1160,10 @@ pub mod pallet { .map_err(|_| Error::::ConversionError)?, ); - Self::deposit_event(Event::::MarketBonded { asset_id, market_bond }); + Self::deposit_event(Event::::MarketBonded { + asset_id, + market_bond, + }); Ok(().into()) } } @@ -1190,7 +1223,10 @@ impl Pallet { lf_borrowed_value.into_inner(), lf_base_position.into_inner(), ); - match (total_collateral_value > total_borrow_value, lf_base_position > lf_borrowed_value) { + match ( + total_collateral_value > total_borrow_value, + lf_base_position > lf_borrowed_value, + ) { (true, true) => Ok(( total_collateral_value - total_borrow_value, FixedU128::zero(), @@ -1237,7 +1273,10 @@ impl Pallet { lf_base_position.into_inner(), ); - match (total_collateral_value > total_borrow_value, lf_base_position > lf_borrowed_value) { + match ( + total_collateral_value > total_borrow_value, + lf_base_position > lf_borrowed_value, + ) { (true, true) => Ok(( total_collateral_value - total_borrow_value, FixedU128::zero(), @@ -1352,7 +1391,9 @@ impl Pallet { let mut total_asset_value: FixedU128 = FixedU128::zero(); for (asset_id, _market) in Self::active_markets() { total_asset_value = total_asset_value - .checked_add(&Self::liquidation_threshold_asset_value(borrower, asset_id)?) + .checked_add(&Self::liquidation_threshold_asset_value( + borrower, asset_id, + )?) .ok_or(ArithmeticError::Overflow)?; } @@ -1432,8 +1473,9 @@ impl Pallet { Ok(()) })?; TotalSupply::::try_mutate(asset_id, |total_balance| -> DispatchResult { - let new_balance = - total_balance.checked_sub(voucher_amount).ok_or(ArithmeticError::Underflow)?; + let new_balance = total_balance + .checked_sub(voucher_amount) + .ok_or(ArithmeticError::Underflow)?; *total_balance = new_balance; Ok(()) })?; @@ -1501,8 +1543,9 @@ impl Pallet { repay_amount, Preservation::Expendable, )?; - let account_borrows_new = - account_borrows.checked_sub(repay_amount).ok_or(ArithmeticError::Underflow)?; + let account_borrows_new = account_borrows + .checked_sub(repay_amount) + .ok_or(ArithmeticError::Underflow)?; let total_borrows = TotalBorrows::::get(asset_id); // NOTE : total_borrows use a different way to calculate interest // so when user repays all borrows, total_borrows can be less than account_borrows @@ -1613,8 +1656,10 @@ impl Pallet { account_borrows_value }; - if market.close_factor.mul_ceil(effects_borrows_value.into_inner()) < - repay_value.into_inner() + if market + .close_factor + .mul_ceil(effects_borrows_value.into_inner()) + < repay_value.into_inner() { return Err(Error::::TooMuchRepay.into()); } @@ -1736,11 +1781,13 @@ impl Pallet { // 2.the system reduce borrower's debt let account_borrows = Self::current_borrow_balance(borrower, liquidation_asset_id)?; - let account_borrows_new = - account_borrows.checked_sub(repay_amount).ok_or(ArithmeticError::Underflow)?; + let account_borrows_new = account_borrows + .checked_sub(repay_amount) + .ok_or(ArithmeticError::Underflow)?; let total_borrows = TotalBorrows::::get(liquidation_asset_id); - let total_borrows_new = - total_borrows.checked_sub(repay_amount).ok_or(ArithmeticError::Underflow)?; + let total_borrows_new = total_borrows + .checked_sub(repay_amount) + .ok_or(ArithmeticError::Underflow)?; AccountBorrows::::insert( liquidation_asset_id, borrower, @@ -1831,8 +1878,13 @@ impl Pallet { let market = Self::market(asset_id)?; // Assets holded by market currently. let current_cash = T::Assets::balance(asset_id, &Self::account_id()); - let total_cash = current_cash.checked_add(amount).ok_or(ArithmeticError::Overflow)?; - ensure!(total_cash <= market.supply_cap, Error::::SupplyCapacityExceeded); + let total_cash = current_cash + .checked_add(amount) + .ok_or(ArithmeticError::Overflow)?; + ensure!( + total_cash <= market.supply_cap, + Error::::SupplyCapacityExceeded + ); Ok(()) } @@ -1841,9 +1893,13 @@ impl Pallet { fn ensure_under_borrow_cap(asset_id: AssetIdOf, amount: BalanceOf) -> DispatchResult { let market = Self::market(asset_id)?; let total_borrows = TotalBorrows::::get(asset_id); - let new_total_borrows = - total_borrows.checked_add(amount).ok_or(ArithmeticError::Overflow)?; - ensure!(new_total_borrows <= market.borrow_cap, Error::::BorrowCapacityExceeded); + let new_total_borrows = total_borrows + .checked_add(amount) + .ok_or(ArithmeticError::Overflow)?; + ensure!( + new_total_borrows <= market.borrow_cap, + Error::::BorrowCapacityExceeded + ); Ok(()) } @@ -1869,7 +1925,10 @@ impl Pallet { ); // The lend token id should not be the same as the id of any asset in markets - ensure!(!Markets::::contains_key(lend_token_id), Error::::InvalidLendTokenId); + ensure!( + !Markets::::contains_key(lend_token_id), + Error::::InvalidLendTokenId + ); Ok(()) } @@ -1931,7 +1990,9 @@ impl Pallet { voucher_amount: BalanceOf, exchange_rate: Rate, ) -> Result, DispatchError> { - Ok(exchange_rate.checked_mul_int(voucher_amount).ok_or(ArithmeticError::Overflow)?) + Ok(exchange_rate + .checked_mul_int(voucher_amount) + .ok_or(ArithmeticError::Overflow)?) } pub fn calc_collateral_amount( @@ -2007,12 +2068,15 @@ impl Pallet { where F: FnOnce(&mut Market>) -> Market>, { - Markets::::try_mutate(asset_id, |opt| -> Result>, DispatchError> { - if let Some(market) = opt { - return Ok(cb(market)); - } - Err(Error::::MarketDoesNotExist.into()) - }) + Markets::::try_mutate( + asset_id, + |opt| -> Result>, DispatchError> { + if let Some(market) = opt { + return Ok(cb(market)); + } + Err(Error::::MarketDoesNotExist.into()) + }, + ) } // All markets that are `MarketStatus::Active`. @@ -2097,8 +2161,9 @@ impl LendMarketTrait, AccountIdOf, BalanceOf> for Ok(()) })?; TotalSupply::::try_mutate(asset_id, |total_balance| -> DispatchResult { - let new_balance = - total_balance.checked_add(voucher_amount).ok_or(ArithmeticError::Overflow)?; + let new_balance = total_balance + .checked_add(voucher_amount) + .ok_or(ArithmeticError::Overflow)?; *total_balance = new_balance; Ok(()) })?; @@ -2122,11 +2187,13 @@ impl LendMarketTrait, AccountIdOf, BalanceOf> for Self::distribute_borrower_reward(asset_id, borrower)?; let account_borrows = Self::current_borrow_balance(borrower, asset_id)?; - let account_borrows_new = - account_borrows.checked_add(amount).ok_or(ArithmeticError::Overflow)?; + let account_borrows_new = account_borrows + .checked_add(amount) + .ok_or(ArithmeticError::Overflow)?; let total_borrows = TotalBorrows::::get(asset_id); - let total_borrows_new = - total_borrows.checked_add(amount).ok_or(ArithmeticError::Overflow)?; + let total_borrows_new = total_borrows + .checked_add(amount) + .ok_or(ArithmeticError::Overflow)?; AccountBorrows::::insert( asset_id, borrower, @@ -2153,7 +2220,10 @@ impl LendMarketTrait, AccountIdOf, BalanceOf> for enable: bool, ) -> Result<(), DispatchError> { Self::ensure_active_market(asset_id)?; - ensure!(AccountDeposits::::contains_key(asset_id, supplier), Error::::NoDeposit); + ensure!( + AccountDeposits::::contains_key(asset_id, supplier), + Error::::NoDeposit + ); let mut deposits = AccountDeposits::::get(asset_id, supplier); // turn on the collateral button if enable { @@ -2173,8 +2243,8 @@ impl LendMarketTrait, AccountIdOf, BalanceOf> for collateral_asset_value.into_inner(), total_borrowed_value.into_inner(), ); - if total_collateral_value < - total_borrowed_value + if total_collateral_value + < total_borrowed_value .checked_add(&collateral_asset_value) .ok_or(ArithmeticError::Overflow)? { @@ -2183,7 +2253,10 @@ impl LendMarketTrait, AccountIdOf, BalanceOf> for deposits.is_collateral = false; AccountDeposits::::insert(asset_id, supplier, deposits); - Self::deposit_event(Event::::CollateralAssetRemoved(supplier.clone(), asset_id)); + Self::deposit_event(Event::::CollateralAssetRemoved( + supplier.clone(), + asset_id, + )); Ok(()) } @@ -2212,7 +2285,11 @@ impl LendMarketTrait, AccountIdOf, BalanceOf> for Self::update_earned_stored(supplier, asset_id, exchange_rate)?; let voucher_amount = Self::calc_collateral_amount(amount, exchange_rate)?; let redeem_amount = Self::do_redeem_voucher(supplier, asset_id, voucher_amount)?; - Self::deposit_event(Event::::Redeemed(supplier.clone(), asset_id, redeem_amount)); + Self::deposit_event(Event::::Redeemed( + supplier.clone(), + asset_id, + redeem_amount, + )); Ok(()) } } diff --git a/pallets/lend-market/src/migrations/v1.rs b/pallets/lend-market/src/migrations/v1.rs index e79155a624..d60ba91f7f 100644 --- a/pallets/lend-market/src/migrations/v1.rs +++ b/pallets/lend-market/src/migrations/v1.rs @@ -18,11 +18,9 @@ use crate::*; use frame_support::{ - ensure, pallet_prelude::StorageVersion, - traits::{GetStorageVersion, Len, OnRuntimeUpgrade}, + traits::{GetStorageVersion, OnRuntimeUpgrade}, }; -use parity_scale_codec::{Decode, Encode}; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -95,7 +93,11 @@ impl OnRuntimeUpgrade for MigrateToV1 { // print out the pre-migrate storage count log::info!(target: LOG_TARGET, "LiquidationFreeCollaterals pre-migrate storage count: {:?}", liquidation_free_collaterals_count); log::info!(target: LOG_TARGET, "MarketBond pre-migrate storage count: {:?}", market_bond_count); - Ok((liquidation_free_collaterals_count as u64, market_bond_count as u64).encode()) + Ok(( + liquidation_free_collaterals_count as u64, + market_bond_count as u64, + ) + .encode()) } #[cfg(feature = "try-runtime")] diff --git a/pallets/lend-market/src/mock.rs b/pallets/lend-market/src/mock.rs index 332debd7d5..63ea2fcfce 100644 --- a/pallets/lend-market/src/mock.rs +++ b/pallets/lend-market/src/mock.rs @@ -1,16 +1,21 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 - -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + #![allow(ambiguous_glob_reexports)] #![allow(hidden_glob_reexports)] @@ -160,7 +165,10 @@ pub type TimeStampedPrice = orml_oracle::TimestampedValue; pub struct MockDataProvider; impl DataProvider for MockDataProvider { fn get(_asset_id: &CurrencyId) -> Option { - Some(TimeStampedPrice { value: Price::saturating_from_integer(100), timestamp: 0 }) + Some(TimeStampedPrice { + value: Price::saturating_from_integer(100), + timestamp: 0, + }) } } @@ -227,7 +235,9 @@ impl MockOraclePriceProvider { pub fn set_price(asset_id: CurrencyId, price: Price) { Self::PRICES.with(|prices| { - prices.borrow_mut().insert(CurrencyIdWrap(asset_id), Some((price, 1u64))); + prices + .borrow_mut() + .insert(CurrencyIdWrap(asset_id), Some((price, 1u64))); }); } @@ -323,10 +333,13 @@ impl Config for Test { type RewardAssetId = RewardAssetId; type LiquidationFreeAssetId = LiquidationFreeAssetId; type MaxLengthLimit = MaxLengthLimit; + type BlockNumberProvider = System; } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); bifrost_asset_registry::GenesisConfig:: { currency: vec![ @@ -389,7 +402,13 @@ pub(crate) fn new_test_ext() -> sp_io::TestExternalities { Assets::mint(RuntimeOrigin::signed(ALICE), KSM.into(), ALICE, unit(1000)).unwrap(); Assets::mint(RuntimeOrigin::signed(ALICE), DOT.into(), ALICE, unit(1000)).unwrap(); - Assets::mint(RuntimeOrigin::signed(ALICE), DOT_U.into(), ALICE, unit(1000)).unwrap(); + Assets::mint( + RuntimeOrigin::signed(ALICE), + DOT_U.into(), + ALICE, + unit(1000), + ) + .unwrap(); Assets::mint(RuntimeOrigin::signed(ALICE), PHA.into(), ALICE, unit(1000)).unwrap(); Assets::mint(RuntimeOrigin::signed(ALICE), KSM.into(), BOB, unit(1000)).unwrap(); Assets::mint(RuntimeOrigin::signed(ALICE), DOT.into(), BOB, unit(1000)).unwrap(); diff --git a/pallets/lend-market/src/rate_model.rs b/pallets/lend-market/src/rate_model.rs index 8d674d36aa..bdcf9ddc74 100644 --- a/pallets/lend-market/src/rate_model.rs +++ b/pallets/lend-market/src/rate_model.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . use bifrost_primitives::{Rate, Ratio}; use scale_info::TypeInfo; @@ -44,7 +48,12 @@ impl InterestRateModel { full_rate: Rate, jump_utilization: Ratio, ) -> Self { - Self::Jump(JumpModel::new_model(base_rate, jump_rate, full_rate, jump_utilization)) + Self::Jump(JumpModel::new_model( + base_rate, + jump_rate, + full_rate, + jump_utilization, + )) } pub fn new_curve_model(base_rate: Rate) -> Self { @@ -102,14 +111,19 @@ impl JumpModel { full_rate: Rate, jump_utilization: Ratio, ) -> JumpModel { - Self { base_rate, jump_rate, full_rate, jump_utilization } + Self { + base_rate, + jump_rate, + full_rate, + jump_utilization, + } } /// Check the jump model for sanity pub fn check_model(&self) -> bool { - if self.base_rate > Self::MAX_BASE_RATE || - self.jump_rate > Self::MAX_JUMP_RATE || - self.full_rate > Self::MAX_FULL_RATE + if self.base_rate > Self::MAX_BASE_RATE + || self.jump_rate > Self::MAX_JUMP_RATE + || self.full_rate > Self::MAX_FULL_RATE { return false; } @@ -172,7 +186,9 @@ impl CurveModel { pub fn get_borrow_rate(&self, utilization: Ratio) -> Option { const NINE: usize = 9; let utilization_rate: Rate = utilization.into(); - utilization_rate.saturating_pow(NINE).checked_add(&self.base_rate) + utilization_rate + .saturating_pow(NINE) + .checked_add(&self.base_rate) } } @@ -229,9 +245,9 @@ mod tests { let excess_util = util.saturating_sub(jump_utilization); assert_eq!( borrow_rate, - (jump_model.full_rate - jump_model.jump_rate).saturating_mul(excess_util.into()) / - FixedU128::saturating_from_rational(20, 100) + - normal_rate, + (jump_model.full_rate - jump_model.jump_rate).saturating_mul(excess_util.into()) + / FixedU128::saturating_from_rational(20, 100) + + normal_rate, ); } diff --git a/pallets/lend-market/src/tests.rs b/pallets/lend-market/src/tests.rs index b17c7a9dfe..9e9e9c4501 100644 --- a/pallets/lend-market/src/tests.rs +++ b/pallets/lend-market/src/tests.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . mod edge_cases; mod interest_rate; @@ -71,15 +75,27 @@ fn init_markets_ok() { )); assert_eq!(LendMarket::market(KSM).unwrap().state, MarketState::Active); assert_eq!(LendMarket::market(DOT).unwrap().state, MarketState::Active); - assert_eq!(LendMarket::market(DOT_U).unwrap().state, MarketState::Active); + assert_eq!( + LendMarket::market(DOT_U).unwrap().state, + MarketState::Active + ); assert_eq!(BorrowIndex::::get(BNC), Rate::one()); assert_eq!(BorrowIndex::::get(KSM), Rate::one()); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); assert_eq!(BorrowIndex::::get(DOT_U), Rate::one()); - assert_eq!(ExchangeRate::::get(KSM), Rate::saturating_from_rational(2, 100)); - assert_eq!(ExchangeRate::::get(DOT), Rate::saturating_from_rational(2, 100)); - assert_eq!(ExchangeRate::::get(DOT_U), Rate::saturating_from_rational(2, 100)); + assert_eq!( + ExchangeRate::::get(KSM), + Rate::saturating_from_rational(2, 100) + ); + assert_eq!( + ExchangeRate::::get(DOT), + Rate::saturating_from_rational(2, 100) + ); + assert_eq!( + ExchangeRate::::get(DOT_U), + Rate::saturating_from_rational(2, 100) + ); }); } @@ -104,8 +120,15 @@ fn lend_market_native_token_works() { assert_eq!(::Assets::balance(BNC, &DAVE), unit(1000)); assert_eq!(LendMarket::market(BNC).unwrap().state, MarketState::Active); assert_eq!(BorrowIndex::::get(BNC), Rate::one()); - assert_eq!(ExchangeRate::::get(BNC), Rate::saturating_from_rational(2, 100)); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(DAVE), BNC, unit(1000))); + assert_eq!( + ExchangeRate::::get(BNC), + Rate::saturating_from_rational(2, 100) + ); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(DAVE), + BNC, + unit(1000) + )); // Redeem 1001 BNC should cause InsufficientDeposit assert_noop!( @@ -115,12 +138,24 @@ fn lend_market_native_token_works() { // Redeem 1000 BNC is ok assert_ok!(LendMarket::redeem_allowed(BNC, &DAVE, unit(50000),)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(DAVE), BNC, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(DAVE), + BNC, + true + )); // Borrow 500 BNC will reduce 500 BNC liquidity for collateral_factor is 50% - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(DAVE), BNC, unit(500))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(500) + )); // Repay 400 BNC - assert_ok!(LendMarket::repay_borrow(RuntimeOrigin::signed(DAVE), BNC, unit(400))); + assert_ok!(LendMarket::repay_borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(400) + )); // BNC collateral: deposit = 1000 // BNC borrow balance: borrow - repay = 500 - 400 = 100 @@ -156,7 +191,11 @@ fn mint_works() { vec![DOT, BNC, KSM, DOT_U, PHA] )); // Deposit 100 DOT - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); // DOT collateral: deposit = 100 // DOT: cash - deposit = 1000 - 100 = 900 @@ -166,7 +205,10 @@ fn mint_works() { unit(100) ); assert_eq!(::Assets::balance(DOT, &ALICE), unit(900),); - assert_eq!(::Assets::balance(DOT, &LendMarket::account_id()), unit(100),); + assert_eq!( + ::Assets::balance(DOT, &LendMarket::account_id()), + unit(100), + ); }) } @@ -191,7 +233,10 @@ fn mint_must_return_err_when_overflows_occur() { LendMarket::force_update_market( RuntimeOrigin::root(), DOT, - Market { supply_cap: u128::MAX, ..ACTIVE_MARKET_MOCK }, + Market { + supply_cap: u128::MAX, + ..ACTIVE_MARKET_MOCK + }, ) .unwrap(); // MAX_DEPOSIT = u128::MAX * exchangeRate @@ -263,7 +308,11 @@ fn redeem_allowed_works() { // Redeem 200 KSM is ok assert_ok!(LendMarket::redeem_allowed(KSM, &ALICE, 10000)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); // Borrow 50 DOT will reduce 100 KSM liquidity for collateral_factor is 50% assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, 50)); // Redeem 101 KSM should cause InsufficientLiquidity @@ -350,8 +399,16 @@ fn redeem_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(20))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(20) + )); // DOT collateral: deposit - redeem = 100 - 20 = 80 // DOT: cash - deposit + redeem = 1000 - 100 + 20 = 920 @@ -413,7 +470,11 @@ fn redeem_fails_when_insufficient_liquidity() { // Deposit 200 KSM as collateral assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, 200)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); // Borrow 50 DOT will reduce 100 KSM liquidity for collateral_factor is 50% assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, 50)); @@ -448,10 +509,19 @@ fn redeem_fails_when_would_use_reserved_balanace() { // Deposit 200 KSM as collateral assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, 200)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); // Borrow 50 DOT will reduce 100 KSM liquidity for collateral_factor is 50% assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, 50)); - assert_ok!(LendMarket::add_reserves(RuntimeOrigin::root(), ALICE, DOT, 50)); + assert_ok!(LendMarket::add_reserves( + RuntimeOrigin::root(), + ALICE, + DOT, + 50 + )); assert_noop!( LendMarket::redeem(RuntimeOrigin::signed(BOB), DOT, 151), @@ -505,7 +575,11 @@ fn redeem_all_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); assert_ok!(LendMarket::redeem_all(RuntimeOrigin::signed(ALICE), DOT)); // DOT: cash - deposit + redeem = 1000 - 100 + 100 = 1000 @@ -541,7 +615,11 @@ fn borrow_allowed_works() { // Deposit 200 DOT as collateral assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, 200)); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, 200)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); // Borrow 101 DOT should cause InsufficientLiquidity assert_noop!( LendMarket::borrow_allowed(DOT, &ALICE, 101), @@ -554,7 +632,10 @@ fn borrow_allowed_works() { assert_ok!(LendMarket::force_update_market( RuntimeOrigin::root(), DOT, - Market { borrow_cap: 10, ..ACTIVE_MARKET_MOCK }, + Market { + borrow_cap: 10, + ..ACTIVE_MARKET_MOCK + }, )); // Borrow 10 DOT is ok assert_ok!(LendMarket::borrow_allowed(DOT, &ALICE, 10)); @@ -722,10 +803,22 @@ fn borrow_works() { vec![DOT, BNC, KSM, DOT_U, PHA] )); // Deposit 200 DOT as collateral - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); // Borrow 100 DOT - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); // DOT collateral: deposit = 200 // DOT borrow balance: borrow = 100 @@ -766,7 +859,11 @@ fn lf_borrow_works() { LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), PHA, true).unwrap(); // Borrow 100 DOT - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); // CDOT collateral: deposit = 200 // DOT borrow balance: borrow = 100 @@ -802,12 +899,28 @@ fn repay_borrow_works() { vec![DOT, BNC, KSM, DOT_U, PHA] )); // Deposit 200 DOT as collateral - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); // Borrow 100 DOT - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); // Repay 30 DOT - assert_ok!(LendMarket::repay_borrow(RuntimeOrigin::signed(ALICE), DOT, unit(30))); + assert_ok!(LendMarket::repay_borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(30) + )); // DOT collateral: deposit = 200 // DOT borrow balance: borrow - repay = 100 - 30 = 70 @@ -845,13 +958,28 @@ fn repay_borrow_all_works() { // Bob deposits 200 KSM assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), KSM, unit(200))); // Alice deposit 200 DOT as collateral - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); // Alice borrow 50 KSM - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(50))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(50) + )); // Alice repay all borrow balance - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), KSM)); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + KSM + )); // DOT: cash - deposit + = 1000 - 200 = 800 // DOT collateral: deposit = 200 @@ -894,7 +1022,11 @@ fn collateral_asset_works() { ); // Deposit 200 DOT as collateral assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, 200)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); assert_eq!(AccountDeposits::::get(DOT, ALICE).is_collateral, true); assert_noop!( LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true), @@ -907,9 +1039,19 @@ fn collateral_asset_works() { Error::::InsufficientLiquidity ); // Repay all the borrows - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), DOT)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, false)); - assert_eq!(AccountDeposits::::get(DOT, ALICE).is_collateral, false); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + DOT + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + false + )); + assert_eq!( + AccountDeposits::::get(DOT, ALICE).is_collateral, + false + ); assert_noop!( LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, false), Error::::DuplicateOperation @@ -937,11 +1079,31 @@ fn total_collateral_value_works() { )); // Mock the price for DOT = 1, KSM = 1 let collateral_factor = Rate::saturating_from_rational(50, 100); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(200))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT_U, unit(300))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(200) + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT_U, + unit(300) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); assert_eq!( LendMarket::total_collateral_value(&ALICE).unwrap(), (collateral_factor.saturating_mul(FixedU128::from_inner(unit(100) + unit(200)))) @@ -968,10 +1130,18 @@ fn add_reserves_works() { vec![DOT, BNC, KSM, DOT_U, PHA] )); // Add 100 DOT reserves - assert_ok!(LendMarket::add_reserves(RuntimeOrigin::root(), ALICE, DOT, unit(100))); + assert_ok!(LendMarket::add_reserves( + RuntimeOrigin::root(), + ALICE, + DOT, + unit(100) + )); assert_eq!(TotalReserves::::get(DOT), unit(100)); - assert_eq!(::Assets::balance(DOT, &LendMarket::account_id()), unit(100),); + assert_eq!( + ::Assets::balance(DOT, &LendMarket::account_id()), + unit(100), + ); assert_eq!(::Assets::balance(DOT, &ALICE), unit(900),); }) } @@ -995,13 +1165,26 @@ fn reduce_reserves_works() { vec![DOT, BNC, KSM, DOT_U, PHA] )); // Add 100 DOT reserves - assert_ok!(LendMarket::add_reserves(RuntimeOrigin::root(), ALICE, DOT, unit(100))); + assert_ok!(LendMarket::add_reserves( + RuntimeOrigin::root(), + ALICE, + DOT, + unit(100) + )); // Reduce 20 DOT reserves - assert_ok!(LendMarket::reduce_reserves(RuntimeOrigin::root(), ALICE, DOT, unit(20))); + assert_ok!(LendMarket::reduce_reserves( + RuntimeOrigin::root(), + ALICE, + DOT, + unit(20) + )); assert_eq!(TotalReserves::::get(DOT), unit(80)); - assert_eq!(::Assets::balance(DOT, &LendMarket::account_id()), unit(80),); + assert_eq!( + ::Assets::balance(DOT, &LendMarket::account_id()), + unit(80), + ); assert_eq!(::Assets::balance(DOT, &ALICE), unit(920),); }) } @@ -1024,7 +1207,12 @@ fn reduce_reserve_reduce_amount_must_be_less_than_total_reserves() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::add_reserves(RuntimeOrigin::root(), ALICE, DOT, unit(100))); + assert_ok!(LendMarket::add_reserves( + RuntimeOrigin::root(), + ALICE, + DOT, + unit(100) + )); assert_noop!( LendMarket::reduce_reserves(RuntimeOrigin::root(), ALICE, DOT, unit(200)), Error::::InsufficientReserves @@ -1062,14 +1250,26 @@ fn ratio_and_rate_works() { // FixedU128 (one = 1_000_000_000_000_000_000_000) let value1 = FixedU128::saturating_from_integer(100); let value2 = FixedU128::saturating_from_integer(10); - assert_eq!(value1.checked_mul(&value2), Some(FixedU128::saturating_from_integer(1000))); - assert_eq!(value1.checked_div(&value2), Some(FixedU128::saturating_from_integer(10))); - assert_eq!(value1.saturating_mul(permill.into()), FixedU128::saturating_from_integer(50)); + assert_eq!( + value1.checked_mul(&value2), + Some(FixedU128::saturating_from_integer(1000)) + ); + assert_eq!( + value1.checked_div(&value2), + Some(FixedU128::saturating_from_integer(10)) + ); + assert_eq!( + value1.saturating_mul(permill.into()), + FixedU128::saturating_from_integer(50) + ); let value1 = FixedU128::saturating_from_rational(9, 10); let value2 = 10_u128; let value3 = FixedU128::saturating_from_integer(10_u128); - assert_eq!(value1.reciprocal(), Some(FixedU128::saturating_from_rational(10, 9))); + assert_eq!( + value1.reciprocal(), + Some(FixedU128::saturating_from_rational(10, 9)) + ); // u128 div FixedU128 assert_eq!( FixedU128::saturating_from_integer(value2).checked_div(&value1), @@ -1077,7 +1277,10 @@ fn ratio_and_rate_works() { ); // FixedU128 div u128 - assert_eq!(value1.reciprocal().and_then(|r| r.checked_mul_int(value2)), Some(11)); + assert_eq!( + value1.reciprocal().and_then(|r| r.checked_mul_int(value2)), + Some(11) + ); assert_eq!( FixedU128::from_inner(17_777_777_777_777_777_777).checked_div_int(value2), Some(1) @@ -1158,7 +1361,10 @@ fn update_exchange_rate_works() { vec![DOT, BNC, KSM, DOT_U, PHA] )); // Initialize value of exchange rate is 0.02 - assert_eq!(ExchangeRate::::get(DOT), Rate::saturating_from_rational(2, 100)); + assert_eq!( + ExchangeRate::::get(DOT), + Rate::saturating_from_rational(2, 100) + ); // total_supply = 0 TotalSupply::::insert(DOT, 0); @@ -1171,7 +1377,11 @@ fn update_exchange_rate_works() { // exchange_rate = total_cash + total_borrows - total_reverse / total_supply // total_cash = 10, total_supply = 500 // exchange_rate = 10 + 5 - 1 / 500 - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); TotalBorrows::::insert(DOT, unit(5)); TotalReserves::::insert(DOT, unit(1)); // assert_ok!(LendMarket::update_exchange_rate(DOT)); @@ -1204,7 +1414,10 @@ fn current_borrow_balance_works() { AccountBorrows::::insert( DOT, ALICE, - BorrowSnapshot { principal: 0, borrow_index: Rate::one() }, + BorrowSnapshot { + principal: 0, + borrow_index: Rate::one(), + }, ); assert_eq!(LendMarket::current_borrow_balance(&ALICE, DOT).unwrap(), 0); @@ -1212,7 +1425,10 @@ fn current_borrow_balance_works() { AccountBorrows::::insert( DOT, ALICE, - BorrowSnapshot { principal: 100, borrow_index: Rate::zero() }, + BorrowSnapshot { + principal: 100, + borrow_index: Rate::zero(), + }, ); assert_eq!(LendMarket::current_borrow_balance(&ALICE, DOT).unwrap(), 0); @@ -1221,16 +1437,25 @@ fn current_borrow_balance_works() { AccountBorrows::::insert( DOT, ALICE, - BorrowSnapshot { principal: 100, borrow_index: Rate::one() }, + BorrowSnapshot { + principal: 100, + borrow_index: Rate::one(), + }, + ); + assert_eq!( + LendMarket::current_borrow_balance(&ALICE, DOT).unwrap(), + 120 ); - assert_eq!(LendMarket::current_borrow_balance(&ALICE, DOT).unwrap(), 120); }) } #[test] fn calc_collateral_amount_works() { let exchange_rate = Rate::saturating_from_rational(3, 10); - assert_eq!(LendMarket::calc_collateral_amount(1000, exchange_rate).unwrap(), 3333); + assert_eq!( + LendMarket::calc_collateral_amount(1000, exchange_rate).unwrap(), + 3333 + ); assert_eq!( LendMarket::calc_collateral_amount(u128::MAX, exchange_rate), Err(DispatchError::Arithmetic(ArithmeticError::Underflow)) @@ -1238,7 +1463,10 @@ fn calc_collateral_amount_works() { // relative test: prevent_the_exchange_rate_attack let exchange_rate = Rate::saturating_from_rational(30000, 1); - assert_eq!(LendMarket::calc_collateral_amount(10000, exchange_rate).unwrap(), 0); + assert_eq!( + LendMarket::calc_collateral_amount(10000, exchange_rate).unwrap(), + 0 + ); } #[test] @@ -1263,7 +1491,10 @@ fn get_price_works() { assert_noop!(LendMarket::get_price(DOT), Error::::PriceIsZero); MockOraclePriceProvider::set_price(DOT, 2.into()); - assert_eq!(LendMarket::get_price(DOT).unwrap(), Price::saturating_from_integer(2)); + assert_eq!( + LendMarket::get_price(DOT).unwrap(), + Price::saturating_from_integer(2) + ); }) } @@ -1330,15 +1561,15 @@ fn ensure_valid_exchange_rate_works() { LendMarket::ensure_valid_exchange_rate(FixedU128::saturating_from_rational(1, 100)), Error::::InvalidExchangeRate ); - assert_ok!(LendMarket::ensure_valid_exchange_rate(FixedU128::saturating_from_rational( - 2, 100 - ))); - assert_ok!(LendMarket::ensure_valid_exchange_rate(FixedU128::saturating_from_rational( - 3, 100 - ))); - assert_ok!(LendMarket::ensure_valid_exchange_rate(FixedU128::saturating_from_rational( - 99, 100 - ))); + assert_ok!(LendMarket::ensure_valid_exchange_rate( + FixedU128::saturating_from_rational(2, 100) + )); + assert_ok!(LendMarket::ensure_valid_exchange_rate( + FixedU128::saturating_from_rational(3, 100) + )); + assert_ok!(LendMarket::ensure_valid_exchange_rate( + FixedU128::saturating_from_rational(99, 100) + )); assert_noop!( LendMarket::ensure_valid_exchange_rate(Rate::one()), Error::::InvalidExchangeRate, @@ -1370,9 +1601,16 @@ fn withdraw_missing_reward_works() { )); assert_eq!(::Assets::balance(BNC, &DAVE), unit(1000)); - assert_ok!(LendMarket::add_reward(RuntimeOrigin::signed(DAVE), unit(100))); + assert_ok!(LendMarket::add_reward( + RuntimeOrigin::signed(DAVE), + unit(100) + )); - assert_ok!(LendMarket::withdraw_missing_reward(RuntimeOrigin::root(), ALICE, unit(40),)); + assert_ok!(LendMarket::withdraw_missing_reward( + RuntimeOrigin::root(), + ALICE, + unit(40), + )); assert_eq!(::Assets::balance(BNC, &DAVE), unit(900)); @@ -1453,12 +1691,36 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(10))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(10) + )); _run_to_block(10); assert_ok!(LendMarket::update_market_reward_speed( @@ -1482,7 +1744,11 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { assert_eq!(RewardAccrued::::get(ALICE), 0); _run_to_block(20); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); assert_ok!(LendMarket::update_market_reward_speed( RuntimeOrigin::root(), KSM, @@ -1509,10 +1775,26 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { Some(0), Some(0) )); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(10))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(10))); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(10) + )); let supply_state = RewardSupplyState::::get(DOT); assert_eq!(supply_state.block, 30); @@ -1522,7 +1804,10 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { // DOT borrow:20 DOT borrow reward: 40 // KSM supply:200 KSM supply reward: 10 // KSM borrow:20 KSM borrow reward: 10 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(80)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(80)), + true + ); _run_to_block(40); assert_ok!(LendMarket::update_market_reward_speed( @@ -1531,10 +1816,26 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { Some(0), Some(0) )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(10))); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(10) + )); let supply_state = RewardSupplyState::::get(DOT); assert_eq!(supply_state.block, 40); @@ -1544,7 +1845,10 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { // DOT borrow:30 DOT borrow reward: 40 // KSM supply:100 KSM supply reward: 20 // KSM borrow:30 KSM borrow reward: 20 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(100)), true,); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(100)), + true, + ); _run_to_block(50); assert_ok!(LendMarket::update_market_reward_speed( @@ -1553,10 +1857,25 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { Some(unit(1)), Some(unit(1)), )); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), DOT)); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(10))); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + DOT + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(10) + )); let supply_state = RewardSupplyState::::get(DOT); assert_eq!(supply_state.block, 50); @@ -1566,7 +1885,10 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { // DOT borrow:0 DOT borrow reward: 40 // KSM supply:200 KSM supply reward: 20 // KSM borrow:40 KSM borrow reward: 20 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(100)), true,); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(100)), + true, + ); _run_to_block(60); assert_ok!(LendMarket::update_market_reward_speed( @@ -1575,9 +1897,20 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { Some(unit(1)), Some(unit(1)), )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), KSM)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + KSM + )); let supply_state = RewardSupplyState::::get(DOT); assert_eq!(supply_state.block, 60); @@ -1587,7 +1920,10 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { // DOT borrow:0 DOT borrow reward: 40 // KSM supply:100 KSM supply reward: 20 // KSM borrow:0 KSM borrow reward: 20 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(110)), true,); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(110)), + true, + ); _run_to_block(70); assert_ok!(LendMarket::update_market_reward_speed( @@ -1602,8 +1938,16 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { Some(0), Some(0) )); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(100))); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); let supply_state = RewardSupplyState::::get(DOT); assert_eq!(supply_state.block, 70); @@ -1613,13 +1957,22 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { // DOT borrow:0 DOT borrow reward: 40 // KSM supply:600 KSM supply reward: 30 // KSM borrow:0 KSM borrow reward: 20 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(130)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(130)), + true + ); _run_to_block(80); - assert_ok!(LendMarket::add_reward(RuntimeOrigin::signed(DAVE), unit(200))); + assert_ok!(LendMarket::add_reward( + RuntimeOrigin::signed(DAVE), + unit(200) + )); assert_ok!(LendMarket::claim_reward(RuntimeOrigin::signed(ALICE))); assert_eq!(::Assets::balance(BNC, &DAVE), unit(800)); - assert_eq!(almost_equal(::Assets::balance(BNC, &ALICE), unit(130)), true); + assert_eq!( + almost_equal(::Assets::balance(BNC, &ALICE), unit(130)), + true + ); assert_eq!( almost_equal( ::Assets::balance(BNC, &LendMarket::reward_account_id().unwrap()), @@ -1640,7 +1993,10 @@ fn reward_calculation_one_palyer_in_multi_markets_works() { // KSM borrow:0 KSM borrow reward: 20 _run_to_block(90); assert_ok!(LendMarket::claim_reward(RuntimeOrigin::signed(ALICE))); - assert_eq!(almost_equal(::Assets::balance(BNC, &ALICE), unit(140)), true); + assert_eq!( + almost_equal(::Assets::balance(BNC, &ALICE), unit(140)), + true + ); }) } @@ -1662,10 +2018,22 @@ fn reward_calculation_multi_player_in_one_market_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, unit(10))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(BOB), DOT, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(BOB), + DOT, + true + )); _run_to_block(10); assert_ok!(LendMarket::update_market_reward_speed( @@ -1682,7 +2050,11 @@ fn reward_calculation_multi_player_in_one_market_works() { assert_eq!(RewardAccrued::::get(BOB), 0); _run_to_block(20); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(70))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(70) + )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, unit(10))); // Alice supply:80 supply reward: 5 // Alice borrow:0 borrow reward: 0 @@ -1692,9 +2064,21 @@ fn reward_calculation_multi_player_in_one_market_works() { assert_eq!(RewardAccrued::::get(BOB), unit(5)); _run_to_block(30); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(70))); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(BOB), DOT, unit(10))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(1))); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(70) + )); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(BOB), + DOT, + unit(10) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(1) + )); assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(BOB), DOT, unit(1))); // Alice supply:10 supply reward: 13 // Alice borrow:1 borrow reward: 0 @@ -1704,48 +2088,112 @@ fn reward_calculation_multi_player_in_one_market_works() { assert_eq!(RewardAccrued::::get(BOB), unit(7)); _run_to_block(40); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, unit(10))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(1))); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(BOB), DOT)); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(1) + )); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(BOB), + DOT + )); // Alice supply:20 supply reward: 18 // Alice borrow:2 borrow reward: 5 // BOB supply:20 supply reward: 12 // BOB borrow:0 borrow reward: 5 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(23)), true); - assert_eq!(almost_equal(RewardAccrued::::get(BOB), unit(17)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(23)), + true + ); + assert_eq!( + almost_equal(RewardAccrued::::get(BOB), unit(17)), + true + ); _run_to_block(50); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); assert_ok!(LendMarket::redeem_all(RuntimeOrigin::signed(BOB), DOT)); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), DOT)); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(BOB), DOT)); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + DOT + )); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(BOB), + DOT + )); // Alice supply:10 supply reward: 23 // Alice borrow:0 borrow reward: 15 // BOB supply:0 supply reward: 17 // BOB borrow:0 borrow reward: 5 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(38)), true); - assert_eq!(almost_equal(RewardAccrued::::get(BOB), unit(22)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(38)), + true + ); + assert_eq!( + almost_equal(RewardAccrued::::get(BOB), unit(22)), + true + ); _run_to_block(60); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); assert_ok!(LendMarket::redeem_all(RuntimeOrigin::signed(BOB), DOT)); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), DOT)); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(BOB), DOT)); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + DOT + )); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(BOB), + DOT + )); // Alice supply:10 supply reward: 33 // Alice borrow:0 borrow reward: 15 // BOB supply:0 supply reward: 17 // BOB borrow:0 borrow reward: 5 - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(48)), true); - assert_eq!(almost_equal(RewardAccrued::::get(BOB), unit(22)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(48)), + true + ); + assert_eq!( + almost_equal(RewardAccrued::::get(BOB), unit(22)), + true + ); _run_to_block(70); - assert_ok!(LendMarket::add_reward(RuntimeOrigin::signed(DAVE), unit(200))); - assert_ok!(LendMarket::claim_reward_for_market(RuntimeOrigin::signed(ALICE), DOT)); - assert_ok!(LendMarket::claim_reward_for_market(RuntimeOrigin::signed(BOB), DOT)); + assert_ok!(LendMarket::add_reward( + RuntimeOrigin::signed(DAVE), + unit(200) + )); + assert_ok!(LendMarket::claim_reward_for_market( + RuntimeOrigin::signed(ALICE), + DOT + )); + assert_ok!(LendMarket::claim_reward_for_market( + RuntimeOrigin::signed(BOB), + DOT + )); assert_eq!(::Assets::balance(BNC, &DAVE), unit(800)); - assert_eq!(almost_equal(::Assets::balance(BNC, &ALICE), unit(58)), true); - assert_eq!(almost_equal(::Assets::balance(BNC, &BOB), unit(22)), true); + assert_eq!( + almost_equal(::Assets::balance(BNC, &ALICE), unit(58)), + true + ); + assert_eq!( + almost_equal(::Assets::balance(BNC, &BOB), unit(22)), + true + ); assert_eq!( almost_equal( ::Assets::balance(BNC, &LendMarket::reward_account_id().unwrap()), @@ -1774,12 +2222,32 @@ fn reward_calculation_after_liquidate_borrow_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), KSM, unit(500))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(BOB), KSM, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(50))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(BOB), KSM, unit(75))); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(BOB), + KSM, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(50) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(BOB), + KSM, + unit(75) + )); _run_to_block(10); assert_ok!(LendMarket::update_market_reward_speed( @@ -1810,8 +2278,14 @@ fn reward_calculation_after_liquidate_borrow_works() { assert_ok!(LendMarket::distribute_borrower_reward(KSM, &ALICE)); assert_ok!(LendMarket::distribute_borrower_reward(KSM, &BOB)); - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), unit(14)), true); - assert_eq!(almost_equal(RewardAccrued::::get(BOB), unit(16)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), unit(14)), + true + ); + assert_eq!( + almost_equal(RewardAccrued::::get(BOB), unit(16)), + true + ); MockOraclePriceProvider::set_price(KSM, 2.into()); // since we set liquidate_threshold more than collateral_factor,with KSM price as 2 alice @@ -1856,8 +2330,14 @@ fn reward_calculation_after_liquidate_borrow_works() { &LendMarket::incentive_reward_account_id().unwrap(), )); - assert_eq!(almost_equal(RewardAccrued::::get(ALICE), milli_unit(22375)), true); - assert_eq!(almost_equal(RewardAccrued::::get(BOB), micro_unit(37512500)), true); + assert_eq!( + almost_equal(RewardAccrued::::get(ALICE), milli_unit(22375)), + true + ); + assert_eq!( + almost_equal(RewardAccrued::::get(BOB), micro_unit(37512500)), + true + ); assert_eq!( almost_equal( RewardAccrued::::get(LendMarket::incentive_reward_account_id().unwrap()), diff --git a/pallets/lend-market/src/tests/edge_cases.rs b/pallets/lend-market/src/tests/edge_cases.rs index 640ff35f91..007b501831 100644 --- a/pallets/lend-market/src/tests/edge_cases.rs +++ b/pallets/lend-market/src/tests/edge_cases.rs @@ -5,7 +5,13 @@ use sp_runtime::FixedPointNumber; #[test] fn exceeded_supply_cap() { new_test_ext().execute_with(|| { - assert_ok!(Tokens::set_balance(RuntimeOrigin::root(), ALICE, DOT, million_unit(1001), 0,)); + assert_ok!(Tokens::set_balance( + RuntimeOrigin::root(), + ALICE, + DOT, + million_unit(1001), + 0, + )); let amount = million_unit(501); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, amount)); // Exceed upper bound. @@ -23,17 +29,36 @@ fn exceeded_supply_cap() { #[test] fn repay_borrow_all_no_underflow() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![KSM] + )); // Alice deposits 200 KSM as collateral - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); // Alice borrow only 1/1e5 KSM which is hard to accrue total borrows interest in 100 seconds - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, 10_u128.pow(7))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + 10_u128.pow(7) + )); accrue_interest_per_block(KSM, 100, 9); - assert_eq!(LendMarket::current_borrow_balance(&ALICE, KSM), Ok(10000005)); + assert_eq!( + LendMarket::current_borrow_balance(&ALICE, KSM), + Ok(10000005) + ); // FIXME since total_borrows is too small and we accrue internal on it every 100 seconds // accrue_interest fails every time // as you can see the current borrow balance is not equal to total_borrows anymore @@ -41,9 +66,15 @@ fn repay_borrow_all_no_underflow() { // Alice repay all borrow balance. total_borrows = total_borrows.saturating_sub(10000005) = // 0. - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), KSM)); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + KSM + )); - assert_eq!(::Assets::balance(KSM, &ALICE), unit(800) - 5); + assert_eq!( + ::Assets::balance(KSM, &ALICE), + unit(800) - 5 + ); assert_eq!( ExchangeRate::::get(DOT) @@ -70,16 +101,38 @@ fn ensure_capacity_fails_when_market_not_existed() { #[test] fn redeem_all_should_be_accurate() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![KSM])); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(50))); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![KSM] + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(50) + )); // let exchange_rate greater than 0.02 accrue_interest_per_block(KSM, 6, 2); - assert_eq!(ExchangeRate::::get(KSM), Rate::from_inner(20000000036387000)); + assert_eq!( + ExchangeRate::::get(KSM), + Rate::from_inner(20000000036387000) + ); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), KSM)); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + KSM + )); // It failed with InsufficientLiquidity before #839 assert_ok!(LendMarket::redeem_all(RuntimeOrigin::signed(ALICE), KSM)); }) diff --git a/pallets/lend-market/src/tests/interest_rate.rs b/pallets/lend-market/src/tests/interest_rate.rs index fa391ca8f4..6e08290ea5 100644 --- a/pallets/lend-market/src/tests/interest_rate.rs +++ b/pallets/lend-market/src/tests/interest_rate.rs @@ -9,12 +9,24 @@ use sp_runtime::{ #[test] fn utilization_rate_works() { // 50% borrow - assert_eq!(LendMarket::calc_utilization_ratio(1, 1, 0).unwrap(), Ratio::from_percent(50)); - assert_eq!(LendMarket::calc_utilization_ratio(100, 100, 0).unwrap(), Ratio::from_percent(50)); + assert_eq!( + LendMarket::calc_utilization_ratio(1, 1, 0).unwrap(), + Ratio::from_percent(50) + ); + assert_eq!( + LendMarket::calc_utilization_ratio(100, 100, 0).unwrap(), + Ratio::from_percent(50) + ); // no borrow - assert_eq!(LendMarket::calc_utilization_ratio(1, 0, 0).unwrap(), Ratio::zero()); + assert_eq!( + LendMarket::calc_utilization_ratio(1, 0, 0).unwrap(), + Ratio::zero() + ); // full borrow - assert_eq!(LendMarket::calc_utilization_ratio(0, 1, 0).unwrap(), Ratio::from_percent(100)); + assert_eq!( + LendMarket::calc_utilization_ratio(0, 1, 0).unwrap(), + Ratio::from_percent(100) + ); } #[test] @@ -44,9 +56,21 @@ fn interest_rate_model_works() { 0, )); // Deposit 200 DOT and borrow 100 DOT - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, million_unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, million_unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + million_unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + million_unit(100) + )); let total_cash = million_unit(200) - million_unit(100); let total_supply = @@ -88,8 +112,8 @@ fn interest_rate_model_works() { total_reserves = Markets::::get(&DOT) .unwrap() .reserve_factor - .mul_floor(interest_accumulated) + - total_reserves; + .mul_floor(interest_accumulated) + + total_reserves; assert_eq!(TotalReserves::::get(DOT), total_reserves); // exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply @@ -108,7 +132,10 @@ fn interest_rate_model_works() { assert_eq!(total_borrows, 100000063926960646826); assert_eq!(total_reserves, 9589044097001); assert_eq!(borrow_index, Rate::from_inner(1000000639269606444)); - assert_eq!(ExchangeRate::::get(DOT), Rate::from_inner(20000005433791654)); + assert_eq!( + ExchangeRate::::get(DOT), + Rate::from_inner(20000005433791654) + ); // Calculate borrow accrued interest let borrow_principal = (borrow_index / borrow_snapshot.borrow_index) @@ -145,14 +172,33 @@ fn last_accrued_interest_time_should_be_update_correctly() { )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); assert_eq!(LastAccruedInterestTime::::get(DOT), 0); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); assert_eq!(LastAccruedInterestTime::::get(DOT), 6); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000013318112633),); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000013318112633), + ); }) } @@ -174,13 +220,32 @@ fn accrue_interest_works_after_mint() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000013318112633),); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000013318112633), + ); }) } @@ -202,12 +267,27 @@ fn accrue_interest_works_after_borrow() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000003805175038),); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000003805175038), + ); }) } @@ -229,19 +309,41 @@ fn accrue_interest_works_after_redeem() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::redeem(RuntimeOrigin::signed(ALICE), DOT, unit(10))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000004756468797),); + assert_ok!(LendMarket::redeem( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000004756468797), + ); assert_eq!( ExchangeRate::::get(DOT) .saturating_mul_int(AccountDeposits::::get(DOT, BOB).voucher_balance), 0, ); - assert_eq!(::Assets::balance(DOT, &ALICE), 819999999999999); + assert_eq!( + ::Assets::balance(DOT, &ALICE), + 819999999999999 + ); }) } @@ -264,19 +366,37 @@ fn accrue_interest_works_after_redeem_all() { vec![DOT, BNC, KSM, DOT_U, PHA] )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, unit(20))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(10))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); assert_ok!(LendMarket::redeem_all(RuntimeOrigin::signed(BOB), DOT)); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000004669977168),); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000004669977168), + ); assert_eq!( ExchangeRate::::get(DOT) .saturating_mul_int(AccountDeposits::::get(DOT, BOB).voucher_balance), 0, ); - assert_eq!(::Assets::balance(DOT, &BOB), 1000000000003608); + assert_eq!( + ::Assets::balance(DOT, &BOB), + 1000000000003608 + ); assert!(!AccountDeposits::::contains_key(DOT, &BOB)) }) } @@ -299,13 +419,32 @@ fn accrue_interest_works_after_repay() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(20))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(20) + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::repay_borrow(RuntimeOrigin::signed(ALICE), DOT, unit(10))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000005707762557),); + assert_ok!(LendMarket::repay_borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(10) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000005707762557), + ); }) } @@ -328,14 +467,35 @@ fn accrue_interest_works_after_repay_all() { vec![DOT, BNC, KSM, DOT_U, PHA] )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), KSM, unit(200))); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(50))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(50) + )); assert_eq!(BorrowIndex::::get(KSM), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::repay_borrow_all(RuntimeOrigin::signed(ALICE), KSM)); - assert_eq!(BorrowIndex::::get(KSM), Rate::from_inner(1000000008561643835),); - assert_eq!(::Assets::balance(KSM, &ALICE), 999999999571918); + assert_ok!(LendMarket::repay_borrow_all( + RuntimeOrigin::signed(ALICE), + KSM + )); + assert_eq!( + BorrowIndex::::get(KSM), + Rate::from_inner(1000000008561643835), + ); + assert_eq!( + ::Assets::balance(KSM, &ALICE), + 999999999571918 + ); let borrow_snapshot = AccountBorrows::::get(KSM, ALICE); assert_eq!(borrow_snapshot.principal, 0); assert_eq!(borrow_snapshot.borrow_index, BorrowIndex::::get(KSM)); @@ -362,11 +522,27 @@ fn accrue_interest_works_after_liquidate_borrow() { )); // Bob deposits 200 KSM assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), KSM, unit(200))); // Alice deposits 300 DOT as collateral - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(300))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(300) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); // Alice borrows 100 KSM and 50 DOT - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(50))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(50) + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); assert_eq!(BorrowIndex::::get(KSM), Rate::one()); TimestampPallet::set_timestamp(12000); @@ -380,8 +556,14 @@ fn accrue_interest_works_after_liquidate_borrow() { unit(50), DOT )); - assert_eq!(BorrowIndex::::get(KSM), Rate::from_inner(1000000013318112633),); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000006976141552),); + assert_eq!( + BorrowIndex::::get(KSM), + Rate::from_inner(1000000013318112633), + ); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000006976141552), + ); }) } @@ -403,17 +585,47 @@ fn different_markets_can_accrue_interest_in_one_block() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), KSM, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), KSM, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + KSM, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + KSM, + true + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); assert_eq!(BorrowIndex::::get(KSM), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(100))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000003805175038),); - assert_eq!(BorrowIndex::::get(KSM), Rate::from_inner(1000000003805175038),); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000003805175038), + ); + assert_eq!( + BorrowIndex::::get(KSM), + Rate::from_inner(1000000003805175038), + ); }) } @@ -435,14 +647,37 @@ fn a_market_can_only_accrue_interest_once_in_a_block() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT, + true + )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(BOB), DOT, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(BOB), + DOT, + true + )); assert_eq!(BorrowIndex::::get(DOT), Rate::one()); TimestampPallet::set_timestamp(12000); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), DOT, unit(100))); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(BOB), DOT, unit(100))); - assert_eq!(BorrowIndex::::get(DOT), Rate::from_inner(1000000003805175038),); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + DOT, + unit(100) + )); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(BOB), + DOT, + unit(100) + )); + assert_eq!( + BorrowIndex::::get(DOT), + Rate::from_inner(1000000003805175038), + ); }) } diff --git a/pallets/lend-market/src/tests/lend_tokens.rs b/pallets/lend-market/src/tests/lend_tokens.rs index f8c33973dc..91ea8b0729 100644 --- a/pallets/lend-market/src/tests/lend_tokens.rs +++ b/pallets/lend-market/src/tests/lend_tokens.rs @@ -43,16 +43,28 @@ fn trait_inspect_methods_works() { assert_eq!(LendMarket::balance(VBNC, &DAVE), 0); // DAVE Deposit 100 BNC - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(DAVE), BNC, unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(DAVE), + BNC, + unit(100) + )); assert_eq!(LendMarket::balance(VBNC, &DAVE), unit(100) * 50); assert_eq!( LendMarket::reducible_balance(VBNC, &DAVE, Preservation::Expendable, Fortitude::Polite), unit(100) * 50 ); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(DAVE), BNC, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(DAVE), + BNC, + true + )); // Borrow 25 BNC will reduce 25 BNC liquidity for collateral_factor is 50% - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(DAVE), BNC, unit(25))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(25) + )); assert_eq!( ExchangeRate::::get(BNC) @@ -72,7 +84,11 @@ fn trait_inspect_methods_works() { // DAVE Deposit 100 BNC, 50 DOT_U, Borrow 25 BNC // Liquidity BNC = 25, DOT_U = 25 // lend tokens = dollar(25 + 25) / 1 / 0.5 / 0.02 = dollar(50) * 100 - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(DAVE), DOT_U, unit(50))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(DAVE), + DOT_U, + unit(50) + )); assert_eq!(LendMarket::balance(LUSDT, &DAVE), unit(50) * 50); assert_eq!( LendMarket::reducible_balance( @@ -84,13 +100,21 @@ fn trait_inspect_methods_works() { unit(25) * 2 * 50 ); // enable DOT_U collateral - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(DAVE), DOT_U, true)); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(DAVE), + DOT_U, + true + )); assert_eq!( LendMarket::reducible_balance(VBNC, &DAVE, Preservation::Expendable, Fortitude::Polite), unit(25 + 25) * 2 * 50 ); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(DAVE), BNC, unit(50))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(50) + )); assert_eq!( LendMarket::reducible_balance(VBNC, &DAVE, Preservation::Expendable, Fortitude::Polite), 0 @@ -151,7 +175,11 @@ fn transfer_lend_token_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); // DAVE Deposit 100 BNC - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(DAVE), BNC, unit(100))); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(DAVE), + BNC, + unit(100) + )); // DAVE BNC collateral: deposit = 100 // BNC: cash - deposit = 1000 - 100 = 900 @@ -212,13 +240,29 @@ fn transfer_lend_tokens_under_collateral_works() { BNC, vec![DOT, BNC, KSM, DOT_U, PHA] )); // DAVE Deposit 100 BNC - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(DAVE), BNC, unit(100))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(DAVE), BNC, true)); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(DAVE), + BNC, + unit(100) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(DAVE), + BNC, + true + )); // Borrow 50 BNC will reduce 50 BNC liquidity for collateral_factor is 50% - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(DAVE), BNC, unit(50))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(50) + )); // Repay 40 BNC - assert_ok!(LendMarket::repay_borrow(RuntimeOrigin::signed(DAVE), BNC, unit(40))); + assert_ok!(LendMarket::repay_borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(40) + )); // Transfer 20 lend tokens from DAVE to ALICE LendMarket::transfer(VBNC, &DAVE, &ALICE, unit(20) * 50, true).unwrap(); @@ -236,7 +280,11 @@ fn transfer_lend_tokens_under_collateral_works() { LendMarket::borrow(RuntimeOrigin::signed(DAVE), BNC, unit(31)), Error::::InsufficientLiquidity ); - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(DAVE), BNC, unit(30))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(DAVE), + BNC, + unit(30) + )); // Assert ALICE Supply BNC 20 assert_eq!( diff --git a/pallets/lend-market/src/tests/liquidate_borrow.rs b/pallets/lend-market/src/tests/liquidate_borrow.rs index 17cb806dab..e0fa0dd555 100644 --- a/pallets/lend-market/src/tests/liquidate_borrow.rs +++ b/pallets/lend-market/src/tests/liquidate_borrow.rs @@ -13,9 +13,21 @@ use sp_runtime::FixedPointNumber; #[test] fn liquidate_borrow_allowed_works() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); // Borrower should have a positive shortfall + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); // Borrower should have a positive shortfall let dot_market = LendMarket::market(DOT).unwrap(); assert_noop!( LendMarket::liquidate_borrow_allowed(&ALICE, DOT, 100, &dot_market), @@ -34,16 +46,33 @@ fn liquidate_borrow_allowed_works() { LendMarket::liquidate_borrow_allowed(&ALICE, KSM, unit(51), &ksm_market), Error::::TooMuchRepay ); - assert_ok!(LendMarket::liquidate_borrow_allowed(&ALICE, KSM, unit(50), &ksm_market)); + assert_ok!(LendMarket::liquidate_borrow_allowed( + &ALICE, + KSM, + unit(50), + &ksm_market + )); }) } #[test] fn lf_liquidate_borrow_fails_due_to_lf_collateral() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); LendMarket::update_liquidation_free_collateral(RuntimeOrigin::root(), vec![PHA]).unwrap(); assert_err!( @@ -60,13 +89,21 @@ fn lf_liquidate_borrow_fails_due_to_lf_collateral() { #[test] fn lf_liquidate_borrow_allowed_works() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); assert_ok!(LendMarket::add_market_bond( RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); LendMarket::update_liquidation_free_collateral(RuntimeOrigin::root(), vec![PHA]).unwrap(); // Bob deposits $200 DOT LendMarket::mint(RuntimeOrigin::signed(BOB), DOT, unit(200)).unwrap(); @@ -96,21 +133,43 @@ fn lf_liquidate_borrow_allowed_works() { LendMarket::liquidate_borrow_allowed(&ALICE, DOT, unit(51), &dot_market), Error::::TooMuchRepay ); - assert_ok!(LendMarket::liquidate_borrow_allowed(&ALICE, DOT, unit(50), &dot_market)); + assert_ok!(LendMarket::liquidate_borrow_allowed( + &ALICE, + DOT, + unit(50), + &dot_market + )); // Remove CDOT from lf collateral LendMarket::update_liquidation_free_collateral(RuntimeOrigin::root(), vec![]).unwrap(); // The max repay amount = 400 * 50 = $200 - assert_ok!(LendMarket::liquidate_borrow_allowed(&ALICE, DOT, unit(100), &dot_market)); + assert_ok!(LendMarket::liquidate_borrow_allowed( + &ALICE, + DOT, + unit(100), + &dot_market + )); }) } #[test] fn deposit_of_borrower_must_be_collateral() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); initial_setup(); alice_borrows_100_ksm(); // Adjust KSM price to make shortfall @@ -130,9 +189,21 @@ fn deposit_of_borrower_must_be_collateral() { #[test] fn collateral_value_must_be_greater_than_liquidation_value() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); initial_setup(); alice_borrows_100_ksm(); MockOraclePriceProvider::set_price(KSM, Rate::from_float(2000.0)); @@ -151,9 +222,21 @@ fn collateral_value_must_be_greater_than_liquidation_value() { #[test] fn full_workflow_works_as_expected() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); initial_setup(); alice_borrows_100_ksm(); // adjust KSM price to make ALICE generate shortfall @@ -191,7 +274,10 @@ fn full_workflow_works_as_expected() { ); // 3 dollar reserved in our incentive reward account let incentive_reward_account = LendMarket::incentive_reward_account_id().unwrap(); - println!("incentive reserve account:{:?}", incentive_reward_account.clone()); + println!( + "incentive reserve account:{:?}", + incentive_reward_account.clone() + ); assert_eq!( ExchangeRate::::get(DOT_U).saturating_mul_int( AccountDeposits::::get(DOT_U, incentive_reward_account.clone()) @@ -215,16 +301,31 @@ fn full_workflow_works_as_expected() { unit(1), ); // 2 dollar transfer to alice - assert_eq!(::Assets::balance(DOT_U, &ALICE), unit(800) + unit(2),); + assert_eq!( + ::Assets::balance(DOT_U, &ALICE), + unit(800) + unit(2), + ); }) } #[test] fn liquidator_cannot_take_inactive_market_currency() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); initial_setup(); alice_borrows_100_ksm(); // Adjust KSM price to make shortfall @@ -243,9 +344,21 @@ fn liquidator_cannot_take_inactive_market_currency() { #[test] fn liquidator_can_not_repay_more_than_the_close_factor_pct_multiplier() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); initial_setup(); alice_borrows_100_ksm(); MockOraclePriceProvider::set_price(KSM, 20.into()); @@ -259,9 +372,21 @@ fn liquidator_can_not_repay_more_than_the_close_factor_pct_multiplier() { #[test] fn liquidator_must_not_be_borrower() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), KSM, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, KSM])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, KSM])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + KSM, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, KSM] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, KSM] + )); initial_setup(); assert_noop!( LendMarket::liquidate_borrow(RuntimeOrigin::signed(ALICE), ALICE, KSM, 0, DOT), @@ -271,7 +396,11 @@ fn liquidator_must_not_be_borrower() { } fn alice_borrows_100_ksm() { - assert_ok!(LendMarket::borrow(RuntimeOrigin::signed(ALICE), KSM, unit(100))); + assert_ok!(LendMarket::borrow( + RuntimeOrigin::signed(ALICE), + KSM, + unit(100) + )); } fn initial_setup() { @@ -280,14 +409,41 @@ fn initial_setup() { KSM, vec![DOT, BNC, KSM, DOT_U, PHA] )); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, DOT_U, PHA])); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), BNC, vec![DOT, BNC, DOT_U, PHA])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, DOT_U, PHA] + )); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + BNC, + vec![DOT, BNC, DOT_U, PHA] + )); // Bob deposits 200 KSM assert_ok!(LendMarket::mint(RuntimeOrigin::signed(BOB), KSM, unit(200))); // Alice deposits 200 DOT as collateral - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), DOT_U, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), DOT_U, true)); - assert_ok!(LendMarket::mint(RuntimeOrigin::signed(ALICE), PHA, unit(200))); - assert_ok!(LendMarket::collateral_asset(RuntimeOrigin::signed(ALICE), PHA, true)); - assert_ok!(LendMarket::update_liquidation_free_collateral(RuntimeOrigin::root(), vec![PHA])); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + DOT_U, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + DOT_U, + true + )); + assert_ok!(LendMarket::mint( + RuntimeOrigin::signed(ALICE), + PHA, + unit(200) + )); + assert_ok!(LendMarket::collateral_asset( + RuntimeOrigin::signed(ALICE), + PHA, + true + )); + assert_ok!(LendMarket::update_liquidation_free_collateral( + RuntimeOrigin::root(), + vec![PHA] + )); } diff --git a/pallets/lend-market/src/tests/market.rs b/pallets/lend-market/src/tests/market.rs index 0c48761c29..3b66d38f6e 100644 --- a/pallets/lend-market/src/tests/market.rs +++ b/pallets/lend-market/src/tests/market.rs @@ -90,7 +90,10 @@ macro_rules! rate_model_sanity_check { fn active_market_sets_state_to_active() { new_test_ext().execute_with(|| { LendMarket::add_market(RuntimeOrigin::root(), VDOT, MARKET_MOCK).unwrap(); - assert_eq!(LendMarket::market(VDOT).unwrap().state, MarketState::Pending); + assert_eq!( + LendMarket::market(VDOT).unwrap().state, + MarketState::Pending + ); LendMarket::activate_market(RuntimeOrigin::root(), VDOT).unwrap(); assert_eq!(LendMarket::market(VDOT).unwrap().state, MarketState::Active); }) @@ -142,7 +145,11 @@ fn add_market_successfully_stores_a_new_market() { #[test] fn add_market_ensures_that_market_does_not_exist() { new_test_ext().execute_with(|| { - assert_ok!(LendMarket::add_market(RuntimeOrigin::root(), VDOT, MARKET_MOCK)); + assert_ok!(LendMarket::add_market( + RuntimeOrigin::root(), + VDOT, + MARKET_MOCK + )); assert_noop!( LendMarket::add_market(RuntimeOrigin::root(), VDOT, MARKET_MOCK), Error::::MarketAlreadyExists @@ -174,7 +181,11 @@ fn force_update_market_works() { LendMarket::force_update_market(RuntimeOrigin::root(), DOT, market_mock(LUSDT)), Error::::InvalidLendTokenId ); - assert_ok!(LendMarket::force_update_market(RuntimeOrigin::root(), DOT, market_mock(LDOT))); + assert_ok!(LendMarket::force_update_market( + RuntimeOrigin::root(), + DOT, + market_mock(LDOT) + )); assert_eq!(LendMarket::market(DOT).unwrap().lend_token_id, LDOT); }) } @@ -218,7 +229,10 @@ fn update_market_ensures_that_it_is_not_possible_to_modify_unknown_market_curren #[test] fn update_market_works() { new_test_ext().execute_with(|| { - assert_eq!(LendMarket::market(DOT).unwrap().close_factor, Ratio::from_percent(50)); + assert_eq!( + LendMarket::market(DOT).unwrap().close_factor, + Ratio::from_percent(50) + ); let market = MARKET_MOCK; assert_ok!(LendMarket::update_market( @@ -234,15 +248,24 @@ fn update_market_works() { None, )); - assert_eq!(LendMarket::market(DOT).unwrap().close_factor, Default::default()); - assert_eq!(LendMarket::market(DOT).unwrap().supply_cap, market.supply_cap); + assert_eq!( + LendMarket::market(DOT).unwrap().close_factor, + Default::default() + ); + assert_eq!( + LendMarket::market(DOT).unwrap().supply_cap, + market.supply_cap + ); }) } #[test] fn update_market_should_not_work_if_with_invalid_params() { new_test_ext().execute_with(|| { - assert_eq!(LendMarket::market(DOT).unwrap().close_factor, Ratio::from_percent(50)); + assert_eq!( + LendMarket::market(DOT).unwrap().close_factor, + Ratio::from_percent(50) + ); // check error code while collateral_factor is [0%, 100%) assert_ok!(LendMarket::update_market( @@ -331,7 +354,11 @@ fn update_rate_model_works() { Rate::saturating_from_rational(35, 100), Ratio::from_percent(80), ); - assert_ok!(LendMarket::update_rate_model(RuntimeOrigin::root(), DOT, new_rate_model,)); + assert_ok!(LendMarket::update_rate_model( + RuntimeOrigin::root(), + DOT, + new_rate_model, + )); assert_eq!(LendMarket::market(DOT).unwrap().rate_model, new_rate_model); // Invalid base_rate diff --git a/pallets/lend-market/src/weights.rs b/pallets/lend-market/src/weights.rs index 2c62a2570a..96ae775757 100644 --- a/pallets/lend-market/src/weights.rs +++ b/pallets/lend-market/src/weights.rs @@ -1,19 +1,20 @@ -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Copyright (C) 2022 Parallel Finance Developer. -// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . //! Autogenerated weights for pallet_loans //! diff --git a/pallets/leverage-staking/Cargo.toml b/pallets/leverage-staking/Cargo.toml index 8d95f22ac6..b07f8ddae8 100644 --- a/pallets/leverage-staking/Cargo.toml +++ b/pallets/leverage-staking/Cargo.toml @@ -1,5 +1,5 @@ [package] -authors = ["yooml "] +authors = ["Liebi Technologies "] edition = "2021" name = "leverage-staking" version = "0.8.0" diff --git a/pallets/leverage-staking/src/benchmarking.rs b/pallets/leverage-staking/src/benchmarking.rs index a4e055a542..9f6cd3e9bd 100644 --- a/pallets/leverage-staking/src/benchmarking.rs +++ b/pallets/leverage-staking/src/benchmarking.rs @@ -99,13 +99,19 @@ fn init< KSM, market_mock(VKSM) )); - assert_ok!(lend_market::Pallet::::activate_market(SystemOrigin::Root.into(), KSM)); + assert_ok!(lend_market::Pallet::::activate_market( + SystemOrigin::Root.into(), + KSM + )); assert_ok!(lend_market::Pallet::::add_market( SystemOrigin::Root.into(), VKSM, market_mock(VBNC) )); - assert_ok!(lend_market::Pallet::::activate_market(SystemOrigin::Root.into(), VKSM)); + assert_ok!(lend_market::Pallet::::activate_market( + SystemOrigin::Root.into(), + VKSM + )); assert_ok!(lend_market::Pallet::::mint( SystemOrigin::Signed(caller.clone()).into(), KSM, diff --git a/pallets/leverage-staking/src/lib.rs b/pallets/leverage-staking/src/lib.rs index 4ddf4b32d9..9d7081ecb8 100644 --- a/pallets/leverage-staking/src/lib.rs +++ b/pallets/leverage-staking/src/lib.rs @@ -172,7 +172,7 @@ impl Pallet { .ok_or(ArithmeticError::Overflow)? }; Self::reduce_leverage(&who, asset_id, vtoken_id, reduce_amount)?; - }, + } Ordering::Equal => return Err(Error::::ArgumentsError.into()), Ordering::Greater => { let increase_amount = rate @@ -180,7 +180,7 @@ impl Pallet { .and_then(|r| r.checked_mul_int(base_token_value)) .ok_or(ArithmeticError::Overflow)?; Self::increase_leverage(&who, asset_id, vtoken_id, increase_amount)?; - }, + } } Self::deposit_event(Event::::FlashLoanDeposited { who, diff --git a/pallets/leverage-staking/src/mock.rs b/pallets/leverage-staking/src/mock.rs index e984ffb6b0..79a082ddd8 100644 --- a/pallets/leverage-staking/src/mock.rs +++ b/pallets/leverage-staking/src/mock.rs @@ -252,6 +252,7 @@ impl bifrost_stable_asset::Config for Test { type WeightInfo = (); type ListingOrigin = EnsureSignedBy; type EnsurePoolAssetId = EnsurePoolAssetId; + type BlockNumberProvider = System; } impl bifrost_stable_pool::Config for Test { @@ -311,6 +312,7 @@ impl bifrost_vtoken_minting::Config for Test { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } pub struct Slp; @@ -355,7 +357,10 @@ pub type TimeStampedPrice = orml_oracle::TimestampedValue; pub struct MockDataProvider; impl DataProvider for MockDataProvider { fn get(_asset_id: &CurrencyId) -> Option { - Some(TimeStampedPrice { value: Price::saturating_from_integer(100), timestamp: 0 }) + Some(TimeStampedPrice { + value: Price::saturating_from_integer(100), + timestamp: 0, + }) } } @@ -393,7 +398,9 @@ impl MockOraclePriceProvider { pub fn set_price(asset_id: CurrencyId, price: Price) { Self::PRICES.with(|prices| { - prices.borrow_mut().insert(CurrencyIdWrap(asset_id), Some((price, 1u64))); + prices + .borrow_mut() + .insert(CurrencyIdWrap(asset_id), Some((price, 1u64))); }); } @@ -448,6 +455,7 @@ impl lend_market::Config for Test { type RewardAssetId = RewardAssetId; type LiquidationFreeAssetId = LiquidationFreeAssetId; type MaxLengthLimit = MaxLengthLimit; + type BlockNumberProvider = System; } impl pallet_prices::Config for Test { @@ -493,7 +501,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -514,7 +524,10 @@ impl ExtBuilder { // Build genesis storage according to the mock runtime. pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap().into(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap() + .into(); bifrost_asset_registry::GenesisConfig:: { currency: vec![ diff --git a/pallets/leverage-staking/src/tests.rs b/pallets/leverage-staking/src/tests.rs index 0cbc7adca1..5caab33026 100644 --- a/pallets/leverage-staking/src/tests.rs +++ b/pallets/leverage-staking/src/tests.rs @@ -23,9 +23,17 @@ use lend_market::{AccountBorrows, BorrowSnapshot, Deposits}; fn init() { env_logger::try_init().unwrap_or(()); - assert_ok!(LendMarket::add_market(RuntimeOrigin::root(), DOT, market_mock(LDOT))); + assert_ok!(LendMarket::add_market( + RuntimeOrigin::root(), + DOT, + market_mock(LDOT) + )); assert_ok!(LendMarket::activate_market(RuntimeOrigin::root(), DOT)); - assert_ok!(LendMarket::add_market(RuntimeOrigin::root(), VDOT, market_mock(LVDOT))); + assert_ok!(LendMarket::add_market( + RuntimeOrigin::root(), + VDOT, + market_mock(LVDOT) + )); assert_ok!(LendMarket::activate_market(RuntimeOrigin::root(), VDOT)); TimestampPallet::set_timestamp(6000); @@ -46,7 +54,11 @@ fn init() { 0, vec![(DOT, (1, 1)), (VDOT, (100_000_000, 100_000_000))] )); - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 1000)); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 1000 + )); assert_ok!(VtokenMinting::mint( Some(0).into(), DOT, @@ -55,131 +67,194 @@ fn init() { None )); assert_eq!(Tokens::balance(VDOT, &0), unit(100_000)); - assert_ok!(VtokenMinting::mint(Some(1).into(), DOT, unit(10), BoundedVec::default(), None)); + assert_ok!(VtokenMinting::mint( + Some(1).into(), + DOT, + unit(10), + BoundedVec::default(), + None + )); assert_eq!(Tokens::balance(VDOT, &1), unit(10)); let amounts = vec![unit(100), unit(100)]; - assert_ok!(StablePool::add_liquidity(RuntimeOrigin::signed(0), 0, amounts, 0)); + assert_ok!(StablePool::add_liquidity( + RuntimeOrigin::signed(0), + 0, + amounts, + 0 + )); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(0), DOT, unit(100))); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(0), VDOT, unit(100))); assert_ok!(LendMarket::mint(RuntimeOrigin::signed(1), VDOT, 100_000)); - assert_ok!(LendMarket::add_market_bond(RuntimeOrigin::root(), DOT, vec![DOT, BNC, VDOT])); + assert_ok!(LendMarket::add_market_bond( + RuntimeOrigin::root(), + DOT, + vec![DOT, BNC, VDOT] + )); } #[test] fn increase_leverage_should_not_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - init(); - assert_noop!( - LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(unit(1_000_100)), - ), - lend_market::Error::::InsufficientLiquidity - ); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + init(); + assert_noop!( + LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(unit(1_000_100)), + ), + lend_market::Error::::InsufficientLiquidity + ); + }); } #[test] fn increase_leverage_should_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - init(); - assert_ok!(LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(unit(100_000)), - )); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 5500000, is_collateral: true }, - ); - assert_eq!( - AccountBorrows::::get(DOT, 1), - BorrowSnapshot { principal: 10_000, borrow_index: 1.into() }, - ); - assert_ok!(LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(unit(800_000)), - )); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 9_000_000, is_collateral: true }, - ); - assert_eq!( - AccountBorrows::::get(DOT, 1), - BorrowSnapshot { principal: 80_000, borrow_index: 1.into() }, - ); - assert_ok!(LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(unit(900_000)), - )); - assert_eq!( - AccountBorrows::::get(DOT, 1), - BorrowSnapshot { principal: 90_000, borrow_index: 1.into() }, - ); - assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 9500000, is_collateral: true }, - ); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + init(); + assert_ok!(LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(unit(100_000)), + )); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 5500000, + is_collateral: true + }, + ); + assert_eq!( + AccountBorrows::::get(DOT, 1), + BorrowSnapshot { + principal: 10_000, + borrow_index: 1.into() + }, + ); + assert_ok!(LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(unit(800_000)), + )); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 9_000_000, + is_collateral: true + }, + ); + assert_eq!( + AccountBorrows::::get(DOT, 1), + BorrowSnapshot { + principal: 80_000, + borrow_index: 1.into() + }, + ); + assert_ok!(LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(unit(900_000)), + )); + assert_eq!( + AccountBorrows::::get(DOT, 1), + BorrowSnapshot { + principal: 90_000, + borrow_index: 1.into() + }, + ); + assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 9500000, + is_collateral: true + }, + ); + }); } #[test] fn reduce_leverage_should_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - init(); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 5_000_000, is_collateral: false }, - ); - assert_ok!(LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(unit(900_000)), - )); - assert_eq!( - AccountBorrows::::get(DOT, 1), - BorrowSnapshot { principal: 90_000, borrow_index: 1.into() }, - ); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 9500000, is_collateral: true }, - ); - assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); - assert_eq!(Tokens::balance(DOT, &1), 990000000000000); - assert_ok!(LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(unit(800_000)), - )); - assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); - assert_eq!(Tokens::balance(DOT, &1), 990000000000098); - assert_eq!( - AccountBorrows::::get(DOT, 1), - BorrowSnapshot { principal: 80_000, borrow_index: 1.into() }, - ); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 8994050, is_collateral: true }, - ); - assert_ok!(LeverageStaking::flash_loan_deposit( - RuntimeOrigin::signed(1), - DOT, - FixedU128::from_inner(0), - )); - assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); - assert_eq!(Tokens::balance(DOT, &1), 990000000000196); - assert_eq!( - AccountBorrows::::get(DOT, 1), - BorrowSnapshot { principal: 0, borrow_index: 1.into() }, - ); - assert_eq!( - AccountDeposits::::get(VDOT, 1), - Deposits { voucher_balance: 4981100, is_collateral: true }, - ); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + init(); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 5_000_000, + is_collateral: false + }, + ); + assert_ok!(LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(unit(900_000)), + )); + assert_eq!( + AccountBorrows::::get(DOT, 1), + BorrowSnapshot { + principal: 90_000, + borrow_index: 1.into() + }, + ); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 9500000, + is_collateral: true + }, + ); + assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); + assert_eq!(Tokens::balance(DOT, &1), 990000000000000); + assert_ok!(LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(unit(800_000)), + )); + assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); + assert_eq!(Tokens::balance(DOT, &1), 990000000000098); + assert_eq!( + AccountBorrows::::get(DOT, 1), + BorrowSnapshot { + principal: 80_000, + borrow_index: 1.into() + }, + ); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 8994050, + is_collateral: true + }, + ); + assert_ok!(LeverageStaking::flash_loan_deposit( + RuntimeOrigin::signed(1), + DOT, + FixedU128::from_inner(0), + )); + assert_eq!(Tokens::balance(VDOT, &1), 9999999900000); + assert_eq!(Tokens::balance(DOT, &1), 990000000000196); + assert_eq!( + AccountBorrows::::get(DOT, 1), + BorrowSnapshot { + principal: 0, + borrow_index: 1.into() + }, + ); + assert_eq!( + AccountDeposits::::get(VDOT, 1), + Deposits { + voucher_balance: 4981100, + is_collateral: true + }, + ); + }); } diff --git a/pallets/parachain-staking/src/benchmarks.rs b/pallets/parachain-staking/src/benchmarks.rs index e5acf26356..2e94e606e9 100644 --- a/pallets/parachain-staking/src/benchmarks.rs +++ b/pallets/parachain-staking/src/benchmarks.rs @@ -65,7 +65,11 @@ fn create_funded_delegator( collator_delegator_count: u32, ) -> Result, &'static str> { let (user, total) = create_funded_user::(string, n, extra); - let bond = if min_bond { min_delegator_stk::() } else { total }; + let bond = if min_bond { + min_delegator_stk::() + } else { + total + }; Pallet::::delegate( RawOrigin::Signed(user.clone()).into(), collator, @@ -85,8 +89,16 @@ fn create_funded_collator( candidate_count: u32, ) -> Result, &'static str> { let (user, total) = create_funded_user::(string, n, extra); - let bond = if min_bond { min_candidate_stk::() } else { total }; - Pallet::::join_candidates(RawOrigin::Signed(user.clone()).into(), bond, candidate_count)?; + let bond = if min_bond { + min_candidate_stk::() + } else { + total + }; + Pallet::::join_candidates( + RawOrigin::Signed(user.clone()).into(), + bond, + candidate_count, + )?; Ok(user) } @@ -1071,7 +1083,9 @@ mod tests { use crate::{benchmarks::*, mock::Test}; pub fn new_test_ext() -> TestExternalities { - let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); TestExternalities::new(t) } @@ -1286,4 +1300,8 @@ mod tests { } } -impl_benchmark_test_suite!(Pallet, crate::benchmarks::tests::new_test_ext(), crate::mock::Test); +impl_benchmark_test_suite!( + Pallet, + crate::benchmarks::tests::new_test_ext(), + crate::mock::Test +); diff --git a/pallets/parachain-staking/src/delegation_requests.rs b/pallets/parachain-staking/src/delegation_requests.rs index d96f46ab7b..fb4984c808 100644 --- a/pallets/parachain-staking/src/delegation_requests.rs +++ b/pallets/parachain-staking/src/delegation_requests.rs @@ -82,11 +82,15 @@ impl Pallet { let mut scheduled_requests = >::get(&collator); ensure!( - !scheduled_requests.iter().any(|req| req.delegator == delegator), + !scheduled_requests + .iter() + .any(|req| req.delegator == delegator), >::PendingDelegationRequestAlreadyExists, ); - let bonded_amount = state.get_bond_amount(&collator).ok_or(>::DelegationDNE)?; + let bonded_amount = state + .get_bond_amount(&collator) + .ok_or(>::DelegationDNE)?; let now = >::get().current; let when = now.saturating_add(T::RevokeDelegationDelay::get()); scheduled_requests.push(ScheduledRequest { @@ -117,20 +121,33 @@ impl Pallet { let mut scheduled_requests = >::get(&collator); ensure!( - !scheduled_requests.iter().any(|req| req.delegator == delegator), + !scheduled_requests + .iter() + .any(|req| req.delegator == delegator), >::PendingDelegationRequestAlreadyExists, ); - let bonded_amount = state.get_bond_amount(&collator).ok_or(>::DelegationDNE)?; - ensure!(bonded_amount > decrease_amount, >::DelegatorBondBelowMin); + let bonded_amount = state + .get_bond_amount(&collator) + .ok_or(>::DelegationDNE)?; + ensure!( + bonded_amount > decrease_amount, + >::DelegatorBondBelowMin + ); let new_amount: BalanceOf = bonded_amount - decrease_amount; - ensure!(new_amount >= T::MinDelegation::get(), >::DelegationBelowMin); + ensure!( + new_amount >= T::MinDelegation::get(), + >::DelegationBelowMin + ); // Net Total is total after pending orders are executed let net_total = state.total().saturating_sub(state.less_total); // Net Total is always >= MinDelegatorStk let max_subtracted_amount = net_total.saturating_sub(T::MinDelegatorStk::get()); - ensure!(decrease_amount <= max_subtracted_amount, >::DelegatorBondBelowMin); + ensure!( + decrease_amount <= max_subtracted_amount, + >::DelegatorBondBelowMin + ); let now = >::get().current; let when = now.saturating_add(T::RevokeDelegationDelay::get()); @@ -180,7 +197,9 @@ impl Pallet { state: &mut Delegator, BalanceOf>, scheduled_requests: &mut Vec, BalanceOf>>, ) -> Option, BalanceOf>> { - let request_idx = scheduled_requests.iter().position(|req| &req.delegator == delegator)?; + let request_idx = scheduled_requests + .iter() + .position(|req| &req.delegator == delegator)?; let request = scheduled_requests.remove(request_idx); let amount = request.action.amount(); @@ -202,7 +221,10 @@ impl Pallet { let request = &scheduled_requests[request_idx]; let now = >::get().current; - ensure!(request.when_executable <= now, >::PendingDelegationRequestNotDueYet); + ensure!( + request.when_executable <= now, + >::PendingDelegationRequestNotDueYet + ); match request.action { DelegationAction::Revoke(amount) => { @@ -243,7 +265,7 @@ impl Pallet { >::insert(&delegator, state); } Ok(().into()) - }, + } DelegationAction::Decrease(_) => { // remove from pending requests let amount = scheduled_requests.remove(request_idx).action.amount(); @@ -302,7 +324,7 @@ impl Pallet { } } Err(>::DelegationDNE.into()) - }, + } } } @@ -338,7 +360,7 @@ impl Pallet { Some(revoke_req) if matches!(revoke_req.action, DelegationAction::Revoke(_)) => { existing_revoke_count += 1; revoke_req // re-insert the same Revoke request - }, + } _ => ScheduledRequest { delegator: delegator.clone(), action: DelegationAction::Revoke(bonded_amount), @@ -437,7 +459,10 @@ impl Pallet { // backwards compatible handling for DelegatorStatus::Leaving #[allow(deprecated)] if let DelegatorStatus::Leaving(when) = state.status { - ensure!(>::get().current >= when, Error::::DelegatorCannotLeaveYet); + ensure!( + >::get().current >= when, + Error::::DelegatorCannotLeaveYet + ); for bond in state.delegations.0.clone() { if let Err(error) = Self::delegator_leaves_candidate( @@ -454,7 +479,10 @@ impl Pallet { Self::delegation_remove_request_with_state(&bond.owner, &delegator, &mut state); } >::remove(&delegator); - Self::deposit_event(Event::DelegatorLeft { delegator, unstaked_amount: state.total }); + Self::deposit_event(Event::DelegatorLeft { + delegator, + unstaked_amount: state.total, + }); return Ok(().into()); } @@ -470,7 +498,10 @@ impl Pallet { .ok_or(>::DelegatorNotLeaving)?; let request = &scheduled_requests[request_idx]; - ensure!(request.when_executable <= now, >::DelegatorCannotLeaveYet); + ensure!( + request.when_executable <= now, + >::DelegatorCannotLeaveYet + ); validated_scheduled_requests.push((bond.clone(), scheduled_requests, request_idx)) } @@ -505,7 +536,10 @@ impl Pallet { >::insert(collator, scheduled_requests); }); - Self::deposit_event(Event::DelegatorLeft { delegator: delegator.clone(), unstaked_amount }); + Self::deposit_event(Event::DelegatorLeft { + delegator: delegator.clone(), + unstaked_amount, + }); >::remove(&delegator); Ok(().into()) @@ -520,8 +554,9 @@ impl Pallet { ) { let mut scheduled_requests = >::get(collator); - let maybe_request_idx = - scheduled_requests.iter().position(|req| &req.delegator == delegator); + let maybe_request_idx = scheduled_requests + .iter() + .position(|req| &req.delegator == delegator); if let Some(request_idx) = maybe_request_idx { let request = scheduled_requests.remove(request_idx); @@ -547,9 +582,11 @@ impl Pallet { collator: &AccountIdOf, delegator: &AccountIdOf, ) -> bool { - >::get(collator).iter().any(|req| { - &req.delegator == delegator && matches!(req.action, DelegationAction::Revoke(_)) - }) + >::get(collator) + .iter() + .any(|req| { + &req.delegator == delegator && matches!(req.action, DelegationAction::Revoke(_)) + }) } } @@ -562,7 +599,10 @@ mod tests { fn test_cancel_request_with_state_removes_request_for_correct_delegator_and_updates_state() { let mut state = Delegator { id: 1, - delegations: OrderedSet::from(vec![Bond { amount: 100, owner: 2 }]), + delegations: OrderedSet::from(vec![Bond { + amount: 100, + owner: 2, + }]), total: 100, less_total: 100, status: crate::DelegatorStatus::Active, @@ -602,7 +642,10 @@ mod tests { state, Delegator { id: 1, - delegations: OrderedSet::from(vec![Bond { amount: 100, owner: 2 }]), + delegations: OrderedSet::from(vec![Bond { + amount: 100, + owner: 2 + }]), total: 100, less_total: 0, status: crate::DelegatorStatus::Active, @@ -614,7 +657,10 @@ mod tests { fn test_cancel_request_with_state_does_nothing_when_request_does_not_exist() { let mut state = Delegator { id: 1, - delegations: OrderedSet::from(vec![Bond { amount: 100, owner: 2 }]), + delegations: OrderedSet::from(vec![Bond { + amount: 100, + owner: 2, + }]), total: 100, less_total: 100, status: crate::DelegatorStatus::Active, @@ -640,7 +686,10 @@ mod tests { state, Delegator { id: 1, - delegations: OrderedSet::from(vec![Bond { amount: 100, owner: 2 }]), + delegations: OrderedSet::from(vec![Bond { + amount: 100, + owner: 2 + }]), total: 100, less_total: 100, status: crate::DelegatorStatus::Active, diff --git a/pallets/parachain-staking/src/inflation.rs b/pallets/parachain-staking/src/inflation.rs index a013143759..b21b35de4b 100644 --- a/pallets/parachain-staking/src/inflation.rs +++ b/pallets/parachain-staking/src/inflation.rs @@ -64,7 +64,11 @@ impl Range { impl From for Range { fn from(other: T) -> Range { - Range { min: other, ideal: other, max: other } + Range { + min: other, + ideal: other, + max: other, + } } } /// Convert an annual inflation to a round inflation @@ -123,7 +127,11 @@ impl InflationInfo { annual: Range, expect: Range, ) -> InflationInfo { - InflationInfo { expect, annual, round: annual_to_round::(annual) } + InflationInfo { + expect, + annual, + round: annual_to_round::(annual), + } } /// Set round inflation range according to input annual inflation range pub fn set_round_from_annual(&mut self, new: Range) { @@ -163,8 +171,11 @@ mod tests { // 5% inflation for 10_000_0000 = 500,000 minted over the year // let's assume there are 10 periods in a year // => mint 500_000 over 10 periods => 50_000 minted per period - let expected_round_issuance_range: Range = - Range { min: 48_909, ideal: 48_909, max: 48_909 }; + let expected_round_issuance_range: Range = Range { + min: 48_909, + ideal: 48_909, + max: 48_909, + }; let schedule = Range { min: Perbill::from_percent(5), ideal: Perbill::from_percent(5), @@ -180,8 +191,11 @@ mod tests { // 3-5% inflation for 10_000_0000 = 300_000-500,000 minted over the year // let's assume there are 10 periods in a year // => mint 300_000-500_000 over 10 periods => 30_000-50_000 minted per period - let expected_round_issuance_range: Range = - Range { min: 29_603, ideal: 39298, max: 48_909 }; + let expected_round_issuance_range: Range = Range { + min: 29_603, + ideal: 39298, + max: 48_909, + }; let schedule = Range { min: Perbill::from_percent(3), ideal: Perbill::from_percent(4), @@ -194,7 +208,11 @@ mod tests { } #[test] fn expected_parameterization() { - let expected_round_schedule: Range = Range { min: 45, ideal: 56, max: 56 }; + let expected_round_schedule: Range = Range { + min: 45, + ideal: 56, + max: 56, + }; let schedule = Range { min: Perbill::from_percent(4), ideal: Perbill::from_percent(5), diff --git a/pallets/parachain-staking/src/lib.rs b/pallets/parachain-staking/src/lib.rs index 709d4ec44a..3aad21574e 100755 --- a/pallets/parachain-staking/src/lib.rs +++ b/pallets/parachain-staking/src/lib.rs @@ -343,7 +343,10 @@ pub mod pallet { scheduled_exit: RoundIndex, }, /// Delegator has left the set of delegators. - DelegatorLeft { delegator: AccountIdOf, unstaked_amount: BalanceOf }, + DelegatorLeft { + delegator: AccountIdOf, + unstaked_amount: BalanceOf, + }, /// Delegation revoked. DelegationRevoked { delegator: AccountIdOf, @@ -379,11 +382,20 @@ pub mod pallet { total_candidate_staked: BalanceOf, }, /// Paid the account (delegator or collator) the balance as liquid rewards. - Rewarded { account: AccountIdOf, rewards: BalanceOf }, + Rewarded { + account: AccountIdOf, + rewards: BalanceOf, + }, /// Transferred to account which holds funds reserved for parachain bond. - ReservedForParachainBond { account: AccountIdOf, value: BalanceOf }, + ReservedForParachainBond { + account: AccountIdOf, + value: BalanceOf, + }, /// Account (re)set for parachain bond treasury. - ParachainBondAccountSet { old: AccountIdOf, new: AccountIdOf }, + ParachainBondAccountSet { + old: AccountIdOf, + new: AccountIdOf, + }, /// Percent of inflation reserved for parachain bond (re)set. ParachainBondReservePercentSet { old: Percent, new: Percent }, /// Annual inflation input (first 3) was used to derive new per-round inflation (last 3) @@ -633,10 +645,16 @@ pub mod pallet { >::get_delegator_stakable_free_balance(delegator) >= balance, "Account does not have enough balance to place delegation." ); - let cd_count = - if let Some(x) = col_delegator_count.get(target) { *x } else { 0u32 }; - let dd_count = - if let Some(x) = del_delegation_count.get(delegator) { *x } else { 0u32 }; + let cd_count = if let Some(x) = col_delegator_count.get(target) { + *x + } else { + 0u32 + }; + let dd_count = if let Some(x) = del_delegation_count.get(delegator) { + *x + } else { + 0u32 + }; if let Err(error) = >::delegate( T::RuntimeOrigin::from(Some(delegator.clone()).into()), target.clone(), @@ -702,7 +720,10 @@ pub mod pallet { T::MonetaryGovernanceOrigin::ensure_origin(origin)?; ensure!(expectations.is_valid(), Error::::InvalidSchedule); let mut config = >::get(); - ensure!(config.expect != expectations, Error::::NoWritingSameValue); + ensure!( + config.expect != expectations, + Error::::NoWritingSameValue + ); config.set_expectations(expectations); Self::deposit_event(Event::StakeExpectationsSet { expect_min: config.expect.min, @@ -744,8 +765,11 @@ pub mod pallet { new: AccountIdOf, ) -> DispatchResultWithPostInfo { T::MonetaryGovernanceOrigin::ensure_origin(origin)?; - let ParachainBondConfig { account: old, percent, payment_in_round } = - >::get(); + let ParachainBondConfig { + account: old, + percent, + payment_in_round, + } = >::get(); ensure!(old != new, Error::::NoWritingSameValue); >::put(ParachainBondConfig { account: new.clone(), @@ -763,8 +787,11 @@ pub mod pallet { new: Percent, ) -> DispatchResultWithPostInfo { T::MonetaryGovernanceOrigin::ensure_origin(origin)?; - let ParachainBondConfig { account, percent: old, payment_in_round } = - >::get(); + let ParachainBondConfig { + account, + percent: old, + payment_in_round, + } = >::get(); ensure!(old != new, Error::::NoWritingSameValue); >::put(ParachainBondConfig { account, @@ -780,7 +807,10 @@ pub mod pallet { /// - changes are not applied until the start of the next round pub fn set_total_selected(origin: OriginFor, new: u32) -> DispatchResultWithPostInfo { frame_system::ensure_root(origin)?; - ensure!(new >= T::MinSelectedCandidates::get(), Error::::CannotSetBelowMin); + ensure!( + new >= T::MinSelectedCandidates::get(), + Error::::CannotSetBelowMin + ); let old = >::get(); ensure!(old != new, Error::::NoWritingSameValue); ensure!( @@ -813,7 +843,10 @@ pub mod pallet { /// - also updates per-round inflation config pub fn set_blocks_per_round(origin: OriginFor, new: u32) -> DispatchResultWithPostInfo { frame_system::ensure_root(origin)?; - ensure!(new >= T::MinBlocksPerRound::get(), Error::::CannotSetBelowMin); + ensure!( + new >= T::MinBlocksPerRound::get(), + Error::::CannotSetBelowMin + ); let mut round = >::get(); let (now, first, old) = (round.current, round.first, round.length); ensure!(old != new, Error::::NoWritingSameValue); @@ -849,7 +882,10 @@ pub mod pallet { let acc = ensure_signed(origin)?; ensure!(!Self::is_candidate(&acc), Error::::CandidateExists); ensure!(!Self::is_delegator(&acc), Error::::DelegatorExists); - ensure!(bond >= T::MinCandidateStk::get(), Error::::CandidateBondBelowMin); + ensure!( + bond >= T::MinCandidateStk::get(), + Error::::CandidateBondBelowMin + ); let mut candidates = >::get(); let old_count = candidates.0.len() as u32; ensure!( @@ -857,7 +893,10 @@ pub mod pallet { Error::::TooLowCandidateCountWeightHintJoinCandidates ); ensure!( - candidates.insert(Bond { owner: acc.clone(), amount: bond }), + candidates.insert(Bond { + owner: acc.clone(), + amount: bond + }), Error::::CandidateExists ); ensure!( @@ -1008,12 +1047,17 @@ pub mod pallet { Error::::TooLowCandidateCountWeightHintCancelLeaveCandidates ); ensure!( - candidates.insert(Bond { owner: collator.clone(), amount: state.total_counted }), + candidates.insert(Bond { + owner: collator.clone(), + amount: state.total_counted + }), Error::::AlreadyActive ); >::put(candidates); >::insert(&collator, state); - Self::deposit_event(Event::CancelledCandidateExit { candidate: collator }); + Self::deposit_event(Event::CancelledCandidateExit { + candidate: collator, + }); Ok(().into()) } #[pallet::call_index(11)] @@ -1029,7 +1073,9 @@ pub mod pallet { >::put(candidates); } >::insert(&collator, state); - Self::deposit_event(Event::CandidateWentOffline { candidate: collator }); + Self::deposit_event(Event::CandidateWentOffline { + candidate: collator, + }); Ok(().into()) } #[pallet::call_index(12)] @@ -1043,12 +1089,17 @@ pub mod pallet { state.go_online(); let mut candidates = >::get(); ensure!( - candidates.insert(Bond { owner: collator.clone(), amount: state.total_counted }), + candidates.insert(Bond { + owner: collator.clone(), + amount: state.total_counted + }), Error::::AlreadyActive ); >::put(candidates); >::insert(&collator, state); - Self::deposit_event(Event::CandidateBackOnline { candidate: collator }); + Self::deposit_event(Event::CandidateBackOnline { + candidate: collator, + }); Ok(().into()) } #[pallet::call_index(13)] @@ -1274,7 +1325,10 @@ pub mod pallet { let mut delegator_state = if let Some(mut state) = >::get(&delegator) { // delegation after first - ensure!(amount >= T::MinDelegation::get(), Error::::DelegationBelowMin); + ensure!( + amount >= T::MinDelegation::get(), + Error::::DelegationBelowMin + ); ensure!( delegation_count >= state.delegations.0.len() as u32, Error::::TooLowDelegationCountToDelegate @@ -1284,13 +1338,19 @@ pub mod pallet { Error::::ExceedMaxDelegationsPerDelegator ); ensure!( - state.add_delegation(Bond { owner: candidate.clone(), amount }), + state.add_delegation(Bond { + owner: candidate.clone(), + amount + }), Error::::AlreadyDelegatedCandidate ); state } else { // first delegation - ensure!(amount >= T::MinDelegatorStk::get(), Error::::DelegatorBondBelowMin); + ensure!( + amount >= T::MinDelegatorStk::get(), + Error::::DelegatorBondBelowMin + ); ensure!(!Self::is_candidate(&delegator), Error::::CandidateExists); Delegator::new(delegator.clone(), candidate.clone(), amount) }; @@ -1299,8 +1359,13 @@ pub mod pallet { candidate_delegation_count >= state.delegation_count, Error::::TooLowCandidateDelegationCountToDelegate ); - let (delegator_position, less_total_staked) = - state.add_delegation::(&candidate, Bond { owner: delegator.clone(), amount })?; + let (delegator_position, less_total_staked) = state.add_delegation::( + &candidate, + Bond { + owner: delegator.clone(), + amount, + }, + )?; // TODO: causes redundant free_balance check delegator_state.adjust_bond_lock::(BondAdjust::Increase(amount))?; // only is_some if kicked the lowest bottom as a consequence of this new delegation @@ -1365,7 +1430,10 @@ pub mod pallet { pub(crate) fn update_active(candidate: AccountIdOf, total: BalanceOf) { let mut candidates = >::get(); candidates.remove(&Bond::from_owner(candidate.clone())); - candidates.insert(Bond { owner: candidate, amount: total }); + candidates.insert(Bond { + owner: candidate, + amount: total, + }); >::put(candidates); } /// Compute round issuance based on total staked for the given round @@ -1511,10 +1579,13 @@ pub mod pallet { ExistenceRequirement::KeepAlive, ); match result { - Ok(_) => Self::deposit_event(Event::Rewarded { account: to, rewards: amt }), + Ok(_) => Self::deposit_event(Event::Rewarded { + account: to, + rewards: amt, + }), Err(e) => { log::error!("reward from pool account fail as {:?}", e); - }, + } } } }; @@ -1636,8 +1707,10 @@ pub mod pallet { delegation_count = delegation_count.saturating_add(state.delegation_count); total = total.saturating_add(state.total_counted); - let CountedDelegations { uncounted_stake, rewardable_delegations } = - Self::get_rewardable_delegators(&account); + let CountedDelegations { + uncounted_stake, + rewardable_delegations, + } = Self::get_rewardable_delegators(&account); let total_counted = state.total_counted.saturating_sub(uncounted_stake); let snapshot = CollatorSnapshot { @@ -1683,17 +1756,20 @@ pub mod pallet { Some(DelegationAction::Revoke(_)) => { uncounted_stake = uncounted_stake.saturating_add(bond.amount); BalanceOf::::zero() - }, + } Some(DelegationAction::Decrease(amount)) => { uncounted_stake = uncounted_stake.saturating_add(*amount); bond.amount.saturating_sub(*amount) - }, + } }; bond }) .collect(); - CountedDelegations { uncounted_stake, rewardable_delegations } + CountedDelegations { + uncounted_stake, + rewardable_delegations, + } } /// Add reward points to block authors: diff --git a/pallets/parachain-staking/src/migrations.rs b/pallets/parachain-staking/src/migrations.rs index 8ef72994d5..1afd4714f9 100644 --- a/pallets/parachain-staking/src/migrations.rs +++ b/pallets/parachain-staking/src/migrations.rs @@ -81,7 +81,11 @@ impl OnRuntimeUpgrade for InitGenesisMigration { let inflation_info: InflationInfo> = InflationInfo { // staking expectations - expect: Range { min: expected, ideal: expected, max: expected }, + expect: Range { + min: expected, + ideal: expected, + max: expected, + }, // annual inflation annual, round: to_round_inflation(annual), @@ -165,13 +169,13 @@ impl SplitDelegatorStateIntoDelegationScheduledRequests { "delegator({:?})_when({})_Revoke({:?})", delegator, request.when_executable, request.amount ) - }, + } DelegationChange::Decrease => { format!( "delegator({:?})_when({})_Decrease({:?})", delegator, request.when_executable, request.amount ) - }, + } } } @@ -183,13 +187,13 @@ impl SplitDelegatorStateIntoDelegationScheduledRequests { "delegator({:?})_when({})_Revoke({:?})", request.delegator, request.when_executable, v ) - }, + } DelegationAction::Decrease(v) => { format!( "delegator({:?})_when({})_Decrease({:?})", request.delegator, request.when_executable, v ) - }, + } } } } @@ -309,8 +313,12 @@ impl OnRuntimeUpgrade for SplitDelegatorStateIntoDelegationScheduledR collator_state_map, expected_delegator_state_entries, expected_requests, - ): (BTreeMap>, BTreeMap, u64, u64) = - Decode::decode(&mut &state[..]).expect("pre_upgrade provides a valid state; qed"); + ): ( + BTreeMap>, + BTreeMap, + u64, + u64, + ) = Decode::decode(&mut &state[..]).expect("pre_upgrade provides a valid state; qed"); // Scheduled decrease amount (bond_less) is correctly migrated let mut actual_delegator_state_entries = 0; for (delegator, state) in >::iter() { @@ -403,7 +411,10 @@ impl OnRuntimeUpgrade for PatchIncorrectDelegationSums { "Correcting total from {:?} to {:?}", delegations.total, correct_total ); - Delegations { delegations: delegations.delegations, total: correct_total } + Delegations { + delegations: delegations.delegations, + total: correct_total, + } } for (account, old_top_delegations) in stored_top_delegations { let new_top_delegations = fix_delegations::(old_top_delegations); @@ -424,7 +435,10 @@ impl OnRuntimeUpgrade for PatchIncorrectDelegationSums { let top = migrated_candidates_top_count.saturating_mul(3 * weight.write + 3 * weight.read); let bottom = migrated_candidates_bottom_count.saturating_mul(weight.write + weight.read); // 20% max block weight as margin for error - Weight::from_parts(top.saturating_add(bottom).saturating_add(100_000_000_000), 0) + Weight::from_parts( + top.saturating_add(bottom).saturating_add(100_000_000_000), + 0, + ) } #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { @@ -561,7 +575,10 @@ impl OnRuntimeUpgrade for RemoveDelegatorReserveToLockAndCollatorRese #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec) -> Result<(), TryRuntimeError> { - assert_eq!(DelegatorReserveToLockMigrations::::iter_keys().count(), 0); + assert_eq!( + DelegatorReserveToLockMigrations::::iter_keys().count(), + 0 + ); assert_eq!(CollatorReserveToLockMigrations::::iter_keys().count(), 0); Ok(()) } diff --git a/pallets/parachain-staking/src/mock.rs b/pallets/parachain-staking/src/mock.rs index c7a574670b..c74f01a92a 100644 --- a/pallets/parachain-staking/src/mock.rs +++ b/pallets/parachain-staking/src/mock.rs @@ -146,7 +146,11 @@ impl Default for ExtBuilder { delegations: vec![], collators: vec![], inflation: InflationInfo { - expect: Range { min: 700, ideal: 700, max: 700 }, + expect: Range { + min: 700, + ideal: 700, + max: 700, + }, // not used annual: Range { min: Perbill::from_percent(50), @@ -194,9 +198,11 @@ impl ExtBuilder { .build_storage() .expect("Frame system builds valid default genesis config"); - pallet_balances::GenesisConfig:: { balances: self.balances } - .assimilate_storage(&mut t) - .expect("Pallet balances storage can be assimilated"); + pallet_balances::GenesisConfig:: { + balances: self.balances, + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); pallet_parachain_staking::GenesisConfig:: { candidates: self.collators, delegations: self.delegations, @@ -260,9 +266,13 @@ pub(crate) fn events() -> Vec> { System::events() .into_iter() .map(|r| r.event) - .filter_map( - |e| if let RuntimeEvent::ParachainStaking(inner) = e { Some(inner) } else { None }, - ) + .filter_map(|e| { + if let RuntimeEvent::ParachainStaking(inner) = e { + Some(inner) + } else { + None + } + }) .collect::>() } @@ -355,7 +365,7 @@ macro_rules! assert_event_emitted { e, $crate::mock::events() ); - }, + } } }; } @@ -372,7 +382,7 @@ macro_rules! assert_event_not_emitted { e, $crate::mock::events() ); - }, + } } }; } @@ -413,11 +423,17 @@ fn geneses() { .execute_with(|| { assert!(System::events().is_empty()); // collators - assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 500); + assert_eq!( + ParachainStaking::get_collator_stakable_free_balance(&1), + 500 + ); assert_eq!(query_lock_amount(1, COLLATOR_LOCK_ID), Some(500)); assert!(ParachainStaking::is_candidate(&1)); assert_eq!(query_lock_amount(2, COLLATOR_LOCK_ID), Some(200)); - assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&2), 100); + assert_eq!( + ParachainStaking::get_collator_stakable_free_balance(&2), + 100 + ); assert!(ParachainStaking::is_candidate(&2)); // delegators for x in 3..7 { @@ -431,13 +447,19 @@ fn geneses() { } // no delegator staking locks assert_eq!(query_lock_amount(7, DELEGATOR_LOCK_ID), None); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&7), 100); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&7), + 100 + ); assert_eq!(query_lock_amount(8, DELEGATOR_LOCK_ID), None); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&8), 9); assert_eq!(query_lock_amount(9, DELEGATOR_LOCK_ID), None); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&9), 4); // no collator staking locks - assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&7), 100); + assert_eq!( + ParachainStaking::get_collator_stakable_free_balance(&7), + 100 + ); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&8), 9); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&9), 4); }); @@ -455,7 +477,13 @@ fn geneses() { (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) - .with_delegations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) + .with_delegations(vec![ + (6, 1, 10), + (7, 1, 10), + (8, 2, 10), + (9, 2, 10), + (10, 1, 10), + ]) .build() .execute_with(|| { assert!(System::events().is_empty()); @@ -472,7 +500,10 @@ fn geneses() { for x in 6..11 { assert!(ParachainStaking::is_delegator(&x)); assert_eq!(query_lock_amount(x, DELEGATOR_LOCK_ID), Some(10)); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&x), 90); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&x), + 90 + ); } }); } diff --git a/pallets/parachain-staking/src/set.rs b/pallets/parachain-staking/src/set.rs index 95e8ea6516..451ca05361 100644 --- a/pallets/parachain-staking/src/set.rs +++ b/pallets/parachain-staking/src/set.rs @@ -55,7 +55,7 @@ impl OrderedSet { Err(loc) => { self.0.insert(loc, value); true - }, + } } } @@ -66,7 +66,7 @@ impl OrderedSet { Ok(loc) => { self.0.remove(loc); true - }, + } Err(_) => false, } } diff --git a/pallets/parachain-staking/src/tests.rs b/pallets/parachain-staking/src/tests.rs index 5bc26eb34e..cdf94e387f 100644 --- a/pallets/parachain-staking/src/tests.rs +++ b/pallets/parachain-staking/src/tests.rs @@ -72,8 +72,14 @@ fn invalid_root_origin_fails() { fn set_total_selected_event_emits_correctly() { ExtBuilder::default().build().execute_with(|| { // before we can bump total_selected we must bump the blocks per round - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 7u32)); - assert_ok!(ParachainStaking::set_total_selected(RuntimeOrigin::root(), 6u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 7u32 + )); + assert_ok!(ParachainStaking::set_total_selected( + RuntimeOrigin::root(), + 6u32 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::TotalSelectedSet { old: 5u32, new: 6u32 @@ -95,7 +101,10 @@ fn set_total_selected_fails_if_above_blocks_per_round() { #[test] fn set_total_selected_fails_if_equal_to_blocks_per_round() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 10u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 10u32 + )); assert_noop!( ParachainStaking::set_total_selected(RuntimeOrigin::root(), 10u32), Error::::RoundLengthMustBeGreaterThanTotalSelectedCollators, @@ -106,16 +115,28 @@ fn set_total_selected_fails_if_equal_to_blocks_per_round() { #[test] fn set_total_selected_passes_if_below_blocks_per_round() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 10u32)); - assert_ok!(ParachainStaking::set_total_selected(RuntimeOrigin::root(), 9u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 10u32 + )); + assert_ok!(ParachainStaking::set_total_selected( + RuntimeOrigin::root(), + 9u32 + )); }); } #[test] fn set_blocks_per_round_fails_if_below_total_selected() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 20u32)); - assert_ok!(ParachainStaking::set_total_selected(RuntimeOrigin::root(), 15u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 20u32 + )); + assert_ok!(ParachainStaking::set_total_selected( + RuntimeOrigin::root(), + 15u32 + )); assert_noop!( ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 14u32), Error::::RoundLengthMustBeGreaterThanTotalSelectedCollators, @@ -126,8 +147,14 @@ fn set_blocks_per_round_fails_if_below_total_selected() { #[test] fn set_blocks_per_round_fails_if_equal_to_total_selected() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 10u32)); - assert_ok!(ParachainStaking::set_total_selected(RuntimeOrigin::root(), 9u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 10u32 + )); + assert_ok!(ParachainStaking::set_total_selected( + RuntimeOrigin::root(), + 9u32 + )); assert_noop!( ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 9u32), Error::::RoundLengthMustBeGreaterThanTotalSelectedCollators, @@ -139,7 +166,10 @@ fn set_blocks_per_round_fails_if_equal_to_total_selected() { fn set_blocks_per_round_passes_if_above_total_selected() { ExtBuilder::default().build().execute_with(|| { assert_eq!(Round::::get().length, 5); // test relies on this - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 6u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 6u32 + )); }); } @@ -147,10 +177,16 @@ fn set_blocks_per_round_passes_if_above_total_selected() { fn set_total_selected_storage_updates_correctly() { ExtBuilder::default().build().execute_with(|| { // round length must be >= total_selected, so update that first - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 10u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 10u32 + )); assert_eq!(TotalSelected::::get(), 5u32); - assert_ok!(ParachainStaking::set_total_selected(RuntimeOrigin::root(), 6u32)); + assert_ok!(ParachainStaking::set_total_selected( + RuntimeOrigin::root(), + 6u32 + )); assert_eq!(TotalSelected::::get(), 6u32); }); } @@ -221,7 +257,10 @@ fn cannot_set_collator_commission_to_current_collator_commission() { #[test] fn set_blocks_per_round_event_emits_correctly() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 6u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 6u32 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::BlocksPerRoundSet { current_round: 1, first_block: 0, @@ -238,7 +277,10 @@ fn set_blocks_per_round_event_emits_correctly() { fn set_blocks_per_round_storage_updates_correctly() { ExtBuilder::default().build().execute_with(|| { assert_eq!(Round::::get().length, 5); - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 6u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 6u32 + )); assert_eq!(Round::::get().length, 6); }); } @@ -273,7 +315,10 @@ fn round_immediately_jumps_if_current_duration_exceeds_new_blocks_per_round() { // we can't lower the blocks per round because it must be above the number of collators, // and we can't lower the number of collators because it must be above // MinSelectedCandidates. so we first raise blocks per round, then lower it. - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 10u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 10u32 + )); roll_to(17); assert_last_event!(MetaEvent::ParachainStaking(Event::NewRound { @@ -282,7 +327,10 @@ fn round_immediately_jumps_if_current_duration_exceeds_new_blocks_per_round() { selected_collators_number: 1, total_balance: 20 })); - assert_ok!(ParachainStaking::set_blocks_per_round(RuntimeOrigin::root(), 6u32)); + assert_ok!(ParachainStaking::set_blocks_per_round( + RuntimeOrigin::root(), + 6u32 + )); roll_to(18); assert_last_event!(MetaEvent::ParachainStaking(Event::NewRound { starting_block: 18, @@ -301,7 +349,11 @@ fn invalid_monetary_origin_fails() { assert_noop!( ParachainStaking::set_staking_expectations( RuntimeOrigin::signed(45), - Range { min: 3u32.into(), ideal: 4u32.into(), max: 5u32.into() } + Range { + min: 3u32.into(), + ideal: 4u32.into(), + max: 5u32.into() + } ), sp_runtime::DispatchError::BadOrigin ); @@ -349,7 +401,11 @@ fn set_staking_event_emits_event_correctly() { // valid call succeeds assert_ok!(ParachainStaking::set_staking_expectations( RuntimeOrigin::root(), - Range { min: 3u128, ideal: 4u128, max: 5u128 } + Range { + min: 3u128, + ideal: 4u128, + max: 5u128 + } )); assert_last_event!(MetaEvent::ParachainStaking(Event::StakeExpectationsSet { expect_min: 3u128, @@ -362,14 +418,29 @@ fn set_staking_event_emits_event_correctly() { #[test] fn set_staking_updates_storage_correctly() { ExtBuilder::default().build().execute_with(|| { - assert_eq!(InflationConfig::::get().expect, Range { min: 700, ideal: 700, max: 700 }); + assert_eq!( + InflationConfig::::get().expect, + Range { + min: 700, + ideal: 700, + max: 700 + } + ); assert_ok!(ParachainStaking::set_staking_expectations( RuntimeOrigin::root(), - Range { min: 3u128, ideal: 4u128, max: 5u128 } + Range { + min: 3u128, + ideal: 4u128, + max: 5u128 + } )); assert_eq!( InflationConfig::::get().expect, - Range { min: 3u128, ideal: 4u128, max: 5u128 } + Range { + min: 3u128, + ideal: 4u128, + max: 5u128 + } ); }); } @@ -381,7 +452,11 @@ fn cannot_set_invalid_staking_expectations() { assert_noop!( ParachainStaking::set_staking_expectations( RuntimeOrigin::root(), - Range { min: 5u128, ideal: 4u128, max: 3u128 } + Range { + min: 5u128, + ideal: 4u128, + max: 3u128 + } ), Error::::InvalidSchedule ); @@ -393,12 +468,20 @@ fn cannot_set_same_staking_expectations() { ExtBuilder::default().build().execute_with(|| { assert_ok!(ParachainStaking::set_staking_expectations( RuntimeOrigin::root(), - Range { min: 3u128, ideal: 4u128, max: 5u128 } + Range { + min: 3u128, + ideal: 4u128, + max: 5u128 + } )); assert_noop!( ParachainStaking::set_staking_expectations( RuntimeOrigin::root(), - Range { min: 3u128, ideal: 4u128, max: 5u128 } + Range { + min: 3u128, + ideal: 4u128, + max: 5u128 + } ), Error::::NoWritingSameValue ); @@ -410,8 +493,11 @@ fn cannot_set_same_staking_expectations() { #[test] fn set_inflation_event_emits_correctly() { ExtBuilder::default().build().execute_with(|| { - let (min, ideal, max): (Perbill, Perbill, Perbill) = - (Perbill::from_percent(3), Perbill::from_percent(4), Perbill::from_percent(5)); + let (min, ideal, max): (Perbill, Perbill, Perbill) = ( + Perbill::from_percent(3), + Perbill::from_percent(4), + Perbill::from_percent(5), + ); assert_ok!(ParachainStaking::set_inflation( RuntimeOrigin::root(), Range { min, ideal, max } @@ -430,8 +516,11 @@ fn set_inflation_event_emits_correctly() { #[test] fn set_inflation_storage_updates_correctly() { ExtBuilder::default().build().execute_with(|| { - let (min, ideal, max): (Perbill, Perbill, Perbill) = - (Perbill::from_percent(3), Perbill::from_percent(4), Perbill::from_percent(5)); + let (min, ideal, max): (Perbill, Perbill, Perbill) = ( + Perbill::from_percent(3), + Perbill::from_percent(4), + Perbill::from_percent(5), + ); assert_eq!( InflationConfig::::get().annual, Range { @@ -452,7 +541,10 @@ fn set_inflation_storage_updates_correctly() { RuntimeOrigin::root(), Range { min, ideal, max } ),); - assert_eq!(InflationConfig::::get().annual, Range { min, ideal, max }); + assert_eq!( + InflationConfig::::get().annual, + Range { min, ideal, max } + ); assert_eq!( InflationConfig::::get().round, Range { @@ -484,8 +576,11 @@ fn cannot_set_invalid_inflation() { #[test] fn cannot_set_same_inflation() { ExtBuilder::default().build().execute_with(|| { - let (min, ideal, max): (Perbill, Perbill, Perbill) = - (Perbill::from_percent(3), Perbill::from_percent(4), Perbill::from_percent(5)); + let (min, ideal, max): (Perbill, Perbill, Perbill) = ( + Perbill::from_percent(3), + Perbill::from_percent(4), + Perbill::from_percent(5), + ); assert_ok!(ParachainStaking::set_inflation( RuntimeOrigin::root(), Range { min, ideal, max } @@ -502,11 +597,13 @@ fn cannot_set_same_inflation() { #[test] fn set_parachain_bond_account_event_emits_correctly() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(ParachainStaking::set_parachain_bond_account(RuntimeOrigin::root(), 11)); - assert_last_event!(MetaEvent::ParachainStaking(Event::ParachainBondAccountSet { - old: 0, - new: 11 - })); + assert_ok!(ParachainStaking::set_parachain_bond_account( + RuntimeOrigin::root(), + 11 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::ParachainBondAccountSet { old: 0, new: 11 } + )); }); } @@ -514,7 +611,10 @@ fn set_parachain_bond_account_event_emits_correctly() { fn set_parachain_bond_account_storage_updates_correctly() { ExtBuilder::default().build().execute_with(|| { assert_eq!(ParachainBondInfo::::get().account, 0); - assert_ok!(ParachainStaking::set_parachain_bond_account(RuntimeOrigin::root(), 11)); + assert_ok!(ParachainStaking::set_parachain_bond_account( + RuntimeOrigin::root(), + 11 + )); assert_eq!(ParachainBondInfo::::get().account, 11); }); } @@ -528,22 +628,30 @@ fn set_parachain_bond_reserve_percent_event_emits_correctly() { RuntimeOrigin::root(), Percent::from_percent(50) )); - assert_last_event!(MetaEvent::ParachainStaking(Event::ParachainBondReservePercentSet { - old: Percent::from_percent(30), - new: Percent::from_percent(50), - })); + assert_last_event!(MetaEvent::ParachainStaking( + Event::ParachainBondReservePercentSet { + old: Percent::from_percent(30), + new: Percent::from_percent(50), + } + )); }); } #[test] fn set_parachain_bond_reserve_percent_storage_updates_correctly() { ExtBuilder::default().build().execute_with(|| { - assert_eq!(ParachainBondInfo::::get().percent, Percent::from_percent(30)); + assert_eq!( + ParachainBondInfo::::get().percent, + Percent::from_percent(30) + ); assert_ok!(ParachainStaking::set_parachain_bond_reserve_percent( RuntimeOrigin::root(), Percent::from_percent(50) )); - assert_eq!(ParachainBondInfo::::get().percent, Percent::from_percent(50)); + assert_eq!( + ParachainBondInfo::::get().percent, + Percent::from_percent(50) + ); }); } @@ -566,53 +674,90 @@ fn cannot_set_same_parachain_bond_reserve_percent() { #[test] fn join_candidates_event_emits_correctly() { - ExtBuilder::default().with_balances(vec![(1, 10)]).build().execute_with(|| { - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 10u128, 0u32)); - assert_last_event!(MetaEvent::ParachainStaking(Event::JoinedCollatorCandidates { - account: 1, - amount_locked: 10u128, - new_total_amt_locked: 10u128, - })); - }); + ExtBuilder::default() + .with_balances(vec![(1, 10)]) + .build() + .execute_with(|| { + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(1), + 10u128, + 0u32 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::JoinedCollatorCandidates { + account: 1, + amount_locked: 10u128, + new_total_amt_locked: 10u128, + } + )); + }); } #[test] fn join_candidates_reserves_balance() { - ExtBuilder::default().with_balances(vec![(1, 10)]).build().execute_with(|| { - assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 10); - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 10u128, 0u32)); - assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 0); - }); + ExtBuilder::default() + .with_balances(vec![(1, 10)]) + .build() + .execute_with(|| { + assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 10); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(1), + 10u128, + 0u32 + )); + assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 0); + }); } #[test] fn join_candidates_increases_total_staked() { - ExtBuilder::default().with_balances(vec![(1, 10)]).build().execute_with(|| { - assert_eq!(Total::::get(), 0); - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 10u128, 0u32)); - assert_eq!(Total::::get(), 10); - }); + ExtBuilder::default() + .with_balances(vec![(1, 10)]) + .build() + .execute_with(|| { + assert_eq!(Total::::get(), 0); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(1), + 10u128, + 0u32 + )); + assert_eq!(Total::::get(), 10); + }); } #[test] fn join_candidates_creates_candidate_state() { - ExtBuilder::default().with_balances(vec![(1, 10)]).build().execute_with(|| { - assert!(CandidateInfo::::get(1).is_none()); - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 10u128, 0u32)); - let candidate_state = CandidateInfo::::get(1).expect("just joined => exists"); - assert_eq!(candidate_state.bond, 10u128); - }); + ExtBuilder::default() + .with_balances(vec![(1, 10)]) + .build() + .execute_with(|| { + assert!(CandidateInfo::::get(1).is_none()); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(1), + 10u128, + 0u32 + )); + let candidate_state = CandidateInfo::::get(1).expect("just joined => exists"); + assert_eq!(candidate_state.bond, 10u128); + }); } #[test] fn join_candidates_adds_to_candidate_pool() { - ExtBuilder::default().with_balances(vec![(1, 10)]).build().execute_with(|| { - assert!(CandidatePool::::get().0.is_empty()); - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 10u128, 0u32)); - let candidate_pool = CandidatePool::::get(); - assert_eq!(candidate_pool.0[0].owner, 1); - assert_eq!(candidate_pool.0[0].amount, 10); - }); + ExtBuilder::default() + .with_balances(vec![(1, 10)]) + .build() + .execute_with(|| { + assert!(CandidatePool::::get().0.is_empty()); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(1), + 10u128, + 0u32 + )); + let candidate_pool = CandidatePool::::get(); + assert_eq!(candidate_pool.0[0].owner, 1); + assert_eq!(candidate_pool.0[0].amount, 10); + }); } #[test] @@ -646,26 +791,32 @@ fn cannot_join_candidates_if_delegator() { #[test] fn cannot_join_candidates_without_min_bond() { - ExtBuilder::default().with_balances(vec![(1, 1000)]).build().execute_with(|| { - assert_noop!( - ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 9u128, 100u32), - Error::::CandidateBondBelowMin - ); - }); + ExtBuilder::default() + .with_balances(vec![(1, 1000)]) + .build() + .execute_with(|| { + assert_noop!( + ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 9u128, 100u32), + Error::::CandidateBondBelowMin + ); + }); } #[test] fn cannot_join_candidates_with_more_than_available_balance() { - ExtBuilder::default().with_balances(vec![(1, 500)]).build().execute_with(|| { - assert_noop!( - ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 501u128, 100u32), - DispatchError::Module(ModuleError { - index: 2, - error: [8, 0, 0, 0], - message: Some("InsufficientBalance") - }) - ); - }); + ExtBuilder::default() + .with_balances(vec![(1, 500)]) + .build() + .execute_with(|| { + assert_noop!( + ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 501u128, 100u32), + DispatchError::Module(ModuleError { + index: 2, + error: [8, 0, 0, 0], + message: Some("InsufficientBalance") + }) + ); + }); } #[test] @@ -703,7 +854,11 @@ fn sufficient_join_candidates_weight_hint_succeeds() { .execute_with(|| { let mut count = 5u32; for i in 6..10 { - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(i), 20, count)); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(i), + 20, + count + )); count += 1u32; } }); @@ -718,7 +873,10 @@ fn leave_candidates_event_emits_correctly() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateScheduledExit { exit_allowed_round: 1, candidate: 1, @@ -735,7 +893,10 @@ fn leave_candidates_removes_candidate_from_candidate_pool() { .build() .execute_with(|| { assert_eq!(CandidatePool::::get().0.len(), 1); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); assert!(CandidatePool::::get().0.is_empty()); }); } @@ -757,7 +918,10 @@ fn cannot_leave_candidates_if_already_leaving_candidates() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); assert_noop!( ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32), Error::::CandidateAlreadyLeaving @@ -808,9 +972,16 @@ fn execute_leave_candidates_emits_event() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 0 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateLeft { ex_candidate: 1, unlocked_amount: 10, @@ -826,9 +997,16 @@ fn execute_leave_candidates_callable_by_any_signed() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(2), + 1, + 0 + )); }); } @@ -840,7 +1018,10 @@ fn execute_leave_candidates_requires_correct_weight_hint() { .with_delegations(vec![(2, 1, 10), (3, 1, 10), (4, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); roll_to(10); for i in 0..3 { assert_noop!( @@ -848,7 +1029,11 @@ fn execute_leave_candidates_requires_correct_weight_hint() { Error::::TooLowCandidateDelegationCountToLeaveCandidates ); } - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 1, 3)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(2), + 1, + 3 + )); }); } @@ -860,9 +1045,16 @@ fn execute_leave_candidates_unreserves_balance() { .build() .execute_with(|| { assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 0); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 0 + )); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 10); }); } @@ -875,9 +1067,16 @@ fn execute_leave_candidates_decreases_total_staked() { .build() .execute_with(|| { assert_eq!(Total::::get(), 10); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 0 + )); assert_eq!(Total::::get(), 0); }); } @@ -889,12 +1088,19 @@ fn execute_leave_candidates_removes_candidate_state() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); // candidate state is not immediately removed let candidate_state = CandidateInfo::::get(1).expect("just left => still exists"); assert_eq!(candidate_state.bond, 10u128); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 0 + )); assert!(CandidateInfo::::get(1).is_none()); }); } @@ -921,15 +1127,24 @@ fn execute_leave_candidates_removes_pending_delegation_requests() { action: DelegationAction::Decrease(5), }], ); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); // candidate state is not immediately removed let candidate_state = CandidateInfo::::get(1).expect("just left => still exists"); assert_eq!(candidate_state.bond, 10u128); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 1 + )); assert!(CandidateInfo::::get(1).is_none()); assert!( - !DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2), + !DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2), "delegation request not removed" ); assert!( @@ -946,7 +1161,10 @@ fn cannot_execute_leave_candidates_before_delay() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); assert_noop!( ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(3), 1, 0), Error::::CandidateCannotLeaveYet @@ -957,7 +1175,11 @@ fn cannot_execute_leave_candidates_before_delay() { Error::::CandidateCannotLeaveYet ); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(3), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(3), + 1, + 0 + )); }); } @@ -970,8 +1192,14 @@ fn cancel_leave_candidates_emits_event() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); - assert_ok!(ParachainStaking::cancel_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); + assert_ok!(ParachainStaking::cancel_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::CancelledCandidateExit { candidate: 1 })); @@ -985,8 +1213,14 @@ fn cancel_leave_candidates_updates_candidate_state() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); - assert_ok!(ParachainStaking::cancel_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); + assert_ok!(ParachainStaking::cancel_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); let candidate = CandidateInfo::::get(&1).expect("just cancelled leave so exists"); assert!(candidate.is_active()); }); @@ -999,8 +1233,14 @@ fn cancel_leave_candidates_adds_to_candidate_pool() { .with_candidates(vec![(1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); - assert_ok!(ParachainStaking::cancel_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1u32 + )); + assert_ok!(ParachainStaking::cancel_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); assert_eq!(CandidatePool::::get().0[0].owner, 1); assert_eq!(CandidatePool::::get().0[0].amount, 10); }); @@ -1155,7 +1395,10 @@ fn cannot_go_online_if_leaving() { .with_candidates(vec![(1, 20)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); assert_noop!( ParachainStaking::go_online(RuntimeOrigin::signed(1)), Error::::CannotGoOnlineIfLeaving @@ -1172,7 +1415,10 @@ fn candidate_bond_more_emits_correct_event() { .with_candidates(vec![(1, 20)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::candidate_bond_more(RuntimeOrigin::signed(1), 30)); + assert_ok!(ParachainStaking::candidate_bond_more( + RuntimeOrigin::signed(1), + 30 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateBondedMore { candidate: 1, amount: 30, @@ -1189,7 +1435,10 @@ fn candidate_bond_more_reserves_balance() { .build() .execute_with(|| { assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 30); - assert_ok!(ParachainStaking::candidate_bond_more(RuntimeOrigin::signed(1), 30)); + assert_ok!(ParachainStaking::candidate_bond_more( + RuntimeOrigin::signed(1), + 30 + )); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 0); }); } @@ -1202,7 +1451,10 @@ fn candidate_bond_more_increases_total() { .build() .execute_with(|| { let mut total = Total::::get(); - assert_ok!(ParachainStaking::candidate_bond_more(RuntimeOrigin::signed(1), 30)); + assert_ok!(ParachainStaking::candidate_bond_more( + RuntimeOrigin::signed(1), + 30 + )); total += 30; assert_eq!(Total::::get(), total); }); @@ -1217,7 +1469,10 @@ fn candidate_bond_more_updates_candidate_state() { .execute_with(|| { let candidate_state = CandidateInfo::::get(1).expect("updated => exists"); assert_eq!(candidate_state.bond, 20); - assert_ok!(ParachainStaking::candidate_bond_more(RuntimeOrigin::signed(1), 30)); + assert_ok!(ParachainStaking::candidate_bond_more( + RuntimeOrigin::signed(1), + 30 + )); let candidate_state = CandidateInfo::::get(1).expect("updated => exists"); assert_eq!(candidate_state.bond, 50); }); @@ -1232,7 +1487,10 @@ fn candidate_bond_more_updates_candidate_pool() { .execute_with(|| { assert_eq!(CandidatePool::::get().0[0].owner, 1); assert_eq!(CandidatePool::::get().0[0].amount, 20); - assert_ok!(ParachainStaking::candidate_bond_more(RuntimeOrigin::signed(1), 30)); + assert_ok!(ParachainStaking::candidate_bond_more( + RuntimeOrigin::signed(1), + 30 + )); assert_eq!(CandidatePool::::get().0[0].owner, 1); assert_eq!(CandidatePool::::get().0[0].amount, 50); }); @@ -1251,11 +1509,13 @@ fn schedule_candidate_bond_less_event_emits_correctly() { RuntimeOrigin::signed(1), 10 )); - assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateBondLessRequested { - candidate: 1, - amount_to_decrease: 10, - execute_round: 3, - })); + assert_last_event!(MetaEvent::ParachainStaking( + Event::CandidateBondLessRequested { + candidate: 1, + amount_to_decrease: 10, + execute_round: 3, + } + )); }); } @@ -1266,7 +1526,10 @@ fn cannot_schedule_candidate_bond_less_if_request_exists() { .with_candidates(vec![(1, 30)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_candidate_bond_less(RuntimeOrigin::signed(1), 5)); + assert_ok!(ParachainStaking::schedule_candidate_bond_less( + RuntimeOrigin::signed(1), + 5 + )); assert_noop!( ParachainStaking::schedule_candidate_bond_less(RuntimeOrigin::signed(1), 5), Error::::PendingCandidateRequestAlreadyExists @@ -1305,7 +1568,10 @@ fn can_schedule_candidate_bond_less_if_leaving_candidates() { .with_candidates(vec![(1, 30)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); assert_ok!(ParachainStaking::schedule_candidate_bond_less( RuntimeOrigin::signed(1), 10 @@ -1320,9 +1586,16 @@ fn cannot_schedule_candidate_bond_less_if_exited_candidates() { .with_candidates(vec![(1, 30)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 0)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 0 + )); assert_noop!( ParachainStaking::schedule_candidate_bond_less(RuntimeOrigin::signed(1), 10), Error::::CandidateDNE @@ -1344,9 +1617,12 @@ fn execute_candidate_bond_less_emits_correct_event() { 30 )); roll_to(10); - assert_ok!(ParachainStaking::execute_candidate_bond_less(RuntimeOrigin::signed(1), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateBondedLess { - candidate: 1, + assert_ok!(ParachainStaking::execute_candidate_bond_less( + RuntimeOrigin::signed(1), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateBondedLess { + candidate: 1, amount: 30, new_bond: 20 })); @@ -1366,7 +1642,10 @@ fn execute_candidate_bond_less_unreserves_balance() { 10 )); roll_to(10); - assert_ok!(ParachainStaking::execute_candidate_bond_less(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::execute_candidate_bond_less( + RuntimeOrigin::signed(1), + 1 + )); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 10); }); } @@ -1384,7 +1663,10 @@ fn execute_candidate_bond_less_decreases_total() { 10 )); roll_to(10); - assert_ok!(ParachainStaking::execute_candidate_bond_less(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::execute_candidate_bond_less( + RuntimeOrigin::signed(1), + 1 + )); total -= 10; assert_eq!(Total::::get(), total); }); @@ -1404,7 +1686,10 @@ fn execute_candidate_bond_less_updates_candidate_state() { 10 )); roll_to(10); - assert_ok!(ParachainStaking::execute_candidate_bond_less(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::execute_candidate_bond_less( + RuntimeOrigin::signed(1), + 1 + )); let candidate_state = CandidateInfo::::get(1).expect("updated => exists"); assert_eq!(candidate_state.bond, 20); }); @@ -1424,7 +1709,10 @@ fn execute_candidate_bond_less_updates_candidate_pool() { 10 )); roll_to(10); - assert_ok!(ParachainStaking::execute_candidate_bond_less(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::execute_candidate_bond_less( + RuntimeOrigin::signed(1), + 1 + )); assert_eq!(CandidatePool::::get().0[0].owner, 1); assert_eq!(CandidatePool::::get().0[0].amount, 20); }); @@ -1443,12 +1731,16 @@ fn cancel_candidate_bond_less_emits_event() { RuntimeOrigin::signed(1), 10 )); - assert_ok!(ParachainStaking::cancel_candidate_bond_less(RuntimeOrigin::signed(1))); - assert_last_event!(MetaEvent::ParachainStaking(Event::CancelledCandidateBondLess { - candidate: 1, - amount: 10, - execute_round: 3, - })); + assert_ok!(ParachainStaking::cancel_candidate_bond_less( + RuntimeOrigin::signed(1) + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::CancelledCandidateBondLess { + candidate: 1, + amount: 10, + execute_round: 3, + } + )); }); } @@ -1463,7 +1755,9 @@ fn cancel_candidate_bond_less_updates_candidate_state() { RuntimeOrigin::signed(1), 10 )); - assert_ok!(ParachainStaking::cancel_candidate_bond_less(RuntimeOrigin::signed(1))); + assert_ok!(ParachainStaking::cancel_candidate_bond_less( + RuntimeOrigin::signed(1) + )); assert!(CandidateInfo::::get(&1).unwrap().request.is_none()); }); } @@ -1495,7 +1789,13 @@ fn delegate_event_emits_correctly() { .with_candidates(vec![(1, 30)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 10, 0, 0)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 1, + 10, + 0, + 0 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::Delegation { delegator: 2, locked_amount: 10, @@ -1512,8 +1812,17 @@ fn delegate_reserves_balance() { .with_candidates(vec![(1, 30)]) .build() .execute_with(|| { - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 10); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 10, 0, 0)); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&2), + 10 + ); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 1, + 10, + 0, + 0 + )); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 0); }); } @@ -1526,7 +1835,13 @@ fn delegate_updates_delegator_state() { .build() .execute_with(|| { assert!(DelegatorState::::get(2).is_none()); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 10, 0, 0)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 1, + 10, + 0, + 0 + )); let delegator_state = DelegatorState::::get(2).expect("just delegated => exists"); assert_eq!(delegator_state.total(), 10); assert_eq!(delegator_state.delegations.0[0].owner, 1); @@ -1546,7 +1861,13 @@ fn delegate_updates_collator_state() { let top_delegations = TopDelegations::::get(1).expect("registered in genesis"); assert!(top_delegations.delegations.is_empty()); assert!(top_delegations.total.is_zero()); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 10, 0, 0)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 1, + 10, + 0, + 0 + )); let candidate_state = CandidateInfo::::get(1).expect("just delegated => exists"); assert_eq!(candidate_state.total_counted, 40); let top_delegations = TopDelegations::::get(1).expect("just delegated => exists"); @@ -1562,8 +1883,18 @@ fn can_delegate_immediately_after_other_join_candidates() { .with_balances(vec![(1, 20), (2, 20)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(1), 20, 0)); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 20, 0, 0)); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(1), + 20, + 0 + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 1, + 20, + 0, + 0 + )); }); } @@ -1575,8 +1906,17 @@ fn can_delegate_if_revoking() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 4, 10, 0, 2)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 4, + 10, + 0, + 2 + )); }); } @@ -1645,13 +1985,22 @@ fn can_delegate_if_full_and_new_delegation_greater_than_lowest_bottom() { ]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(11), 1, 11, 8, 0)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(11), + 1, + 11, + 8, + 0 + )); assert_event_emitted!(Event::DelegationKicked { delegator: 10, candidate: 1, unstaked_amount: 10 }); - assert_event_emitted!(Event::DelegatorLeft { delegator: 10, unstaked_amount: 10 }); + assert_event_emitted!(Event::DelegatorLeft { + delegator: 10, + unstaked_amount: 10 + }); }); } @@ -1663,8 +2012,16 @@ fn can_still_delegate_if_leaving() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 3, 10, 0, 1),); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 3, + 10, + 0, + 1 + ),); }); } @@ -1815,7 +2172,9 @@ fn schedule_leave_delegators_event_emits_correctly() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_last_event!(MetaEvent::ParachainStaking(Event::DelegatorExitScheduled { round: 1, delegator: 2, @@ -1832,7 +2191,9 @@ fn cannot_schedule_leave_delegators_if_already_leaving() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_noop!( ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2)), Error::::DelegatorAlreadyLeaving @@ -1864,10 +2225,19 @@ fn execute_leave_delegators_event_emits_correctly() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); - assert_event_emitted!(Event::DelegatorLeft { delegator: 2, unstaked_amount: 10 }); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); + assert_event_emitted!(Event::DelegatorLeft { + delegator: 2, + unstaked_amount: 10 + }); }); } @@ -1879,11 +2249,23 @@ fn execute_leave_delegators_unreserves_balance() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 00); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&2), + 00 + ); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 10); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&2), + 10 + ); assert_eq!(crate::mock::query_lock_amount(2, DELEGATOR_LOCK_ID), None); }); } @@ -1897,9 +2279,15 @@ fn execute_leave_delegators_decreases_total_staked() { .build() .execute_with(|| { assert_eq!(Total::::get(), 40); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); assert_eq!(Total::::get(), 30); }); } @@ -1913,9 +2301,15 @@ fn execute_leave_delegators_removes_delegator_state() { .build() .execute_with(|| { assert!(DelegatorState::::get(2).is_some()); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); assert!(DelegatorState::::get(2).is_none()); }); } @@ -1942,12 +2336,20 @@ fn execute_leave_delegators_removes_pending_delegation_requests() { action: DelegationAction::Decrease(5), }], ); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); assert!(DelegatorState::::get(2).is_none()); assert!( - !DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2), + !DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2), "delegation request not removed" ) }); @@ -1971,10 +2373,19 @@ fn execute_leave_delegators_removes_delegations_from_collator_state() { assert_eq!(top_delegations.delegations[0].amount, 10); assert_eq!(top_delegations.total, 10); } - assert_eq!(DelegatorState::::get(1).unwrap().delegations.0.len(), 4usize); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(1))); + assert_eq!( + DelegatorState::::get(1).unwrap().delegations.0.len(), + 4usize + ); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(1) + )); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(1), 1, 10)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(1), + 1, + 10 + )); for i in 2..6 { let candidate_state = CandidateInfo::::get(i).expect("initialized in ext builder"); @@ -1994,14 +2405,20 @@ fn cannot_execute_leave_delegators_before_delay() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_noop!( ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1), Error::::DelegatorCannotLeaveYet ); // can execute after delay roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); }); } @@ -2013,8 +2430,13 @@ fn cannot_execute_leave_delegators_if_single_delegation_revoke_manually_cancelle .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 3)); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 3 + )); roll_to(10); assert_noop!( ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 2), @@ -2022,9 +2444,16 @@ fn cannot_execute_leave_delegators_if_single_delegation_revoke_manually_cancelle ); // can execute after manually scheduling revoke, and the round delay after which // all revokes can be executed - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 3)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 3 + )); roll_to(20); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 2)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 2 + )); }); } @@ -2037,7 +2466,9 @@ fn insufficient_execute_leave_delegators_weight_hint_fails() { .build() .execute_with(|| { for i in 3..7 { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(i))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(i) + )); } roll_to(10); for i in 3..7 { @@ -2058,7 +2489,9 @@ fn sufficient_execute_leave_delegators_weight_hint_succeeds() { .build() .execute_with(|| { for i in 3..7 { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(i))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(i) + )); } roll_to(10); for i in 3..7 { @@ -2081,8 +2514,12 @@ fn cancel_leave_delegators_emits_correct_event() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); - assert_ok!(ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); + assert_ok!(ParachainStaking::cancel_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_last_event!(MetaEvent::ParachainStaking(Event::DelegatorExitCancelled { delegator: 2 })); @@ -2097,8 +2534,12 @@ fn cancel_leave_delegators_updates_delegator_state() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); - assert_ok!(ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); + assert_ok!(ParachainStaking::cancel_leave_delegators( + RuntimeOrigin::signed(2) + )); let delegator = DelegatorState::::get(&2).expect("just cancelled exit so exists"); assert!(delegator.is_active()); }); @@ -2112,8 +2553,13 @@ fn cannot_cancel_leave_delegators_if_single_delegation_revoke_manually_cancelled .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 3)); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 3 + )); roll_to(10); assert_noop!( ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2)), @@ -2121,8 +2567,13 @@ fn cannot_cancel_leave_delegators_if_single_delegation_revoke_manually_cancelled ); // can execute after manually scheduling revoke, without waiting for round delay after // which all revokes can be executed - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 3)); - assert_ok!(ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 3 + )); + assert_ok!(ParachainStaking::cancel_leave_delegators( + RuntimeOrigin::signed(2) + )); }); } @@ -2136,13 +2587,18 @@ fn revoke_delegation_event_emits_correctly() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationRevocationScheduled { - round: 1, - delegator: 2, - candidate: 1, - scheduled_exit: 3, - })); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationRevocationScheduled { + round: 1, + delegator: 2, + candidate: 1, + scheduled_exit: 3, + } + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2166,9 +2622,15 @@ fn can_revoke_delegation_if_revoking_another_delegation() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); // this is an exit implicitly because last delegation revoked - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 3)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 3 + )); }); } @@ -2180,7 +2642,9 @@ fn delegator_not_allowed_revoke_if_already_leaving() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_noop!( ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 3), >::PendingDelegationRequestAlreadyExists, @@ -2223,7 +2687,10 @@ fn can_schedule_revoke_delegation_below_min_delegator_stake() { .with_delegations(vec![(2, 1, 5), (2, 3, 3)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); }); } @@ -2238,7 +2705,11 @@ fn delegator_bond_more_reserves_balance() { .build() .execute_with(|| { assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 5); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 0); }); } @@ -2252,7 +2723,11 @@ fn delegator_bond_more_increases_total_staked() { .build() .execute_with(|| { assert_eq!(Total::::get(), 40); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); assert_eq!(Total::::get(), 45); }); } @@ -2266,7 +2741,11 @@ fn delegator_bond_more_updates_delegator_state() { .build() .execute_with(|| { assert_eq!(DelegatorState::::get(2).expect("exists").total(), 10); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); assert_eq!(DelegatorState::::get(2).expect("exists").total(), 15); }); } @@ -2279,12 +2758,28 @@ fn delegator_bond_more_updates_candidate_state_top_delegations() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].owner, 2); - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].amount, 10); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].owner, + 2 + ); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].amount, + 10 + ); assert_eq!(TopDelegations::::get(1).unwrap().total, 10); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].owner, 2); - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].amount, 15); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].owner, + 2 + ); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].amount, + 15 + ); assert_eq!(TopDelegations::::get(1).unwrap().total, 15); }); } @@ -2294,25 +2789,53 @@ fn delegator_bond_more_updates_candidate_state_bottom_delegations() { ExtBuilder::default() .with_balances(vec![(1, 30), (2, 20), (3, 20), (4, 20), (5, 20), (6, 20)]) .with_candidates(vec![(1, 30)]) - .with_delegations(vec![(2, 1, 10), (3, 1, 20), (4, 1, 20), (5, 1, 20), (6, 1, 20)]) + .with_delegations(vec![ + (2, 1, 10), + (3, 1, 20), + (4, 1, 20), + (5, 1, 20), + (6, 1, 20), + ]) .build() .execute_with(|| { - assert_eq!(BottomDelegations::::get(1).expect("exists").delegations[0].owner, 2); assert_eq!( - BottomDelegations::::get(1).expect("exists").delegations[0].amount, + BottomDelegations::::get(1) + .expect("exists") + .delegations[0] + .owner, + 2 + ); + assert_eq!( + BottomDelegations::::get(1) + .expect("exists") + .delegations[0] + .amount, 10 ); assert_eq!(BottomDelegations::::get(1).unwrap().total, 10); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationIncreased { delegator: 2, candidate: 1, amount: 5, in_top: false })); - assert_eq!(BottomDelegations::::get(1).expect("exists").delegations[0].owner, 2); assert_eq!( - BottomDelegations::::get(1).expect("exists").delegations[0].amount, + BottomDelegations::::get(1) + .expect("exists") + .delegations[0] + .owner, + 2 + ); + assert_eq!( + BottomDelegations::::get(1) + .expect("exists") + .delegations[0] + .amount, 15 ); assert_eq!(BottomDelegations::::get(1).unwrap().total, 15); @@ -2328,7 +2851,11 @@ fn delegator_bond_more_increases_total() { .build() .execute_with(|| { assert_eq!(Total::::get(), 40); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); assert_eq!(Total::::get(), 45); }); } @@ -2341,8 +2868,15 @@ fn can_delegator_bond_more_for_leaving_candidate() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); }); } @@ -2354,7 +2888,10 @@ fn delegator_bond_more_disallowed_when_revoke_scheduled() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); assert_noop!( ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5), >::PendingDelegationRevoke @@ -2375,7 +2912,11 @@ fn delegator_bond_more_allowed_when_bond_decrease_scheduled() { 1, 5, )); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 1, 5)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 1, + 5 + )); }); } @@ -2394,12 +2935,14 @@ fn delegator_bond_less_event_emits_correctly() { 1, 5 )); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationDecreaseScheduled { - delegator: 2, - candidate: 1, - amount_to_decrease: 5, - execute_round: 3, - })); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationDecreaseScheduled { + delegator: 2, + candidate: 1, + amount_to_decrease: 5, + execute_round: 3, + } + )); }); } @@ -2436,7 +2979,9 @@ fn delegator_not_allowed_bond_less_if_leaving() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_noop!( ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 1), >::PendingDelegationRequestAlreadyExists, @@ -2452,7 +2997,10 @@ fn cannot_delegator_bond_less_if_revoking() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); assert_noop!( ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 1), Error::::PendingDelegationRequestAlreadyExists @@ -2558,7 +3106,10 @@ fn execute_revoke_delegation_emits_exit_event_if_exit_happens() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2571,7 +3122,10 @@ fn execute_revoke_delegation_emits_exit_event_if_exit_happens() { unstaked_amount: 10, total_candidate_staked: 30 }); - assert_event_emitted!(Event::DelegatorLeft { delegator: 2, unstaked_amount: 10 }); + assert_event_emitted!(Event::DelegatorLeft { + delegator: 2, + unstaked_amount: 10 + }); }); } @@ -2583,19 +3137,31 @@ fn cannot_execute_revoke_delegation_below_min_delegator_stake() { .with_delegations(vec![(2, 1, 5), (2, 3, 3)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_noop!( ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 1), Error::::DelegatorBondBelowMin ); // but delegator can cancel the request and request to leave instead: - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); - roll_to(20); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 2)); - }); -} + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); + roll_to(20); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 2 + )); + }); +} #[test] fn revoke_delegation_executes_exit_if_last_delegation() { @@ -2606,7 +3172,10 @@ fn revoke_delegation_executes_exit_if_last_delegation() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2619,7 +3188,10 @@ fn revoke_delegation_executes_exit_if_last_delegation() { unstaked_amount: 10, total_candidate_staked: 30 }); - assert_event_emitted!(Event::DelegatorLeft { delegator: 2, unstaked_amount: 10 }); + assert_event_emitted!(Event::DelegatorLeft { + delegator: 2, + unstaked_amount: 10 + }); }); } @@ -2631,7 +3203,10 @@ fn execute_revoke_delegation_emits_correct_event() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2656,14 +3231,20 @@ fn execute_revoke_delegation_unreserves_balance() { .build() .execute_with(|| { assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 0); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), 2, 1 )); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 10); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&2), + 10 + ); }); } @@ -2675,9 +3256,16 @@ fn execute_revoke_delegation_adds_revocation_to_delegator_state() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert!(!DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert!(DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2)); + assert!(!DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert!(DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2)); }); } @@ -2689,14 +3277,19 @@ fn execute_revoke_delegation_removes_revocation_from_delegator_state_upon_execut .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), 2, 1 )); - assert!(!DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2)); + assert!(!DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2)); }); } @@ -2708,7 +3301,10 @@ fn execute_revoke_delegation_removes_revocation_from_state_for_single_delegation .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2716,7 +3312,9 @@ fn execute_revoke_delegation_removes_revocation_from_state_for_single_delegation 1 )); assert!( - !DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2), + !DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2), "delegation was not removed" ); }); @@ -2731,7 +3329,10 @@ fn execute_revoke_delegation_decreases_total_staked() { .build() .execute_with(|| { assert_eq!(Total::::get(), 40); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2751,7 +3352,10 @@ fn execute_revoke_delegation_for_last_delegation_removes_delegator_state() { .build() .execute_with(|| { assert!(DelegatorState::::get(2).is_some()); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); // this will be confusing for people // if status is leaving, then execute_delegation_request works if last delegation @@ -2772,15 +3376,26 @@ fn execute_revoke_delegation_removes_delegation_from_candidate_state() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_eq!(CandidateInfo::::get(1).expect("exists").delegation_count, 1u32); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_eq!( + CandidateInfo::::get(1) + .expect("exists") + .delegation_count, + 1u32 + ); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), 2, 1 )); - assert!(CandidateInfo::::get(1).expect("exists").delegation_count.is_zero()); + assert!(CandidateInfo::::get(1) + .expect("exists") + .delegation_count + .is_zero()); }); } @@ -2792,8 +3407,14 @@ fn can_execute_revoke_delegation_for_leaving_candidate() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); // can execute delegation request for leaving candidate assert_ok!(ParachainStaking::execute_delegation_request( @@ -2812,11 +3433,21 @@ fn can_execute_leave_candidates_if_revoking_candidate() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); roll_to(10); // revocation executes during execute leave candidates (callable by anyone) - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(1), + 1, + 1 + )); assert!(!ParachainStaking::is_delegator(&2)); assert_eq!(Balances::reserved_balance(&2), 0); assert_eq!(Balances::free_balance(&2), 10); @@ -2831,8 +3462,15 @@ fn delegator_bond_more_after_revoke_delegation_does_not_effect_exit() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(2), 3, 10)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(2), + 3, + 10 + )); roll_to(100); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(2), @@ -2840,7 +3478,10 @@ fn delegator_bond_more_after_revoke_delegation_does_not_effect_exit() { 1 )); assert!(ParachainStaking::is_delegator(&2)); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 10); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&2), + 10 + ); }); } @@ -2852,13 +3493,18 @@ fn delegator_bond_less_after_revoke_delegation_does_not_effect_exit() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationRevocationScheduled { - round: 1, - delegator: 2, - candidate: 1, - scheduled_exit: 3, - })); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationRevocationScheduled { + round: 1, + delegator: 2, + candidate: 1, + scheduled_exit: 3, + } + )); assert_noop!( ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 2), Error::::PendingDelegationRequestAlreadyExists @@ -2886,7 +3532,10 @@ fn delegator_bond_less_after_revoke_delegation_does_not_effect_exit() { in_top: true })); assert!(ParachainStaking::is_delegator(&2)); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 22); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&2), + 22 + ); }); } @@ -2972,8 +3621,14 @@ fn execute_delegator_bond_less_updates_candidate_state() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].owner, 2); - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].amount, 10); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].owner, + 2 + ); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].amount, + 10 + ); assert_ok!(ParachainStaking::schedule_delegator_bond_less( RuntimeOrigin::signed(2), 1, @@ -2985,8 +3640,14 @@ fn execute_delegator_bond_less_updates_candidate_state() { 2, 1 )); - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].owner, 2); - assert_eq!(TopDelegations::::get(1).unwrap().delegations[0].amount, 5); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].owner, + 2 + ); + assert_eq!( + TopDelegations::::get(1).unwrap().delegations[0].amount, + 5 + ); }); } @@ -3019,7 +3680,13 @@ fn execute_delegator_bond_less_updates_just_bottom_delegations() { ExtBuilder::default() .with_balances(vec![(1, 20), (2, 10), (3, 11), (4, 12), (5, 14), (6, 15)]) .with_candidates(vec![(1, 20)]) - .with_delegations(vec![(2, 1, 10), (3, 1, 11), (4, 1, 12), (5, 1, 14), (6, 1, 15)]) + .with_delegations(vec![ + (2, 1, 10), + (3, 1, 11), + (4, 1, 12), + (5, 1, 14), + (6, 1, 15), + ]) .build() .execute_with(|| { let pre_call_candidate_info = @@ -3047,8 +3714,10 @@ fn execute_delegator_bond_less_updates_just_bottom_delegations() { BottomDelegations::::get(&1).expect("delegated by all so exists"); let mut not_equal = false; for Bond { owner, amount } in pre_call_bottom_delegations.delegations { - for Bond { owner: post_owner, amount: post_amount } in - &post_call_bottom_delegations.delegations + for Bond { + owner: post_owner, + amount: post_amount, + } in &post_call_bottom_delegations.delegations { if &owner == post_owner && &amount != post_amount { not_equal = true; @@ -3059,8 +3728,10 @@ fn execute_delegator_bond_less_updates_just_bottom_delegations() { assert!(not_equal); let mut equal = true; for Bond { owner, amount } in pre_call_top_delegations.delegations { - for Bond { owner: post_owner, amount: post_amount } in - &post_call_top_delegations.delegations + for Bond { + owner: post_owner, + amount: post_amount, + } in &post_call_top_delegations.delegations { if &owner == post_owner && &amount != post_amount { equal = false; @@ -3081,7 +3752,13 @@ fn execute_delegator_bond_less_does_not_delete_bottom_delegations() { ExtBuilder::default() .with_balances(vec![(1, 20), (2, 10), (3, 11), (4, 12), (5, 14), (6, 15)]) .with_candidates(vec![(1, 20)]) - .with_delegations(vec![(2, 1, 10), (3, 1, 11), (4, 1, 12), (5, 1, 14), (6, 1, 15)]) + .with_delegations(vec![ + (2, 1, 10), + (3, 1, 11), + (4, 1, 12), + (5, 1, 14), + (6, 1, 15), + ]) .build() .execute_with(|| { let pre_call_candidate_info = @@ -3109,8 +3786,10 @@ fn execute_delegator_bond_less_does_not_delete_bottom_delegations() { BottomDelegations::::get(&1).expect("delegated by all so exists"); let mut equal = true; for Bond { owner, amount } in pre_call_bottom_delegations.delegations { - for Bond { owner: post_owner, amount: post_amount } in - &post_call_bottom_delegations.delegations + for Bond { + owner: post_owner, + amount: post_amount, + } in &post_call_bottom_delegations.delegations { if &owner == post_owner && &amount != post_amount { equal = false; @@ -3121,8 +3800,10 @@ fn execute_delegator_bond_less_does_not_delete_bottom_delegations() { assert!(equal); let mut not_equal = false; for Bond { owner, amount } in pre_call_top_delegations.delegations { - for Bond { owner: post_owner, amount: post_amount } in - &post_call_top_delegations.delegations + for Bond { + owner: post_owner, + amount: post_amount, + } in &post_call_top_delegations.delegations { if &owner == post_owner && &amount != post_amount { not_equal = true; @@ -3146,7 +3827,10 @@ fn can_execute_delegator_bond_less_for_leaving_candidate() { .with_delegations(vec![(2, 1, 15)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(1), + 1 + )); assert_ok!(ParachainStaking::schedule_delegator_bond_less( RuntimeOrigin::signed(2), 1, @@ -3173,16 +3857,24 @@ fn cancel_revoke_delegation_emits_correct_event() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::CancelledDelegationRequest { - delegator: 2, - collator: 1, - cancelled_request: CancelledScheduledRequest { - when_executable: 3, - action: DelegationAction::Revoke(10), - }, - })); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::CancelledDelegationRequest { + delegator: 2, + collator: 1, + cancelled_request: CancelledScheduledRequest { + when_executable: 3, + action: DelegationAction::Revoke(10), + }, + } + )); }); } @@ -3194,7 +3886,10 @@ fn cancel_revoke_delegation_updates_delegator_state() { .with_delegations(vec![(2, 1, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); let state = DelegationScheduledRequests::::get(&1); assert_eq!( state, @@ -3210,8 +3905,13 @@ fn cancel_revoke_delegation_updates_delegator_state() { .expect("delegator state must exist"), 10 ); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert!(!DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2)); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); + assert!(!DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2)); assert_eq!( DelegatorState::::get(&2) .map(|x| x.less_total) @@ -3236,15 +3936,20 @@ fn cancel_delegator_bond_less_correct_event() { 1, 5 )); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::CancelledDelegationRequest { - delegator: 2, - collator: 1, - cancelled_request: CancelledScheduledRequest { - when_executable: 3, - action: DelegationAction::Decrease(5), - }, - })); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::CancelledDelegationRequest { + delegator: 2, + collator: 1, + cancelled_request: CancelledScheduledRequest { + when_executable: 3, + action: DelegationAction::Decrease(5), + }, + } + )); }); } @@ -3276,8 +3981,13 @@ fn cancel_delegator_bond_less_updates_delegator_state() { .expect("delegator state must exist"), 5 ); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert!(!DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2)); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); + assert!(!DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2)); assert_eq!( DelegatorState::::get(&2) .map(|x| x.less_total) @@ -3297,7 +4007,10 @@ fn delegator_schedule_revocation_total() { .with_delegations(vec![(2, 1, 10), (2, 3, 10), (2, 4, 10)]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); assert_eq!( DelegatorState::::get(&2) .map(|x| x.less_total) @@ -3316,9 +4029,21 @@ fn delegator_schedule_revocation_total() { .expect("delegator state must exist"), 0 ); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 5, 10, 0, 2)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 3)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 4)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 5, + 10, + 0, + 2 + )); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 3 + )); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 4 + )); assert_eq!( DelegatorState::::get(&2) .map(|x| x.less_total) @@ -3368,22 +4093,51 @@ fn parachain_bond_inflation_reserve_matches_config() { (11, 1), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) - .with_delegations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) + .with_delegations(vec![ + (6, 1, 10), + (7, 1, 10), + (8, 2, 10), + (9, 2, 10), + (10, 1, 10), + ]) .build() .execute_with(|| { assert_eq!(Balances::free_balance(&11), 1); // set parachain bond account so DefaultParachainBondReservePercent = 30% of inflation // is allocated to this account hereafter - assert_ok!(ParachainStaking::set_parachain_bond_account(RuntimeOrigin::root(), 11)); + assert_ok!(ParachainStaking::set_parachain_bond_account( + RuntimeOrigin::root(), + 11 + )); roll_to(8); // chooses top TotalSelectedCandidates (5), in order let mut expected = vec![ Event::ParachainBondAccountSet { old: 0, new: 11 }, - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 5, round: 2, @@ -3398,33 +4152,88 @@ fn parachain_bond_inflation_reserve_matches_config() { roll_to(16); // distribute total issuance to collator 1 and its delegators 6, 7, 19 let mut new = vec![ - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 3, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 3, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 10, round: 3, selected_collators_number: 5, total_balance: 140, }, - Event::ReservedForParachainBond { account: 11, value: 15 }, - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 4, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 4, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 4, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 4, collator_account: 5, total_exposed_amount: 10 }, + Event::ReservedForParachainBond { + account: 11, + value: 15, + }, + Event::CollatorChosen { + round: 4, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 4, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 4, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 4, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 4, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 15, round: 4, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 20 }, - Event::Rewarded { account: 6, rewards: 5 }, - Event::Rewarded { account: 7, rewards: 5 }, - Event::Rewarded { account: 10, rewards: 5 }, + Event::Rewarded { + account: 1, + rewards: 20, + }, + Event::Rewarded { + account: 6, + rewards: 5, + }, + Event::Rewarded { + account: 7, + rewards: 5, + }, + Event::Rewarded { + account: 10, + rewards: 5, + }, ]; expected.append(&mut new); assert_eq_events!(expected.clone()); @@ -3438,67 +4247,182 @@ fn parachain_bond_inflation_reserve_matches_config() { ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(66)), Error::::DelegatorDNE ); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(6))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(6) + )); // fast forward to block in which delegator 6 exit executes roll_to(25); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(6), 6, 10)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(6), + 6, + 10 + )); roll_to(30); let mut new2 = vec![ - Event::DelegatorExitScheduled { round: 4, delegator: 6, scheduled_exit: 6 }, - Event::ReservedForParachainBond { account: 11, value: 16 }, - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 5, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 5, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 5, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 5, collator_account: 5, total_exposed_amount: 10 }, + Event::DelegatorExitScheduled { + round: 4, + delegator: 6, + scheduled_exit: 6, + }, + Event::ReservedForParachainBond { + account: 11, + value: 16, + }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 5, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 5, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 5, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 5, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 20, round: 5, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 21 }, - Event::Rewarded { account: 6, rewards: 5 }, - Event::Rewarded { account: 7, rewards: 5 }, - Event::Rewarded { account: 10, rewards: 5 }, - Event::ReservedForParachainBond { account: 11, value: 16 }, - Event::CollatorChosen { round: 6, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 6, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 6, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 6, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 6, collator_account: 5, total_exposed_amount: 10 }, + Event::Rewarded { + account: 1, + rewards: 21, + }, + Event::Rewarded { + account: 6, + rewards: 5, + }, + Event::Rewarded { + account: 7, + rewards: 5, + }, + Event::Rewarded { + account: 10, + rewards: 5, + }, + Event::ReservedForParachainBond { + account: 11, + value: 16, + }, + Event::CollatorChosen { + round: 6, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 6, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 6, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 6, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 6, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 25, round: 6, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 22 }, - Event::Rewarded { account: 6, rewards: 6 }, - Event::Rewarded { account: 7, rewards: 6 }, - Event::Rewarded { account: 10, rewards: 6 }, + Event::Rewarded { + account: 1, + rewards: 22, + }, + Event::Rewarded { + account: 6, + rewards: 6, + }, + Event::Rewarded { + account: 7, + rewards: 6, + }, + Event::Rewarded { + account: 10, + rewards: 6, + }, Event::DelegatorLeftCandidate { delegator: 6, candidate: 1, unstaked_amount: 10, total_candidate_staked: 40, }, - Event::DelegatorLeft { delegator: 6, unstaked_amount: 10 }, - Event::ReservedForParachainBond { account: 11, value: 17 }, - Event::CollatorChosen { round: 7, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 7, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 7, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 7, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 7, collator_account: 5, total_exposed_amount: 10 }, - Event::NewRound { - starting_block: 30, + Event::DelegatorLeft { + delegator: 6, + unstaked_amount: 10, + }, + Event::ReservedForParachainBond { + account: 11, + value: 17, + }, + Event::CollatorChosen { round: 7, - selected_collators_number: 5, - total_balance: 130, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 7, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 7, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 7, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 7, + collator_account: 5, + total_exposed_amount: 10, + }, + Event::NewRound { + starting_block: 30, + round: 7, + selected_collators_number: 5, + total_balance: 130, + }, + Event::Rewarded { + account: 1, + rewards: 26, + }, + Event::Rewarded { + account: 7, + rewards: 7, + }, + Event::Rewarded { + account: 10, + rewards: 7, }, - Event::Rewarded { account: 1, rewards: 26 }, - Event::Rewarded { account: 7, rewards: 7 }, - Event::Rewarded { account: 10, rewards: 7 }, ]; expected.append(&mut new2); assert_eq_events!(expected.clone()); @@ -3516,21 +4440,53 @@ fn parachain_bond_inflation_reserve_matches_config() { old: Percent::from_percent(30), new: Percent::from_percent(50), }, - Event::ReservedForParachainBond { account: 11, value: 30 }, - Event::CollatorChosen { round: 8, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 8, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 8, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 8, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 8, collator_account: 5, total_exposed_amount: 10 }, + Event::ReservedForParachainBond { + account: 11, + value: 30, + }, + Event::CollatorChosen { + round: 8, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 8, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 8, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 8, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 8, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 35, round: 8, selected_collators_number: 5, total_balance: 130, }, - Event::Rewarded { account: 1, rewards: 21 }, - Event::Rewarded { account: 7, rewards: 5 }, - Event::Rewarded { account: 10, rewards: 5 }, + Event::Rewarded { + account: 1, + rewards: 21, + }, + Event::Rewarded { + account: 7, + rewards: 5, + }, + Event::Rewarded { + account: 10, + rewards: 5, + }, ]; expected.append(&mut new3); assert_eq_events!(expected.clone()); @@ -3539,27 +4495,65 @@ fn parachain_bond_inflation_reserve_matches_config() { roll_to(40); // no more paying 6 let mut new4 = vec![ - Event::ReservedForParachainBond { account: 11, value: 32 }, - Event::CollatorChosen { round: 9, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 9, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 9, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 9, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 9, collator_account: 5, total_exposed_amount: 10 }, + Event::ReservedForParachainBond { + account: 11, + value: 32, + }, + Event::CollatorChosen { + round: 9, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 9, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 9, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 9, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 9, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 40, round: 9, selected_collators_number: 5, total_balance: 130, }, - Event::Rewarded { account: 1, rewards: 22 }, - Event::Rewarded { account: 7, rewards: 5 }, - Event::Rewarded { account: 10, rewards: 5 }, + Event::Rewarded { + account: 1, + rewards: 22, + }, + Event::Rewarded { + account: 7, + rewards: 5, + }, + Event::Rewarded { + account: 10, + rewards: 5, + }, ]; expected.append(&mut new4); assert_eq_events!(expected.clone()); assert_eq!(Balances::free_balance(&11), 127); set_author(8, 1, 100); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(8), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(8), + 1, + 10, + 10, + 10 + )); roll_to(45); // new delegation is not rewarded yet let mut new5 = vec![ @@ -3569,21 +4563,53 @@ fn parachain_bond_inflation_reserve_matches_config() { candidate: 1, delegator_position: DelegatorAdded::AddedToTop { new_total: 50 }, }, - Event::ReservedForParachainBond { account: 11, value: 33 }, - Event::CollatorChosen { round: 10, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 10, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 10, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 10, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 10, collator_account: 5, total_exposed_amount: 10 }, + Event::ReservedForParachainBond { + account: 11, + value: 33, + }, + Event::CollatorChosen { + round: 10, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 10, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 10, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 10, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 10, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 45, round: 10, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 23 }, - Event::Rewarded { account: 7, rewards: 5 }, - Event::Rewarded { account: 10, rewards: 5 }, + Event::Rewarded { + account: 1, + rewards: 23, + }, + Event::Rewarded { + account: 7, + rewards: 5, + }, + Event::Rewarded { + account: 10, + rewards: 5, + }, ]; expected.append(&mut new5); assert_eq_events!(expected.clone()); @@ -3593,21 +4619,53 @@ fn parachain_bond_inflation_reserve_matches_config() { roll_to(50); // new delegation is still not rewarded yet let mut new6 = vec![ - Event::ReservedForParachainBond { account: 11, value: 35 }, - Event::CollatorChosen { round: 11, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 11, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 11, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 11, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 11, collator_account: 5, total_exposed_amount: 10 }, + Event::ReservedForParachainBond { + account: 11, + value: 35, + }, + Event::CollatorChosen { + round: 11, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 11, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 11, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 11, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 11, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 50, round: 11, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 24 }, - Event::Rewarded { account: 7, rewards: 5 }, - Event::Rewarded { account: 10, rewards: 5 }, + Event::Rewarded { + account: 1, + rewards: 24, + }, + Event::Rewarded { + account: 7, + rewards: 5, + }, + Event::Rewarded { + account: 10, + rewards: 5, + }, ]; expected.append(&mut new6); assert_eq_events!(expected.clone()); @@ -3615,22 +4673,57 @@ fn parachain_bond_inflation_reserve_matches_config() { roll_to(55); // new delegation is rewarded, 2 rounds after joining (`RewardPaymentDelay` is 2) let mut new7 = vec![ - Event::ReservedForParachainBond { account: 11, value: 37 }, - Event::CollatorChosen { round: 12, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 12, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 12, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 12, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 12, collator_account: 5, total_exposed_amount: 10 }, + Event::ReservedForParachainBond { + account: 11, + value: 37, + }, + Event::CollatorChosen { + round: 12, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 12, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 12, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 12, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 12, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 55, round: 12, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 24 }, - Event::Rewarded { account: 7, rewards: 4 }, - Event::Rewarded { account: 10, rewards: 4 }, - Event::Rewarded { account: 8, rewards: 4 }, + Event::Rewarded { + account: 1, + rewards: 24, + }, + Event::Rewarded { + account: 7, + rewards: 4, + }, + Event::Rewarded { + account: 10, + rewards: 4, + }, + Event::Rewarded { + account: 8, + rewards: 4, + }, ]; expected.append(&mut new7); assert_eq_events!(expected); @@ -3641,7 +4734,14 @@ fn parachain_bond_inflation_reserve_matches_config() { #[test] fn paid_collator_commission_matches_config() { ExtBuilder::default() - .with_balances(vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100)]) + .with_balances(vec![ + (1, 100), + (2, 100), + (3, 100), + (4, 100), + (5, 100), + (6, 100), + ]) .with_candidates(vec![(1, 20)]) .with_delegations(vec![(2, 1, 10), (3, 1, 10)]) .build() @@ -3649,7 +4749,11 @@ fn paid_collator_commission_matches_config() { roll_to(8); // chooses top TotalSelectedCandidates (5), in order let mut expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 40 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 40, + }, Event::NewRound { starting_block: 5, round: 2, @@ -3658,15 +4762,33 @@ fn paid_collator_commission_matches_config() { }, ]; assert_eq_events!(expected.clone()); - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(4), 20u128, 100u32)); - assert_last_event!(MetaEvent::ParachainStaking(Event::JoinedCollatorCandidates { - account: 4, - amount_locked: 20u128, - new_total_amt_locked: 60u128, - })); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(4), + 20u128, + 100u32 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::JoinedCollatorCandidates { + account: 4, + amount_locked: 20u128, + new_total_amt_locked: 60u128, + } + )); roll_to(9); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(5), 4, 10, 10, 10)); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(6), 4, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(5), + 4, + 10, + 10, + 10 + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(6), + 4, + 10, + 10, + 10 + )); roll_to(11); let mut new = vec![ Event::JoinedCollatorCandidates { @@ -3686,8 +4808,16 @@ fn paid_collator_commission_matches_config() { candidate: 4, delegator_position: DelegatorAdded::AddedToTop { new_total: 40 }, }, - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 40 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 40, + }, Event::NewRound { starting_block: 10, round: 3, @@ -3703,25 +4833,50 @@ fn paid_collator_commission_matches_config() { // 20% of 10 is commission + due_portion (0) = 2 + 4 = 6 // all delegator payouts are 10-2 = 8 * stake_pct let mut new2 = vec![ - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 4, collator_account: 4, total_exposed_amount: 40 }, + Event::CollatorChosen { + round: 4, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 4, + collator_account: 4, + total_exposed_amount: 40, + }, Event::NewRound { starting_block: 15, round: 4, selected_collators_number: 2, total_balance: 80, }, - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 5, collator_account: 4, total_exposed_amount: 40 }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 5, + collator_account: 4, + total_exposed_amount: 40, + }, Event::NewRound { starting_block: 20, round: 5, selected_collators_number: 2, total_balance: 80, }, - Event::Rewarded { account: 4, rewards: 18 }, - Event::Rewarded { account: 5, rewards: 6 }, - Event::Rewarded { account: 6, rewards: 6 }, + Event::Rewarded { + account: 4, + rewards: 18, + }, + Event::Rewarded { + account: 5, + rewards: 6, + }, + Event::Rewarded { + account: 6, + rewards: 6, + }, ]; expected.append(&mut new2); assert_eq_events!(expected); @@ -3747,25 +4902,48 @@ fn collator_exit_executes_after_delay() { .build() .execute_with(|| { roll_to(11); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(2), 2)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(2), + 2 + )); let info = CandidateInfo::::get(&2).unwrap(); assert_eq!(info.status, CollatorStatus::Leaving(5)); roll_to(21); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 2, 2)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(2), + 2, + 2 + )); // we must exclude leaving collators from rewards while // holding them retroactively accountable for previous faults // (within the last T::SlashingWindow blocks) let expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 700 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 400 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 700, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 400, + }, Event::NewRound { starting_block: 5, round: 2, selected_collators_number: 2, total_balance: 1100, }, - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 700 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 400 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 700, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 400, + }, Event::NewRound { starting_block: 10, round: 3, @@ -3777,14 +4955,22 @@ fn collator_exit_executes_after_delay() { candidate: 2, scheduled_exit: 5, }, - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 700 }, + Event::CollatorChosen { + round: 4, + collator_account: 1, + total_exposed_amount: 700, + }, Event::NewRound { starting_block: 15, round: 4, selected_collators_number: 1, total_balance: 700, }, - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 700 }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 700, + }, Event::NewRound { starting_block: 20, round: 5, @@ -3821,11 +5007,31 @@ fn collator_selection_chooses_top_candidates() { roll_to(8); // should choose top TotalSelectedCandidates (5), in order let expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 2, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 2, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 5, round: 2, @@ -3834,28 +5040,61 @@ fn collator_selection_chooses_top_candidates() { }, ]; assert_eq_events!(expected); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(6), 6)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(6), + 6 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateScheduledExit { exit_allowed_round: 2, candidate: 6, scheduled_exit: 4 })); roll_to(21); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(6), 6, 0)); - assert_ok!(ParachainStaking::join_candidates(RuntimeOrigin::signed(6), 69u128, 100u32)); - assert_last_event!(MetaEvent::ParachainStaking(Event::JoinedCollatorCandidates { - account: 6, - amount_locked: 69u128, - new_total_amt_locked: 469u128, - })); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(6), + 6, + 0 + )); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(6), + 69u128, + 100u32 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::JoinedCollatorCandidates { + account: 6, + amount_locked: 69u128, + new_total_amt_locked: 469u128, + } + )); roll_to(27); // should choose top TotalSelectedCandidates (5), in order let expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 2, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 2, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 5, round: 2, @@ -3867,33 +5106,93 @@ fn collator_selection_chooses_top_candidates() { candidate: 6, scheduled_exit: 4, }, - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 3, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 3, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 3, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 3, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 10, round: 3, selected_collators_number: 5, total_balance: 400, }, - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 4, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 4, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 4, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 4, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 4, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 4, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 4, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 4, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 4, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 15, round: 4, selected_collators_number: 5, total_balance: 400, }, - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 5, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 5, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 5, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 5, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 5, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 5, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 5, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 5, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 20, round: 5, @@ -3910,11 +5209,31 @@ fn collator_selection_chooses_top_candidates() { amount_locked: 69, new_total_amt_locked: 469, }, - Event::CollatorChosen { round: 6, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 6, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 6, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 6, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 6, collator_account: 6, total_exposed_amount: 69 }, + Event::CollatorChosen { + round: 6, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 6, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 6, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 6, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 6, + collator_account: 6, + total_exposed_amount: 69, + }, Event::NewRound { starting_block: 25, round: 6, @@ -3946,11 +5265,31 @@ fn payout_distribution_to_solo_collators() { roll_to(8); // should choose top TotalCandidatesSelected (5), in order let mut expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 2, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 2, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 5, round: 2, @@ -3964,63 +5303,152 @@ fn payout_distribution_to_solo_collators() { roll_to(16); // pay total issuance to 1 let mut new = vec![ - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 3, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 3, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 3, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 3, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 10, round: 3, selected_collators_number: 5, total_balance: 400, }, - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 4, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 4, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 4, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 4, collator_account: 5, total_exposed_amount: 60 }, - Event::NewRound { - starting_block: 15, + Event::CollatorChosen { round: 4, - selected_collators_number: 5, - total_balance: 400, + collator_account: 1, + total_exposed_amount: 100, }, - Event::Rewarded { account: 1, rewards: 305 }, - ]; - expected.append(&mut new); - assert_eq_events!(expected.clone()); - // ~ set block author as 1 for 3 blocks this round + Event::CollatorChosen { + round: 4, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 4, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 4, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 4, + collator_account: 5, + total_exposed_amount: 60, + }, + Event::NewRound { + starting_block: 15, + round: 4, + selected_collators_number: 5, + total_balance: 400, + }, + Event::Rewarded { + account: 1, + rewards: 305, + }, + ]; + expected.append(&mut new); + assert_eq_events!(expected.clone()); + // ~ set block author as 1 for 3 blocks this round set_author(4, 1, 60); // ~ set block author as 2 for 2 blocks this round set_author(4, 2, 40); roll_to(26); // pay 60% total issuance to 1 and 40% total issuance to 2 let mut new1 = vec![ - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 5, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 5, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 5, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 5, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 5, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 5, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 5, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 5, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 20, round: 5, selected_collators_number: 5, total_balance: 400, }, - Event::CollatorChosen { round: 6, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 6, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 6, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 6, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 6, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 6, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 6, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 6, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 6, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 6, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 25, round: 6, selected_collators_number: 5, total_balance: 400, }, - Event::Rewarded { account: 1, rewards: 192 }, - Event::Rewarded { account: 2, rewards: 128 }, + Event::Rewarded { + account: 1, + rewards: 192, + }, + Event::Rewarded { + account: 2, + rewards: 128, + }, ]; expected.append(&mut new1); assert_eq_events!(expected.clone()); @@ -4033,33 +5461,88 @@ fn payout_distribution_to_solo_collators() { roll_to(39); // pay 20% issuance for all collators let mut new2 = vec![ - Event::CollatorChosen { round: 7, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 7, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 7, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 7, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 7, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 7, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 7, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 7, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 7, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 7, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 30, round: 7, selected_collators_number: 5, total_balance: 400, }, - Event::CollatorChosen { round: 8, collator_account: 1, total_exposed_amount: 100 }, - Event::CollatorChosen { round: 8, collator_account: 2, total_exposed_amount: 90 }, - Event::CollatorChosen { round: 8, collator_account: 3, total_exposed_amount: 80 }, - Event::CollatorChosen { round: 8, collator_account: 4, total_exposed_amount: 70 }, - Event::CollatorChosen { round: 8, collator_account: 5, total_exposed_amount: 60 }, + Event::CollatorChosen { + round: 8, + collator_account: 1, + total_exposed_amount: 100, + }, + Event::CollatorChosen { + round: 8, + collator_account: 2, + total_exposed_amount: 90, + }, + Event::CollatorChosen { + round: 8, + collator_account: 3, + total_exposed_amount: 80, + }, + Event::CollatorChosen { + round: 8, + collator_account: 4, + total_exposed_amount: 70, + }, + Event::CollatorChosen { + round: 8, + collator_account: 5, + total_exposed_amount: 60, + }, Event::NewRound { starting_block: 35, round: 8, selected_collators_number: 5, total_balance: 400, }, - Event::Rewarded { account: 5, rewards: 67 }, - Event::Rewarded { account: 3, rewards: 67 }, - Event::Rewarded { account: 4, rewards: 67 }, - Event::Rewarded { account: 1, rewards: 67 }, - Event::Rewarded { account: 2, rewards: 67 }, + Event::Rewarded { + account: 5, + rewards: 67, + }, + Event::Rewarded { + account: 3, + rewards: 67, + }, + Event::Rewarded { + account: 4, + rewards: 67, + }, + Event::Rewarded { + account: 1, + rewards: 67, + }, + Event::Rewarded { + account: 2, + rewards: 67, + }, ]; expected.append(&mut new2); assert_eq_events!(expected); @@ -4091,17 +5574,43 @@ fn multiple_delegations() { (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) - .with_delegations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) + .with_delegations(vec![ + (6, 1, 10), + (7, 1, 10), + (8, 2, 10), + (9, 2, 10), + (10, 1, 10), + ]) .build() .execute_with(|| { roll_to(8); // chooses top TotalSelectedCandidates (5), in order let mut expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 5, round: 2, @@ -4110,9 +5619,27 @@ fn multiple_delegations() { }, ]; assert_eq_events!(expected.clone()); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(6), 2, 10, 10, 10)); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(6), 3, 10, 10, 10)); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(6), 4, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(6), + 2, + 10, + 10, + 10 + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(6), + 3, + 10, + 10, + 10 + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(6), + 4, + 10, + 10, + 10 + )); roll_to(16); let mut new = vec![ Event::Delegation { @@ -4133,22 +5660,62 @@ fn multiple_delegations() { candidate: 4, delegator_position: DelegatorAdded::AddedToTop { new_total: 30 }, }, - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 3, collator_account: 3, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 3, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 3, + collator_account: 3, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 3, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 10, round: 3, selected_collators_number: 5, total_balance: 170, }, - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 4, collator_account: 2, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 4, collator_account: 3, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 4, collator_account: 4, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 4, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 4, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 4, + collator_account: 2, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 4, + collator_account: 3, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 4, + collator_account: 4, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 4, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 15, round: 4, @@ -4159,15 +5726,47 @@ fn multiple_delegations() { expected.append(&mut new); assert_eq_events!(expected.clone()); roll_to(21); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(7), 2, 80, 10, 10)); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(10), 2, 10, 10, 10),); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(7), + 2, + 80, + 10, + 10 + )); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(10), + 2, + 10, + 10, + 10 + ),); roll_to(26); let mut new2 = vec![ - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 5, collator_account: 2, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 5, collator_account: 3, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 5, collator_account: 4, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 5, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 5, + collator_account: 2, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 5, + collator_account: 3, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 5, + collator_account: 4, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 5, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 20, round: 5, @@ -4186,11 +5785,31 @@ fn multiple_delegations() { candidate: 2, delegator_position: DelegatorAdded::AddedToBottom, }, - Event::CollatorChosen { round: 6, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 6, collator_account: 2, total_exposed_amount: 130 }, - Event::CollatorChosen { round: 6, collator_account: 3, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 6, collator_account: 4, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 6, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 6, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 6, + collator_account: 2, + total_exposed_amount: 130, + }, + Event::CollatorChosen { + round: 6, + collator_account: 3, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 6, + collator_account: 4, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 6, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 25, round: 6, @@ -4200,7 +5819,10 @@ fn multiple_delegations() { ]; expected.append(&mut new2); assert_eq_events!(expected.clone()); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(2), 5)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(2), + 5 + )); assert_last_event!(MetaEvent::ParachainStaking(Event::CandidateScheduledExit { exit_allowed_round: 6, candidate: 2, @@ -4213,10 +5835,26 @@ fn multiple_delegations() { candidate: 2, scheduled_exit: 8, }, - Event::CollatorChosen { round: 7, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 7, collator_account: 3, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 7, collator_account: 4, total_exposed_amount: 30 }, - Event::CollatorChosen { round: 7, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 7, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 7, + collator_account: 3, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 7, + collator_account: 4, + total_exposed_amount: 30, + }, + Event::CollatorChosen { + round: 7, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 30, round: 7, @@ -4228,21 +5866,49 @@ fn multiple_delegations() { assert_eq_events!(expected); // verify that delegations are removed after collator leaves, not before assert_eq!(DelegatorState::::get(7).unwrap().total(), 90); - assert_eq!(DelegatorState::::get(7).unwrap().delegations.0.len(), 2usize); + assert_eq!( + DelegatorState::::get(7).unwrap().delegations.0.len(), + 2usize + ); assert_eq!(DelegatorState::::get(6).unwrap().total(), 40); - assert_eq!(DelegatorState::::get(6).unwrap().delegations.0.len(), 4usize); + assert_eq!( + DelegatorState::::get(6).unwrap().delegations.0.len(), + 4usize + ); assert_eq!(Balances::locks(&6)[0].amount, 40); assert_eq!(Balances::locks(&7)[0].amount, 90); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&6), 60); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&7), 10); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&6), + 60 + ); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&7), + 10 + ); roll_to(40); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 2, 5)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(2), + 2, + 5 + )); assert_eq!(DelegatorState::::get(7).unwrap().total(), 10); assert_eq!(DelegatorState::::get(6).unwrap().total(), 30); - assert_eq!(DelegatorState::::get(7).unwrap().delegations.0.len(), 1usize); - assert_eq!(DelegatorState::::get(6).unwrap().delegations.0.len(), 3usize); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&6), 70); - assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&7), 90); + assert_eq!( + DelegatorState::::get(7).unwrap().delegations.0.len(), + 1usize + ); + assert_eq!( + DelegatorState::::get(6).unwrap().delegations.0.len(), + 3usize + ); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&6), + 70 + ); + assert_eq!( + ParachainStaking::get_delegator_stakable_free_balance(&7), + 90 + ); }); } @@ -4257,17 +5923,33 @@ fn execute_leave_candidate_removes_delegations() { .build() .execute_with(|| { // Verifies the revocation request is initially empty - assert!(!DelegationScheduledRequests::::get(&2).iter().any(|x| x.delegator == 3)); + assert!(!DelegationScheduledRequests::::get(&2) + .iter() + .any(|x| x.delegator == 3)); - assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(2), 2)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(3), 2)); + assert_ok!(ParachainStaking::schedule_leave_candidates( + RuntimeOrigin::signed(2), + 2 + )); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(3), + 2 + )); // Verifies the revocation request is present - assert!(DelegationScheduledRequests::::get(&2).iter().any(|x| x.delegator == 3)); + assert!(DelegationScheduledRequests::::get(&2) + .iter() + .any(|x| x.delegator == 3)); roll_to(16); - assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 2, 2)); + assert_ok!(ParachainStaking::execute_leave_candidates( + RuntimeOrigin::signed(2), + 2, + 2 + )); // Verifies the revocation request is again empty - assert!(!DelegationScheduledRequests::::get(&2).iter().any(|x| x.delegator == 3)); + assert!(!DelegationScheduledRequests::::get(&2) + .iter() + .any(|x| x.delegator == 3)); }); } @@ -4287,17 +5969,43 @@ fn payouts_follow_delegation_changes() { (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) - .with_delegations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) + .with_delegations(vec![ + (6, 1, 10), + (7, 1, 10), + (8, 2, 10), + (9, 2, 10), + (10, 1, 10), + ]) .build() .execute_with(|| { roll_to(8); // chooses top TotalSelectedCandidates (5), in order let mut expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 5, round: 2, @@ -4311,32 +6019,84 @@ fn payouts_follow_delegation_changes() { roll_to(16); // distribute total issuance to collator 1 and its delegators 6, 7, 19 let mut new = vec![ - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 3, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 3, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 10, round: 3, selected_collators_number: 5, total_balance: 140, }, - Event::CollatorChosen { round: 4, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 4, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 4, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 4, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 4, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 4, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 4, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 4, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 4, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 4, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 15, round: 4, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 26 }, - Event::Rewarded { account: 6, rewards: 8 }, - Event::Rewarded { account: 7, rewards: 8 }, - Event::Rewarded { account: 10, rewards: 8 }, + Event::Rewarded { + account: 1, + rewards: 26, + }, + Event::Rewarded { + account: 6, + rewards: 8, + }, + Event::Rewarded { + account: 7, + rewards: 8, + }, + Event::Rewarded { + account: 10, + rewards: 8, + }, ]; expected.append(&mut new); assert_eq_events!(expected.clone()); @@ -4350,50 +6110,127 @@ fn payouts_follow_delegation_changes() { ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(66)), Error::::DelegatorDNE ); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(6))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(6) + )); // fast forward to block in which delegator 6 exit executes roll_to(25); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(6), 6, 10)); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(6), + 6, + 10 + )); // keep paying 6 (note: inflation is in terms of total issuance so that's why 1 is 21) let mut new2 = vec![ - Event::DelegatorExitScheduled { round: 4, delegator: 6, scheduled_exit: 6 }, - Event::CollatorChosen { round: 5, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 5, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 5, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 5, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 5, collator_account: 5, total_exposed_amount: 10 }, + Event::DelegatorExitScheduled { + round: 4, + delegator: 6, + scheduled_exit: 6, + }, + Event::CollatorChosen { + round: 5, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 5, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 5, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 5, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 5, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 20, round: 5, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 27 }, - Event::Rewarded { account: 6, rewards: 8 }, - Event::Rewarded { account: 7, rewards: 8 }, - Event::Rewarded { account: 10, rewards: 8 }, - Event::CollatorChosen { round: 6, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 6, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 6, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 6, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 6, collator_account: 5, total_exposed_amount: 10 }, + Event::Rewarded { + account: 1, + rewards: 27, + }, + Event::Rewarded { + account: 6, + rewards: 8, + }, + Event::Rewarded { + account: 7, + rewards: 8, + }, + Event::Rewarded { + account: 10, + rewards: 8, + }, + Event::CollatorChosen { + round: 6, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 6, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 6, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 6, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 6, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 25, round: 6, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 29 }, - Event::Rewarded { account: 6, rewards: 9 }, - Event::Rewarded { account: 7, rewards: 9 }, - Event::Rewarded { account: 10, rewards: 9 }, + Event::Rewarded { + account: 1, + rewards: 29, + }, + Event::Rewarded { + account: 6, + rewards: 9, + }, + Event::Rewarded { + account: 7, + rewards: 9, + }, + Event::Rewarded { + account: 10, + rewards: 9, + }, Event::DelegatorLeftCandidate { delegator: 6, candidate: 1, unstaked_amount: 10, total_candidate_staked: 40, }, - Event::DelegatorLeft { delegator: 6, unstaked_amount: 10 }, + Event::DelegatorLeft { + delegator: 6, + unstaked_amount: 10, + }, ]; expected.append(&mut new2); assert_eq_events!(expected.clone()); @@ -4402,34 +6239,92 @@ fn payouts_follow_delegation_changes() { roll_to(35); // keep paying 6 let mut new3 = vec![ - Event::CollatorChosen { round: 7, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 7, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 7, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 7, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 7, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 7, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 7, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 7, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 7, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 7, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 30, round: 7, selected_collators_number: 5, total_balance: 130, }, - Event::Rewarded { account: 1, rewards: 35 }, - Event::Rewarded { account: 7, rewards: 11 }, - Event::Rewarded { account: 10, rewards: 11 }, - Event::CollatorChosen { round: 8, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 8, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 8, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 8, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 8, collator_account: 5, total_exposed_amount: 10 }, + Event::Rewarded { + account: 1, + rewards: 35, + }, + Event::Rewarded { + account: 7, + rewards: 11, + }, + Event::Rewarded { + account: 10, + rewards: 11, + }, + Event::CollatorChosen { + round: 8, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 8, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 8, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 8, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 8, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 35, round: 8, selected_collators_number: 5, total_balance: 130, }, - Event::Rewarded { account: 1, rewards: 36 }, - Event::Rewarded { account: 7, rewards: 12 }, - Event::Rewarded { account: 10, rewards: 12 }, + Event::Rewarded { + account: 1, + rewards: 36, + }, + Event::Rewarded { + account: 7, + rewards: 12, + }, + Event::Rewarded { + account: 10, + rewards: 12, + }, ]; expected.append(&mut new3); assert_eq_events!(expected.clone()); @@ -4437,25 +6332,60 @@ fn payouts_follow_delegation_changes() { roll_to(40); // no more paying 6 let mut new4 = vec![ - Event::CollatorChosen { round: 9, collator_account: 1, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 9, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 9, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 9, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 9, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 9, + collator_account: 1, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 9, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 9, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 9, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 9, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 40, round: 9, selected_collators_number: 5, total_balance: 130, }, - Event::Rewarded { account: 1, rewards: 38 }, - Event::Rewarded { account: 7, rewards: 13 }, - Event::Rewarded { account: 10, rewards: 13 }, + Event::Rewarded { + account: 1, + rewards: 38, + }, + Event::Rewarded { + account: 7, + rewards: 13, + }, + Event::Rewarded { + account: 10, + rewards: 13, + }, ]; expected.append(&mut new4); assert_eq_events!(expected.clone()); set_author(9, 1, 100); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(8), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(8), + 1, + 10, + 10, + 10 + )); roll_to(45); // new delegation is not rewarded yet let mut new5 = vec![ @@ -4465,20 +6395,49 @@ fn payouts_follow_delegation_changes() { candidate: 1, delegator_position: DelegatorAdded::AddedToTop { new_total: 50 }, }, - Event::CollatorChosen { round: 10, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 10, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 10, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 10, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 10, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 10, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 10, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 10, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 10, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 10, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 45, round: 10, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 40 }, - Event::Rewarded { account: 7, rewards: 13 }, - Event::Rewarded { account: 10, rewards: 13 }, + Event::Rewarded { + account: 1, + rewards: 40, + }, + Event::Rewarded { + account: 7, + rewards: 13, + }, + Event::Rewarded { + account: 10, + rewards: 13, + }, ]; expected.append(&mut new5); assert_eq_events!(expected.clone()); @@ -4486,42 +6445,103 @@ fn payouts_follow_delegation_changes() { roll_to(50); // new delegation not rewarded yet let mut new6 = vec![ - Event::CollatorChosen { round: 11, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 11, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 11, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 11, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 11, collator_account: 5, total_exposed_amount: 10 }, + Event::CollatorChosen { + round: 11, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 11, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 11, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 11, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 11, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 50, round: 11, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 42 }, - Event::Rewarded { account: 7, rewards: 14 }, - Event::Rewarded { account: 10, rewards: 14 }, - ]; - expected.append(&mut new6); - assert_eq_events!(expected.clone()); - roll_to(55); - // new delegation is rewarded for first time - // 2 rounds after joining (`RewardPaymentDelay` = 2) - let mut new7 = vec![ - Event::CollatorChosen { round: 12, collator_account: 1, total_exposed_amount: 50 }, - Event::CollatorChosen { round: 12, collator_account: 2, total_exposed_amount: 40 }, - Event::CollatorChosen { round: 12, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 12, collator_account: 4, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 12, collator_account: 5, total_exposed_amount: 10 }, + Event::Rewarded { + account: 1, + rewards: 42, + }, + Event::Rewarded { + account: 7, + rewards: 14, + }, + Event::Rewarded { + account: 10, + rewards: 14, + }, + ]; + expected.append(&mut new6); + assert_eq_events!(expected.clone()); + roll_to(55); + // new delegation is rewarded for first time + // 2 rounds after joining (`RewardPaymentDelay` = 2) + let mut new7 = vec![ + Event::CollatorChosen { + round: 12, + collator_account: 1, + total_exposed_amount: 50, + }, + Event::CollatorChosen { + round: 12, + collator_account: 2, + total_exposed_amount: 40, + }, + Event::CollatorChosen { + round: 12, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 12, + collator_account: 4, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 12, + collator_account: 5, + total_exposed_amount: 10, + }, Event::NewRound { starting_block: 55, round: 12, selected_collators_number: 5, total_balance: 140, }, - Event::Rewarded { account: 1, rewards: 39 }, - Event::Rewarded { account: 7, rewards: 12 }, - Event::Rewarded { account: 10, rewards: 12 }, - Event::Rewarded { account: 8, rewards: 12 }, + Event::Rewarded { + account: 1, + rewards: 39, + }, + Event::Rewarded { + account: 7, + rewards: 12, + }, + Event::Rewarded { + account: 10, + rewards: 12, + }, + Event::Rewarded { + account: 8, + rewards: 12, + }, ]; expected.append(&mut new7); assert_eq_events!(expected); @@ -4541,25 +6561,49 @@ fn bottom_delegations_are_empty_when_top_delegations_not_full() { assert!(top_delegations.delegations.is_empty()); assert!(bottom_delegations.delegations.is_empty()); // 1 delegator => 1 top delegator, 0 bottom delegators - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(2), + 1, + 10, + 10, + 10 + )); let top_delegations = TopDelegations::::get(1).unwrap(); let bottom_delegations = BottomDelegations::::get(1).unwrap(); assert_eq!(top_delegations.delegations.len(), 1usize); assert!(bottom_delegations.delegations.is_empty()); // 2 delegators => 2 top delegators, 0 bottom delegators - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(3), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(3), + 1, + 10, + 10, + 10 + )); let top_delegations = TopDelegations::::get(1).unwrap(); let bottom_delegations = BottomDelegations::::get(1).unwrap(); assert_eq!(top_delegations.delegations.len(), 2usize); assert!(bottom_delegations.delegations.is_empty()); // 3 delegators => 3 top delegators, 0 bottom delegators - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(4), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(4), + 1, + 10, + 10, + 10 + )); let top_delegations = TopDelegations::::get(1).unwrap(); let bottom_delegations = BottomDelegations::::get(1).unwrap(); assert_eq!(top_delegations.delegations.len(), 3usize); assert!(bottom_delegations.delegations.is_empty()); // 4 delegators => 4 top delegators, 0 bottom delegators - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(5), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(5), + 1, + 10, + 10, + 10 + )); let top_delegations = TopDelegations::::get(1).unwrap(); let bottom_delegations = BottomDelegations::::get(1).unwrap(); assert_eq!(top_delegations.delegations.len(), 4usize); @@ -4608,11 +6652,19 @@ fn candidate_pool_updates_when_total_counted_changes() { } // 15 + 16 + 17 + 18 + 20 = 86 (top 4 + self bond) is_candidate_pool_bond(1, 86); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(3), 1, 8)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(3), + 1, + 8 + )); // 3: 11 -> 19 => 3 is in top, bumps out 7 // 16 + 17 + 18 + 19 + 20 = 90 (top 4 + self bond) is_candidate_pool_bond(1, 90); - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(4), 1, 8)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(4), + 1, + 8 + )); // 4: 12 -> 20 => 4 is in top, bumps out 8 // 17 + 18 + 19 + 20 + 20 = 94 (top 4 + self bond) is_candidate_pool_bond(1, 94); @@ -4681,7 +6733,11 @@ fn only_top_collators_are_counted() { // 15 + 16 + 17 + 18 + 20 = 86 (top 4 + self bond) assert_eq!(collator_state.total_counted, 86); // bump bottom to the top - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(3), 1, 8)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(3), + 1, + 8 + )); assert_event_emitted!(Event::DelegationIncreased { delegator: 3, candidate: 1, @@ -4692,7 +6748,11 @@ fn only_top_collators_are_counted() { // 16 + 17 + 18 + 19 + 20 = 90 (top 4 + self bond) assert_eq!(collator_state.total_counted, 90); // bump bottom to the top - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(4), 1, 8)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(4), + 1, + 8 + )); assert_event_emitted!(Event::DelegationIncreased { delegator: 4, candidate: 1, @@ -4703,7 +6763,11 @@ fn only_top_collators_are_counted() { // 17 + 18 + 19 + 20 + 20 = 94 (top 4 + self bond) assert_eq!(collator_state.total_counted, 94); // bump bottom to the top - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(5), 1, 8)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(5), + 1, + 8 + )); assert_event_emitted!(Event::DelegationIncreased { delegator: 5, candidate: 1, @@ -4714,7 +6778,11 @@ fn only_top_collators_are_counted() { // 18 + 19 + 20 + 21 + 20 = 98 (top 4 + self bond) assert_eq!(collator_state.total_counted, 98); // bump bottom to the top - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(6), 1, 8)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(6), + 1, + 8 + )); assert_event_emitted!(Event::DelegationIncreased { delegator: 6, candidate: 1, @@ -4750,7 +6818,13 @@ fn delegation_events_convey_correct_position() { // 11 + 12 + 13 + 14 + 20 = 70 (top 4 + self bond) assert_eq!(collator1_state.total_counted, 70); // Top delegations are full, new highest delegation is made - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(7), 1, 15, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(7), + 1, + 15, + 10, + 10 + )); assert_event_emitted!(Event::Delegation { delegator: 7, locked_amount: 15, @@ -4761,7 +6835,13 @@ fn delegation_events_convey_correct_position() { // 12 + 13 + 14 + 15 + 20 = 70 (top 4 + self bond) assert_eq!(collator1_state.total_counted, 74); // New delegation is added to the bottom - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(8), 1, 10, 10, 10)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(8), + 1, + 10, + 10, + 10 + )); assert_event_emitted!(Event::Delegation { delegator: 8, locked_amount: 10, @@ -4772,7 +6852,11 @@ fn delegation_events_convey_correct_position() { // 12 + 13 + 14 + 15 + 20 = 70 (top 4 + self bond) assert_eq!(collator1_state.total_counted, 74); // 8 increases delegation to the top - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(8), 1, 3)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(8), + 1, + 3 + )); assert_event_emitted!(Event::DelegationIncreased { delegator: 8, candidate: 1, @@ -4783,7 +6867,11 @@ fn delegation_events_convey_correct_position() { // 13 + 13 + 14 + 15 + 20 = 75 (top 4 + self bond) assert_eq!(collator1_state.total_counted, 75); // 3 increases delegation but stays in bottom - assert_ok!(ParachainStaking::delegator_bond_more(RuntimeOrigin::signed(3), 1, 1)); + assert_ok!(ParachainStaking::delegator_bond_more( + RuntimeOrigin::signed(3), + 1, + 1 + )); assert_event_emitted!(Event::DelegationIncreased { delegator: 3, candidate: 1, @@ -4865,10 +6953,26 @@ fn no_rewards_paid_until_after_reward_payment_delay() { set_author(1, 4, 1); set_author(1, 4, 1); let mut expected = vec![ - Event::CollatorChosen { round: 2, collator_account: 1, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 2, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 2, collator_account: 4, total_exposed_amount: 20 }, + Event::CollatorChosen { + round: 2, + collator_account: 1, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 2, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 2, + collator_account: 4, + total_exposed_amount: 20, + }, Event::NewRound { starting_block: 5, round: 2, @@ -4880,10 +6984,26 @@ fn no_rewards_paid_until_after_reward_payment_delay() { roll_to_round_begin(3); expected.append(&mut vec![ - Event::CollatorChosen { round: 3, collator_account: 1, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 2, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 3, total_exposed_amount: 20 }, - Event::CollatorChosen { round: 3, collator_account: 4, total_exposed_amount: 20 }, + Event::CollatorChosen { + round: 3, + collator_account: 1, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 2, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 3, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round: 3, + collator_account: 4, + total_exposed_amount: 20, + }, Event::NewRound { starting_block: 10, round: 3, @@ -4891,22 +7011,34 @@ fn no_rewards_paid_until_after_reward_payment_delay() { total_balance: 80, }, // rewards will begin immediately following a NewRound - Event::Rewarded { account: 3, rewards: 1 }, + Event::Rewarded { + account: 3, + rewards: 1, + }, ]); assert_eq_events!(expected); // roll to the next block where we start round 3; we should have round change and first // payout made. roll_one_block(); - expected.push(Event::Rewarded { account: 4, rewards: 2 }); + expected.push(Event::Rewarded { + account: 4, + rewards: 2, + }); assert_eq_events!(expected); roll_one_block(); - expected.push(Event::Rewarded { account: 1, rewards: 1 }); + expected.push(Event::Rewarded { + account: 1, + rewards: 1, + }); assert_eq_events!(expected); roll_one_block(); - expected.push(Event::Rewarded { account: 2, rewards: 1 }); + expected.push(Event::Rewarded { + account: 2, + rewards: 1, + }); assert_eq_events!(expected); // there should be no more payments in this round... @@ -4939,8 +7071,16 @@ fn deferred_payment_storage_items_are_cleaned_up() { round = 2; roll_to_round_begin(round.into()); let mut expected = vec![ - Event::CollatorChosen { round, collator_account: 1, total_exposed_amount: 20 }, - Event::CollatorChosen { round, collator_account: 2, total_exposed_amount: 20 }, + Event::CollatorChosen { + round, + collator_account: 1, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round, + collator_account: 2, + total_exposed_amount: 20, + }, Event::NewRound { starting_block: 5, round, @@ -4983,15 +7123,26 @@ fn deferred_payment_storage_items_are_cleaned_up() { round = 3; roll_to_round_begin(round.into()); expected.append(&mut vec![ - Event::CollatorChosen { round, collator_account: 1, total_exposed_amount: 20 }, - Event::CollatorChosen { round, collator_account: 2, total_exposed_amount: 20 }, + Event::CollatorChosen { + round, + collator_account: 1, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round, + collator_account: 2, + total_exposed_amount: 20, + }, Event::NewRound { starting_block: 10, round, selected_collators_number: 2, total_balance: 40, }, - Event::Rewarded { account: 1, rewards: 1 }, + Event::Rewarded { + account: 1, + rewards: 1, + }, ]); assert_eq_events!(expected); @@ -5012,11 +7163,17 @@ fn deferred_payment_storage_items_are_cleaned_up() { ); assert!(!>::contains_key(2)); - assert!(!>::contains_key(2), "We never rewarded points for round 2"); + assert!( + !>::contains_key(2), + "We never rewarded points for round 2" + ); assert!(>::contains_key(2)); assert!(!>::contains_key(3)); - assert!(!>::contains_key(3), "We never awarded points for round 3"); + assert!( + !>::contains_key(3), + "We never awarded points for round 3" + ); assert!(>::contains_key(3)); // collator 1 has been paid in this last block and associated storage cleaned up @@ -5030,9 +7187,20 @@ fn deferred_payment_storage_items_are_cleaned_up() { round = 4; roll_to_round_begin(round.into()); expected.append(&mut vec![ - Event::Rewarded { account: 2, rewards: 1 }, // from previous round - Event::CollatorChosen { round, collator_account: 1, total_exposed_amount: 20 }, - Event::CollatorChosen { round, collator_account: 2, total_exposed_amount: 20 }, + Event::Rewarded { + account: 2, + rewards: 1, + }, // from previous round + Event::CollatorChosen { + round, + collator_account: 1, + total_exposed_amount: 20, + }, + Event::CollatorChosen { + round, + collator_account: 2, + total_exposed_amount: 20, + }, Event::NewRound { starting_block: 15, round, @@ -5137,7 +7305,10 @@ fn deferred_payment_steady_state_event_flow() { // returns new round index let roll_through_steady_state_round = |round: u64| -> u64 { let num_rounds_rolled = roll_to_round_begin(round); - assert_eq!(num_rounds_rolled, 1, "expected to be at round begin already"); + assert_eq!( + num_rounds_rolled, 1, + "expected to be at round begin already" + ); let expected = vec![ Event::CollatorChosen { @@ -5167,9 +7338,18 @@ fn deferred_payment_steady_state_event_flow() { total_balance: 1600, }, // first payout should occur on round change - Event::Rewarded { account: 3, rewards: 19 }, - Event::Rewarded { account: 22, rewards: 6 }, - Event::Rewarded { account: 33, rewards: 6 }, + Event::Rewarded { + account: 3, + rewards: 19, + }, + Event::Rewarded { + account: 22, + rewards: 6, + }, + Event::Rewarded { + account: 33, + rewards: 6, + }, ]; assert_eq_last_events!(expected); @@ -5177,32 +7357,62 @@ fn deferred_payment_steady_state_event_flow() { roll_one_block(); let expected = vec![ - Event::Rewarded { account: 4, rewards: 19 }, - Event::Rewarded { account: 33, rewards: 6 }, - Event::Rewarded { account: 44, rewards: 6 }, + Event::Rewarded { + account: 4, + rewards: 19, + }, + Event::Rewarded { + account: 33, + rewards: 6, + }, + Event::Rewarded { + account: 44, + rewards: 6, + }, ]; assert_eq_last_events!(expected); roll_one_block(); let expected = vec![ - Event::Rewarded { account: 1, rewards: 19 }, - Event::Rewarded { account: 11, rewards: 6 }, - Event::Rewarded { account: 44, rewards: 6 }, + Event::Rewarded { + account: 1, + rewards: 19, + }, + Event::Rewarded { + account: 11, + rewards: 6, + }, + Event::Rewarded { + account: 44, + rewards: 6, + }, ]; assert_eq_last_events!(expected); roll_one_block(); let expected = vec![ - Event::Rewarded { account: 2, rewards: 19 }, - Event::Rewarded { account: 11, rewards: 6 }, - Event::Rewarded { account: 22, rewards: 6 }, + Event::Rewarded { + account: 2, + rewards: 19, + }, + Event::Rewarded { + account: 11, + rewards: 6, + }, + Event::Rewarded { + account: 22, + rewards: 6, + }, ]; assert_eq_last_events!(expected); roll_one_block(); let expected = vec![ // we paid everyone out by now, should repeat last event - Event::Rewarded { account: 22, rewards: 6 }, + Event::Rewarded { + account: 22, + rewards: 6, + }, ]; assert_eq_last_events!(expected); @@ -5234,10 +7444,22 @@ fn patch_incorrect_delegations_sums() { // corrupt top and bottom delegations so totals are incorrect let old_top_delegations = Delegations { delegations: vec![ - Bond { owner: 2, amount: 103 }, - Bond { owner: 3, amount: 102 }, - Bond { owner: 4, amount: 101 }, - Bond { owner: 5, amount: 100 }, + Bond { + owner: 2, + amount: 103, + }, + Bond { + owner: 3, + amount: 102, + }, + Bond { + owner: 4, + amount: 101, + }, + Bond { + owner: 5, + amount: 100, + }, ], // should be 406 total: 453, @@ -5245,10 +7467,22 @@ fn patch_incorrect_delegations_sums() { >::insert(&1, old_top_delegations); let old_bottom_delegations = Delegations { delegations: vec![ - Bond { owner: 6, amount: 25 }, - Bond { owner: 7, amount: 24 }, - Bond { owner: 8, amount: 23 }, - Bond { owner: 9, amount: 22 }, + Bond { + owner: 6, + amount: 25, + }, + Bond { + owner: 7, + amount: 24, + }, + Bond { + owner: 8, + amount: 23, + }, + Bond { + owner: 9, + amount: 22, + }, ], // should be 94 total: 222, @@ -5270,7 +7504,10 @@ fn patch_incorrect_delegations_sums() { status: CollatorStatus::Active, }, ); - >::put(OrderedSet::from(vec![Bond { owner: 1, amount: 478 }])); + >::put(OrderedSet::from(vec![Bond { + owner: 1, + amount: 478, + }])); crate::migrations::PatchIncorrectDelegationSums::::on_runtime_upgrade(); let top = >::get(&1).expect("just updated so exists"); assert_eq!(top.total, 406); @@ -5452,7 +7689,11 @@ fn verify_purge_storage_migration_works() { } // set the round information to the 10th round // (we do not use roll_to because the payment logic uses `take` in the code) - >::put(RoundInfo { current: 10, first: 45, length: 5 }); + >::put(RoundInfo { + current: 10, + first: 45, + length: 5, + }); // execute the migration crate::migrations::PurgeStaleStorage::::on_runtime_upgrade(); // verify that all inserted items are removed except last 2 rounds @@ -5498,9 +7739,18 @@ fn delegation_kicked_from_bottom_removes_pending_request() { ]) .build() .execute_with(|| { - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); // 10 delegates to full 1 => kicks lowest delegation (2, 19) - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(10), 1, 20, 8, 0)); + assert_ok!(ParachainStaking::delegate( + RuntimeOrigin::signed(10), + 1, + 20, + 8, + 0 + )); // check the event assert_event_emitted!(Event::DelegationKicked { delegator: 2, @@ -5508,7 +7758,9 @@ fn delegation_kicked_from_bottom_removes_pending_request() { unstaked_amount: 19, }); // ensure request DNE - assert!(!DelegationScheduledRequests::::get(&1).iter().any(|x| x.delegator == 2)); + assert!(!DelegationScheduledRequests::::get(&1) + .iter() + .any(|x| x.delegator == 2)); }); } @@ -5550,7 +7802,10 @@ fn no_selected_candidates_defaults_to_last_round_collators() { assert_eq!(old_selected_candidates, new_selected_candidates); let mut index = 0usize; for account in new_selected_candidates { - assert_eq!(old_at_stake_snapshots[index], >::get(new_round, account)); + assert_eq!( + old_at_stake_snapshots[index], + >::get(new_round, account) + ); index += 1usize; } }); @@ -5567,32 +7822,49 @@ fn test_delegator_scheduled_for_revoke_is_rewarded_for_previous_rounds_but_not_f // preset rewards for rounds 1, 2 and 3 (1..=3).for_each(|round| set_author(round, 1, 1)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationRevocationScheduled { - round: 1, - delegator: 2, - candidate: 1, - scheduled_exit: 3, - })); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationRevocationScheduled { + round: 1, + delegator: 2, + candidate: 1, + scheduled_exit: 3, + } + )); let collator = CandidateInfo::::get(1).expect("candidate must exist"); assert_eq!( 1, collator.delegation_count, "collator's delegator count was reduced unexpectedly" ); - assert_eq!(30, collator.total_counted, "collator's total was reduced unexpectedly"); + assert_eq!( + 30, collator.total_counted, + "collator's total was reduced unexpectedly" + ); roll_to_round_begin(3); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 4 }, - Event::::Rewarded { account: 2, rewards: 1 }, + Event::::Rewarded { + account: 1, + rewards: 4 + }, + Event::::Rewarded { + account: 2, + rewards: 1 + }, ], "delegator was not rewarded as intended" ); roll_to_round_begin(4); assert_eq_last_events!( - vec![Event::::Rewarded { account: 1, rewards: 5 }], + vec![Event::::Rewarded { + account: 1, + rewards: 5 + }], "delegator was rewarded unexpectedly" ); let collator_snapshot = AtStake::::get(Round::::get().current, 1); @@ -5619,26 +7891,40 @@ fn test_delegator_scheduled_for_revoke_is_rewarded_when_request_cancelled() { // preset rewards for rounds 2, 3 and 4 (2..=4).for_each(|round| set_author(round, 1, 1)); - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationRevocationScheduled { - round: 1, - delegator: 2, - candidate: 1, - scheduled_exit: 3, - })); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(2), + 1 + )); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationRevocationScheduled { + round: 1, + delegator: 2, + candidate: 1, + scheduled_exit: 3, + } + )); let collator = CandidateInfo::::get(1).expect("candidate must exist"); assert_eq!( 1, collator.delegation_count, "collator's delegator count was reduced unexpectedly" ); - assert_eq!(30, collator.total_counted, "collator's total was reduced unexpectedly"); + assert_eq!( + 30, collator.total_counted, + "collator's total was reduced unexpectedly" + ); roll_to_round_begin(2); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); roll_to_round_begin(4); assert_eq_last_events!( - vec![Event::::Rewarded { account: 1, rewards: 5 }], + vec![Event::::Rewarded { + account: 1, + rewards: 5 + }], "delegator was rewarded unexpectedly", ); let collator_snapshot = AtStake::::get(Round::::get().current, 1); @@ -5655,8 +7941,14 @@ fn test_delegator_scheduled_for_revoke_is_rewarded_when_request_cancelled() { roll_to_round_begin(5); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 4 }, - Event::::Rewarded { account: 2, rewards: 1 }, + Event::::Rewarded { + account: 1, + rewards: 4 + }, + Event::::Rewarded { + account: 2, + rewards: 1 + }, ], "delegator was not rewarded as intended", ); @@ -5680,24 +7972,35 @@ fn test_delegator_scheduled_for_bond_decrease_is_rewarded_for_previous_rounds_bu 1, 10, )); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationDecreaseScheduled { - execute_round: 3, - delegator: 2, - candidate: 1, - amount_to_decrease: 10, - })); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationDecreaseScheduled { + execute_round: 3, + delegator: 2, + candidate: 1, + amount_to_decrease: 10, + } + )); let collator = CandidateInfo::::get(1).expect("candidate must exist"); assert_eq!( 1, collator.delegation_count, "collator's delegator count was reduced unexpectedly" ); - assert_eq!(40, collator.total_counted, "collator's total was reduced unexpectedly"); + assert_eq!( + 40, collator.total_counted, + "collator's total was reduced unexpectedly" + ); roll_to_round_begin(3); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 3 }, - Event::::Rewarded { account: 2, rewards: 2 }, + Event::::Rewarded { + account: 1, + rewards: 3 + }, + Event::::Rewarded { + account: 2, + rewards: 2 + }, ], "delegator was not rewarded as intended" ); @@ -5705,8 +8008,14 @@ fn test_delegator_scheduled_for_bond_decrease_is_rewarded_for_previous_rounds_bu roll_to_round_begin(4); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 4 }, - Event::::Rewarded { account: 2, rewards: 1 }, + Event::::Rewarded { + account: 1, + rewards: 4 + }, + Event::::Rewarded { + account: 2, + rewards: 1 + }, ], "delegator was rewarded unexpectedly" ); @@ -5739,27 +8048,41 @@ fn test_delegator_scheduled_for_bond_decrease_is_rewarded_when_request_cancelled 1, 10, )); - assert_last_event!(MetaEvent::ParachainStaking(Event::DelegationDecreaseScheduled { - execute_round: 3, - delegator: 2, - candidate: 1, - amount_to_decrease: 10, - })); + assert_last_event!(MetaEvent::ParachainStaking( + Event::DelegationDecreaseScheduled { + execute_round: 3, + delegator: 2, + candidate: 1, + amount_to_decrease: 10, + } + )); let collator = CandidateInfo::::get(1).expect("candidate must exist"); assert_eq!( 1, collator.delegation_count, "collator's delegator count was reduced unexpectedly" ); - assert_eq!(40, collator.total_counted, "collator's total was reduced unexpectedly"); + assert_eq!( + 40, collator.total_counted, + "collator's total was reduced unexpectedly" + ); roll_to_round_begin(2); - assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); + assert_ok!(ParachainStaking::cancel_delegation_request( + RuntimeOrigin::signed(2), + 1 + )); roll_to_round_begin(4); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 4 }, - Event::::Rewarded { account: 2, rewards: 1 }, + Event::::Rewarded { + account: 1, + rewards: 4 + }, + Event::::Rewarded { + account: 2, + rewards: 1 + }, ], "delegator was rewarded unexpectedly", ); @@ -5777,8 +8100,14 @@ fn test_delegator_scheduled_for_bond_decrease_is_rewarded_when_request_cancelled roll_to_round_begin(5); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 3 }, - Event::::Rewarded { account: 2, rewards: 2 }, + Event::::Rewarded { + account: 1, + rewards: 3 + }, + Event::::Rewarded { + account: 2, + rewards: 2 + }, ], "delegator was not rewarded as intended", ); @@ -5796,7 +8125,9 @@ fn test_delegator_scheduled_for_leave_is_rewarded_for_previous_rounds_but_not_fo // preset rewards for rounds 1, 2 and 3 (1..=3).for_each(|round| set_author(round, 1, 1)); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2),)); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2), + )); assert_last_event!(MetaEvent::ParachainStaking(Event::DelegatorExitScheduled { round: 1, delegator: 2, @@ -5807,20 +8138,32 @@ fn test_delegator_scheduled_for_leave_is_rewarded_for_previous_rounds_but_not_fo 1, collator.delegation_count, "collator's delegator count was reduced unexpectedly" ); - assert_eq!(30, collator.total_counted, "collator's total was reduced unexpectedly"); + assert_eq!( + 30, collator.total_counted, + "collator's total was reduced unexpectedly" + ); roll_to_round_begin(3); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 4 }, - Event::::Rewarded { account: 2, rewards: 1 }, + Event::::Rewarded { + account: 1, + rewards: 4 + }, + Event::::Rewarded { + account: 2, + rewards: 1 + }, ], "delegator was not rewarded as intended" ); roll_to_round_begin(4); assert_eq_last_events!( - vec![Event::::Rewarded { account: 1, rewards: 5 },], + vec![Event::::Rewarded { + account: 1, + rewards: 5 + },], "delegator was rewarded unexpectedly" ); let collator_snapshot = AtStake::::get(Round::::get().current, 1); @@ -5847,7 +8190,9 @@ fn test_delegator_scheduled_for_leave_is_rewarded_when_request_cancelled() { // preset rewards for rounds 2, 3 and 4 (2..=4).for_each(|round| set_author(round, 1, 1)); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_last_event!(MetaEvent::ParachainStaking(Event::DelegatorExitScheduled { round: 1, delegator: 2, @@ -5858,14 +8203,22 @@ fn test_delegator_scheduled_for_leave_is_rewarded_when_request_cancelled() { 1, collator.delegation_count, "collator's delegator count was reduced unexpectedly" ); - assert_eq!(30, collator.total_counted, "collator's total was reduced unexpectedly"); + assert_eq!( + 30, collator.total_counted, + "collator's total was reduced unexpectedly" + ); roll_to_round_begin(2); - assert_ok!(ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::cancel_leave_delegators( + RuntimeOrigin::signed(2) + )); roll_to_round_begin(4); assert_eq_last_events!( - vec![Event::::Rewarded { account: 1, rewards: 5 },], + vec![Event::::Rewarded { + account: 1, + rewards: 5 + },], "delegator was rewarded unexpectedly", ); let collator_snapshot = AtStake::::get(Round::::get().current, 1); @@ -5882,8 +8235,14 @@ fn test_delegator_scheduled_for_leave_is_rewarded_when_request_cancelled() { roll_to_round_begin(5); assert_eq_last_events!( vec![ - Event::::Rewarded { account: 1, rewards: 4 }, - Event::::Rewarded { account: 2, rewards: 1 }, + Event::::Rewarded { + account: 1, + rewards: 4 + }, + Event::::Rewarded { + account: 2, + rewards: 1 + }, ], "delegator was not rewarded as intended", ); @@ -6010,10 +8369,12 @@ fn test_hotfix_remove_delegation_requests_exited_candidates_cleans_up() { 3, Vec::>::new(), ); - assert_ok!(ParachainStaking::hotfix_remove_delegation_requests_exited_candidates( - RuntimeOrigin::signed(1), - vec![2, 3, 4] // 4 does not exist, but is OK for idempotency - )); + assert_ok!( + ParachainStaking::hotfix_remove_delegation_requests_exited_candidates( + RuntimeOrigin::signed(1), + vec![2, 3, 4] // 4 does not exist, but is OK for idempotency + ) + ); assert!(!>::contains_key(2)); assert!(!>::contains_key(3)); @@ -6036,10 +8397,12 @@ fn test_hotfix_remove_delegation_requests_exited_candidates_cleans_up_only_speci 3, Vec::>::new(), ); - assert_ok!(ParachainStaking::hotfix_remove_delegation_requests_exited_candidates( - RuntimeOrigin::signed(1), - vec![2] - )); + assert_ok!( + ParachainStaking::hotfix_remove_delegation_requests_exited_candidates( + RuntimeOrigin::signed(1), + vec![2] + ) + ); assert!(!>::contains_key(2)); assert!(>::contains_key(3)); @@ -6106,16 +8469,22 @@ fn locking_zero_amount_removes_lock() { // this test demonstrates the behavior of pallet Balance's `LockableCurrency` implementation of // `set_locks()` when an amount of 0 is provided: it is a no-op - ExtBuilder::default().with_balances(vec![(1, 100)]).build().execute_with(|| { - assert_eq!(crate::mock::query_lock_amount(1, DELEGATOR_LOCK_ID), None); + ExtBuilder::default() + .with_balances(vec![(1, 100)]) + .build() + .execute_with(|| { + assert_eq!(crate::mock::query_lock_amount(1, DELEGATOR_LOCK_ID), None); - Balances::set_lock(DELEGATOR_LOCK_ID, &1, 1, WithdrawReasons::all()); - assert_eq!(crate::mock::query_lock_amount(1, DELEGATOR_LOCK_ID), Some(1)); + Balances::set_lock(DELEGATOR_LOCK_ID, &1, 1, WithdrawReasons::all()); + assert_eq!( + crate::mock::query_lock_amount(1, DELEGATOR_LOCK_ID), + Some(1) + ); - Balances::set_lock(DELEGATOR_LOCK_ID, &1, 0, WithdrawReasons::all()); - // Note that we tried to call `set_lock(0)` and the previous lock gets removed - assert_eq!(crate::mock::query_lock_amount(1, DELEGATOR_LOCK_ID), None); - }); + Balances::set_lock(DELEGATOR_LOCK_ID, &1, 0, WithdrawReasons::all()); + // Note that we tried to call `set_lock(0)` and the previous lock gets removed + assert_eq!(crate::mock::query_lock_amount(1, DELEGATOR_LOCK_ID), None); + }); } #[test] @@ -6126,20 +8495,32 @@ fn revoke_last_removes_lock() { .with_delegations(vec![(3, 1, 30), (3, 2, 25)]) .build() .execute_with(|| { - assert_eq!(crate::mock::query_lock_amount(3, DELEGATOR_LOCK_ID), Some(55)); + assert_eq!( + crate::mock::query_lock_amount(3, DELEGATOR_LOCK_ID), + Some(55) + ); // schedule and remove one... - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(3), 1)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(3), + 1 + )); roll_to_round_begin(3); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(3), 3, 1 )); - assert_eq!(crate::mock::query_lock_amount(3, DELEGATOR_LOCK_ID), Some(25)); + assert_eq!( + crate::mock::query_lock_amount(3, DELEGATOR_LOCK_ID), + Some(25) + ); // schedule and remove the other... - assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(3), 2)); + assert_ok!(ParachainStaking::schedule_revoke_delegation( + RuntimeOrigin::signed(3), + 2 + )); roll_to_round_begin(5); assert_ok!(ParachainStaking::execute_delegation_request( RuntimeOrigin::signed(3), @@ -6167,7 +8548,9 @@ fn test_delegator_with_deprecated_status_leaving_can_schedule_leave_delegators_a let state = >::get(2); assert!(matches!(state.unwrap().status, DelegatorStatus::Leaving(_))); - assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::schedule_leave_delegators( + RuntimeOrigin::signed(2) + )); assert!(>::get(1) .iter() .any(|r| r.delegator == 2 && matches!(r.action, DelegationAction::Revoke(_)))); @@ -6199,7 +8582,9 @@ fn test_delegator_with_deprecated_status_leaving_can_cancel_leave_delegators_as_ let state = >::get(2); assert!(matches!(state.unwrap().status, DelegatorStatus::Leaving(_))); - assert_ok!(ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2))); + assert_ok!(ParachainStaking::cancel_leave_delegators( + RuntimeOrigin::signed(2) + )); assert_last_event!(MetaEvent::ParachainStaking(Event::DelegatorExitCancelled { delegator: 2 })); @@ -6227,8 +8612,15 @@ fn test_delegator_with_deprecated_status_leaving_can_execute_leave_delegators_as assert!(matches!(state.unwrap().status, DelegatorStatus::Leaving(_))); roll_to(10); - assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); - assert_event_emitted!(Event::DelegatorLeft { delegator: 2, unstaked_amount: 10 }); + assert_ok!(ParachainStaking::execute_leave_delegators( + RuntimeOrigin::signed(2), + 2, + 1 + )); + assert_event_emitted!(Event::DelegatorLeft { + delegator: 2, + unstaked_amount: 10 + }); let state = >::get(2); assert!(state.is_none()); diff --git a/pallets/parachain-staking/src/types.rs b/pallets/parachain-staking/src/types.rs index 69a176423a..c30dddb057 100644 --- a/pallets/parachain-staking/src/types.rs +++ b/pallets/parachain-staking/src/types.rs @@ -57,7 +57,10 @@ impl Default for Bond { impl Bond { pub fn from_owner(owner: A) -> Self { - Bond { owner, amount: B::default() } + Bond { + owner, + amount: B::default(), + } } } @@ -120,8 +123,16 @@ impl PartialEq for CollatorSnapshot { if !must_be_true { return false; } - for (Bond { owner: o1, amount: a1 }, Bond { owner: o2, amount: a2 }) in - self.delegations.iter().zip(other.delegations.iter()) + for ( + Bond { + owner: o1, + amount: a1, + }, + Bond { + owner: o2, + amount: a2, + }, + ) in self.delegations.iter().zip(other.delegations.iter()) { if o1 != o2 || a1 != a2 { return false; @@ -133,7 +144,11 @@ impl PartialEq for CollatorSnapshot { impl Default for CollatorSnapshot { fn default() -> CollatorSnapshot { - CollatorSnapshot { bond: B::default(), delegations: Vec::new(), total: B::default() } + CollatorSnapshot { + bond: B::default(), + delegations: Vec::new(), + total: B::default(), + } } } @@ -226,7 +241,10 @@ pub struct Delegations { impl Default for Delegations { fn default() -> Delegations { - Delegations { delegations: Vec::new(), total: B::default() } + Delegations { + delegations: Vec::new(), + total: B::default(), + } } } @@ -251,7 +269,10 @@ impl { @@ -265,7 +286,7 @@ impl self.delegations.insert(i, delegation), } } @@ -280,19 +301,26 @@ impl(&self) -> CapacityStatus { match &self.delegations { - x if x.len() as u32 >= T::MaxBottomDelegationsPerCandidate::get() => - CapacityStatus::Full, + x if x.len() as u32 >= T::MaxBottomDelegationsPerCandidate::get() => { + CapacityStatus::Full + } x if x.is_empty() => CapacityStatus::Empty, _ => CapacityStatus::Partial, } } /// Return last delegation amount without popping the delegation pub fn lowest_delegation_amount(&self) -> Balance { - self.delegations.last().map(|x| x.amount).unwrap_or_else(Balance::zero) + self.delegations + .last() + .map(|x| x.amount) + .unwrap_or_else(Balance::zero) } /// Return highest delegation amount pub fn highest_delegation_amount(&self) -> Balance { - self.delegations.first().map(|x| x.amount).unwrap_or_else(Balance::zero) + self.delegations + .first() + .map(|x| x.amount) + .unwrap_or_else(Balance::zero) } } @@ -372,7 +400,10 @@ impl< } pub fn can_leave(&self) -> DispatchResult { if let CollatorStatus::Leaving(when) = self.status { - ensure!(>::get().current >= when, Error::::CandidateCannotLeaveYet); + ensure!( + >::get().current >= when, + Error::::CandidateCannotLeaveYet + ); Ok(()) } else { Err(Error::::CandidateNotLeaving.into()) @@ -395,7 +426,12 @@ impl< let new_total = >::get().saturating_add(more.into()); >::put(new_total); self.bond = self.bond.saturating_add(more); - T::Currency::set_lock(COLLATOR_LOCK_ID, &who, self.bond.into(), WithdrawReasons::all()); + T::Currency::set_lock( + COLLATOR_LOCK_ID, + &who, + self.bond.into(), + WithdrawReasons::all(), + ); self.total_counted = self.total_counted.saturating_add(more); >::deposit_event(Event::CandidateBondedMore { candidate: who, @@ -414,7 +450,10 @@ impl< BalanceOf: Into, { // ensure no pending request - ensure!(self.request.is_none(), Error::::PendingCandidateRequestAlreadyExists); + ensure!( + self.request.is_none(), + Error::::PendingCandidateRequestAlreadyExists + ); // ensure bond above min after decrease ensure!(self.bond > less, Error::::CandidateBondBelowMin); ensure!( @@ -422,7 +461,10 @@ impl< Error::::CandidateBondBelowMin ); let when_executable = >::get().current + T::CandidateBondLessDelay::get(); - self.request = Some(CandidateBondLessRequest { amount: less, when_executable }); + self.request = Some(CandidateBondLessRequest { + amount: less, + when_executable, + }); Ok(when_executable) } /// Execute pending request to decrease the collator self bond @@ -431,7 +473,9 @@ impl< where BalanceOf: From, { - let request = self.request.ok_or(Error::::PendingCandidateRequestsDNE)?; + let request = self + .request + .ok_or(Error::::PendingCandidateRequestsDNE)?; ensure!( request.when_executable <= >::get().current, Error::::PendingCandidateRequestNotDueYet @@ -441,7 +485,12 @@ impl< // Arithmetic assumptions are self.bond > less && self.bond - less > CollatorMinBond // (assumptions enforced by `schedule_bond_less`; if storage corrupts, must re-verify) self.bond = self.bond.saturating_sub(request.amount); - T::Currency::set_lock(COLLATOR_LOCK_ID, &who, self.bond.into(), WithdrawReasons::all()); + T::Currency::set_lock( + COLLATOR_LOCK_ID, + &who, + self.bond.into(), + WithdrawReasons::all(), + ); self.total_counted = self.total_counted.saturating_sub(request.amount); let event = Event::CandidateBondedLess { candidate: who.clone(), @@ -462,7 +511,9 @@ impl< where BalanceOf: From, { - let request = self.request.ok_or(Error::::PendingCandidateRequestsDNE)?; + let request = self + .request + .ok_or(Error::::PendingCandidateRequestsDNE)?; let event = Event::CancelledCandidateBondLess { candidate: who, amount: request.amount.into(), @@ -522,7 +573,9 @@ impl< if self.lowest_top_delegation_amount < delegation.amount.into() { // bumps lowest top to the bottom inside this function call less_total_staked = self.add_top_delegation::(candidate, delegation); - DelegatorAdded::AddedToTop { new_total: self.total_counted } + DelegatorAdded::AddedToTop { + new_total: self.total_counted, + } } else { // if bottom is full, only insert if greater than lowest bottom (which will // be bumped out) @@ -538,12 +591,14 @@ impl< self.add_bottom_delegation::(false, candidate, delegation); DelegatorAdded::AddedToBottom } - }, + } // top is either empty or partially full _ => { self.add_top_delegation::(candidate, delegation); - DelegatorAdded::AddedToTop { new_total: self.total_counted } - }, + DelegatorAdded::AddedToTop { + new_total: self.total_counted, + } + } }; Ok((delegator_added, less_total_staked)) } @@ -565,8 +620,9 @@ impl< if top_delegations.delegations.len() as u32 == max_top_delegations_per_candidate { // pop lowest top delegation let new_bottom_delegation = top_delegations.delegations.pop().expect(""); - top_delegations.total = - top_delegations.total.saturating_sub(new_bottom_delegation.amount); + top_delegations.total = top_delegations + .total + .saturating_sub(new_bottom_delegation.amount); if matches!(self.bottom_capacity, CapacityStatus::Full) { less_total_staked = Some(self.lowest_bottom_delegation_amount); } @@ -599,8 +655,8 @@ impl< .expect("CandidateInfo existence => BottomDelegations existence"); // if bottom is full, kick the lowest bottom (which is expected to be lower than input // as per check) - let increase_delegation_count = if bottom_delegations.delegations.len() as u32 == - T::MaxBottomDelegationsPerCandidate::get() + let increase_delegation_count = if bottom_delegations.delegations.len() as u32 + == T::MaxBottomDelegationsPerCandidate::get() { let lowest_bottom_to_be_kicked = bottom_delegations .delegations @@ -609,8 +665,9 @@ impl< // EXPECT lowest_bottom_to_be_kicked.amount < delegation.amount enforced by caller // if lowest_bottom_to_be_kicked.amount == delegation.amount, we will still kick // the lowest bottom to enforce first come first served - bottom_delegations.total = - bottom_delegations.total.saturating_sub(lowest_bottom_to_be_kicked.amount); + bottom_delegations.total = bottom_delegations + .total + .saturating_sub(lowest_bottom_to_be_kicked.amount); // update delegator state // total staked is updated via propagation of lowest bottom delegation amount prior // to call @@ -717,8 +774,9 @@ impl< >::get(candidate).expect("bottom is nonempty as just checked"); // expect already stored greatest to least by bond amount let highest_bottom_delegation = bottom_delegations.delegations.remove(0); - bottom_delegations.total = - bottom_delegations.total.saturating_sub(highest_bottom_delegation.amount); + bottom_delegations.total = bottom_delegations + .total + .saturating_sub(highest_bottom_delegation.amount); self.reset_bottom_data::(&bottom_delegations); >::insert(candidate, bottom_delegations); // insert highest bottom into top delegations @@ -820,7 +878,10 @@ impl< } else { in_top = true; let new_amount = d.amount.saturating_add(more); - Bond { owner: d.owner, amount: new_amount } + Bond { + owner: d.owner, + amount: new_amount, + } } }) .collect(); @@ -876,8 +937,9 @@ impl< .delegations .pop() .expect("Top capacity full => Exists at least 1 top delegation"); - top_delegations.total = - top_delegations.total.saturating_sub(new_bottom_delegation.amount); + top_delegations.total = top_delegations + .total + .saturating_sub(new_bottom_delegation.amount); bottom_delegations.insert_sorted_greatest_to_least(new_bottom_delegation); } // insert into top @@ -897,7 +959,10 @@ impl< d } else { in_bottom = true; - Bond { owner: d.owner, amount: d.amount.saturating_add(more) } + Bond { + owner: d.owner, + amount: d.amount.saturating_add(more), + } } }) .collect(); @@ -958,8 +1023,8 @@ impl< let bond_after_less_than_highest_bottom = bond.saturating_sub(less).into() < self.highest_bottom_delegation_amount; // The top delegations is full and the bottom delegations has at least one delegation - let full_top_and_nonempty_bottom = matches!(self.top_capacity, CapacityStatus::Full) && - !matches!(self.bottom_capacity, CapacityStatus::Empty); + let full_top_and_nonempty_bottom = matches!(self.top_capacity, CapacityStatus::Full) + && !matches!(self.bottom_capacity, CapacityStatus::Empty); let mut top_delegations = >::get(candidate).ok_or(Error::::CandidateDNE)?; let in_top_after = if bond_after_less_than_highest_bottom && full_top_and_nonempty_bottom { @@ -987,8 +1052,9 @@ impl< let mut bottom_delegations = >::get(candidate) .expect("CandidateInfo existence => BottomDelegations existence"); let highest_bottom_delegation = bottom_delegations.delegations.remove(0); - bottom_delegations.total = - bottom_delegations.total.saturating_sub(highest_bottom_delegation.amount); + bottom_delegations.total = bottom_delegations + .total + .saturating_sub(highest_bottom_delegation.amount); // insert highest bottom into top top_delegations.insert_sorted_greatest_to_least(highest_bottom_delegation); // insert previous top into bottom @@ -1008,7 +1074,10 @@ impl< d } else { is_in_top = true; - Bond { owner: d.owner, amount: d.amount.saturating_sub(less) } + Bond { + owner: d.owner, + amount: d.amount.saturating_sub(less), + } } }) .collect(); @@ -1043,7 +1112,10 @@ impl< d } else { in_bottom = true; - Bond { owner: d.owner, amount: d.amount.saturating_sub(less) } + Bond { + owner: d.owner, + amount: d.amount.saturating_sub(less), + } } }) .collect(); @@ -1058,12 +1130,12 @@ impl< // Temporary manual implementation for migration testing purposes impl PartialEq for CollatorCandidate { fn eq(&self, other: &Self) -> bool { - let must_be_true = self.id == other.id && - self.bond == other.bond && - self.total_counted == other.total_counted && - self.total_backing == other.total_backing && - self.request == other.request && - self.state == other.state; + let must_be_true = self.id == other.id + && self.bond == other.bond + && self.total_counted == other.total_counted + && self.total_backing == other.total_backing + && self.request == other.request + && self.state == other.state; if !must_be_true { return false; } @@ -1072,15 +1144,37 @@ impl PartialEq for CollatorCandidate { return false; } } - for (Bond { owner: o1, amount: a1 }, Bond { owner: o2, amount: a2 }) in - self.top_delegations.iter().zip(other.top_delegations.iter()) + for ( + Bond { + owner: o1, + amount: a1, + }, + Bond { + owner: o2, + amount: a2, + }, + ) in self + .top_delegations + .iter() + .zip(other.top_delegations.iter()) { if o1 != o2 || a1 != a2 { return false; } } - for (Bond { owner: o1, amount: a1 }, Bond { owner: o2, amount: a2 }) in - self.bottom_delegations.iter().zip(other.bottom_delegations.iter()) + for ( + Bond { + owner: o1, + amount: a1, + }, + Bond { + owner: o2, + amount: a2, + }, + ) in self + .bottom_delegations + .iter() + .zip(other.bottom_delegations.iter()) { if o1 != o2 || a1 != a2 { return false; @@ -1150,15 +1244,23 @@ pub struct Delegator { // Temporary manual implementation for migration testing purposes impl PartialEq for Delegator { fn eq(&self, other: &Self) -> bool { - let must_be_true = self.id == other.id && - self.total == other.total && - self.less_total == other.less_total && - self.status == other.status; + let must_be_true = self.id == other.id + && self.total == other.total + && self.less_total == other.less_total + && self.status == other.status; if !must_be_true { return false; } - for (Bond { owner: o1, amount: a1 }, Bond { owner: o2, amount: a2 }) in - self.delegations.0.iter().zip(other.delegations.0.iter()) + for ( + Bond { + owner: o1, + amount: a1, + }, + Bond { + owner: o2, + amount: a2, + }, + ) in self.delegations.0.iter().zip(other.delegations.0.iter()) { if o1 != o2 || a1 != a2 { return false; @@ -1184,7 +1286,10 @@ impl< pub fn new(id: AccountId, collator: AccountId, amount: Balance) -> Self { Delegator { id, - delegations: OrderedSet::from(vec![Bond { owner: collator, amount }]), + delegations: OrderedSet::from(vec![Bond { + owner: collator, + amount, + }]), total: amount, less_total: Balance::zero(), status: DelegatorStatus::Active, @@ -1277,7 +1382,8 @@ impl< .collect(); if let Some(balance) = amt { self.delegations = OrderedSet::from(delegations); - self.total_sub::(balance).expect("Decreasing lock cannot fail, qed"); + self.total_sub::(balance) + .expect("Decreasing lock cannot fail, qed"); Some(self.total) } else { None @@ -1354,8 +1460,8 @@ impl< match additional_required_balance { BondAdjust::Increase(amount) => { ensure!( - >::get_delegator_stakable_free_balance(&self.id.clone().into()) >= - amount.into(), + >::get_delegator_stakable_free_balance(&self.id.clone().into()) + >= amount.into(), Error::::InsufficientBalance, ); @@ -1364,7 +1470,7 @@ impl< log::warn!("LOGIC ERROR: request to reserve more than bond total"); return Err(DispatchError::Other("Invalid additional_required_balance")); } - }, + } BondAdjust::Decrease => (), // do nothing on decrease }; @@ -1384,7 +1490,11 @@ impl< /// Retrieves the bond amount that a delegator has provided towards a collator. /// Returns `None` if missing. pub fn get_bond_amount(&self, collator: &AccountId) -> Option { - self.delegations.0.iter().find(|b| &b.owner == collator).map(|b| b.amount) + self.delegations + .0 + .iter() + .find(|b| &b.owner == collator) + .map(|b| b.amount) } } @@ -1516,7 +1626,11 @@ impl< > RoundInfo { pub fn new(current: RoundIndex, first: B, length: u32) -> RoundInfo { - RoundInfo { current, first, length } + RoundInfo { + current, + first, + length, + } } /// Check if the round should be updated pub fn should_update(&self, now: B) -> bool { diff --git a/pallets/prices/src/lib.rs b/pallets/prices/src/lib.rs index 5ca2071f59..40cf6e8d92 100644 --- a/pallets/prices/src/lib.rs +++ b/pallets/prices/src/lib.rs @@ -187,7 +187,8 @@ impl Pallet { asset_id, mantissa ); - p.checked_div(&FixedU128::from_inner(mantissa)).map(|price| (price, 0)) + p.checked_div(&FixedU128::from_inner(mantissa)) + .map(|price| (price, 0)) }) } @@ -263,8 +264,9 @@ impl OraclePriceProvider for Pallet { let total_value = price_in .mul(FixedU128::from_inner(amount_in)) .div(FixedU128::from_inner(currency_in_mantissa)); - let amount_out = - total_value.mul(FixedU128::from_inner(currency_out_mantissa)).div(price_out); + let amount_out = total_value + .mul(FixedU128::from_inner(currency_out_mantissa)) + .div(price_out); Some(amount_out.into_inner()) } diff --git a/pallets/prices/src/mock.rs b/pallets/prices/src/mock.rs index 157ce59cf0..2d1fac7879 100644 --- a/pallets/prices/src/mock.rs +++ b/pallets/prices/src/mock.rs @@ -58,10 +58,14 @@ impl DataProvider for MockDataProvider { value: Price::from_inner(200_000_000_000_000_000), timestamp: 0, }), - DOT => - Some(TimeStampedPrice { value: Price::saturating_from_integer(100), timestamp: 0 }), - KSM => - Some(TimeStampedPrice { value: Price::saturating_from_integer(500), timestamp: 0 }), + DOT => Some(TimeStampedPrice { + value: Price::saturating_from_integer(100), + timestamp: 0, + }), + KSM => Some(TimeStampedPrice { + value: Price::saturating_from_integer(500), + timestamp: 0, + }), MANTA => Some(TimeStampedPrice { value: Price::from_inner(600_000_000_000_000_000), timestamp: 0, @@ -86,10 +90,14 @@ impl DataProvider for MockDataProvider { impl DataProviderExtended for MockDataProvider { fn get_no_op(asset_id: &CurrencyId) -> Option { match *asset_id { - DOT => - Some(TimeStampedPrice { value: Price::saturating_from_integer(100), timestamp: 0 }), - KSM => - Some(TimeStampedPrice { value: Price::saturating_from_integer(500), timestamp: 0 }), + DOT => Some(TimeStampedPrice { + value: Price::saturating_from_integer(100), + timestamp: 0, + }), + KSM => Some(TimeStampedPrice { + value: Price::saturating_from_integer(500), + timestamp: 0, + }), _ => None, } } @@ -235,7 +243,9 @@ construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); bifrost_asset_registry::GenesisConfig:: { currency: vec![ @@ -283,9 +293,27 @@ pub fn new_test_ext() -> sp_io::TestExternalities { Assets::force_create(RuntimeOrigin::root(), VDOT.into(), ALICE, true, 1).unwrap(); Assets::force_create(RuntimeOrigin::root(), FIL.into(), ALICE, true, 1).unwrap(); - Assets::mint(RuntimeOrigin::signed(ALICE), DOT.into(), ALICE, 1000 * PRICE_ONE).unwrap(); - Assets::mint(RuntimeOrigin::signed(ALICE), VDOT.into(), ALICE, 1000 * PRICE_ONE).unwrap(); - Assets::mint(RuntimeOrigin::signed(ALICE), FIL.into(), ALICE, 1000 * PRICE_ONE).unwrap(); + Assets::mint( + RuntimeOrigin::signed(ALICE), + DOT.into(), + ALICE, + 1000 * PRICE_ONE, + ) + .unwrap(); + Assets::mint( + RuntimeOrigin::signed(ALICE), + VDOT.into(), + ALICE, + 1000 * PRICE_ONE, + ) + .unwrap(); + Assets::mint( + RuntimeOrigin::signed(ALICE), + FIL.into(), + ALICE, + 1000 * PRICE_ONE, + ) + .unwrap(); Prices::set_foreign_asset(RuntimeOrigin::signed(ALICE), VFIL, FIL).unwrap(); }); diff --git a/pallets/prices/src/tests.rs b/pallets/prices/src/tests.rs index 581cc74bde..f6e2407fee 100644 --- a/pallets/prices/src/tests.rs +++ b/pallets/prices/src/tests.rs @@ -57,7 +57,10 @@ fn set_price_work() { KSM, Price::saturating_from_integer(1) )); - assert_eq!(Prices::get_emergency_price(&KSM), Some((1_000_000.into(), 0))); + assert_eq!( + Prices::get_emergency_price(&KSM), + Some((1_000_000.into(), 0)) + ); }); } @@ -113,9 +116,13 @@ fn set_price_call_work() { ); // check the event - let set_price_event = - RuntimeEvent::Prices(crate::Event::SetPrice(DOT, Price::saturating_from_integer(90))); - assert!(System::events().iter().any(|record| record.event == set_price_event)); + let set_price_event = RuntimeEvent::Prices(crate::Event::SetPrice( + DOT, + Price::saturating_from_integer(90), + )); + assert!(System::events() + .iter() + .any(|record| record.event == set_price_event)); assert_eq!( Prices::set_price( RuntimeOrigin::signed(ALICE), @@ -148,7 +155,10 @@ fn reset_price_call_work() { ); // try reset price - assert_noop!(Prices::reset_price(RuntimeOrigin::signed(CHARLIE), DOT), BadOrigin); + assert_noop!( + Prices::reset_price(RuntimeOrigin::signed(CHARLIE), DOT), + BadOrigin + ); assert_ok!(Prices::reset_price(RuntimeOrigin::signed(ALICE), DOT)); // price need to be 100 after reset_price @@ -159,8 +169,13 @@ fn reset_price_call_work() { // check the event let reset_price_event = RuntimeEvent::Prices(crate::Event::ResetPrice(DOT)); - assert!(System::events().iter().any(|record| record.event == reset_price_event)); - assert_eq!(Prices::reset_price(RuntimeOrigin::signed(ALICE), DOT), Ok(().into())); + assert!(System::events() + .iter() + .any(|record| record.event == reset_price_event)); + assert_eq!( + Prices::reset_price(RuntimeOrigin::signed(ALICE), DOT), + Ok(().into()) + ); }); } diff --git a/pallets/salp/Cargo.toml b/pallets/salp/Cargo.toml index ae26cb32ef..ffd9bd12f8 100644 --- a/pallets/salp/Cargo.toml +++ b/pallets/salp/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp" version = "0.8.0" -authors = ["Edwin Wang ", "Ron yang"] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/salp/rpc/Cargo.toml b/pallets/salp/rpc/Cargo.toml index 1015d62ab0..89f9f40ea8 100644 --- a/pallets/salp/rpc/Cargo.toml +++ b/pallets/salp/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp-rpc" version = "0.8.0" -authors = ["Ron Yang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/salp/rpc/runtime-api/Cargo.toml b/pallets/salp/rpc/runtime-api/Cargo.toml index 4d40d9b248..bceea138d5 100644 --- a/pallets/salp/rpc/runtime-api/Cargo.toml +++ b/pallets/salp/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-salp-rpc-runtime-api" version = "0.8.0" -authors = ["Ron Yang"] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/salp/rpc/src/lib.rs b/pallets/salp/rpc/src/lib.rs index ebd2a82223..0a0dd409de 100644 --- a/pallets/salp/rpc/src/lib.rs +++ b/pallets/salp/rpc/src/lib.rs @@ -39,7 +39,10 @@ pub struct SalpRpc { impl SalpRpc { pub fn new(client: Arc) -> Self { - Self { client, _marker: PhantomData } + Self { + client, + _marker: PhantomData, + } } } diff --git a/pallets/salp/src/lib.rs b/pallets/salp/src/lib.rs index ae042ac7af..87daa390b4 100644 --- a/pallets/salp/src/lib.rs +++ b/pallets/salp/src/lib.rs @@ -188,11 +188,23 @@ pub mod pallet { /// Withdrew full balance of a contributor. [who, fund_index, amount] Withdrew(ParaId, BalanceOf), /// refund to account. [who, fund_index,value] - Refunded(AccountIdOf, ParaId, LeasePeriod, LeasePeriod, BalanceOf), + Refunded( + AccountIdOf, + ParaId, + LeasePeriod, + LeasePeriod, + BalanceOf, + ), /// all refund AllRefunded(ParaId), /// redeem to account. [who, fund_index, first_slot, last_slot, value] - Redeemed(AccountIdOf, ParaId, LeasePeriod, LeasePeriod, BalanceOf), + Redeemed( + AccountIdOf, + ParaId, + LeasePeriod, + LeasePeriod, + BalanceOf, + ), /// Fund is edited. [fund_index] Edited(ParaId), /// Fund is dissolved. [fund_index] @@ -366,9 +378,15 @@ pub mod pallet { T::EnsureConfirmAsGovernance::ensure_origin(origin)?; let fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; - ensure!(fund.status == FundStatus::Success, Error::::InvalidFundStatus); + ensure!( + fund.status == FundStatus::Success, + Error::::InvalidFundStatus + ); - let fund_new = FundInfo { status: FundStatus::Retired, ..fund }; + let fund_new = FundInfo { + status: FundStatus::Retired, + ..fund + }; Funds::::insert(index, Some(fund_new)); Self::deposit_event(Event::::Retired(index)); @@ -382,12 +400,15 @@ pub mod pallet { let fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; ensure!( - fund.status == FundStatus::RefundWithdrew || - fund.status == FundStatus::RedeemWithdrew, + fund.status == FundStatus::RefundWithdrew + || fund.status == FundStatus::RedeemWithdrew, Error::::InvalidFundStatus ); - let fund_new = FundInfo { status: FundStatus::End, ..fund }; + let fund_new = FundInfo { + status: FundStatus::End, + ..fund + }; Funds::::insert(index, Some(fund_new)); Self::deposit_event(Event::::End(index)); @@ -449,10 +470,16 @@ pub mod pallet { RedeemPool::::set(total); if fund.status == FundStatus::Retired { - let fund_new = FundInfo { status: FundStatus::RedeemWithdrew, ..fund }; + let fund_new = FundInfo { + status: FundStatus::RedeemWithdrew, + ..fund + }; Funds::::insert(index, Some(fund_new)); } else if fund.status == FundStatus::Failed { - let fund_new = FundInfo { status: FundStatus::RefundWithdrew, ..fund }; + let fund_new = FundInfo { + status: FundStatus::RefundWithdrew, + ..fund + }; Funds::::insert(index, Some(fund_new)); } @@ -475,8 +502,8 @@ pub mod pallet { let mut fund = Self::find_fund(index, first_slot, last_slot) .map_err(|_| Error::::InvalidFundNotExist)?; ensure!( - fund.status == FundStatus::FailedToContinue || - fund.status == FundStatus::RefundWithdrew, + fund.status == FundStatus::FailedToContinue + || fund.status == FundStatus::RefundWithdrew, Error::::InvalidRefund ); ensure!( @@ -484,7 +511,10 @@ pub mod pallet { Error::::InvalidRefund ); ensure!(fund.raised >= value, Error::::NotEnoughBalanceInFund); - ensure!(RedeemPool::::get() >= value, Error::::NotEnoughBalanceInRefundPool); + ensure!( + RedeemPool::::get() >= value, + Error::::NotEnoughBalanceInRefundPool + ); let vs_token = T::CurrencyIdConversion::convert_to_vstoken(T::RelayChainToken::get()) .map_err(|_| Error::::NotSupportTokenType)?; @@ -543,8 +573,14 @@ pub mod pallet { let who = ensure_signed(origin.clone())?; let mut fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; - ensure!(fund.status == FundStatus::RedeemWithdrew, Error::::InvalidFundStatus); - ensure!(fund.raised >= value, Error::::NotEnoughBalanceInRedeemPool); + ensure!( + fund.status == FundStatus::RedeemWithdrew, + Error::::InvalidFundStatus + ); + ensure!( + fund.raised >= value, + Error::::NotEnoughBalanceInRedeemPool + ); let vs_token = T::CurrencyIdConversion::convert_to_vstoken(T::RelayChainToken::get()) .map_err(|_| Error::::NotSupportTokenType)?; @@ -556,7 +592,10 @@ pub mod pallet { ) .map_err(|_| Error::::NotSupportTokenType)?; - ensure!(RedeemPool::::get() >= value, Error::::NotEnoughBalanceInRedeemPool); + ensure!( + RedeemPool::::get() >= value, + Error::::NotEnoughBalanceInRedeemPool + ); let cur_block = >::block_number(); let expired = Self::is_expired(cur_block, fund.last_slot)?; ensure!(!expired, Error::::VSBondExpired); @@ -603,7 +642,10 @@ pub mod pallet { let fund = FailedFundsToRefund::::get((index, first_slot, last_slot)) .ok_or(Error::::InvalidRefund)?; - ensure!(fund.status == FundStatus::FailedToContinue, Error::::InvalidFundStatus); + ensure!( + fund.status == FundStatus::FailedToContinue, + Error::::InvalidFundStatus + ); FailedFundsToRefund::::remove((index, first_slot, last_slot)); @@ -619,7 +661,10 @@ pub mod pallet { T::EnsureConfirmAsGovernance::ensure_origin(origin)?; let mut fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; - ensure!(fund.status == FundStatus::End, Error::::InvalidFundStatus); + ensure!( + fund.status == FundStatus::End, + Error::::InvalidFundStatus + ); let mut refund_count = 0u32; // Try killing the crowdloan child trie and Assume everyone will be refunded. @@ -686,9 +731,11 @@ pub mod pallet { T::StablePool::get_pool_token_index(pool_id, relay_vstoken_id) .ok_or(Error::::ArgumentsError)?, value.saturated_into(), - Percent::from_percent(50).saturating_reciprocal_mul(value).saturated_into(), + Percent::from_percent(50) + .saturating_reciprocal_mul(value) + .saturated_into(), )?; - }, + } cid if cid == relay_vtoken_id => { let token_value = T::VtokenMinting::get_currency_amount_by_v_currency_amount( relay_currency_id, @@ -707,11 +754,15 @@ pub mod pallet { .saturating_reciprocal_mul(token_value) .saturated_into(), )?; - }, + } _ => return Err(Error::::ArgumentsError.into()), } - Self::deposit_event(Event::::BuybackByStablePool { pool_id, currency_id_in, value }); + Self::deposit_event(Event::::BuybackByStablePool { + pool_id, + currency_id_in, + value, + }); Ok(()) } } diff --git a/pallets/slp-v2/src/astar_dapp_staking/impls.rs b/pallets/slp-v2/src/astar_dapp_staking/impls.rs index b9f8324979..f99daf17cd 100644 --- a/pallets/slp-v2/src/astar_dapp_staking/impls.rs +++ b/pallets/slp-v2/src/astar_dapp_staking/impls.rs @@ -42,10 +42,12 @@ impl Pallet { ) -> DispatchResultWithPostInfo { let validators = ValidatorsByStakingProtocolAndDelegator::::get(ASTAR_DAPP_STAKING, delegator); - let is_exist = validators.iter().any(|storage_validator| match storage_validator { - Validator::AstarDappStaking(astar_validator) => *astar_validator == validator, - _ => false, - }); + let is_exist = validators + .iter() + .any(|storage_validator| match storage_validator { + Validator::AstarDappStaking(astar_validator) => *astar_validator == validator, + _ => false, + }); ensure!(is_exist, Error::::ValidatorNotFound); Ok(().into()) } @@ -58,17 +60,15 @@ impl Pallet { let (call, pending_status) = match task.clone() { DappStaking::Lock(amount) => ( AstarCall::::DappStaking(DappStaking::::Lock(amount)).encode(), - Some(PendingStatus::AstarDappStaking(AstarDappStakingPendingStatus::Lock( - delegator.clone(), - amount, - ))), + Some(PendingStatus::AstarDappStaking( + AstarDappStakingPendingStatus::Lock(delegator.clone(), amount), + )), ), DappStaking::Unlock(amount) => ( AstarCall::::DappStaking(DappStaking::::Unlock(amount)).encode(), - Some(PendingStatus::AstarDappStaking(AstarDappStakingPendingStatus::UnLock( - delegator.clone(), - amount, - ))), + Some(PendingStatus::AstarDappStaking( + AstarDappStakingPendingStatus::UnLock(delegator.clone(), amount), + )), ), DappStaking::ClaimUnlocked => ( AstarCall::::DappStaking(DappStaking::::ClaimUnlocked).encode(), @@ -86,7 +86,7 @@ impl Pallet { .encode(), None, ) - }, + } DappStaking::Unstake(validator, amount) => { Self::ensure_validator_exist(delegator.clone(), validator.clone())?; ( @@ -97,7 +97,7 @@ impl Pallet { .encode(), None, ) - }, + } DappStaking::ClaimStakerRewards => ( AstarCall::::DappStaking(DappStaking::::ClaimStakerRewards) .encode(), @@ -112,7 +112,7 @@ impl Pallet { .encode(), None, ) - }, + } DappStaking::RelockUnlocking => ( AstarCall::::DappStaking(DappStaking::::RelockUnlocking).encode(), None, @@ -167,8 +167,9 @@ impl Pallet { pending_status: PendingStatus, ) -> Result<(), Error> { let delegator = match pending_status.clone() { - PendingStatus::AstarDappStaking(AstarDappStakingPendingStatus::Lock(delegator, _)) => - delegator, + PendingStatus::AstarDappStaking(AstarDappStakingPendingStatus::Lock(delegator, _)) => { + delegator + } PendingStatus::AstarDappStaking(AstarDappStakingPendingStatus::UnLock( delegator, _, @@ -188,7 +189,7 @@ impl Pallet { amount, )) => { pending_ledger.add_lock_amount(amount); - }, + } PendingStatus::AstarDappStaking(AstarDappStakingPendingStatus::UnLock( _, amount, @@ -206,9 +207,12 @@ impl Pallet { .ok_or(Error::::TimeUnitNotFound)?; pending_ledger .unlocking - .try_push(AstarUnlockingRecord { amount, unlock_time }) + .try_push(AstarUnlockingRecord { + amount, + unlock_time, + }) .map_err(|_| Error::::UnlockRecordOverflow)?; - }, + } PendingStatus::AstarDappStaking( AstarDappStakingPendingStatus::ClaimUnlocked(_), ) => { @@ -219,14 +223,17 @@ impl Pallet { pending_ledger.unlocking.retain(|record| { current_time_unit.cmp(&record.unlock_time) != Ordering::Greater }); - }, + } }; *ledger = Some(Ledger::AstarDappStaking(pending_ledger)); }; Ok(()) }, )?; - Self::deposit_event(Event::::NotifyResponseReceived { responder, pending_status }); + Self::deposit_event(Event::::NotifyResponseReceived { + responder, + pending_status, + }); Ok(()) } } diff --git a/pallets/slp-v2/src/benchmarking.rs b/pallets/slp-v2/src/benchmarking.rs index 92f1246539..2d07faf23f 100644 --- a/pallets/slp-v2/src/benchmarking.rs +++ b/pallets/slp-v2/src/benchmarking.rs @@ -42,7 +42,10 @@ where RawOrigin::Root.into(), STAKING_PROTOCOL, ProtocolConfiguration { - xcm_task_fee: XcmFee { weight: Weight::zero(), fee: 100 }, + xcm_task_fee: XcmFee { + weight: Weight::zero(), + fee: 100 + }, protocol_fee_rate: Permill::from_perthousand(100), unlock_period: TimeUnit::Era(9), operator: AccountId::from([0u8; 32]).into(), @@ -70,7 +73,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); #[extrinsic_call] _(RawOrigin::Root, STAKING_PROTOCOL, delegator); @@ -84,7 +91,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); let validator = Validator::AstarDappStaking(AstarValidator::Evm(H160::zero())); #[extrinsic_call] _(RawOrigin::Root, STAKING_PROTOCOL, delegator, validator); @@ -98,7 +109,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); let validator = Validator::AstarDappStaking(AstarValidator::Evm(H160::zero())); assert_ok!(SlpV2::::add_validator( RawOrigin::Root.into(), @@ -118,7 +133,10 @@ mod benchmarks { RawOrigin::Root, STAKING_PROTOCOL, ProtocolConfiguration { - xcm_task_fee: XcmFee { weight: Weight::zero(), fee: 100 }, + xcm_task_fee: XcmFee { + weight: Weight::zero(), + fee: 100, + }, protocol_fee_rate: Permill::from_perthousand(100), unlock_period: TimeUnit::Era(9), operator: AccountId::from([0u8; 32]).into(), @@ -141,7 +159,11 @@ mod benchmarks { locked: 100, unlocking: Default::default(), }); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); #[extrinsic_call] _(RawOrigin::Root, STAKING_PROTOCOL, delegator, ledger); @@ -155,7 +177,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); #[extrinsic_call] _(RawOrigin::Root, STAKING_PROTOCOL, delegator); Ok(()) @@ -168,7 +194,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); do_set_protocol_configuration::(); #[extrinsic_call] _(RawOrigin::Root, STAKING_PROTOCOL, delegator, 1000); @@ -189,7 +219,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); #[extrinsic_call] _(RawOrigin::Root, STAKING_PROTOCOL, delegator, 1000); Ok(()) @@ -202,7 +236,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); do_set_protocol_configuration::(); let task = DappStaking::Lock(100); #[extrinsic_call] @@ -217,7 +255,11 @@ mod benchmarks { .unwrap() .into(), ); - assert_ok!(SlpV2::::add_delegator(RawOrigin::Root.into(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::::add_delegator( + RawOrigin::Root.into(), + STAKING_PROTOCOL, + None + )); do_set_protocol_configuration::(); PendingStatusByQueryId::::insert( @@ -228,7 +270,11 @@ mod benchmarks { )), ); #[extrinsic_call] - _(RawOrigin::Root, 0, xcm::v4::Response::DispatchResult(MaybeErrorCode::Success)); + _( + RawOrigin::Root, + 0, + xcm::v4::Response::DispatchResult(MaybeErrorCode::Success), + ); Ok(()) } diff --git a/pallets/slp-v2/src/common/impls.rs b/pallets/slp-v2/src/common/impls.rs index 3364548743..2e3143a74e 100644 --- a/pallets/slp-v2/src/common/impls.rs +++ b/pallets/slp-v2/src/common/impls.rs @@ -57,7 +57,9 @@ impl Pallet { staking_protocol, |index| -> DispatchResultWithPostInfo { delegator_index = *index; - *index = index.checked_add(1).ok_or(Error::::DelegatorIndexOverflow)?; + *index = index + .checked_add(1) + .ok_or(Error::::DelegatorIndexOverflow)?; let delegator = delegator.unwrap_or(staking_protocol.get_delegator::(delegator_index)?); ensure!( @@ -214,9 +216,17 @@ impl Pallet { ) -> Result, Error> { let xcm_pallet_index = staking_protocol.info().xcm_pallet_index; let bifrost_dest_location = staking_protocol.info().bifrost_dest_location; - let account_id = - to.encode().try_into().map_err(|_| Error::::DerivativeAccountIdFailed)?; - let beneficiary = Location::new(0, AccountId32 { network: None, id: account_id }); + let account_id = to + .encode() + .try_into() + .map_err(|_| Error::::DerivativeAccountIdFailed)?; + let beneficiary = Location::new( + 0, + AccountId32 { + network: None, + id: account_id, + }, + ); let fee_asset_item = 0u32; let weight_limit = WeightLimit::Unlimited; @@ -251,8 +261,10 @@ impl Pallet { .ok_or(Error::::ConfigurationNotFound)?; let fee_location = staking_protocol.info().remote_fee_location; let refund_beneficiary = staking_protocol.info().remote_refund_beneficiary; - let asset = - Asset { id: AssetId(fee_location), fun: Fungible(configuration.xcm_task_fee.fee) }; + let asset = Asset { + id: AssetId(fee_location), + fun: Fungible(configuration.xcm_task_fee.fee), + }; let assets: Assets = Assets::from(asset.clone()); let require_weight_at_most = configuration.xcm_task_fee.weight; let call: DoubleEncoded<()> = call.into(); @@ -342,14 +354,14 @@ impl Pallet { Some(c) => { ensure!(c.operator == signer, Error::::NotAuthorized); Ok(()) - }, + } None => Err(Error::::NotAuthorized), } - }, + } _ => { T::ControlOrigin::ensure_origin(origin).map_err(|_| Error::::NotAuthorized)?; Ok(()) - }, + } } } diff --git a/pallets/slp-v2/src/common/types/kusama.rs b/pallets/slp-v2/src/common/types/kusama.rs index 19aba6a091..512cffcd68 100644 --- a/pallets/slp-v2/src/common/types/kusama.rs +++ b/pallets/slp-v2/src/common/types/kusama.rs @@ -83,18 +83,29 @@ impl StakingProtocol { delegator: Delegator, ) -> Option { match (self, delegator) { - (StakingProtocol::KusamaStaking, Delegator::Substrate(account_id)) => + (StakingProtocol::KusamaStaking, Delegator::Substrate(account_id)) => { account_id.encode().try_into().ok().and_then(|account_id| { - Some(Location::new(1, [AccountId32 { network: None, id: account_id }])) - }), - (StakingProtocol::MoonriverParachainStaking, Delegator::Ethereum(account_id)) => + Some(Location::new( + 1, + [AccountId32 { + network: None, + id: account_id, + }], + )) + }) + } + (StakingProtocol::MoonriverParachainStaking, Delegator::Ethereum(account_id)) => { Some(Location::new( 1, [ Parachain(MoonriverChainId::get()), - AccountKey20 { network: None, key: account_id.to_fixed_bytes() }, + AccountKey20 { + network: None, + key: account_id.to_fixed_bytes(), + }, ], - )), + )) + } _ => None, } } diff --git a/pallets/slp-v2/src/common/types/polkadot.rs b/pallets/slp-v2/src/common/types/polkadot.rs index a3120a22b0..71e39a6a3e 100644 --- a/pallets/slp-v2/src/common/types/polkadot.rs +++ b/pallets/slp-v2/src/common/types/polkadot.rs @@ -104,28 +104,43 @@ impl StakingProtocol { delegator: Delegator, ) -> Option { match (self, delegator) { - (StakingProtocol::AstarDappStaking, Delegator::Substrate(account_id)) => + (StakingProtocol::AstarDappStaking, Delegator::Substrate(account_id)) => { account_id.encode().try_into().ok().and_then(|account_id| { Some(Location::new( 1, [ Parachain(AstarChainId::get()), - AccountId32 { network: None, id: account_id }, + AccountId32 { + network: None, + id: account_id, + }, ], )) - }), - (StakingProtocol::PolkadotStaking, Delegator::Substrate(account_id)) => + }) + } + (StakingProtocol::PolkadotStaking, Delegator::Substrate(account_id)) => { account_id.encode().try_into().ok().and_then(|account_id| { - Some(Location::new(1, [AccountId32 { network: None, id: account_id }])) - }), - (StakingProtocol::MoonbeamParachainStaking, Delegator::Ethereum(account_id)) => + Some(Location::new( + 1, + [AccountId32 { + network: None, + id: account_id, + }], + )) + }) + } + (StakingProtocol::MoonbeamParachainStaking, Delegator::Ethereum(account_id)) => { Some(Location::new( 1, [ Parachain(MoonbeamChainId::get()), - AccountKey20 { network: None, key: account_id.to_fixed_bytes() }, + AccountKey20 { + network: None, + key: account_id.to_fixed_bytes(), + }, ], - )), + )) + } _ => None, } } @@ -141,15 +156,16 @@ impl StakingProtocol { delegator_index, )?; Ok(Delegator::Substrate(sub_sibling_account)) - }, + } _ => Err(Error::::UnsupportedStakingProtocol), } } pub fn get_default_ledger(&self) -> Ledger { match self { - StakingProtocol::AstarDappStaking => - Ledger::AstarDappStaking(AstarDappStakingLedger::default()), + StakingProtocol::AstarDappStaking => { + Ledger::AstarDappStaking(AstarDappStakingLedger::default()) + } _ => unreachable!(), } } diff --git a/pallets/slp-v2/src/lib.rs b/pallets/slp-v2/src/lib.rs index ce08dca9a9..86cc785cb1 100644 --- a/pallets/slp-v2/src/lib.rs +++ b/pallets/slp-v2/src/lib.rs @@ -457,7 +457,10 @@ pub mod pallet { staking_protocol, delegator.clone(), |validators| -> DispatchResultWithPostInfo { - ensure!(!validators.contains(&validator), Error::::ValidatorAlreadyExists); + ensure!( + !validators.contains(&validator), + Error::::ValidatorAlreadyExists + ); validators .try_push(validator.clone()) .map_err(|_| Error::::ValidatorsOverflow)?; @@ -493,7 +496,10 @@ pub mod pallet { staking_protocol, delegator.clone(), |validators| -> DispatchResultWithPostInfo { - ensure!(validators.contains(&validator), Error::::ValidatorNotFound); + ensure!( + validators.contains(&validator), + Error::::ValidatorNotFound + ); validators.retain(|v| *v != validator); Self::deposit_event(Event::::RemoveValidator { staking_protocol, @@ -527,9 +533,16 @@ pub mod pallet { staking_protocol, delegator.clone(), |storage_ledger| -> DispatchResultWithPostInfo { - ensure!(Some(ledger.clone()).ne(storage_ledger), Error::::InvalidParameter); + ensure!( + Some(ledger.clone()).ne(storage_ledger), + Error::::InvalidParameter + ); *storage_ledger = Some(ledger.clone()); - Self::deposit_event(Event::SetLedger { staking_protocol, delegator, ledger }); + Self::deposit_event(Event::SetLedger { + staking_protocol, + delegator, + ledger, + }); Ok(().into()) }, ) @@ -613,14 +626,17 @@ pub mod pallet { let current_time_unit = T::VtokenMinting::get_ongoing_time_unit(currency_id) .ok_or(Error::::TimeUnitNotFound)?; current_time_unit.add_one() - }, + } }; T::VtokenMinting::update_ongoing_time_unit(currency_id, time_unit.clone())?; LastUpdateOngoingTimeUnitBlockNumber::::insert( staking_protocol, current_block_number, ); - Self::deposit_event(Event::::TimeUnitUpdated { staking_protocol, time_unit }); + Self::deposit_event(Event::::TimeUnitUpdated { + staking_protocol, + time_unit, + }); Ok(().into()) } @@ -700,7 +716,7 @@ pub mod pallet { Some(Ledger::AstarDappStaking(astar_dapp_staking_ledger)) => { astar_dapp_staking_ledger.add_lock_amount(amount); Ok(()) - }, + } _ => Err(Error::::LedgerNotFound), }, )?; diff --git a/pallets/slp-v2/src/mock.rs b/pallets/slp-v2/src/mock.rs index afa120a69d..7a541d9938 100644 --- a/pallets/slp-v2/src/mock.rs +++ b/pallets/slp-v2/src/mock.rs @@ -250,6 +250,7 @@ impl bifrost_vtoken_minting::Config for Test { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } parameter_types! { @@ -294,14 +295,19 @@ impl slp_v2::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::::default().build_storage().unwrap(); + let t = system::GenesisConfig::::default() + .build_storage() + .unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } pub(crate) fn last_event() -> RuntimeEvent { - system::Pallet::::events().pop().expect("Event expected").event + system::Pallet::::events() + .pop() + .expect("Event expected") + .event } pub(crate) fn expect_event>(e: E) { diff --git a/pallets/slp-v2/src/tests.rs b/pallets/slp-v2/src/tests.rs index 2140d23641..310a6c6889 100644 --- a/pallets/slp-v2/src/tests.rs +++ b/pallets/slp-v2/src/tests.rs @@ -51,7 +51,10 @@ use xcm::{ pub const STAKING_PROTOCOL: StakingProtocol = StakingProtocol::AstarDappStaking; pub const CONFIGURATION: ProtocolConfiguration = ProtocolConfiguration { - xcm_task_fee: XcmFee { weight: Weight::zero(), fee: 100 }, + xcm_task_fee: XcmFee { + weight: Weight::zero(), + fee: 100, + }, protocol_fee_rate: Permill::from_perthousand(100), unlock_period: TimeUnit::Era(9), operator: AccountId::new([0u8; 32]), @@ -110,7 +113,11 @@ fn add_delegator_should_work() { ); let delegator_index = 0; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); expect_event(SlpV2Event::AddDelegator { staking_protocol: STAKING_PROTOCOL, delegator_index, @@ -130,7 +137,10 @@ fn add_delegator_should_work() { ), Some(delegator_index) ); - assert_eq!(NextDelegatorIndexByStakingProtocol::::get(STAKING_PROTOCOL), 1); + assert_eq!( + NextDelegatorIndexByStakingProtocol::::get(STAKING_PROTOCOL), + 1 + ); assert_eq!( LedgerByStakingProtocolAndDelegator::::get(STAKING_PROTOCOL, delegator), Some(Ledger::AstarDappStaking(AstarDappStakingLedger { @@ -155,7 +165,11 @@ fn repeat_add_delegator_should_work() { ); let delegator_index = 1; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); expect_event(SlpV2Event::AddDelegator { staking_protocol: STAKING_PROTOCOL, delegator_index, @@ -175,7 +189,10 @@ fn repeat_add_delegator_should_work() { ), Some(delegator_index) ); - assert_eq!(NextDelegatorIndexByStakingProtocol::::get(STAKING_PROTOCOL), 2); + assert_eq!( + NextDelegatorIndexByStakingProtocol::::get(STAKING_PROTOCOL), + 2 + ); assert_eq!( LedgerByStakingProtocolAndDelegator::::get(STAKING_PROTOCOL, delegator), Some(Ledger::AstarDappStaking(AstarDappStakingLedger { @@ -242,7 +259,11 @@ fn remove_delegator_should_work() { AccountId::from_ss58check("YLF9AnL6V1vQRfuiB832NXNGZYCPAWkKLLkh7cf3KwXhB9o").unwrap(), ); let delegator_index = 0; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::remove_delegator( RuntimeOrigin::root(), STAKING_PROTOCOL, @@ -267,7 +288,10 @@ fn remove_delegator_should_work() { ), None ); - assert_eq!(NextDelegatorIndexByStakingProtocol::::get(STAKING_PROTOCOL), 1); + assert_eq!( + NextDelegatorIndexByStakingProtocol::::get(STAKING_PROTOCOL), + 1 + ); assert_eq!( ValidatorsByStakingProtocolAndDelegator::::get(STAKING_PROTOCOL, delegator) .to_vec(), @@ -297,7 +321,11 @@ fn add_validator_should_work() { ); let validator = Validator::AstarDappStaking(AstarValidator::Evm(H160::default())); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::add_validator( RuntimeOrigin::root(), @@ -329,7 +357,11 @@ fn repeat_add_validator_should_work() { AccountId::from_ss58check("YeKP2BdVpFrXbbqkoVhDFZP9u3nUuop7fpMppQczQXBLhD1").unwrap(), )); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::add_validator( RuntimeOrigin::root(), @@ -368,7 +400,11 @@ fn remove_validator_should_work() { ); let validator = Validator::AstarDappStaking(AstarValidator::Evm(H160::default())); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::add_validator( RuntimeOrigin::root(), @@ -412,7 +448,11 @@ fn astar_dapp_staking_lock() { let dest_location = STAKING_PROTOCOL.info().remote_dest_location; set_protocol_configuration(); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::astar_dapp_staking( RuntimeOrigin::root(), @@ -461,9 +501,17 @@ fn repeat_astar_dapp_staking_lock() { let dest_location = STAKING_PROTOCOL.info().remote_dest_location; set_protocol_configuration(); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); - assert_ok!(SlpV2::astar_dapp_staking(RuntimeOrigin::root(), delegator.clone(), task1)); + assert_ok!(SlpV2::astar_dapp_staking( + RuntimeOrigin::root(), + delegator.clone(), + task1 + )); assert_ok!(SlpV2::notify_astar_dapp_staking( XcmOrigin::Response(Parent.into()).into(), query_id_0, @@ -508,10 +556,18 @@ fn astar_dapp_staking_unlock() { ); let task = DappStaking::Lock(100); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); set_protocol_configuration(); - assert_ok!(SlpV2::astar_dapp_staking(RuntimeOrigin::root(), delegator.clone(), task)); + assert_ok!(SlpV2::astar_dapp_staking( + RuntimeOrigin::root(), + delegator.clone(), + task + )); assert_ok!(SlpV2::notify_astar_dapp_staking( XcmOrigin::Response(Parent.into()).into(), 0, @@ -525,7 +581,11 @@ fn astar_dapp_staking_unlock() { STAKING_PROTOCOL, Some(TimeUnit::Era(1)) )); - assert_ok!(SlpV2::astar_dapp_staking(RuntimeOrigin::root(), delegator.clone(), task)); + assert_ok!(SlpV2::astar_dapp_staking( + RuntimeOrigin::root(), + delegator.clone(), + task + )); assert_ok!(SlpV2::notify_astar_dapp_staking( XcmOrigin::Response(Parent.into()).into(), 1, @@ -560,7 +620,11 @@ fn astar_dapp_staking_stake() { let pending_status = None; let dest_location = STAKING_PROTOCOL.info().remote_dest_location; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::add_validator( RuntimeOrigin::root(), STAKING_PROTOCOL, @@ -596,7 +660,11 @@ fn astar_dapp_staking_unstake() { let pending_status = None; let dest_location = STAKING_PROTOCOL.info().remote_dest_location; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); assert_ok!(SlpV2::add_validator( RuntimeOrigin::root(), STAKING_PROTOCOL, @@ -631,7 +699,13 @@ fn staking_protocol_get_dest_beneficiary_location() { staking_protocol.get_dest_beneficiary_location::(delegator), Some(Location::new( 1, - [Parachain(2006), AccountId32 { network: None, id: account_id.into() }] + [ + Parachain(2006), + AccountId32 { + network: None, + id: account_id.into() + } + ] )) ); }) @@ -671,7 +745,11 @@ fn set_ledger_should_work() { locked: 100, unlocking: Default::default(), }); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), staking_protocol, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + staking_protocol, + None + )); assert_ok!(SlpV2::set_ledger( RuntimeOrigin::root(), staking_protocol, @@ -712,7 +790,11 @@ fn set_ledger_error() { SlpV2Error::::DelegatorIndexNotFound ); - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), staking_protocol, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + staking_protocol, + None + )); assert_ok!(SlpV2::set_ledger( RuntimeOrigin::root(), staking_protocol, @@ -744,16 +826,38 @@ fn update_ongoing_time_unit_should_work() { staking_protocol, Some(TimeUnit::Era(1)) )); - expect_event(SlpV2Event::TimeUnitUpdated { staking_protocol, time_unit: TimeUnit::Era(1) }); - assert_eq!(VtokenMinting::get_ongoing_time_unit(currency_id), Some(TimeUnit::Era(1))); - assert_eq!(LastUpdateOngoingTimeUnitBlockNumber::::get(staking_protocol), 100); + expect_event(SlpV2Event::TimeUnitUpdated { + staking_protocol, + time_unit: TimeUnit::Era(1), + }); + assert_eq!( + VtokenMinting::get_ongoing_time_unit(currency_id), + Some(TimeUnit::Era(1)) + ); + assert_eq!( + LastUpdateOngoingTimeUnitBlockNumber::::get(staking_protocol), + 100 + ); RelaychainDataProvider::set_block_number(200); - assert_ok!(SlpV2::update_ongoing_time_unit(RuntimeOrigin::root(), staking_protocol, None)); - expect_event(SlpV2Event::TimeUnitUpdated { staking_protocol, time_unit: TimeUnit::Era(2) }); - assert_eq!(VtokenMinting::get_ongoing_time_unit(currency_id), Some(TimeUnit::Era(2))); - assert_eq!(LastUpdateOngoingTimeUnitBlockNumber::::get(staking_protocol), 200); + assert_ok!(SlpV2::update_ongoing_time_unit( + RuntimeOrigin::root(), + staking_protocol, + None + )); + expect_event(SlpV2Event::TimeUnitUpdated { + staking_protocol, + time_unit: TimeUnit::Era(2), + }); + assert_eq!( + VtokenMinting::get_ongoing_time_unit(currency_id), + Some(TimeUnit::Era(2)) + ); + assert_eq!( + LastUpdateOngoingTimeUnitBlockNumber::::get(staking_protocol), + 200 + ); }); } @@ -798,7 +902,11 @@ fn update_ongoing_time_unit_update_interval_too_short() { RelaychainDataProvider::set_block_number(200); // current relaychain block number 200 = update_interval 100 + last update block number 100 // => Ok - assert_ok!(SlpV2::update_ongoing_time_unit(RuntimeOrigin::root(), staking_protocol, None)); + assert_ok!(SlpV2::update_ongoing_time_unit( + RuntimeOrigin::root(), + staking_protocol, + None + )); }); } @@ -814,7 +922,11 @@ fn update_token_exchange_rate_should_work() { let token_pool = 24_597_119_664_064_597_684_680_531u128; let vtoken_total_issuance = 21_728_134_208_272_171_009_169_962u128; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); Currencies::set_balance(VASTR, &AccountId::from([0u8; 32]), vtoken_total_issuance); assert_eq!(Currencies::total_issuance(VASTR), vtoken_total_issuance); assert_ok!(VtokenMinting::increase_token_pool(currency_id, token_pool)); @@ -904,7 +1016,11 @@ fn update_token_exchange_rate_limt_error() { let token_pool = 12000u128; let vtoken_total_issuance = 10000u128; - assert_ok!(SlpV2::add_delegator(RuntimeOrigin::root(), STAKING_PROTOCOL, None)); + assert_ok!(SlpV2::add_delegator( + RuntimeOrigin::root(), + STAKING_PROTOCOL, + None + )); Currencies::set_balance(VASTR, &AccountId::from([0u8; 32]), vtoken_total_issuance); assert_ok!(VtokenMinting::increase_token_pool(currency_id, token_pool)); diff --git a/pallets/slp/Cargo.toml b/pallets/slp/Cargo.toml index d07ad9dbfa..c25bf6342f 100644 --- a/pallets/slp/Cargo.toml +++ b/pallets/slp/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-slp" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/pallets/slp/src/agents/astar_agent/agent.rs b/pallets/slp/src/agents/astar_agent/agent.rs index e53639d4ec..9b2563e1e3 100644 --- a/pallets/slp/src/agents/astar_agent/agent.rs +++ b/pallets/slp/src/agents/astar_agent/agent.rs @@ -71,7 +71,10 @@ impl // Generate multi-location by id. let delegator_multilocation = T::AccountConverter::convert((new_delegator_id, currency_id)); - ensure!(delegator_multilocation != MultiLocation::default(), Error::::FailToConvert); + ensure!( + delegator_multilocation != MultiLocation::default(), + Error::::FailToConvert + ); // Add the new delegator into storage Pallet::::inner_add_delegator(new_delegator_id, &delegator_multilocation, currency_id) @@ -92,7 +95,10 @@ impl let contract_multilocation = validator.ok_or(Error::::ValidatorNotProvided)?; let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; // Check if the amount exceeds the minimum requirement. - ensure!(amount >= mins_maxs.bond_extra_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.bond_extra_minimum, + Error::::LowerThanMinimum + ); // check if the validator is in the white list. let validator_list = @@ -104,7 +110,10 @@ impl if DelegatorLedgers::::get(currency_id, who).is_none() { // Check if the amount exceeds the minimum requirement. The first bond requires 500 ASTR - ensure!(amount >= mins_maxs.delegator_bonded_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.delegator_bonded_minimum, + Error::::LowerThanMinimum + ); // Create a new delegator ledger // The real bonded amount will be updated by services once the xcm transaction succeeds. @@ -201,7 +210,10 @@ impl ) -> Result> { // Check if the unbonding amount exceeds minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.unbond_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.unbond_minimum, + Error::::LowerThanMinimum + ); // check if the delegator exists, if not, return error. let contract_multilocation = (*validator).ok_or(Error::::ValidatorNotProvided)?; @@ -440,15 +452,23 @@ impl X1(Parachain(T::ParachainId::get().into())), ))); - let beneficiary = Box::new(VersionedLocation::V3(MultiLocation::from(X1(AccountId32 { - network: None, - id: entrance_account.encode().try_into().map_err(|_| Error::::FailToConvert)?, - })))); + let beneficiary = Box::new(VersionedLocation::V3(MultiLocation::from(X1( + AccountId32 { + network: None, + id: entrance_account + .encode() + .try_into() + .map_err(|_| Error::::FailToConvert)?, + }, + )))); // Prepare parameter assets. let asset = MultiAsset { fun: Fungible(amount.unique_saturated_into()), - id: Concrete(MultiLocation { parents: 0, interior: Here }), + id: Concrete(MultiLocation { + parents: 0, + interior: Here, + }), }; let assets: Box = Box::new(VersionedAssets::V3(MultiAssets::from(asset))); @@ -499,7 +519,10 @@ impl // Make sure from account is the entrance account of vtoken-minting module. let from_account_id = Pallet::::multilocation_to_account(from)?; let (entrance_account, _) = T::VtokenMinting::get_entrance_and_exit_accounts(); - ensure!(from_account_id == entrance_account, Error::::InvalidAccount); + ensure!( + from_account_id == entrance_account, + Error::::InvalidAccount + ); // transfer supplementary fee from treasury to the "from" account. Return the added up // amount @@ -545,11 +568,15 @@ impl DelegatorLedgers::::mutate(currency_id, who, |old_ledger| -> Result<(), Error> { if let Some(Ledger::Substrate(ref mut old_sub_ledger)) = old_ledger { // Increase both the active and total amount. - old_sub_ledger.active = - old_sub_ledger.active.checked_add(&token_amount).ok_or(Error::::OverFlow)?; - - old_sub_ledger.total = - old_sub_ledger.total.checked_add(&token_amount).ok_or(Error::::OverFlow)?; + old_sub_ledger.active = old_sub_ledger + .active + .checked_add(&token_amount) + .ok_or(Error::::OverFlow)?; + + old_sub_ledger.total = old_sub_ledger + .total + .checked_add(&token_amount) + .ok_or(Error::::OverFlow)?; Ok(()) } else { Err(Error::::Unexpected)? @@ -689,7 +716,7 @@ impl AstarAgent { .total .checked_add(&amount) .ok_or(Error::::OverFlow)?; - }, + } Unlock => { old_sub_ledger.active = old_sub_ledger .active @@ -699,14 +726,16 @@ impl AstarAgent { let unlock_time_unit = unlock_time.ok_or(Error::::TimeUnitNotExist)?; - let new_unlock_record = - UnlockChunk { value: amount, unlock_time: unlock_time_unit }; + let new_unlock_record = UnlockChunk { + value: amount, + unlock_time: unlock_time_unit, + }; old_sub_ledger.unlocking.push(new_unlock_record); - }, + } Rebond => { Err(Error::::Unexpected)?; - }, + } Liquidize => { // If it is a liquidize operation. let unlock_unit = unlock_time.ok_or(Error::::InvalidTimeUnit)?; @@ -748,7 +777,7 @@ impl AstarAgent { .total .checked_sub(&accumulated) .ok_or(Error::::OverFlow)?; - }, + } } Ok(()) } else { diff --git a/pallets/slp/src/agents/common.rs b/pallets/slp/src/agents/common.rs index 021bb5b80f..0ef3e128fe 100644 --- a/pallets/slp/src/agents/common.rs +++ b/pallets/slp/src/agents/common.rs @@ -34,7 +34,10 @@ use orml_traits::{MultiCurrency, XcmTransfer}; use polkadot_parachain_primitives::primitives::Sibling; use sp_core::{Get, U256}; use sp_runtime::{ - traits::{AccountIdConversion, CheckedAdd, UniqueSaturatedFrom, UniqueSaturatedInto}, + traits::{ + AccountIdConversion, BlockNumberProvider, CheckedAdd, UniqueSaturatedFrom, + UniqueSaturatedInto, + }, DispatchResult, Saturating, }; use xcm::v3::{prelude::*, MultiLocation}; @@ -67,7 +70,10 @@ impl Pallet { // Ensure delegators count is not greater than maximum. let delegators_count = DelegatorNextIndex::::get(currency_id); let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(delegators_count < mins_maxs.delegators_maximum, Error::::GreaterThanMaximum); + ensure!( + delegators_count < mins_maxs.delegators_maximum, + Error::::GreaterThanMaximum + ); // Revise two delegator storages. DelegatorsIndex2Multilocation::::insert(currency_id, index, who); @@ -115,7 +121,10 @@ impl Pallet { Validators::::insert(currency_id, bounded_list); // Deposit event. - Self::deposit_event(Event::ValidatorsAdded { currency_id, validator_id: *who }); + Self::deposit_event(Event::ValidatorsAdded { + currency_id, + validator_id: *who, + }); Ok(()) } @@ -260,7 +269,10 @@ impl Pallet { // withdraw. If withdraw fails, issue an event and continue. if let Err(_) = T::MultiCurrency::withdraw(currency_id, &source_account, fee) { // Deposit event - Self::deposit_event(Event::BurnFeeFailed { currency_id, amount: fee }); + Self::deposit_event(Event::BurnFeeFailed { + currency_id, + amount: fee, + }); } Ok(()) @@ -281,11 +293,17 @@ impl Pallet { Ok(vec![ xcm::v4::prelude::WithdrawAsset(asset.clone().into()), - xcm::v4::prelude::BuyExecution { fees: asset, weight_limit: Unlimited }, + xcm::v4::prelude::BuyExecution { + fees: asset, + weight_limit: Unlimited, + }, xcm::v4::prelude::RefundSurplus, xcm::v4::prelude::DepositAsset { assets: xcm::v4::prelude::AllCounted(8).into(), - beneficiary: xcm::v4::prelude::Location { parents: 0, interior: refund_receiver }, + beneficiary: xcm::v4::prelude::Location { + parents: 0, + interior: refund_receiver, + }, }, ]) } @@ -348,7 +366,7 @@ impl Pallet { weight_and_fee: Option<(Weight, BalanceOf)>, ) -> Result<(QueryId, BlockNumberFor, BalanceOf, xcm::v4::Xcm<()>), Error> { // prepare the query_id for reporting back transact status - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let timeout = BlockNumberFor::::from(TIMEOUT_BLOCKS).saturating_add(now); let (query_id, notify_call_weight) = Self::get_query_id_and_notify_call_weight(currency_id, &operation)?; @@ -377,22 +395,22 @@ impl Pallet { currency_id: CurrencyId, operation: &XcmOperationType, ) -> Result<(QueryId, Weight), Error> { - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let timeout = BlockNumberFor::::from(TIMEOUT_BLOCKS).saturating_add(now); let responder = Self::convert_currency_to_dest_location(currency_id)?; let (notify_call_weight, callback_option) = match (currency_id, operation) { - (DOT, &XcmOperationType::Delegate) | - (DOT, &XcmOperationType::Undelegate) | - (KSM, &XcmOperationType::Delegate) | - (KSM, &XcmOperationType::Undelegate) => { + (DOT, &XcmOperationType::Delegate) + | (DOT, &XcmOperationType::Undelegate) + | (KSM, &XcmOperationType::Delegate) + | (KSM, &XcmOperationType::Undelegate) => { let notify_call = Self::confirm_validators_by_delegator_call(); (notify_call.get_dispatch_info().weight, Some(notify_call)) - }, + } _ => { let notify_call = Self::confirm_delegator_ledger_call(); (notify_call.get_dispatch_info().weight, Some(notify_call)) - }, + } }; let query_id = @@ -440,11 +458,15 @@ impl Pallet { let dest_location = match currency_id { DOT | KSM => xcm::v4::Location::new( 0, - [xcm::v4::prelude::Parachain(u32::from(T::ParachainId::get()))], + [xcm::v4::prelude::Parachain( + u32::from(T::ParachainId::get()), + )], ), _ => xcm::v4::Location::new( 1, - [xcm::v4::prelude::Parachain(u32::from(T::ParachainId::get()))], + [xcm::v4::prelude::Parachain( + u32::from(T::ParachainId::get()), + )], ), }; @@ -560,8 +582,8 @@ impl Pallet { currency_id, ); xcm_message.insert(3, report_transact_status_instruct); - }, - _ => {}, + } + _ => {} }; Ok(xcm::v4::Xcm(xcm_message)) } @@ -575,41 +597,45 @@ impl Pallet { let delays = CurrencyDelays::::get(currency_id).ok_or(Error::::DelaysNotExist)?; let unlock_time_unit = match (currency_id, current_time_unit) { - (ASTR, TimeUnit::Era(current_era)) | - (KSM, TimeUnit::Era(current_era)) | - (DOT, TimeUnit::Era(current_era)) => + (ASTR, TimeUnit::Era(current_era)) + | (KSM, TimeUnit::Era(current_era)) + | (DOT, TimeUnit::Era(current_era)) => { if let TimeUnit::Era(delay_era) = delays.unlock_delay { - let unlock_era = - current_era.checked_add(delay_era).ok_or(Error::::OverFlow)?; + let unlock_era = current_era + .checked_add(delay_era) + .ok_or(Error::::OverFlow)?; TimeUnit::Era(unlock_era) } else { Err(Error::::InvalidTimeUnit)? - }, + } + } (PHA, TimeUnit::Hour(current_hour)) => { if let TimeUnit::Hour(delay_hour) = delays.unlock_delay { - let unlock_hour = - current_hour.checked_add(delay_hour).ok_or(Error::::OverFlow)?; + let unlock_hour = current_hour + .checked_add(delay_hour) + .ok_or(Error::::OverFlow)?; TimeUnit::Hour(unlock_hour) } else { Err(Error::::InvalidTimeUnit)? } - }, - (BNC, TimeUnit::Round(current_round)) | - (MOVR, TimeUnit::Round(current_round)) | - (GLMR, TimeUnit::Round(current_round)) | - (MANTA, TimeUnit::Round(current_round)) => { + } + (BNC, TimeUnit::Round(current_round)) + | (MOVR, TimeUnit::Round(current_round)) + | (GLMR, TimeUnit::Round(current_round)) + | (MANTA, TimeUnit::Round(current_round)) => { let mut delay = delays.unlock_delay; if if_leave { delay = delays.leave_delegators_delay; } if let TimeUnit::Round(delay_round) = delay { - let unlock_round = - current_round.checked_add(delay_round).ok_or(Error::::OverFlow)?; + let unlock_round = current_round + .checked_add(delay_round) + .ok_or(Error::::OverFlow)?; TimeUnit::Round(unlock_round) } else { Err(Error::::InvalidTimeUnit)? } - }, + } _ => Err(Error::::InvalidTimeUnit)?, }; @@ -637,7 +663,9 @@ impl Pallet { // transfer supplementary_fee from treasury to "from" account T::MultiCurrency::transfer(currency_id, &source_account, &from, supplementary_fee) .map_err(|_| Error::::Unexpected)?; - let added_amount = amount.checked_add(&supplementary_fee).ok_or(Error::::OverFlow)?; + let added_amount = amount + .checked_add(&supplementary_fee) + .ok_or(Error::::OverFlow)?; Ok(added_amount) } diff --git a/pallets/slp/src/agents/filecoin_agent/agent.rs b/pallets/slp/src/agents/filecoin_agent/agent.rs index 22c90e1e62..c5e7a7996b 100644 --- a/pallets/slp/src/agents/filecoin_agent/agent.rs +++ b/pallets/slp/src/agents/filecoin_agent/agent.rs @@ -81,11 +81,17 @@ impl _weight_and_fee: Option<(Weight, BalanceOf)>, ) -> Result> { // Check if it is bonded already. - ensure!(!DelegatorLedgers::::contains_key(currency_id, who), Error::::AlreadyBonded); + ensure!( + !DelegatorLedgers::::contains_key(currency_id, who), + Error::::AlreadyBonded + ); // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.delegator_bonded_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.delegator_bonded_minimum, + Error::::LowerThanMinimum + ); // Ensure the bond doesn't exceeds delegator_active_staking_maximum ensure!( @@ -99,7 +105,10 @@ impl ensure!(miners.len() == 1, Error::::VectorTooLong); // Create a new delegator ledger - let ledger = FilecoinLedger::> { account: *who, initial_pledge: amount }; + let ledger = FilecoinLedger::> { + account: *who, + initial_pledge: amount, + }; let filecoin_ledger = Ledger::>::Filecoin(ledger); DelegatorLedgers::::insert(currency_id, who, filecoin_ledger); @@ -124,12 +133,17 @@ impl // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.bond_extra_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.bond_extra_minimum, + Error::::LowerThanMinimum + ); if let Ledger::Filecoin(filecoin_ledger) = ledger { let initial_pledge = filecoin_ledger.initial_pledge; - let total = amount.checked_add(&initial_pledge).ok_or(Error::::OverFlow)?; + let total = amount + .checked_add(&initial_pledge) + .ok_or(Error::::OverFlow)?; ensure!( total <= mins_maxs.delegator_active_staking_maximum, Error::::ExceedActiveMaximum @@ -178,11 +192,18 @@ impl // Check if the unbonding amount exceeds minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.unbond_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.unbond_minimum, + Error::::LowerThanMinimum + ); - let remaining = - initial_pledge.checked_sub(&amount).ok_or(Error::::NotEnoughToUnbond)?; - ensure!(remaining >= mins_maxs.delegator_bonded_minimum, Error::::NotEnoughToUnbond); + let remaining = initial_pledge + .checked_sub(&amount) + .ok_or(Error::::NotEnoughToUnbond)?; + ensure!( + remaining >= mins_maxs.delegator_bonded_minimum, + Error::::NotEnoughToUnbond + ); // update delegator ledger DelegatorLedgers::::mutate( @@ -245,7 +266,10 @@ impl // Need to check whether this validator is in the whitelist. let validators_vec = Validators::::get(currency_id).ok_or(Error::::ValidatorSetNotExist)?; - ensure!(validators_vec.contains(worker), Error::::ValidatorNotExist); + ensure!( + validators_vec.contains(worker), + Error::::ValidatorNotExist + ); // ensure the length of validators_vec does not exceed the MaxLengthLimit. ensure!( @@ -297,7 +321,10 @@ impl let validators_by_delegator_vec = ValidatorsByDelegator::::get(currency_id, who) .ok_or(Error::::ValidatorNotBonded)?; - ensure!(targets[0] == validators_by_delegator_vec[0], Error::::ValidatorError); + ensure!( + targets[0] == validators_by_delegator_vec[0], + Error::::ValidatorError + ); // remove entry. ValidatorsByDelegator::::remove(currency_id, who); @@ -449,8 +476,9 @@ impl let (fee_permill, _beneficiary) = HostingFees::::get(currency_id).ok_or(Error::::InvalidHostingFee)?; let fee_to_charge = fee_permill.mul_floor(token_amount); - let amount_to_increase = - token_amount.checked_sub(&fee_to_charge).ok_or(Error::::UnderFlow)?; + let amount_to_increase = token_amount + .checked_sub(&fee_to_charge) + .ok_or(Error::::UnderFlow)?; if amount_to_increase > Zero::zero() { // Tune the vtoken exchange rate. diff --git a/pallets/slp/src/agents/parachain_staking_agent/agent.rs b/pallets/slp/src/agents/parachain_staking_agent/agent.rs index b27f51ccfe..5bf2b8c67e 100644 --- a/pallets/slp/src/agents/parachain_staking_agent/agent.rs +++ b/pallets/slp/src/agents/parachain_staking_agent/agent.rs @@ -83,7 +83,10 @@ impl // Generate multi-location by id. let delegator_multilocation = T::AccountConverter::convert((new_delegator_id, currency_id)); - ensure!(delegator_multilocation != MultiLocation::default(), Error::::FailToConvert); + ensure!( + delegator_multilocation != MultiLocation::default(), + Error::::FailToConvert + ); // Add the new delegator into storage Pallet::::inner_add_delegator(new_delegator_id, &delegator_multilocation, currency_id) @@ -109,7 +112,10 @@ impl let collator = validator.ok_or(Error::::ValidatorNotProvided)?; let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; // Ensure amount is no less than delegation_amount_minimum. - ensure!(amount >= mins_maxs.delegation_amount_minimum.into(), Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.delegation_amount_minimum.into(), + Error::::LowerThanMinimum + ); // check if the validator is in the white list. let validator_list = @@ -127,20 +133,30 @@ impl ); // Ensure the bond after wont exceed delegator_active_staking_maximum - let active_amount = - ledger.total.checked_sub(&ledger.less_total).ok_or(Error::::UnderFlow)?; - let add_total = active_amount.checked_add(&amount).ok_or(Error::::OverFlow)?; + let active_amount = ledger + .total + .checked_sub(&ledger.less_total) + .ok_or(Error::::UnderFlow)?; + let add_total = active_amount + .checked_add(&amount) + .ok_or(Error::::OverFlow)?; ensure!( add_total <= mins_maxs.delegator_active_staking_maximum, Error::::ExceedActiveMaximum ); // check if the delegator-validator delegation exists. - ensure!(!ledger.delegations.contains_key(&collator), Error::::AlreadyBonded); + ensure!( + !ledger.delegations.contains_key(&collator), + Error::::AlreadyBonded + ); // check if it will exceeds the delegation limit of the delegator. - let new_deleagtions_count = - ledger.delegations.len().checked_add(1).ok_or(Error::::OverFlow)?; + let new_deleagtions_count = ledger + .delegations + .len() + .checked_add(1) + .ok_or(Error::::OverFlow)?; ensure!( (new_deleagtions_count as u32) <= mins_maxs.validators_back_maximum, Error::::GreaterThanMaximum @@ -148,7 +164,10 @@ impl // check if it will exceeds the delegation limit of the validator. } else { - ensure!(amount >= mins_maxs.delegator_bonded_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.delegator_bonded_minimum, + Error::::LowerThanMinimum + ); // Ensure the bond doesn't exceeds delegator_active_staking_maximum ensure!( @@ -214,16 +233,24 @@ impl old_ledger.status == OneToManyDelegatorStatus::Active, Error::::DelegatorLeaving ); - old_ledger.total = - old_ledger.total.checked_add(&amount).ok_or(Error::::OverFlow)?; + old_ledger.total = old_ledger + .total + .checked_add(&amount) + .ok_or(Error::::OverFlow)?; let amount_rs = old_ledger.delegations.get(validator_multilocation); - let original_amount = - if let Some(amt) = amount_rs { *amt } else { Zero::zero() }; + let original_amount = if let Some(amt) = amount_rs { + *amt + } else { + Zero::zero() + }; - let new_amount = - original_amount.checked_add(&amount).ok_or(Error::::OverFlow)?; - old_ledger.delegations.insert(*validator_multilocation, new_amount); + let new_amount = original_amount + .checked_add(&amount) + .ok_or(Error::::OverFlow)?; + old_ledger + .delegations + .insert(*validator_multilocation, new_amount); Ok(()) } else { Err(Error::::Unexpected) @@ -262,7 +289,7 @@ impl ) .encode() .into() - }, + } MANTA => { let validator_multilocation = validator.as_ref().ok_or(Error::::Unexpected)?; @@ -276,7 +303,7 @@ impl )) .encode() .into() - }, + } _ => Err(Error::::Unsupported)?, }; @@ -328,7 +355,10 @@ impl ) -> Result> { // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.bond_extra_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.bond_extra_minimum, + Error::::LowerThanMinimum + ); // check if the delegator exists, if not, return error. let collator = (*validator).ok_or(Error::::ValidatorNotProvided)?; @@ -345,11 +375,18 @@ impl Error::::DelegatorLeaving ); // check if the delegation exists, if not, return error. - ensure!(ledger.delegations.contains_key(&collator), Error::::ValidatorNotBonded); + ensure!( + ledger.delegations.contains_key(&collator), + Error::::ValidatorNotBonded + ); // Ensure the bond after wont exceed delegator_active_staking_maximum - let active_amount = - ledger.total.checked_sub(&ledger.less_total).ok_or(Error::::UnderFlow)?; - let add_total = active_amount.checked_add(&amount).ok_or(Error::::OverFlow)?; + let active_amount = ledger + .total + .checked_sub(&ledger.less_total) + .ok_or(Error::::UnderFlow)?; + let add_total = active_amount + .checked_add(&amount) + .ok_or(Error::::OverFlow)?; ensure!( add_total <= mins_maxs.delegator_active_staking_maximum, Error::::ExceedActiveMaximum @@ -385,16 +422,24 @@ impl old_ledger.status == OneToManyDelegatorStatus::Active, Error::::DelegatorLeaving ); - old_ledger.total = - old_ledger.total.checked_add(&amount).ok_or(Error::::OverFlow)?; + old_ledger.total = old_ledger + .total + .checked_add(&amount) + .ok_or(Error::::OverFlow)?; let amount_rs = old_ledger.delegations.get(validator_multilocation); - let original_amount = - if let Some(amt) = amount_rs { *amt } else { Zero::zero() }; + let original_amount = if let Some(amt) = amount_rs { + *amt + } else { + Zero::zero() + }; - let new_amount = - original_amount.checked_add(&amount).ok_or(Error::::OverFlow)?; - old_ledger.delegations.insert(*validator_multilocation, new_amount); + let new_amount = original_amount + .checked_add(&amount) + .ok_or(Error::::OverFlow)?; + old_ledger + .delegations + .insert(*validator_multilocation, new_amount); Ok(()) } else { Err(Error::::Unexpected) @@ -416,7 +461,7 @@ impl )) .encode() .into() - }, + } MANTA => { let validator_account = Pallet::::multilocation_to_account(&collator)?; MantaCall::ParachainStaking(MantaParachainStakingCall::::DelegatorBondMore( @@ -425,7 +470,7 @@ impl )) .encode() .into() - }, + } _ => Err(Error::::Unsupported)?, }; @@ -476,7 +521,10 @@ impl ) -> Result> { // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.unbond_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.unbond_minimum, + Error::::LowerThanMinimum + ); // check if the delegator exists, if not, return error. let collator = (*validator).ok_or(Error::::ValidatorNotProvided)?; @@ -488,24 +536,33 @@ impl Error::::DelegatorLeaving ); // check if the delegation exists, if not, return error. - let old_delegate_amount = - ledger.delegations.get(&collator).ok_or(Error::::ValidatorNotBonded)?; + let old_delegate_amount = ledger + .delegations + .get(&collator) + .ok_or(Error::::ValidatorNotBonded)?; // check if there is pending request - ensure!(!ledger.request_briefs.contains_key(&collator), Error::::AlreadyRequested); + ensure!( + !ledger.request_briefs.contains_key(&collator), + Error::::AlreadyRequested + ); - let delegated_amount_after = - old_delegate_amount.checked_sub(&amount).ok_or(Error::::UnderFlow)?; + let delegated_amount_after = old_delegate_amount + .checked_sub(&amount) + .ok_or(Error::::UnderFlow)?; ensure!( delegated_amount_after >= mins_maxs.delegation_amount_minimum.into(), Error::::LowerThanMinimum ); // Ensure the unbond after wont below delegator_bonded_minimum - let active_amount = - ledger.total.checked_sub(&ledger.less_total).ok_or(Error::::UnderFlow)?; - let subtracted_total = - active_amount.checked_sub(&amount).ok_or(Error::::UnderFlow)?; + let active_amount = ledger + .total + .checked_sub(&ledger.less_total) + .ok_or(Error::::UnderFlow)?; + let subtracted_total = active_amount + .checked_sub(&amount) + .ok_or(Error::::UnderFlow)?; ensure!( subtracted_total >= mins_maxs.delegator_bonded_minimum, Error::::LowerThanMinimum @@ -579,7 +636,7 @@ impl ) .encode() .into() - }, + } MANTA => { let validator_account = Pallet::::multilocation_to_account(&collator)?; MantaCall::ParachainStaking( @@ -590,7 +647,7 @@ impl ) .encode() .into() - }, + } _ => Err(Error::::Unsupported)?, }; @@ -645,7 +702,10 @@ impl if let Some(Ledger::ParachainStaking(ledger)) = ledger_option { // check if the delegator is in the state of leaving. - ensure!(ledger.status == OneToManyDelegatorStatus::Active, Error::::AlreadyLeaving); + ensure!( + ledger.status == OneToManyDelegatorStatus::Active, + Error::::AlreadyLeaving + ); } else { Err(Error::::DelegatorNotExist)?; } @@ -682,7 +742,9 @@ impl }; new_requests.push(request_entry); - old_ledger.request_briefs.insert(*vali, (unlock_time.clone(), *amt)); + old_ledger + .request_briefs + .insert(*vali, (unlock_time.clone(), *amt)); } old_ledger.requests = new_requests; @@ -718,15 +780,20 @@ impl Error::::DelegatorLeaving ); - let (_, rebond_amount) = - ledger.request_briefs.get(&collator).ok_or(Error::::RequestNotExist)?; + let (_, rebond_amount) = ledger + .request_briefs + .get(&collator) + .ok_or(Error::::RequestNotExist)?; // check if the pending request amount plus active amount greater than delegator minimum // request. - let active = - ledger.total.checked_sub(&ledger.less_total).ok_or(Error::::UnderFlow)?; - let rebond_after_amount = - active.checked_add(&rebond_amount).ok_or(Error::::OverFlow)?; + let active = ledger + .total + .checked_sub(&ledger.less_total) + .ok_or(Error::::UnderFlow)?; + let rebond_after_amount = active + .checked_add(&rebond_amount) + .ok_or(Error::::OverFlow)?; // ensure the rebond after amount meet the delegator bond requirement. ensure!( @@ -799,7 +866,7 @@ impl ) .encode() .into() - }, + } MANTA => { let validator_account = Pallet::::multilocation_to_account(&collator)?; MantaCall::ParachainStaking( @@ -807,7 +874,7 @@ impl ) .encode() .into() - }, + } _ => Err(Error::::Unsupported)?, }; @@ -876,8 +943,14 @@ impl Error::::DelegatorLeaving ); // Second, check the validators one by one to see if all exist. - ensure!(ledger.delegations.contains_key(validator), Error::::ValidatorNotBonded); - ensure!(!ledger.request_briefs.contains_key(validator), Error::::AlreadyRequested); + ensure!( + ledger.delegations.contains_key(validator), + Error::::ValidatorNotBonded + ); + ensure!( + !ledger.request_briefs.contains_key(validator), + Error::::AlreadyRequested + ); } else { Err(Error::::DelegatorNotExist)?; } @@ -903,8 +976,10 @@ impl Error::::DelegatorLeaving ); - let revoke_amount = - old_ledger.delegations.get(validator).ok_or(Error::::Unexpected)?; + let revoke_amount = old_ledger + .delegations + .get(validator) + .ok_or(Error::::Unexpected)?; old_ledger.less_total = old_ledger .less_total @@ -948,7 +1023,7 @@ impl ) .encode() .into() - }, + } MANTA => { let validator_account = Pallet::::multilocation_to_account(&validator)?; MantaCall::ParachainStaking( @@ -956,7 +1031,7 @@ impl ) .encode() .into() - }, + } _ => Err(Error::::Unsupported)?, }; @@ -1085,10 +1160,15 @@ impl leaving = true; } else { // check if the validator has a delegation request. - ensure!(ledger.delegations.contains_key(&collator), Error::::ValidatorNotBonded); + ensure!( + ledger.delegations.contains_key(&collator), + Error::::ValidatorNotBonded + ); // check whether the request is already due. - let request_info = - ledger.request_briefs.get(&collator).ok_or(Error::::RequestNotExist)?; + let request_info = ledger + .request_briefs + .get(&collator) + .ok_or(Error::::RequestNotExist)?; let due_time = &request_info.0; due_amount = request_info.1; ensure!(now >= due_time.clone(), Error::::RequestNotDue); @@ -1280,7 +1360,7 @@ impl ) .encode() .into() - }, + } MANTA => { let delegator_account = Pallet::::multilocation_to_account(who)?; let validator_account = Pallet::::multilocation_to_account(&collator)?; @@ -1292,7 +1372,7 @@ impl ) .encode() .into() - }, + } _ => Err(Error::::Unsupported)?, }; @@ -1370,8 +1450,10 @@ impl // Make sure the receiving account is the Exit_account from vtoken-minting module. let (entrance_account, _) = T::VtokenMinting::get_entrance_and_exit_accounts(); - let entrance_account_id = - entrance_account.encode().try_into().map_err(|_| Error::::FailToConvert)?; + let entrance_account_id = entrance_account + .encode() + .try_into() + .map_err(|_| Error::::FailToConvert)?; if currency_id == BNC { let from_account = Pallet::::multilocation_to_account(from)?; @@ -1383,7 +1465,10 @@ impl parents: 1, interior: X2( Parachain(T::ParachainId::get().into()), - AccountId32 { network: None, id: entrance_account_id }, + AccountId32 { + network: None, + id: entrance_account_id, + }, ), })); @@ -1397,7 +1482,10 @@ impl Box::new( Location::new( 0, - X1(AccountId32 { network: None, id: entrance_account_id }), + X1(AccountId32 { + network: None, + id: entrance_account_id, + }), ) .into_versioned(), ), @@ -1463,7 +1551,10 @@ impl // Make sure from account is the entrance account of vtoken-minting module. let from_account_id = Pallet::::multilocation_to_account(&from)?; let (entrance_account, _) = T::VtokenMinting::get_entrance_and_exit_accounts(); - ensure!(from_account_id == entrance_account, Error::::InvalidAccount); + ensure!( + from_account_id == entrance_account, + Error::::InvalidAccount + ); if currency_id == BNC { let to_account = Pallet::::multilocation_to_account(to)?; @@ -1539,7 +1630,9 @@ impl currency_id: CurrencyId, ) -> DispatchResult { // Get current VMOVR/MOVR、VGLMR/GLMR exchange rate. - let vtoken = currency_id.to_vtoken().map_err(|_| Error::::NotSupportedCurrencyId)?; + let vtoken = currency_id + .to_vtoken() + .map_err(|_| Error::::NotSupportedCurrencyId)?; let charge_amount = Pallet::::inner_calculate_vtoken_hosting_fee(amount, vtoken, currency_id)?; @@ -1651,14 +1744,17 @@ impl ParachainStakingAgent { .ok_or(Error::::OverFlow)?; let amount_rs = old_ledger.delegations.get(&validator_id); - let original_amount = - if let Some(amt) = amount_rs { *amt } else { Zero::zero() }; + let original_amount = if let Some(amt) = amount_rs { + *amt + } else { + Zero::zero() + }; let new_amount = original_amount .checked_add(&amount) .ok_or(Error::::OverFlow)?; old_ledger.delegations.insert(validator_id, new_amount); - }, + } // schedule bond less request BondLess => { let validator_id = @@ -1689,7 +1785,7 @@ impl ParachainStakingAgent { old_ledger .request_briefs .insert(validator_id, (unlock_time_unit, amount)); - }, + } // schedule revoke request Revoke => { let validator_id = @@ -1725,7 +1821,7 @@ impl ParachainStakingAgent { old_ledger .request_briefs .insert(validator_id, (unlock_time_unit, *revoke_amount)); - }, + } // cancel bond less or revoke request CancelRequest => { let validator_id = @@ -1754,7 +1850,7 @@ impl ParachainStakingAgent { old_ledger.requests.remove(request_index); old_ledger.request_briefs.remove(&validator_id); - }, + } // schedule leave LeaveDelegator => { ensure!( @@ -1790,7 +1886,7 @@ impl ParachainStakingAgent { old_ledger.requests = new_requests; old_ledger.request_briefs = new_request_briefs; - }, + } // cancel leave CancelLeave => { let leaving = matches!( @@ -1804,7 +1900,7 @@ impl ParachainStakingAgent { old_ledger.requests = vec![]; old_ledger.request_briefs = BTreeMap::new(); - }, + } // execute leaving ExecuteLeave => { // make sure leaving time is less than or equal to current time. @@ -1853,7 +1949,7 @@ impl ParachainStakingAgent { *old_ledger_opt = Some(moonbeam_ledger); // execute request - }, + } ExecuteRequest => { let validator_id = validator_id_op.ok_or(Error::::ValidatorError)?; @@ -1927,7 +2023,7 @@ impl ParachainStakingAgent { .delegations .insert(validator_id, new_delegate_amount); } - }, + } } Ok(()) } else { diff --git a/pallets/slp/src/agents/parachain_staking_agent/types/manta_types.rs b/pallets/slp/src/agents/parachain_staking_agent/types/manta_types.rs index 0ee7e0504f..a6ee6aa5d0 100644 --- a/pallets/slp/src/agents/parachain_staking_agent/types/manta_types.rs +++ b/pallets/slp/src/agents/parachain_staking_agent/types/manta_types.rs @@ -42,7 +42,10 @@ impl MantaCall { #[derive(Encode, Decode, RuntimeDebug)] pub enum MantaBalancesCall { #[codec(index = 3)] - TransferKeepAlive(::Source, #[codec(compact)] BalanceOf), + TransferKeepAlive( + ::Source, + #[codec(compact)] BalanceOf, + ), } #[derive(Encode, Decode, RuntimeDebug, Clone)] @@ -86,7 +89,12 @@ pub enum MantaParachainStakingCall { #[derive(Encode, Decode, RuntimeDebug, Clone)] pub enum MantaXtokensCall { #[codec(index = 0)] - Transfer(MantaCurrencyId, BalanceOf, Box, WeightLimit), + Transfer( + MantaCurrencyId, + BalanceOf, + Box, + WeightLimit, + ), } #[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] diff --git a/pallets/slp/src/agents/phala_agent/agent.rs b/pallets/slp/src/agents/phala_agent/agent.rs index bc633fa7e9..1e768b5566 100644 --- a/pallets/slp/src/agents/phala_agent/agent.rs +++ b/pallets/slp/src/agents/phala_agent/agent.rs @@ -71,7 +71,10 @@ impl // Generate multi-location by id. let delegator_multilocation = T::AccountConverter::convert((new_delegator_id, currency_id)); - ensure!(delegator_multilocation != MultiLocation::default(), Error::::FailToConvert); + ensure!( + delegator_multilocation != MultiLocation::default(), + Error::::FailToConvert + ); // Add the new delegator into storage Pallet::::inner_add_delegator(new_delegator_id, &delegator_multilocation, currency_id) @@ -92,8 +95,12 @@ impl // Check if it has already delegated a validator. let (pool_id, is_vault) = if let Some(Ledger::Phala(ledger)) = DelegatorLedgers::::get(currency_id, *who) { - let pool_id = ledger.bonded_pool_id.ok_or(Error::::NotDelegateValidator)?; - let is_vault = ledger.bonded_is_vault.ok_or(Error::::NotDelegateValidator)?; + let pool_id = ledger + .bonded_pool_id + .ok_or(Error::::NotDelegateValidator)?; + let is_vault = ledger + .bonded_is_vault + .ok_or(Error::::NotDelegateValidator)?; (pool_id, is_vault) } else { Err(Error::::DelegatorNotExist)? @@ -101,7 +108,10 @@ impl // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.delegator_bonded_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.delegator_bonded_minimum, + Error::::LowerThanMinimum + ); // Ensure the bond doesn't exceeds delegator_active_staking_maximum ensure!( @@ -203,10 +213,14 @@ impl // Check if it has already delegated a validator. let (pool_id, active_shares, unlocking_shares, is_vault) = if let Some(Ledger::Phala(ledger)) = DelegatorLedgers::::get(currency_id, *who) { - let pool_id = ledger.bonded_pool_id.ok_or(Error::::NotDelegateValidator)?; + let pool_id = ledger + .bonded_pool_id + .ok_or(Error::::NotDelegateValidator)?; let active_shares = ledger.active_shares; let unlocking_shares = ledger.unlocking_shares; - let is_vault = ledger.bonded_is_vault.ok_or(Error::::NotDelegateValidator)?; + let is_vault = ledger + .bonded_is_vault + .ok_or(Error::::NotDelegateValidator)?; Ok((pool_id, active_shares, unlocking_shares, is_vault)) } else { Err(Error::::DelegatorNotExist) @@ -236,10 +250,15 @@ impl ); let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.unbond_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.unbond_minimum, + Error::::LowerThanMinimum + ); // Check if the remaining active shares is enough for withdrawing. - active_shares.checked_sub(&shares).ok_or(Error::::NotEnoughToUnbond)?; + active_shares + .checked_sub(&shares) + .ok_or(Error::::NotEnoughToUnbond)?; let call = { if is_vault { @@ -346,7 +365,10 @@ impl let validators_set = Validators::::get(currency_id).ok_or(Error::::ValidatorSetNotExist)?; - ensure!(validators_set.contains(candidate), Error::::ValidatorNotExist); + ensure!( + validators_set.contains(candidate), + Error::::ValidatorNotExist + ); // if the delegator is new, create a ledger for it if !DelegatorLedgers::::contains_key(currency_id, &who.clone()) { @@ -370,8 +392,14 @@ impl *who, |old_ledger_opt| -> Result<(), Error> { if let Some(Ledger::Phala(ref mut ledger)) = old_ledger_opt { - ensure!(ledger.active_shares == Zero::zero(), Error::::AlreadyBonded); - ensure!(ledger.unlocking_shares == Zero::zero(), Error::::AlreadyBonded); + ensure!( + ledger.active_shares == Zero::zero(), + Error::::AlreadyBonded + ); + ensure!( + ledger.unlocking_shares == Zero::zero(), + Error::::AlreadyBonded + ); // delegate the validator ledger.bonded_pool_id = Some(u64::unique_saturated_from(pool_id)); @@ -418,7 +446,10 @@ impl |old_ledger_opt| -> Result<(), Error> { if let Some(Ledger::Phala(ref mut ledger)) = old_ledger_opt { // Ensure both active_shares and unlocking_shares are zero. - ensure!(ledger.active_shares == Zero::zero(), Error::::ValidatorStillInUse); + ensure!( + ledger.active_shares == Zero::zero(), + Error::::ValidatorStillInUse + ); ensure!( ledger.unlocking_shares == Zero::zero(), Error::::ValidatorStillInUse @@ -475,8 +506,12 @@ impl // Check if it has already delegated a validator. let (pool_id, is_vault) = if let Some(Ledger::Phala(ledger)) = DelegatorLedgers::::get(currency_id, *who) { - let pool_id = ledger.bonded_pool_id.ok_or(Error::::NotDelegateValidator)?; - let is_vault = ledger.bonded_is_vault.ok_or(Error::::NotDelegateValidator)?; + let pool_id = ledger + .bonded_pool_id + .ok_or(Error::::NotDelegateValidator)?; + let is_vault = ledger + .bonded_is_vault + .ok_or(Error::::NotDelegateValidator)?; (pool_id, is_vault) } else { Err(Error::::DelegatorNotExist)? @@ -601,8 +636,11 @@ impl }; // Construct xcm message. - let call: PhalaCall = - PhalaCall::Xtransfer(XtransferCall::Transfer(Box::new(asset), Box::new(dest), None)); + let call: PhalaCall = PhalaCall::Xtransfer(XtransferCall::Transfer( + Box::new(asset), + Box::new(dest), + None, + )); // Wrap the xcm message as it is sent from a subaccount of the parachain account, and // send it out. @@ -639,7 +677,10 @@ impl // Make sure from account is the entrance account of vtoken-minting module. let from_account_id = Pallet::::multilocation_to_account(from)?; let (entrance_account, _) = T::VtokenMinting::get_entrance_and_exit_accounts(); - ensure!(from_account_id == entrance_account, Error::::InvalidAccount); + ensure!( + from_account_id == entrance_account, + Error::::InvalidAccount + ); // transfer supplementary fee from treasury to the "from" account. Return the added up // amount @@ -715,7 +756,10 @@ impl // Ensure delegator has bonded to a validator. if let Some(Ledger::Phala(ledger)) = DelegatorLedgers::::get(currency_id, *who) { - ensure!(ledger.bonded_pool_id.is_some(), Error::::DelegatorNotBonded); + ensure!( + ledger.bonded_pool_id.is_some(), + Error::::DelegatorNotBonded + ); } else { Err(Error::::DelegatorNotExist)?; } @@ -737,8 +781,14 @@ impl if let Ledger::Phala(phala_ledger) = ledger { // Check if ledger bonding and unlocking amount is zero. If not, return error. - ensure!(phala_ledger.active_shares.is_zero(), Error::::AmountNotZero); - ensure!(phala_ledger.unlocking_shares.is_zero(), Error::::AmountNotZero); + ensure!( + phala_ledger.active_shares.is_zero(), + Error::::AmountNotZero + ); + ensure!( + phala_ledger.unlocking_shares.is_zero(), + Error::::AmountNotZero + ); } else { Err(Error::::Unexpected)?; } @@ -876,7 +926,7 @@ impl PhalaAgent { .active_shares .checked_add(&amount) .ok_or(Error::::OverFlow)?; - }, + } // If this is a bonding operation, increase unlocking_shares. Unlock => { // we only allow one unlocking operation at a time. @@ -896,7 +946,7 @@ impl PhalaAgent { unlock_time.ok_or(Error::::TimeUnitNotExist)?; old_pha_ledger.unlocking_time_unit = Some(unlock_time_unit); - }, + } _ => return Err(Error::::Unexpected), } Ok(()) diff --git a/pallets/slp/src/agents/polkadot_agent/agent.rs b/pallets/slp/src/agents/polkadot_agent/agent.rs index 96f4a28828..ac661d15d3 100644 --- a/pallets/slp/src/agents/polkadot_agent/agent.rs +++ b/pallets/slp/src/agents/polkadot_agent/agent.rs @@ -71,7 +71,10 @@ impl // Generate multi-location by id. let delegator_multilocation = T::AccountConverter::convert((new_delegator_id, currency_id)); - ensure!(delegator_multilocation != MultiLocation::default(), Error::::FailToConvert); + ensure!( + delegator_multilocation != MultiLocation::default(), + Error::::FailToConvert + ); // Add the new delegator into storage Pallet::::inner_add_delegator(new_delegator_id, &delegator_multilocation, currency_id) @@ -90,11 +93,17 @@ impl weight_and_fee: Option<(Weight, BalanceOf)>, ) -> Result> { // Check if it is bonded already. - ensure!(!DelegatorLedgers::::contains_key(currency_id, who), Error::::AlreadyBonded); + ensure!( + !DelegatorLedgers::::contains_key(currency_id, who), + Error::::AlreadyBonded + ); // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.delegator_bonded_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.delegator_bonded_minimum, + Error::::LowerThanMinimum + ); // Ensure the bond doesn't exceeds delegator_active_staking_maximum ensure!( @@ -177,7 +186,10 @@ impl // Check if the amount exceeds the minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.bond_extra_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.bond_extra_minimum, + Error::::LowerThanMinimum + ); // Check if the new_add_amount + active_staking_amount doesn't exceeds // delegator_active_staking_maximum @@ -246,19 +258,28 @@ impl DelegatorLedgers::::get(currency_id, who).ok_or(Error::::DelegatorNotBonded)?; if let Ledger::Substrate(substrate_ledger) = ledger { - let (active_staking, unlocking_num) = - (substrate_ledger.active, substrate_ledger.unlocking.len() as u32); + let (active_staking, unlocking_num) = ( + substrate_ledger.active, + substrate_ledger.unlocking.len() as u32, + ); // Check if the unbonding amount exceeds minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.unbond_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.unbond_minimum, + Error::::LowerThanMinimum + ); // Check if the remaining active balance is enough for (unbonding amount + minimum // bonded amount) - let remaining = - active_staking.checked_sub(&amount).ok_or(Error::::NotEnoughToUnbond)?; - ensure!(remaining >= mins_maxs.delegator_bonded_minimum, Error::::NotEnoughToUnbond); + let remaining = active_staking + .checked_sub(&amount) + .ok_or(Error::::NotEnoughToUnbond)?; + ensure!( + remaining >= mins_maxs.delegator_bonded_minimum, + Error::::NotEnoughToUnbond + ); // Check if this unbonding will exceed the maximum unlocking records bound for a single // delegator. @@ -383,7 +404,10 @@ impl // Check if the rebonding amount exceeds minimum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(amount >= mins_maxs.rebond_minimum, Error::::LowerThanMinimum); + ensure!( + amount >= mins_maxs.rebond_minimum, + Error::::LowerThanMinimum + ); // Get the delegator ledger if let Ledger::Substrate(substrate_ledger) = ledger { @@ -392,10 +416,19 @@ impl // Check if the delegator unlocking amount is greater than or equal to the rebond // amount. let mut total_unlocking: BalanceOf = Zero::zero(); - for UnlockChunk { value, unlock_time: _ } in unlock_chunk_list.iter() { - total_unlocking = total_unlocking.checked_add(value).ok_or(Error::::OverFlow)?; + for UnlockChunk { + value, + unlock_time: _, + } in unlock_chunk_list.iter() + { + total_unlocking = total_unlocking + .checked_add(value) + .ok_or(Error::::OverFlow)?; } - ensure!(total_unlocking >= amount, Error::::RebondExceedUnlockingAmount); + ensure!( + total_unlocking >= amount, + Error::::RebondExceedUnlockingAmount + ); } else { Err(Error::::Unexpected)?; } @@ -460,7 +493,10 @@ impl // Check if targets exceeds validators_back_maximum requirement. let mins_maxs = MinimumsAndMaximums::::get(currency_id).ok_or(Error::::NotExist)?; - ensure!(vec_len <= mins_maxs.validators_back_maximum, Error::::GreaterThanMaximum); + ensure!( + vec_len <= mins_maxs.validators_back_maximum, + Error::::GreaterThanMaximum + ); // remove duplicates let dedup_list = Pallet::::remove_validators_duplicates(currency_id, targets)?; @@ -624,9 +660,11 @@ impl }; // Construct xcm message. let call = match currency_id { - KSM => - KusamaCall::Staking(StakingCall::::PayoutStakers(validator_account, payout_era)) - .encode(), + KSM => KusamaCall::Staking(StakingCall::::PayoutStakers( + validator_account, + payout_era, + )) + .encode(), DOT => PolkadotCall::Staking(StakingCall::::PayoutStakers( validator_account, payout_era, @@ -680,8 +718,9 @@ impl // Construct xcm message. let call = match currency_id { - KSM => - KusamaCall::Staking(StakingCall::::WithdrawUnbonded(num_slashing_spans)).encode(), + KSM => { + KusamaCall::Staking(StakingCall::::WithdrawUnbonded(num_slashing_spans)).encode() + } DOT => PolkadotCall::Staking(StakingCall::::WithdrawUnbonded(num_slashing_spans)) .encode(), _ => Err(Error::NotSupportedCurrencyId)?, @@ -811,13 +850,19 @@ impl let beneficiary = Box::new(VersionedLocation::V3(Location::from([AccountId32 { network: None, - id: entrance_account.encode().try_into().map_err(|_| Error::::FailToConvert)?, + id: entrance_account + .encode() + .try_into() + .map_err(|_| Error::::FailToConvert)?, }]))); // Prepare parameter assets. let asset = MultiAsset { fun: Fungible(amount.unique_saturated_into()), - id: Concrete(MultiLocation { parents: 0, interior: Here }), + id: Concrete(MultiLocation { + parents: 0, + interior: Here, + }), }; let assets: Box = Box::new(VersionedAssets::V3(MultiAssets::from(asset))); @@ -886,7 +931,10 @@ impl // Make sure from account is the entrance account of vtoken-minting module. let from_account_id = Pallet::::multilocation_to_account(from)?; let (entrance_account, _) = T::VtokenMinting::get_entrance_and_exit_accounts(); - ensure!(from_account_id == entrance_account, Error::::InvalidAccount); + ensure!( + from_account_id == entrance_account, + Error::::InvalidAccount + ); // transfer supplementary fee from treasury to the "from" account. Return the added up // amount @@ -932,11 +980,15 @@ impl DelegatorLedgers::::mutate(currency_id, who, |old_ledger| -> Result<(), Error> { if let Some(Ledger::Substrate(ref mut old_sub_ledger)) = old_ledger { // Increase both the active and total amount. - old_sub_ledger.active = - old_sub_ledger.active.checked_add(&token_amount).ok_or(Error::::OverFlow)?; - - old_sub_ledger.total = - old_sub_ledger.total.checked_add(&token_amount).ok_or(Error::::OverFlow)?; + old_sub_ledger.active = old_sub_ledger + .active + .checked_add(&token_amount) + .ok_or(Error::::OverFlow)?; + + old_sub_ledger.total = old_sub_ledger + .total + .checked_add(&token_amount) + .ok_or(Error::::OverFlow)?; Ok(()) } else { Err(Error::::Unexpected)? @@ -973,7 +1025,9 @@ impl currency_id: CurrencyId, ) -> DispatchResult { // Get current VKSM/KSM or VDOT/DOT exchange rate. - let vtoken = currency_id.to_vtoken().map_err(|_| Error::::NotSupportedCurrencyId)?; + let vtoken = currency_id + .to_vtoken() + .map_err(|_| Error::::NotSupportedCurrencyId)?; let charge_amount = Pallet::::inner_calculate_vtoken_hosting_fee(amount, vtoken, currency_id)?; @@ -1102,7 +1156,7 @@ impl PolkadotAgent { .total .checked_add(&amount) .ok_or(Error::::OverFlow)?; - }, + } Unlock => { old_sub_ledger.active = old_sub_ledger .active @@ -1112,11 +1166,13 @@ impl PolkadotAgent { let unlock_time_unit = unlock_time.ok_or(Error::::TimeUnitNotExist)?; - let new_unlock_record = - UnlockChunk { value: amount, unlock_time: unlock_time_unit }; + let new_unlock_record = UnlockChunk { + value: amount, + unlock_time: unlock_time_unit, + }; old_sub_ledger.unlocking.push(new_unlock_record); - }, + } Rebond => { // If it is a rebonding operation. // Reduce the unlocking records. @@ -1145,7 +1201,7 @@ impl PolkadotAgent { .active .checked_add(&amount) .ok_or(Error::::OverFlow)?; - }, + } Liquidize => { // If it is a liquidize operation. let unlock_unit = unlock_time.ok_or(Error::::InvalidTimeUnit)?; @@ -1187,7 +1243,7 @@ impl PolkadotAgent { .total .checked_sub(&accumulated) .ok_or(Error::::OverFlow)?; - }, + } } Ok(()) } else { @@ -1215,7 +1271,11 @@ impl PolkadotAgent { ) -> Result<(), Error> { // update ValidatorsByDelegator storage let ValidatorsByDelegatorUpdateEntry::Substrate( - SubstrateValidatorsByDelegatorUpdateEntry { currency_id, delegator_id, validators }, + SubstrateValidatorsByDelegatorUpdateEntry { + currency_id, + delegator_id, + validators, + }, ) = query_entry; // ensure the length of validators does not exceed MaxLengthLimit diff --git a/pallets/slp/src/agents/polkadot_agent/types.rs b/pallets/slp/src/agents/polkadot_agent/types.rs index c2689c93f1..01cbeebfe6 100644 --- a/pallets/slp/src/agents/polkadot_agent/types.rs +++ b/pallets/slp/src/agents/polkadot_agent/types.rs @@ -72,7 +72,10 @@ pub enum SystemCall { #[derive(Encode, Decode, RuntimeDebug, Clone)] pub enum BalancesCall { #[codec(index = 3)] - TransferKeepAlive(::Source, #[codec(compact)] BalanceOf), + TransferKeepAlive( + ::Source, + #[codec(compact)] BalanceOf, + ), } #[derive(Encode, Decode, RuntimeDebug, Clone)] @@ -95,7 +98,10 @@ pub enum PolkadotUtilityCall { pub enum StakingCall { /// Kusama/Polkadot has the same account Id type as Bifrost. #[codec(index = 0)] - Bond(#[codec(compact)] BalanceOf, RewardDestination), + Bond( + #[codec(compact)] BalanceOf, + RewardDestination, + ), #[codec(index = 1)] BondExtra(#[codec(compact)] BalanceOf), #[codec(index = 2)] diff --git a/pallets/slp/src/agents/utils.rs b/pallets/slp/src/agents/utils.rs index 2c970f99ea..4df9c5bf45 100644 --- a/pallets/slp/src/agents/utils.rs +++ b/pallets/slp/src/agents/utils.rs @@ -27,6 +27,7 @@ use bifrost_primitives::{ use frame_support::ensure; use parity_scale_codec::Encode; use sp_core::Get; +use sp_runtime::traits::BlockNumberProvider; use sp_std::prelude::*; use xcm::v3::{prelude::*, MultiLocation}; @@ -40,7 +41,10 @@ impl Pallet { let account_32 = match who { MultiLocation { parents: 0, - interior: X1(AccountId32 { network: _network_id, id: account_id }), + interior: X1(AccountId32 { + network: _network_id, + id: account_id, + }), } => account_id, _ => Err(Error::::AccountNotExist)?, }; @@ -60,7 +64,10 @@ impl Pallet { let mut validators_list: Vec = vec![]; for validator in validators.iter() { // Check if the validator is in the validator whitelist - ensure!(validators_set.contains(&validator), Error::::ValidatorNotExist); + ensure!( + validators_set.contains(&validator), + Error::::ValidatorNotExist + ); if !validators_list.contains(&validator) { validators_list.push(*validator); } @@ -110,11 +117,21 @@ impl Pallet { let account_32 = match who { MultiLocation { parents: _, - interior: X1(AccountId32 { network: _network_id, id: account_id }), + interior: X1(AccountId32 { + network: _network_id, + id: account_id, + }), } => account_id, MultiLocation { parents: _, - interior: X2(_, AccountId32 { network: _network_id, id: account_id }), + interior: + X2( + _, + AccountId32 { + network: _network_id, + id: account_id, + }, + ), } => account_id, _ => Err(Error::::AccountNotExist)?, }; @@ -132,7 +149,10 @@ impl Pallet { pub fn account_32_to_local_location(account_32: [u8; 32]) -> Result> { let local_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: account_32 }), + interior: X1(AccountId32 { + network: None, + id: account_32, + }), }; Ok(local_location) @@ -144,20 +164,49 @@ impl Pallet { let inside: Junction = match location { MultiLocation { parents: _p, - interior: X2(Parachain(_para_id), AccountId32 { network: None, id: account_32 }), - } => AccountId32 { network: None, id: *account_32 }, + interior: + X2( + Parachain(_para_id), + AccountId32 { + network: None, + id: account_32, + }, + ), + } => AccountId32 { + network: None, + id: *account_32, + }, MultiLocation { parents: _p, - interior: X2(Parachain(_para_id), AccountKey20 { network: None, key: account_20 }), - } => AccountKey20 { network: None, key: *account_20 }, + interior: + X2( + Parachain(_para_id), + AccountKey20 { + network: None, + key: account_20, + }, + ), + } => AccountKey20 { + network: None, + key: *account_20, + }, MultiLocation { parents: _p, - interior: X1(AccountId32 { network: None, id: account_32 }), - } => AccountId32 { network: None, id: *account_32 }, + interior: X1(AccountId32 { + network: None, + id: account_32, + }), + } => AccountId32 { + network: None, + id: *account_32, + }, _ => Err(Error::::Unsupported)?, }; - let local_location = MultiLocation { parents: 0, interior: X1(inside) }; + let local_location = MultiLocation { + parents: 0, + interior: X1(inside), + }; Ok(local_location) } @@ -165,7 +214,10 @@ impl Pallet { pub fn account_32_to_parent_location(account_32: [u8; 32]) -> Result> { let parent_location = MultiLocation { parents: 1, - interior: X1(AccountId32 { network: None, id: account_32 }), + interior: X1(AccountId32 { + network: None, + id: account_32, + }), }; Ok(parent_location) @@ -177,7 +229,13 @@ impl Pallet { ) -> Result> { let parachain_location = MultiLocation { parents: 1, - interior: X2(Parachain(chain_id), AccountId32 { network: None, id: account_32 }), + interior: X2( + Parachain(chain_id), + AccountId32 { + network: None, + id: account_32, + }, + ), }; Ok(parachain_location) @@ -188,7 +246,14 @@ impl Pallet { let account_20 = match who { MultiLocation { parents: _, - interior: X2(Parachain(_), AccountKey20 { network: _network_id, key: account_id }), + interior: + X2( + Parachain(_), + AccountKey20 { + network: _network_id, + key: account_id, + }, + ), } => account_id, _ => Err(Error::::AccountNotExist)?, }; @@ -215,13 +280,14 @@ impl Pallet { let (entry, timeout) = DelegatorLedgerXcmUpdateQueue::::get(query_id).ok_or(Error::::QueryNotExist)?; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let mut updated = true; if now <= timeout { let currency_id = match entry.clone() { LedgerUpdateEntry::Substrate(substrate_entry) => Some(substrate_entry.currency_id), - LedgerUpdateEntry::ParachainStaking(moonbeam_entry) => - Some(moonbeam_entry.currency_id), + LedgerUpdateEntry::ParachainStaking(moonbeam_entry) => { + Some(moonbeam_entry.currency_id) + } _ => None, } .ok_or(Error::::NotSupportedCurrencyId)?; @@ -249,12 +315,13 @@ impl Pallet { let (entry, timeout) = ValidatorsByDelegatorXcmUpdateQueue::::get(query_id) .ok_or(Error::::QueryNotExist)?; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let mut updated = true; if now <= timeout { let currency_id = match entry.clone() { - ValidatorsByDelegatorUpdateEntry::Substrate(substrate_entry) => - Some(substrate_entry.currency_id), + ValidatorsByDelegatorUpdateEntry::Substrate(substrate_entry) => { + Some(substrate_entry.currency_id) + } } .ok_or(Error::::NotSupportedCurrencyId)?; @@ -298,8 +365,9 @@ impl Pallet { let (entry, _) = ValidatorsByDelegatorXcmUpdateQueue::::get(query_id) .ok_or(Error::::QueryNotExist)?; let currency_id = match entry { - ValidatorsByDelegatorUpdateEntry::Substrate(substrate_entry) => - Some(substrate_entry.currency_id), + ValidatorsByDelegatorUpdateEntry::Substrate(substrate_entry) => { + Some(substrate_entry.currency_id) + } } .ok_or(Error::::NotSupportedCurrencyId)?; @@ -326,14 +394,22 @@ impl Pallet { 1, [xcm::v4::prelude::Parachain(MoonriverChainId::get())], )), - GLMR => - Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(MoonbeamChainId::get())])), - ASTR => - Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(AstarChainId::get())])), - MANTA => - Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(MantaChainId::get())])), - PHA => - Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(PhalaChainId::get())])), + GLMR => Ok(xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(MoonbeamChainId::get())], + )), + ASTR => Ok(xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(AstarChainId::get())], + )), + MANTA => Ok(xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(MantaChainId::get())], + )), + PHA => Ok(xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(PhalaChainId::get())], + )), _ => Err(Error::::NotSupportedCurrencyId), } } @@ -350,7 +426,10 @@ impl Pallet { parents: 1, interior: X2(Parachain(MoonbeamChainId::get()), PalletInstance(10)), }), - MANTA => Ok(MultiLocation { parents: 1, interior: X1(Parachain(MantaChainId::get())) }), + MANTA => Ok(MultiLocation { + parents: 1, + interior: X1(Parachain(MantaChainId::get())), + }), _ => Err(Error::::NotSupportedCurrencyId), } } diff --git a/pallets/slp/src/benchmarking.rs b/pallets/slp/src/benchmarking.rs index 68cd64d01d..1d533f374e 100644 --- a/pallets/slp/src/benchmarking.rs +++ b/pallets/slp/src/benchmarking.rs @@ -26,10 +26,20 @@ use frame_support::{assert_ok, PalletId}; use frame_system::RawOrigin as SystemOrigin; use sp_runtime::traits::{AccountIdConversion, StaticLookup, UniqueSaturatedFrom}; -const DELEGATOR1: MultiLocation = - MultiLocation { parents: 1, interior: X1(AccountId32 { network: None, id: [1u8; 32] }) }; -const DELEGATOR2: MultiLocation = - MultiLocation { parents: 1, interior: X1(AccountId32 { network: None, id: [2u8; 32] }) }; +const DELEGATOR1: MultiLocation = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: None, + id: [1u8; 32], + }), +}; +const DELEGATOR2: MultiLocation = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: None, + id: [2u8; 32], + }), +}; type TokenBalanceOf = <::MultiCurrency as orml_traits::MultiCurrency< ::AccountId, @@ -143,7 +153,11 @@ pub fn set_mins_and_maxs(origin: ::Runtime }; // Set minimums and maximums - assert_ok!(Pallet::::set_minimums_and_maximums(origin, KSM, Some(mins_and_maxs))); + assert_ok!(Pallet::::set_minimums_and_maximums( + origin, + KSM, + Some(mins_and_maxs) + )); } pub fn init_bond(origin: ::RuntimeOrigin) { @@ -154,7 +168,10 @@ pub fn init_bond(origin: ::RuntimeOrigin) Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(KSM, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + KSM, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( KSM, @@ -187,11 +204,21 @@ pub fn init_ongoing_time(origin: ::Runtime )); // Initialize ongoing timeunit as 1. - assert_ok!(Pallet::::update_ongoing_time_unit(origin.clone(), KSM, TimeUnit::Era(0))); + assert_ok!(Pallet::::update_ongoing_time_unit( + origin.clone(), + KSM, + TimeUnit::Era(0) + )); - let delay = - Delays { unlock_delay: TimeUnit::Era(0), leave_delegators_delay: Default::default() }; - assert_ok!(Pallet::::set_currency_delays(origin.clone(), KSM, Some(delay))); + let delay = Delays { + unlock_delay: TimeUnit::Era(0), + leave_delegators_delay: Default::default(), + }; + assert_ok!(Pallet::::set_currency_delays( + origin.clone(), + KSM, + Some(delay) + )); } #[benchmarks(where T: Config + orml_tokens::Config + bifrost_vtoken_minting::Config+ bifrost_stable_pool::Config+ pallet_balances::Config + bifrost_asset_registry::Config)] @@ -210,7 +237,11 @@ mod benchmarks { set_mins_and_maxs::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, None); + _( + origin as ::RuntimeOrigin, + KSM, + None, + ); Ok(()) } @@ -226,7 +257,10 @@ mod benchmarks { Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(KSM, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + KSM, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( KSM, @@ -443,7 +477,10 @@ mod benchmarks { Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(KSM, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + KSM, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( KSM, @@ -481,7 +518,10 @@ mod benchmarks { Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(KSM, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + KSM, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( KSM, @@ -544,7 +584,10 @@ mod benchmarks { Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(KSM, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + KSM, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( KSM, @@ -586,7 +629,10 @@ mod benchmarks { Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(KSM, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + KSM, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( KSM, @@ -626,7 +672,10 @@ mod benchmarks { Pallet::::account_id_to_account_32(whitelisted_caller()).unwrap(), ) .unwrap(); - FeeSources::::insert(PHA, (fee_source_location, BalanceOf::::from(4100000000u32))); + FeeSources::::insert( + PHA, + (fee_source_location, BalanceOf::::from(4100000000u32)), + ); assert_ok!(::MultiCurrency::deposit( PHA, @@ -673,7 +722,11 @@ mod benchmarks { .map_err(|_| BenchmarkError::Weightless)?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 10u32.into()); + _( + origin as ::RuntimeOrigin, + KSM, + 10u32.into(), + ); Ok(()) } @@ -690,7 +743,11 @@ mod benchmarks { )); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 10u32.into()); + _( + origin as ::RuntimeOrigin, + KSM, + 10u32.into(), + ); Ok(()) } @@ -704,7 +761,11 @@ mod benchmarks { LastTimeUpdatedOngoingTimeUnit::::insert(KSM, BlockNumberFor::::from(0u32)); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, TimeUnit::Era(0)); + _( + origin as ::RuntimeOrigin, + KSM, + TimeUnit::Era(0), + ); Ok(()) } @@ -752,7 +813,11 @@ mod benchmarks { .map_err(|_| BenchmarkError::Weightless)?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Some(whitelisted_caller())); + _( + origin as ::RuntimeOrigin, + KSM, + Some(whitelisted_caller()), + ); Ok(()) } @@ -779,7 +844,12 @@ mod benchmarks { set_mins_and_maxs::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 0u16, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + 0u16, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -798,7 +868,11 @@ mod benchmarks { )); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -810,7 +884,11 @@ mod benchmarks { set_mins_and_maxs::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -828,7 +906,11 @@ mod benchmarks { )); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -865,7 +947,12 @@ mod benchmarks { }))); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1), ledger); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ledger, + ); Ok(()) } @@ -890,7 +977,11 @@ mod benchmarks { }; #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Some(mins_and_maxs)); + _( + origin as ::RuntimeOrigin, + KSM, + Some(mins_and_maxs), + ); Ok(()) } @@ -899,11 +990,17 @@ mod benchmarks { fn set_currency_delays() -> Result<(), BenchmarkError> { let origin = ::ControlOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; - let delay = - Delays { unlock_delay: TimeUnit::Era(0), leave_delegators_delay: Default::default() }; + let delay = Delays { + unlock_delay: TimeUnit::Era(0), + leave_delegators_delay: Default::default(), + }; #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Some(delay)); + _( + origin as ::RuntimeOrigin, + KSM, + Some(delay), + ); Ok(()) } @@ -959,7 +1056,11 @@ mod benchmarks { .map_err(|_| BenchmarkError::Weightless)?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -975,7 +1076,11 @@ mod benchmarks { Box::new(DELEGATOR1) )); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -987,7 +1092,11 @@ mod benchmarks { init_bond::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 0u64); + _( + origin as ::RuntimeOrigin, + KSM, + 0u64, + ); Ok(()) } @@ -999,7 +1108,11 @@ mod benchmarks { init_bond::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 0u64); + _( + origin as ::RuntimeOrigin, + KSM, + 0u64, + ); Ok(()) } @@ -1038,7 +1151,11 @@ mod benchmarks { ), ); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 1u64); + _( + origin as ::RuntimeOrigin, + KSM, + 1u64, + ); Ok(()) } @@ -1077,7 +1194,11 @@ mod benchmarks { ), ); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 1u64); + _( + origin as ::RuntimeOrigin, + KSM, + 1u64, + ); Ok(()) } @@ -1089,7 +1210,11 @@ mod benchmarks { set_mins_and_maxs::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, vec![DELEGATOR1]); + _( + origin as ::RuntimeOrigin, + KSM, + vec![DELEGATOR1], + ); Ok(()) } @@ -1101,7 +1226,11 @@ mod benchmarks { set_mins_and_maxs::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, vec![DELEGATOR1]); + _( + origin as ::RuntimeOrigin, + KSM, + vec![DELEGATOR1], + ); Ok(()) } @@ -1113,7 +1242,11 @@ mod benchmarks { set_mins_and_maxs::(origin.clone()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -1131,7 +1264,11 @@ mod benchmarks { )); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, Box::new(DELEGATOR1)); + _( + origin as ::RuntimeOrigin, + KSM, + Box::new(DELEGATOR1), + ); Ok(()) } @@ -1160,10 +1297,12 @@ mod benchmarks { minimal_balance: Zero::zero(), }; // register DOT in registry pallet - assert_ok!(bifrost_asset_registry::Pallet::::register_token_metadata( - origin.clone(), - Box::new(metadata.clone()) - )); + assert_ok!( + bifrost_asset_registry::Pallet::::register_token_metadata( + origin.clone(), + Box::new(metadata.clone()) + ) + ); #[extrinsic_call] _( @@ -1202,7 +1341,11 @@ mod benchmarks { frame_system::Pallet::::set_block_number((1 + SIX_MONTHS).into()); #[extrinsic_call] - _(origin as ::RuntimeOrigin, KSM, 1u8); + _( + origin as ::RuntimeOrigin, + KSM, + 1u8, + ); Ok(()) } diff --git a/pallets/slp/src/lib.rs b/pallets/slp/src/lib.rs index 443002b58c..96b215c9f9 100644 --- a/pallets/slp/src/lib.rs +++ b/pallets/slp/src/lib.rs @@ -97,6 +97,7 @@ pub mod pallet { use frame_support::dispatch::GetDispatchInfo; use orml_traits::XcmTransfer; use pallet_xcm::ensure_response; + use sp_runtime::traits::BlockNumberProvider; use xcm::v3::{MaybeErrorCode, Response}; #[pallet::config] @@ -169,6 +170,9 @@ pub mod pallet { // asset registry to get asset metadata type AssetIdMaps: CurrencyIdMapping>>; + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; + #[pallet::constant] type TreasuryAccount: Get; } @@ -710,7 +714,10 @@ pub mod pallet { staking_agent.initialize_delegator(currency_id, delegator_location)?; // Deposit event. - Pallet::::deposit_event(Event::DelegatorInitialized { currency_id, delegator_id }); + Pallet::::deposit_event(Event::DelegatorInitialized { + currency_id, + delegator_id, + }); Ok(()) } @@ -1119,7 +1126,11 @@ pub mod pallet { )?; // Deposit event. - Pallet::::deposit_event(Event::ConvertAsset { currency_id, who: *who, amount }); + Pallet::::deposit_event(Event::ConvertAsset { + currency_id, + who: *who, + amount, + }); Ok(()) } @@ -1140,7 +1151,10 @@ pub mod pallet { T::VtokenMinting::increase_token_pool(currency_id, amount)?; // Deposit event. - Pallet::::deposit_event(Event::PoolTokenIncreased { currency_id, amount }); + Pallet::::deposit_event(Event::PoolTokenIncreased { + currency_id, + amount, + }); Ok(()) } @@ -1160,7 +1174,10 @@ pub mod pallet { T::VtokenMinting::decrease_token_pool(currency_id, amount)?; // Deposit event. - Pallet::::deposit_event(Event::PoolTokenDecreased { currency_id, amount }); + Pallet::::deposit_event(Event::PoolTokenDecreased { + currency_id, + amount, + }); Ok(()) } @@ -1180,9 +1197,10 @@ pub mod pallet { let last_update_block = LastTimeUpdatedOngoingTimeUnit::::get(currency_id) .ok_or(Error::::LastTimeUpdatedOngoingTimeUnitNotExist)?; - let current_block = frame_system::Pallet::::block_number(); - let blocks_between = - current_block.checked_sub(&last_update_block).ok_or(Error::::UnderFlow)?; + let current_block = T::BlockNumberProvider::current_block_number(); + let blocks_between = current_block + .checked_sub(&last_update_block) + .ok_or(Error::::UnderFlow)?; ensure!(blocks_between >= interval, Error::::TooFrequent); @@ -1313,7 +1331,10 @@ pub mod pallet { currency_id, amount: fee_to_charge, }); - Pallet::::deposit_event(Event::PoolTokenIncreased { currency_id, amount: value }); + Pallet::::deposit_event(Event::PoolTokenIncreased { + currency_id, + amount: value, + }); Ok(()) } @@ -1337,7 +1358,10 @@ pub mod pallet { }); // Deposit event. - Pallet::::deposit_event(Event::OperateOriginSet { currency_id, operator: who }); + Pallet::::deposit_event(Event::OperateOriginSet { + currency_id, + operator: who, + }); Ok(()) } @@ -1358,7 +1382,10 @@ pub mod pallet { }); // Deposit event. - Pallet::::deposit_event(Event::FeeSourceSet { currency_id, who_and_fee }); + Pallet::::deposit_event(Event::FeeSourceSet { + currency_id, + who_and_fee, + }); Ok(()) } @@ -1401,7 +1428,10 @@ pub mod pallet { staking_agent.remove_delegator(&who, currency_id)?; // Deposit event. - Pallet::::deposit_event(Event::DelegatorRemoved { currency_id, delegator_id: *who }); + Pallet::::deposit_event(Event::DelegatorRemoved { + currency_id, + delegator_id: *who, + }); Ok(()) } @@ -1598,7 +1628,10 @@ pub mod pallet { *fee_set = maybe_fee_set; }); - Pallet::::deposit_event(Event::HostingFeesSet { currency_id, fees: maybe_fee_set }); + Pallet::::deposit_event(Event::HostingFeesSet { + currency_id, + fees: maybe_fee_set, + }); Ok(()) } @@ -1885,7 +1918,7 @@ pub mod pallet { Pallet::::check_length_and_deduplicate(currency_id, validator_list)?; // get current block number - let current_block_number = >::block_number(); + let current_block_number = T::BlockNumberProvider::current_block_number(); // get the due block number let due_block_number = current_block_number .checked_add(&BlockNumberFor::::from(SIX_MONTHS)) @@ -1957,7 +1990,7 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; // get current block number - let current_block_number = >::block_number(); + let current_block_number = T::BlockNumberProvider::current_block_number(); // get the due block number if the validator is not in the validator boost list let mut due_block_number = current_block_number @@ -1971,8 +2004,9 @@ pub mod pallet { // if the validator is in the validator boost list, change the due block // number validator_boost_vec = validator_boost_list.to_vec(); - if let Some(index) = - validator_boost_vec.iter().position(|(validator, _)| validator == who.as_ref()) + if let Some(index) = validator_boost_vec + .iter() + .position(|(validator, _)| validator == who.as_ref()) { let original_due_block = validator_boost_vec[index].1; // get the due block number @@ -2093,7 +2127,9 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; ensure!(amount > Zero::zero(), Error::::AmountZero); - let token = vtoken.to_token().map_err(|_| Error::::NotSupportedCurrencyId)?; + let token = vtoken + .to_token() + .map_err(|_| Error::::NotSupportedCurrencyId)?; let (pool_id, _, _) = T::StablePoolHandler::get_pool_id(&vtoken, &token) .ok_or(Error::::StablePoolNotFound)?; @@ -2155,7 +2191,7 @@ pub mod pallet { 0 }; - let current_block_number = >::block_number(); + let current_block_number = T::BlockNumberProvider::current_block_number(); let mut remove_num = 0; // for each validator in the validator boost list, if the due block number is less than // or equal to the current block number, remove it @@ -2202,12 +2238,14 @@ pub mod pallet { match origin.clone().into() { Ok(RawOrigin::Signed(ref signer)) if Some(signer) == >::get(currency_id).as_ref() => - Ok(()), + { + Ok(()) + } _ => { T::ControlOrigin::ensure_origin(origin) .map_err(|_| Error::::NotAuthorized)?; Ok(()) - }, + } } } @@ -2225,8 +2263,10 @@ pub mod pallet { } pub fn confirm_delegator_ledger_call() -> ::RuntimeCall { - let call = - Call::::confirm_delegator_ledger { query_id: 0, response: Default::default() }; + let call = Call::::confirm_delegator_ledger { + query_id: 0, + response: Default::default(), + }; ::RuntimeCall::from(call) } @@ -2272,10 +2312,13 @@ impl>> derivative_index: DerivativeIndex, ) -> Option> { Self::get_multilocation(token, derivative_index).and_then(|location| { - location.interior.last().and_then(|interior| match interior { - AccountId32 { id, .. } => T::AccountId::decode(&mut &id[..]).ok(), - _ => None, - }) + location + .interior + .last() + .and_then(|interior| match interior { + AccountId32 { id, .. } => T::AccountId::decode(&mut &id[..]).ok(), + _ => None, + }) }) } @@ -2286,8 +2329,10 @@ impl>> Self::get_multilocation(token, derivative_index).and_then(|location| { DelegatorLedgers::::get(token, location).and_then(|ledger| match ledger { Ledger::Substrate(l) if F::contains(&token) => Some((l.total, l.active)), - Ledger::ParachainStaking(l) if F::contains(&token) => - Some((l.total, l.total.checked_sub(&l.less_total).unwrap_or_default())), + Ledger::ParachainStaking(l) if F::contains(&token) => Some(( + l.total, + l.total.checked_sub(&l.less_total).unwrap_or_default(), + )), _ => None, }) }) diff --git a/pallets/slp/src/mocks/mock.rs b/pallets/slp/src/mocks/mock.rs index a8328f5b3a..d6c0d25425 100644 --- a/pallets/slp/src/mocks/mock.rs +++ b/pallets/slp/src/mocks/mock.rs @@ -45,7 +45,7 @@ use sp_runtime::{ traits::{AccountIdConversion, Convert, IdentityLookup, TrailingZeroInput}, AccountId32, BuildStorage, }; -use sp_std::{boxed::Box, vec::Vec}; +use sp_std::vec::Vec; use xcm::v3::{prelude::*, MultiLocation, Weight}; use xcm_builder::{FixedWeightBounds, FrameTransactionalProcessor}; use xcm_executor::XcmExecutor; @@ -207,6 +207,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } parameter_types! { @@ -348,7 +349,7 @@ impl Convert<(u16, CurrencyId), MultiLocation> for SubAccountIndexMultiLocationC } else { MultiLocation::default() } - }, + } } } } @@ -458,6 +459,7 @@ impl Config for Runtime { type StablePoolHandler = (); type AssetIdMaps = AssetIdMaps; type TreasuryAccount = BifrostTreasuryAccount; + type BlockNumberProvider = System; } pub struct XcmDestWeightAndFee; @@ -556,7 +558,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -582,7 +586,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/slp/src/mocks/mock_kusama.rs b/pallets/slp/src/mocks/mock_kusama.rs index 6c7c53986b..fdae37acb3 100644 --- a/pallets/slp/src/mocks/mock_kusama.rs +++ b/pallets/slp/src/mocks/mock_kusama.rs @@ -47,7 +47,7 @@ use sp_runtime::{ traits::{AccountIdConversion, Convert, TrailingZeroInput}, AccountId32, BuildStorage, }; -use sp_std::{boxed::Box, vec::Vec}; +use sp_std::vec::Vec; use xcm::v3::{prelude::*, Weight}; use xcm_builder::{FixedWeightBounds, FrameTransactionalProcessor}; use xcm_executor::traits::{Properties, ShouldExecute}; @@ -109,6 +109,7 @@ impl bifrost_stable_asset::Config for Runtime { type WeightInfo = (); type ListingOrigin = EnsureSignedBy; type EnsurePoolAssetId = EnsurePoolAssetId; + type BlockNumberProvider = System; } parameter_types! { @@ -263,6 +264,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } parameter_types! { @@ -404,7 +406,7 @@ impl Convert<(u16, CurrencyId), MultiLocation> for SubAccountIndexMultiLocationC } else { MultiLocation::default() } - }, + } // Other sibling chains use the Bifrost para account with "sibl" _ => { // get parachain id @@ -434,7 +436,7 @@ impl Convert<(u16, CurrencyId), MultiLocation> for SubAccountIndexMultiLocationC } else { MultiLocation::default() } - }, + } } } } @@ -470,15 +472,26 @@ impl Convert> for CurrencyIdConvert { match id { Token(MOVR) => Some(xcm::v4::Location::new( 1, - [xcm::v4::Junction::Parachain(2023), xcm::v4::Junction::PalletInstance(10)], + [ + xcm::v4::Junction::Parachain(2023), + xcm::v4::Junction::PalletInstance(10), + ], )), Token(KSM) => Some(xcm::v4::Location::parent()), Native(BNC) => Some(xcm::v4::Location::new( 0, - [xcm::v4::Junction::from(BoundedVec::try_from("0x0001".encode()).unwrap())], + [xcm::v4::Junction::from( + BoundedVec::try_from("0x0001".encode()).unwrap(), + )], + )), + Token(PHA) => Some(xcm::v4::Location::new( + 1, + [xcm::v4::Junction::Parachain(2004)], + )), + MANTA => Some(xcm::v4::Location::new( + 1, + [xcm::v4::Junction::Parachain(2104)], )), - Token(PHA) => Some(xcm::v4::Location::new(1, [xcm::v4::Junction::Parachain(2004)])), - MANTA => Some(xcm::v4::Location::new(1, [xcm::v4::Junction::Parachain(2104)])), _ => None, } } @@ -528,6 +541,7 @@ impl Config for Runtime { type StablePoolHandler = StablePool; type AssetIdMaps = AssetIdMaps; type TreasuryAccount = BifrostTreasuryAccount; + type BlockNumberProvider = System; } pub struct XcmDestWeightAndFee; @@ -638,13 +652,17 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/slp/src/tests/astar_tests.rs b/pallets/slp/src/tests/astar_tests.rs index 33b06df81c..2ff988ffa3 100644 --- a/pallets/slp/src/tests/astar_tests.rs +++ b/pallets/slp/src/tests/astar_tests.rs @@ -26,8 +26,13 @@ use crate::{ const SUBACCOUNT_0_32: [u8; 32] = hex_literal::hex!["5a53736d8e96f1c007cf0d630acf5209b20611617af23ce924c8e25328eb5d28"]; -const SUBACCOUNT_0_LOCATION: MultiLocation = - MultiLocation { parents: 1, interior: X1(AccountId32 { network: None, id: SUBACCOUNT_0_32 }) }; +const SUBACCOUNT_0_LOCATION: MultiLocation = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: None, + id: SUBACCOUNT_0_32, + }), +}; #[test] fn test_construct_lock_xcm() { @@ -136,6 +141,9 @@ fn test_construct_claim_bonus_rewards_xcm() { Pallet::::prepare_send_as_subaccount_call(call, &SUBACCOUNT_0_LOCATION, ASTR) .unwrap(); let hex_string = hex::encode(&transact_call_data); - assert_eq!(hex_string, "0b010000220e000000000000000000000000000000000000000000"); + assert_eq!( + hex_string, + "0b010000220e000000000000000000000000000000000000000000" + ); }); } diff --git a/pallets/slp/src/tests/filecoin_tests.rs b/pallets/slp/src/tests/filecoin_tests.rs index d7acc574b2..aa59e36569 100644 --- a/pallets/slp/src/tests/filecoin_tests.rs +++ b/pallets/slp/src/tests/filecoin_tests.rs @@ -43,19 +43,25 @@ fn mins_maxs_setup() { } fn initialize_delegator_setup() { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; mins_maxs_setup(); let _ = Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), FIL, Some(Box::new(location))); } fn delegate_setup() { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; - let owner_location = - MultiLocation { parents: 111, interior: X1(Junction::from(BoundedVec::default())) }; + let owner_location = MultiLocation { + parents: 111, + interior: X1(Junction::from(BoundedVec::default())), + }; initialize_delegator_setup(); @@ -70,8 +76,10 @@ fn delegate_setup() { } fn bond_setup() { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; delegate_setup(); @@ -88,8 +96,10 @@ fn bond_setup() { #[test] fn initialize_delegator_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; System::set_block_number(1); @@ -101,16 +111,24 @@ fn initialize_delegator_should_work() { )); assert_eq!(DelegatorNextIndex::::get(FIL), 1); - assert_eq!(DelegatorsIndex2Multilocation::::get(FIL, 0), Some(location)); - assert_eq!(DelegatorsMultilocation2Index::::get(FIL, location), Some(0)); + assert_eq!( + DelegatorsIndex2Multilocation::::get(FIL, 0), + Some(location) + ); + assert_eq!( + DelegatorsMultilocation2Index::::get(FIL, location), + Some(0) + ); }); } #[test] fn bond_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; System::set_block_number(1); @@ -129,7 +147,14 @@ fn bond_should_work() { delegate_setup(); assert_noop!( - Slp::bond(RuntimeOrigin::signed(ALICE), FIL, Box::new(location), 1_000, None, None), + Slp::bond( + RuntimeOrigin::signed(ALICE), + FIL, + Box::new(location), + 1_000, + None, + None + ), Error::::LowerThanMinimum ); @@ -154,10 +179,16 @@ fn bond_should_work() { None )); - let fil_ledger = FilecoinLedger { account: location, initial_pledge: 1000000000000 }; + let fil_ledger = FilecoinLedger { + account: location, + initial_pledge: 1000000000000, + }; let ledger = Ledger::Filecoin(fil_ledger); - assert_eq!(DelegatorLedgers::::get(FIL, location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(FIL, location), + Some(ledger) + ); assert_noop!( Slp::bond( @@ -176,20 +207,31 @@ fn bond_should_work() { #[test] fn delegate_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; - let owner_location = - MultiLocation { parents: 111, interior: X1(Junction::from(BoundedVec::default())) }; + let owner_location = MultiLocation { + parents: 111, + interior: X1(Junction::from(BoundedVec::default())), + }; System::set_block_number(1); initialize_delegator_setup(); - assert_ok!(Slp::add_validator(RuntimeOrigin::signed(ALICE), FIL, Box::new(owner_location))); + assert_ok!(Slp::add_validator( + RuntimeOrigin::signed(ALICE), + FIL, + Box::new(owner_location) + )); let validator_list = BoundedVec::try_from(vec![owner_location]).unwrap(); - assert_eq!(Validators::::get(FIL), Some(validator_list.clone())); + assert_eq!( + Validators::::get(FIL), + Some(validator_list.clone()) + ); assert_ok!(Slp::delegate( RuntimeOrigin::signed(ALICE), @@ -209,8 +251,10 @@ fn delegate_should_work() { #[test] fn bond_extra_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; assert_noop!( Slp::bond_extra( @@ -235,18 +279,26 @@ fn bond_extra_should_work() { None )); - let fil_ledger = FilecoinLedger { account: location, initial_pledge: 2000000000000 }; + let fil_ledger = FilecoinLedger { + account: location, + initial_pledge: 2000000000000, + }; let ledger = Ledger::Filecoin(fil_ledger); - assert_eq!(DelegatorLedgers::::get(FIL, location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(FIL, location), + Some(ledger) + ); }); } #[test] fn unbond_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; assert_noop!( Slp::unbond( @@ -271,24 +323,36 @@ fn unbond_should_work() { None )); - let fil_ledger = FilecoinLedger { account: location, initial_pledge: 500000000000 }; + let fil_ledger = FilecoinLedger { + account: location, + initial_pledge: 500000000000, + }; let ledger = Ledger::Filecoin(fil_ledger); - assert_eq!(DelegatorLedgers::::get(FIL, location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(FIL, location), + Some(ledger) + ); }); } #[test] fn undelegate_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; - let owner_location = - MultiLocation { parents: 111, interior: X1(Junction::from(BoundedVec::default())) }; + let owner_location = MultiLocation { + parents: 111, + interior: X1(Junction::from(BoundedVec::default())), + }; - let other_location = - MultiLocation { parents: 120, interior: X1(Junction::from(BoundedVec::default())) }; + let other_location = MultiLocation { + parents: 120, + interior: X1(Junction::from(BoundedVec::default())), + }; assert_noop!( Slp::undelegate( @@ -304,7 +368,10 @@ fn undelegate_should_work() { bond_setup(); let validator_list = BoundedVec::try_from(vec![owner_location]).unwrap(); - assert_eq!(ValidatorsByDelegator::::get(FIL, location), Some(validator_list)); + assert_eq!( + ValidatorsByDelegator::::get(FIL, location), + Some(validator_list) + ); assert_noop!( Slp::undelegate( @@ -318,7 +385,10 @@ fn undelegate_should_work() { ); // set ledger to zero - let fil_ledger = FilecoinLedger { account: location, initial_pledge: 0 }; + let fil_ledger = FilecoinLedger { + account: location, + initial_pledge: 0, + }; let ledger = Ledger::Filecoin(fil_ledger); DelegatorLedgers::::insert(FIL, location, ledger); @@ -348,8 +418,10 @@ fn undelegate_should_work() { #[test] fn charge_host_fee_and_tune_vtoken_exchange_rate_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; let treasury_id: AccountId = PalletId(*b"bf/trsry").into_account_truncating(); let treasury_32: [u8; 32] = treasury_id.clone().into(); @@ -370,7 +442,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_should_work() { let pct = Permill::from_percent(20); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -392,7 +467,11 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_should_work() { // First set base vtoken exchange rate. Should be 1:1. assert_ok!(Currencies::deposit(VFIL, &ALICE, 100)); - assert_ok!(Slp::increase_token_pool(RuntimeOrigin::signed(ALICE), FIL, 100)); + assert_ok!(Slp::increase_token_pool( + RuntimeOrigin::signed(ALICE), + FIL, + 100 + )); bond_setup(); @@ -421,8 +500,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_should_work() { #[test] fn remove_delegator_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; assert_noop!( Slp::remove_delegator(RuntimeOrigin::signed(ALICE), FIL, Box::new(location)), @@ -431,11 +512,23 @@ fn remove_delegator_should_work() { bond_setup(); - let fil_ledger = FilecoinLedger { account: location, initial_pledge: 1_000_000_000_000 }; + let fil_ledger = FilecoinLedger { + account: location, + initial_pledge: 1_000_000_000_000, + }; let ledger = Ledger::Filecoin(fil_ledger); - assert_eq!(DelegatorsIndex2Multilocation::::get(FIL, 0), Some(location)); - assert_eq!(DelegatorsMultilocation2Index::::get(FIL, location), Some(0)); - assert_eq!(DelegatorLedgers::::get(FIL, location), Some(ledger)); + assert_eq!( + DelegatorsIndex2Multilocation::::get(FIL, 0), + Some(location) + ); + assert_eq!( + DelegatorsMultilocation2Index::::get(FIL, location), + Some(0) + ); + assert_eq!( + DelegatorLedgers::::get(FIL, location), + Some(ledger) + ); assert_noop!( Slp::remove_delegator(RuntimeOrigin::signed(ALICE), FIL, Box::new(location)), @@ -443,14 +536,24 @@ fn remove_delegator_should_work() { ); // set ledger to zero - let fil_ledger1 = FilecoinLedger { account: location, initial_pledge: 0 }; + let fil_ledger1 = FilecoinLedger { + account: location, + initial_pledge: 0, + }; let ledger1 = Ledger::Filecoin(fil_ledger1); DelegatorLedgers::::insert(FIL, location, ledger1); - assert_ok!(Slp::remove_delegator(RuntimeOrigin::signed(ALICE), FIL, Box::new(location))); + assert_ok!(Slp::remove_delegator( + RuntimeOrigin::signed(ALICE), + FIL, + Box::new(location) + )); assert_eq!(DelegatorsIndex2Multilocation::::get(FIL, 0), None); - assert_eq!(DelegatorsMultilocation2Index::::get(FIL, location), None); + assert_eq!( + DelegatorsMultilocation2Index::::get(FIL, location), + None + ); assert_eq!(DelegatorLedgers::::get(FIL, location), None); }); } @@ -458,11 +561,15 @@ fn remove_delegator_should_work() { #[test] fn remove_validator_should_work() { ExtBuilder::default().build().execute_with(|| { - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; - let owner_location = - MultiLocation { parents: 111, interior: X1(Junction::from(BoundedVec::default())) }; + let owner_location = MultiLocation { + parents: 111, + interior: X1(Junction::from(BoundedVec::default())), + }; assert_noop!( Slp::remove_validator(RuntimeOrigin::signed(ALICE), FIL, Box::new(owner_location)), @@ -472,10 +579,16 @@ fn remove_validator_should_work() { bond_setup(); let validator_list = BoundedVec::try_from(vec![owner_location]).unwrap(); - assert_eq!(Validators::::get(FIL), Some(validator_list.clone())); + assert_eq!( + Validators::::get(FIL), + Some(validator_list.clone()) + ); // set ledger to zero - let fil_ledger = FilecoinLedger { account: location, initial_pledge: 0 }; + let fil_ledger = FilecoinLedger { + account: location, + initial_pledge: 0, + }; let ledger = Ledger::Filecoin(fil_ledger); DelegatorLedgers::::insert(FIL, location, ledger); @@ -501,12 +614,16 @@ fn remove_validator_should_work() { #[test] fn filecoin_transfer_to_works() { // miner - let location = - MultiLocation { parents: 100, interior: X1(Junction::from(BoundedVec::default())) }; + let location = MultiLocation { + parents: 100, + interior: X1(Junction::from(BoundedVec::default())), + }; // worker - let owner_location = - MultiLocation { parents: 111, interior: X1(Junction::from(BoundedVec::default())) }; + let owner_location = MultiLocation { + parents: 111, + interior: X1(Junction::from(BoundedVec::default())), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -517,7 +634,10 @@ fn filecoin_transfer_to_works() { let entrance_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: entrance_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: entrance_account_id_32, + }), }; let exit_account_id_32: [u8; 32] = @@ -526,7 +646,10 @@ fn filecoin_transfer_to_works() { let exit_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: exit_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: exit_account_id_32, + }), }; assert_noop!( diff --git a/pallets/slp/src/tests/kusama_tests.rs b/pallets/slp/src/tests/kusama_tests.rs index 8ca215b76f..848a17dc3b 100644 --- a/pallets/slp/src/tests/kusama_tests.rs +++ b/pallets/slp/src/tests/kusama_tests.rs @@ -28,8 +28,13 @@ use xcm::v3::prelude::*; const SUBACCOUNT_0_32: [u8; 32] = hex_literal::hex!["5a53736d8e96f1c007cf0d630acf5209b20611617af23ce924c8e25328eb5d28"]; -const SUBACCOUNT_0_LOCATION: MultiLocation = - MultiLocation { parents: 1, interior: X1(AccountId32 { network: None, id: SUBACCOUNT_0_32 }) }; +const SUBACCOUNT_0_LOCATION: MultiLocation = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: None, + id: SUBACCOUNT_0_32, + }), +}; #[test] fn construct_xcm_and_send_as_subaccount_should_work() { @@ -71,7 +76,10 @@ fn set_fee_source_works() { KSM, Some((alice_location, 1_000_000_000_000)) )); - assert_eq!(FeeSources::::get(KSM), Some((alice_location, 1_000_000_000_000))); + assert_eq!( + FeeSources::::get(KSM), + Some((alice_location, 1_000_000_000_000)) + ); }); } @@ -122,8 +130,14 @@ fn remove_delegator_works() { )); assert_eq!(DelegatorsIndex2Multilocation::::get(KSM, 0), None); - assert_eq!(DelegatorsMultilocation2Index::::get(KSM, subaccount_0_location), None); - assert_eq!(DelegatorLedgers::::get(KSM, subaccount_0_location), None); + assert_eq!( + DelegatorsMultilocation2Index::::get(KSM, subaccount_0_location), + None + ); + assert_eq!( + DelegatorLedgers::::get(KSM, subaccount_0_location), + None + ); }); } @@ -138,7 +152,11 @@ fn decrease_token_pool_works() { bifrost_vtoken_minting::TokenPool::::insert(KSM, 100); // Decrease token pool by 10. - assert_ok!(Slp::decrease_token_pool(RuntimeOrigin::signed(ALICE), KSM, 10)); + assert_ok!(Slp::decrease_token_pool( + RuntimeOrigin::signed(ALICE), + KSM, + 10 + )); // Check the value after decreasing assert_eq!(TokenPool::::get(KSM), 90); @@ -220,7 +238,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { let pct = Permill::from_percent(20); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -238,7 +259,11 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { // First set base vtoken exchange rate. Should be 1:1. assert_ok!(Currencies::deposit(VKSM, &ALICE, 100)); - assert_ok!(Slp::increase_token_pool(RuntimeOrigin::signed(ALICE), KSM, 100)); + assert_ok!(Slp::increase_token_pool( + RuntimeOrigin::signed(ALICE), + KSM, + 100 + )); // call the charge_host_fee_and_tune_vtoken_exchange_rate assert_ok!(Slp::charge_host_fee_and_tune_vtoken_exchange_rate( @@ -271,7 +296,10 @@ fn set_hosting_fees_works() { let pct = Permill::from_percent(20); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -331,12 +359,22 @@ fn register_subaccount_index_0() { System::set_block_number(600); // Initialize ongoing timeunit as 0. - assert_ok!(Slp::update_ongoing_time_unit(RuntimeOrigin::signed(ALICE), DOT, TimeUnit::Era(0))); + assert_ok!(Slp::update_ongoing_time_unit( + RuntimeOrigin::signed(ALICE), + DOT, + TimeUnit::Era(0) + )); // Initialize currency delays. - let delay = - Delays { unlock_delay: TimeUnit::Era(10), leave_delegators_delay: Default::default() }; - assert_ok!(Slp::set_currency_delays(RuntimeOrigin::signed(ALICE), DOT, Some(delay))); + let delay = Delays { + unlock_delay: TimeUnit::Era(10), + leave_delegators_delay: Default::default(), + }; + assert_ok!(Slp::set_currency_delays( + RuntimeOrigin::signed(ALICE), + DOT, + Some(delay) + )); let mins_and_maxs = MinimumsMaximums { delegator_bonded_minimum: 100_000_000_000, @@ -368,65 +406,85 @@ fn register_subaccount_index_0() { )); // Register Operation weight and fee - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::TransferTo, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::TransferTo, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Bond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Bond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::BondExtra, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::BondExtra, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Unbond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Unbond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Rebond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Rebond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Delegate, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Delegate, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Payout, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Payout, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Liquidize, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Liquidize, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::Chill, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::Chill, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - DOT, - XcmOperationType::TransferBack, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + DOT, + XcmOperationType::TransferBack, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); } #[test] diff --git a/pallets/slp/src/tests/manta_tests.rs b/pallets/slp/src/tests/manta_tests.rs index a149bbd16b..d28a7f307d 100644 --- a/pallets/slp/src/tests/manta_tests.rs +++ b/pallets/slp/src/tests/manta_tests.rs @@ -42,7 +42,10 @@ const VALIDATOR_0_LOCATION: MultiLocation = MultiLocation { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: VALIDATOR_0_ACCOUNT_ID_32 }, + Junction::AccountId32 { + network: None, + id: VALIDATOR_0_ACCOUNT_ID_32, + }, ), }; @@ -52,7 +55,10 @@ const VALIDATOR_1_LOCATION: MultiLocation = MultiLocation { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: VALIDATOR_1_ACCOUNT_ID_32 }, + Junction::AccountId32 { + network: None, + id: VALIDATOR_1_ACCOUNT_ID_32, + }, ), }; @@ -64,7 +70,10 @@ fn initialize_manta_delegator() { .into(); let bifrost_parachain_account_id_32 = Sibling::from(2030).into_account_truncating(); - assert_eq!(bifrost_parachain_account_id_32_right, bifrost_parachain_account_id_32); + assert_eq!( + bifrost_parachain_account_id_32_right, + bifrost_parachain_account_id_32 + ); // subaccount_id_0: 0x863c1faef3c3b8f8735ecb7f8ed18996356dd3de let subaccount_id_0_right: AccountId = @@ -85,7 +94,10 @@ fn initialize_manta_delegator() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_id_0.into() }, + Junction::AccountId32 { + network: None, + id: subaccount_id_0.into(), + }, ), }; @@ -110,7 +122,11 @@ fn initialize_manta_delegator() { Some(mins_and_maxs) )); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), MANTA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + MANTA, + None + )); assert_eq!(DelegatorNextIndex::::get(MANTA), 1); assert_eq!( DelegatorsIndex2Multilocation::::get(MANTA, 0), @@ -127,11 +143,18 @@ fn manta_setup() { let treasury_account_id_32: [u8; 32] = PalletId(*b"bf/trsry").into_account_truncating(); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_account_id_32, + }), }; // set operate_origins - assert_ok!(Slp::set_operate_origin(RuntimeOrigin::signed(ALICE), MANTA, Some(ALICE))); + assert_ok!(Slp::set_operate_origin( + RuntimeOrigin::signed(ALICE), + MANTA, + Some(ALICE) + )); // Set OngoingTimeUnitUpdateInterval as 1/3 round(600 blocks per round, 12 seconds per block) assert_ok!(Slp::set_ongoing_time_unit_update_interval( @@ -150,9 +173,15 @@ fn manta_setup() { )); // Initialize currency delays. - let delay = - Delays { unlock_delay: TimeUnit::Round(24), leave_delegators_delay: TimeUnit::Round(24) }; - assert_ok!(Slp::set_currency_delays(RuntimeOrigin::signed(ALICE), MANTA, Some(delay))); + let delay = Delays { + unlock_delay: TimeUnit::Round(24), + leave_delegators_delay: TimeUnit::Round(24), + }; + assert_ok!(Slp::set_currency_delays( + RuntimeOrigin::signed(ALICE), + MANTA, + Some(delay) + )); let mins_and_maxs = MinimumsMaximums { delegator_bonded_minimum: 100_000_000_000, @@ -176,7 +205,11 @@ fn manta_setup() { )); // First to setup index-multilocation relationship of subaccount_0 - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), MANTA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + MANTA, + None + )); // update some MANTA balance to treasury account assert_ok!(Tokens::set_balance( @@ -194,77 +227,101 @@ fn manta_setup() { Some((treasury_location, 1_000_000_000_000)), )); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::Bond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::Bond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::BondExtra, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::BondExtra, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::Unbond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::Unbond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::Chill, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::Chill, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::Rebond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::Rebond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::Undelegate, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::Undelegate, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::CancelLeave, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::CancelLeave, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::Liquidize, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::Liquidize, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::ExecuteLeave, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::ExecuteLeave, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::TransferBack, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::TransferBack, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::XtokensTransferBack, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::XtokensTransferBack, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MANTA, - XcmOperationType::TransferTo, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MANTA, + XcmOperationType::TransferTo, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); // Set delegator ledger assert_ok!(Slp::add_validator( @@ -287,7 +344,10 @@ fn manta_bond_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -316,7 +376,10 @@ fn manta_bond_extra_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -367,7 +430,10 @@ fn manta_unbond_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -418,7 +484,10 @@ fn manta_rebond_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -438,8 +507,10 @@ fn manta_rebond_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let manta_ledger = OneToManyLedger { @@ -479,7 +550,10 @@ fn manta_undelegate_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -530,7 +604,10 @@ fn manta_liquidize_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -552,8 +629,10 @@ fn manta_liquidize_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let manta_ledger = OneToManyLedger { @@ -616,8 +695,10 @@ fn manta_liquidize_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(50), 10_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(50), 10_000_000_000_000_000_000), + ); // set delegator_0 ledger let manta_ledger = OneToManyLedger { @@ -678,7 +759,10 @@ fn manta_bond_and_bond_extra_confirm_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -729,7 +813,10 @@ fn manta_bond_and_bond_extra_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 5_000_000_000_000_000_000); @@ -749,7 +836,10 @@ fn manta_bond_and_bond_extra_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); // BondExtra confirm let query_id = 1; @@ -776,7 +866,10 @@ fn manta_bond_and_bond_extra_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 10_000_000_000_000_000_000); @@ -796,7 +889,10 @@ fn manta_bond_and_bond_extra_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); }); } @@ -811,7 +907,10 @@ fn manta_unbond_confirm_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -840,7 +939,10 @@ fn manta_unbond_confirm_works() { // Set delegator ledger DelegatorLedgers::::insert(MANTA, subaccount_0_location, ledger.clone()); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); // Unbond confirm let query_id = 2; @@ -867,7 +969,10 @@ fn manta_unbond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 10_000_000_000_000_000_000); @@ -880,8 +985,10 @@ fn manta_unbond_confirm_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let manta_ledger = OneToManyLedger { @@ -896,7 +1003,10 @@ fn manta_unbond_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); // Unbond confirm let query_id = 3; @@ -932,7 +1042,10 @@ fn manta_unbond_confirm_works() { query_id ),); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); System::set_block_number(500); @@ -967,7 +1080,10 @@ fn manta_unbond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 8_000_000_000_000_000_000); @@ -987,7 +1103,10 @@ fn manta_unbond_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); }); } @@ -1002,7 +1121,10 @@ fn manta_unbond_all_confirm_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -1031,7 +1153,10 @@ fn manta_unbond_all_confirm_works() { DelegatorLedgers::::insert(MANTA, subaccount_0_location, ledger.clone()); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); let query_id = 5; let update_entry_5 = @@ -1066,7 +1191,10 @@ fn manta_unbond_all_confirm_works() { query_id ),); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); System::set_block_number(500); @@ -1101,7 +1229,10 @@ fn manta_unbond_all_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let empty_delegation_set: BTreeMap> = BTreeMap::new(); let request_briefs_set: BTreeMap)> = @@ -1135,7 +1266,10 @@ fn manta_rebond_confirm_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -1155,8 +1289,10 @@ fn manta_rebond_confirm_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let manta_ledger = OneToManyLedger { @@ -1172,7 +1308,10 @@ fn manta_rebond_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); DelegatorLedgers::::insert(MANTA, subaccount_0_location, ledger.clone()); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); let query_id = 7; let update_entry_7 = @@ -1198,7 +1337,10 @@ fn manta_rebond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 10_000_000_000_000_000_000); @@ -1218,7 +1360,10 @@ fn manta_rebond_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); }); } @@ -1233,7 +1378,10 @@ fn manta_undelegate_confirm_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -1287,7 +1435,10 @@ fn manta_undelegate_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 5_000_000_000_000_000_000); @@ -1303,8 +1454,10 @@ fn manta_undelegate_confirm_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 5_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 5_000_000_000_000_000_000), + ); // set delegator_0 ledger let manta_ledger = OneToManyLedger { @@ -1319,7 +1472,10 @@ fn manta_undelegate_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); // execute revoke confirm let query_id = 9; @@ -1373,7 +1529,10 @@ fn manta_undelegate_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_1_LOCATION, 5_000_000_000_000_000_000); @@ -1393,7 +1552,10 @@ fn manta_undelegate_confirm_works() { let ledger = Ledger::ParachainStaking(manta_ledger); - assert_eq!(DelegatorLedgers::::get(MANTA, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MANTA, subaccount_0_location), + Some(ledger) + ); }); } @@ -1408,7 +1570,10 @@ fn manta_transfer_back_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -1419,7 +1584,10 @@ fn manta_transfer_back_works() { let exit_account_location = MultiLocation { parents: 0, - interior: X1(Junction::AccountId32 { network: None, id: exit_account_id_32 }), + interior: X1(Junction::AccountId32 { + network: None, + id: exit_account_id_32, + }), }; assert_ok!(Slp::transfer_back( @@ -1444,7 +1612,10 @@ fn manta_transfer_to_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -1455,7 +1626,10 @@ fn manta_transfer_to_works() { let entrance_account_location = MultiLocation { parents: 0, - interior: X1(Junction::AccountId32 { network: None, id: entrance_account_id_32 }), + interior: X1(Junction::AccountId32 { + network: None, + id: entrance_account_id_32, + }), }; assert_ok!(Slp::transfer_to( @@ -1479,7 +1653,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { parents: 1, interior: X2( Parachain(2104), - Junction::AccountId32 { network: None, id: subaccount_0_account_id_32 }, + Junction::AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; @@ -1536,7 +1713,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { let pct = Permill::from_percent(20); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -1554,7 +1734,11 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { // First set base vtoken exchange rate. Should be 1:1. assert_ok!(Currencies::deposit(VMANTA, &ALICE, 100)); - assert_ok!(Slp::increase_token_pool(RuntimeOrigin::signed(ALICE), MANTA, 100)); + assert_ok!(Slp::increase_token_pool( + RuntimeOrigin::signed(ALICE), + MANTA, + 100 + )); // call the charge_host_fee_and_tune_vtoken_exchange_rate assert_ok!(Slp::charge_host_fee_and_tune_vtoken_exchange_rate( @@ -1638,8 +1822,11 @@ fn reset_validators_should_work() { manta_setup(); let validator_list_empty = vec![]; - let validator_list_input = - vec![VALIDATOR_0_LOCATION, VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]; + let validator_list_input = vec![ + VALIDATOR_0_LOCATION, + VALIDATOR_0_LOCATION, + VALIDATOR_1_LOCATION, + ]; let validator_list_output = BoundedVec::try_from(vec![VALIDATOR_1_LOCATION, VALIDATOR_0_LOCATION]).unwrap(); @@ -1655,7 +1842,10 @@ fn reset_validators_should_work() { validator_list_input )); - assert_eq!(Validators::::get(MANTA), Some(validator_list_output)); + assert_eq!( + Validators::::get(MANTA), + Some(validator_list_output) + ); }); } @@ -1666,8 +1856,11 @@ fn set_validator_boost_list_should_work() { let validator_list_empty = vec![]; let validator_list_input_1 = vec![VALIDATOR_0_LOCATION]; - let validator_list_input_2 = - vec![VALIDATOR_0_LOCATION, VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]; + let validator_list_input_2 = vec![ + VALIDATOR_0_LOCATION, + VALIDATOR_0_LOCATION, + VALIDATOR_1_LOCATION, + ]; let validator_list_output_1 = BoundedVec::try_from(vec![(VALIDATOR_0_LOCATION, SIX_MONTHS as u64 + 300)]).unwrap(); @@ -1718,7 +1911,10 @@ fn set_validator_boost_list_should_work() { ); let bounded_validator_0_1 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MANTA), Some(bounded_validator_0_1),); + assert_eq!( + Validators::::get(MANTA), + Some(bounded_validator_0_1), + ); }); } @@ -1735,7 +1931,10 @@ fn add_to_validator_boost_list_should_work() { )]) .unwrap(); let validator_list_output_3 = BoundedVec::try_from(vec![ - (VALIDATOR_0_LOCATION, SIX_MONTHS as u64 + 300 + SIX_MONTHS as u64), + ( + VALIDATOR_0_LOCATION, + SIX_MONTHS as u64 + 300 + SIX_MONTHS as u64, + ), (VALIDATOR_1_LOCATION, SIX_MONTHS as u64 + 400), ]) .unwrap(); @@ -1746,10 +1945,16 @@ fn add_to_validator_boost_list_should_work() { Box::new(VALIDATOR_0_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output_1)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output_1) + ); let bounded_validator_0 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MANTA), Some(bounded_validator_0.clone())); + assert_eq!( + Validators::::get(MANTA), + Some(bounded_validator_0.clone()) + ); System::set_block_number(400); @@ -1761,7 +1966,10 @@ fn add_to_validator_boost_list_should_work() { assert_eq!(Validators::::get(MANTA), Some(bounded_validator_0)); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output_2)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output_2) + ); assert_ok!(Slp::add_to_validator_boost_list( RuntimeOrigin::signed(ALICE), @@ -1769,10 +1977,16 @@ fn add_to_validator_boost_list_should_work() { Box::new(VALIDATOR_1_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output_3)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output_3) + ); let bounded_validator_0_1 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MANTA), Some(bounded_validator_0_1),); + assert_eq!( + Validators::::get(MANTA), + Some(bounded_validator_0_1), + ); }); } @@ -1790,7 +2004,10 @@ fn remove_from_validator_boost_list_should_work() { Box::new(VALIDATOR_0_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output.clone())); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output.clone()) + ); assert_ok!(Slp::remove_from_validator_boot_list( RuntimeOrigin::signed(ALICE), @@ -1798,7 +2015,10 @@ fn remove_from_validator_boost_list_should_work() { Box::new(VALIDATOR_1_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output) + ); assert_ok!(Slp::remove_from_validator_boot_list( RuntimeOrigin::signed(ALICE), @@ -1829,7 +2049,10 @@ fn clean_outdated_validator_boost_list_work() { )]) .unwrap(); let validator_list_output_3 = BoundedVec::try_from(vec![ - (VALIDATOR_0_LOCATION, SIX_MONTHS as u64 + 300 + SIX_MONTHS as u64), + ( + VALIDATOR_0_LOCATION, + SIX_MONTHS as u64 + 300 + SIX_MONTHS as u64, + ), (VALIDATOR_1_LOCATION, SIX_MONTHS as u64 + 400), ]) .unwrap(); @@ -1840,10 +2063,16 @@ fn clean_outdated_validator_boost_list_work() { Box::new(VALIDATOR_0_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output_1)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output_1) + ); let bounded_validator_0 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MANTA), Some(bounded_validator_0.clone())); + assert_eq!( + Validators::::get(MANTA), + Some(bounded_validator_0.clone()) + ); System::set_block_number(400); @@ -1872,7 +2101,10 @@ fn clean_outdated_validator_boost_list_work() { ); let bounded_validator_0_1 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MANTA), Some(bounded_validator_0_1),); + assert_eq!( + Validators::::get(MANTA), + Some(bounded_validator_0_1), + ); // no validator due yet. Everything should be kept after calling // clean_outdated_validator_boost_list @@ -1883,7 +2115,10 @@ fn clean_outdated_validator_boost_list_work() { MANTA, 1 )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output_3)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output_3) + ); // move to block SIX_MONTHS + 400, validator 1 should be removable System::set_block_number(400 + SIX_MONTHS as u64); @@ -1911,7 +2146,10 @@ fn clean_outdated_validator_boost_list_work() { MANTA, 1 )); - assert_eq!(ValidatorBoostList::::get(MANTA), Some(validator_list_output_2)); + assert_eq!( + ValidatorBoostList::::get(MANTA), + Some(validator_list_output_2) + ); assert_noop!( Slp::clean_outdated_validator_boost_list(RuntimeOrigin::signed(ALICE), MANTA, 2), diff --git a/pallets/slp/src/tests/moonriver_tests.rs b/pallets/slp/src/tests/moonriver_tests.rs index 34d7f18395..0bc866a85e 100644 --- a/pallets/slp/src/tests/moonriver_tests.rs +++ b/pallets/slp/src/tests/moonriver_tests.rs @@ -41,7 +41,10 @@ const VALIDATOR_0_LOCATION: MultiLocation = MultiLocation { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: VALIDATOR_0_ACCOUNT_ID_20 }, + Junction::AccountKey20 { + network: None, + key: VALIDATOR_0_ACCOUNT_ID_20, + }, ), }; @@ -51,7 +54,10 @@ const VALIDATOR_1_LOCATION: MultiLocation = MultiLocation { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: VALIDATOR_1_ACCOUNT_ID_20 }, + Junction::AccountKey20 { + network: None, + key: VALIDATOR_1_ACCOUNT_ID_20, + }, ), }; @@ -62,7 +68,10 @@ fn initialize_moonriver_delegator() { hex_literal::hex!["7369626cd1070000000000000000000000000000"].into(); let bifrost_parachain_account_id_20: [u8; 20] = Sibling::from(2001).into_account_truncating(); - assert_eq!(bifrost_parachain_account_id_20_right, bifrost_parachain_account_id_20); + assert_eq!( + bifrost_parachain_account_id_20_right, + bifrost_parachain_account_id_20 + ); // subaccount_id_0: 0x863c1faef3c3b8f8735ecb7f8ed18996356dd3de let subaccount_id_0_right: [u8; 20] = @@ -80,7 +89,10 @@ fn initialize_moonriver_delegator() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_id_0.0 }, + Junction::AccountKey20 { + network: None, + key: subaccount_id_0.0, + }, ), }; @@ -105,7 +117,11 @@ fn initialize_moonriver_delegator() { Some(mins_and_maxs) )); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), MOVR, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + MOVR, + None + )); assert_eq!(DelegatorNextIndex::::get(MOVR), 1); assert_eq!( DelegatorsIndex2Multilocation::::get(MOVR, 0), @@ -122,11 +138,18 @@ fn moonriver_setup() { let treasury_account_id_32: [u8; 32] = PalletId(*b"bf/trsry").into_account_truncating(); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_account_id_32, + }), }; // set operate_origins - assert_ok!(Slp::set_operate_origin(RuntimeOrigin::signed(ALICE), MOVR, Some(ALICE))); + assert_ok!(Slp::set_operate_origin( + RuntimeOrigin::signed(ALICE), + MOVR, + Some(ALICE) + )); // Set OngoingTimeUnitUpdateInterval as 1/3 round(600 blocks per round, 12 seconds per block) assert_ok!(Slp::set_ongoing_time_unit_update_interval( @@ -145,9 +168,15 @@ fn moonriver_setup() { )); // Initialize currency delays. - let delay = - Delays { unlock_delay: TimeUnit::Round(24), leave_delegators_delay: TimeUnit::Round(24) }; - assert_ok!(Slp::set_currency_delays(RuntimeOrigin::signed(ALICE), MOVR, Some(delay))); + let delay = Delays { + unlock_delay: TimeUnit::Round(24), + leave_delegators_delay: TimeUnit::Round(24), + }; + assert_ok!(Slp::set_currency_delays( + RuntimeOrigin::signed(ALICE), + MOVR, + Some(delay) + )); let mins_and_maxs = MinimumsMaximums { delegator_bonded_minimum: 100_000_000_000, @@ -171,7 +200,11 @@ fn moonriver_setup() { )); // First to setup index-multilocation relationship of subaccount_0 - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), MOVR, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + MOVR, + None + )); // update some MOVR balance to treasury account assert_ok!(Tokens::set_balance( @@ -189,77 +222,101 @@ fn moonriver_setup() { Some((treasury_location, 1_000_000_000_000)), )); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::Bond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::Bond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::BondExtra, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::BondExtra, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::Unbond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::Unbond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::Chill, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::Chill, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::Rebond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::Rebond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::Undelegate, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::Undelegate, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::CancelLeave, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::CancelLeave, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::Liquidize, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::Liquidize, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::ExecuteLeave, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::ExecuteLeave, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::TransferBack, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::TransferBack, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::XtokensTransferBack, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::XtokensTransferBack, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - MOVR, - XcmOperationType::TransferTo, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + MOVR, + XcmOperationType::TransferTo, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); // Set delegator ledger assert_ok!(Slp::add_validator( @@ -282,7 +339,10 @@ fn moonriver_bond_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -314,7 +374,10 @@ fn moonriver_bond_extra_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -368,7 +431,10 @@ fn moonriver_unbond_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -422,7 +488,10 @@ fn moonriver_rebond_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -442,8 +511,10 @@ fn moonriver_rebond_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let moonriver_ledger = OneToManyLedger { @@ -486,7 +557,10 @@ fn moonriver_undelegate_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -540,7 +614,10 @@ fn moonriver_liquidize_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -562,8 +639,10 @@ fn moonriver_liquidize_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let moonriver_ledger = OneToManyLedger { @@ -629,8 +708,10 @@ fn moonriver_liquidize_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(50), 10_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(50), 10_000_000_000_000_000_000), + ); // set delegator_0 ledger let moonriver_ledger = OneToManyLedger { @@ -694,7 +775,10 @@ fn moonriver_bond_and_bond_extra_confirm_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -745,7 +829,10 @@ fn moonriver_bond_and_bond_extra_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 5_000_000_000_000_000_000); @@ -765,7 +852,10 @@ fn moonriver_bond_and_bond_extra_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); // BondExtra confirm let query_id = 1; @@ -792,7 +882,10 @@ fn moonriver_bond_and_bond_extra_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 10_000_000_000_000_000_000); @@ -812,7 +905,10 @@ fn moonriver_bond_and_bond_extra_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); }); } @@ -827,7 +923,10 @@ fn moonriver_unbond_confirm_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -856,7 +955,10 @@ fn moonriver_unbond_confirm_works() { // Set delegator ledger DelegatorLedgers::::insert(MOVR, subaccount_0_location, ledger.clone()); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); // Unbond confirm let query_id = 2; @@ -883,7 +985,10 @@ fn moonriver_unbond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 10_000_000_000_000_000_000); @@ -896,8 +1001,10 @@ fn moonriver_unbond_confirm_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let moonriver_ledger = OneToManyLedger { @@ -912,7 +1019,10 @@ fn moonriver_unbond_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); // Unbond confirm let query_id = 3; @@ -948,7 +1058,10 @@ fn moonriver_unbond_confirm_works() { query_id ),); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); System::set_block_number(500); @@ -983,7 +1096,10 @@ fn moonriver_unbond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 8_000_000_000_000_000_000); @@ -1003,7 +1119,10 @@ fn moonriver_unbond_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); }); } @@ -1018,7 +1137,10 @@ fn moonriver_unbond_all_confirm_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -1047,7 +1169,10 @@ fn moonriver_unbond_all_confirm_works() { DelegatorLedgers::::insert(MOVR, subaccount_0_location, ledger.clone()); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); let query_id = 5; let update_entry_5 = @@ -1082,7 +1207,10 @@ fn moonriver_unbond_all_confirm_works() { query_id ),); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); System::set_block_number(500); @@ -1117,7 +1245,10 @@ fn moonriver_unbond_all_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let empty_delegation_set: BTreeMap> = BTreeMap::new(); let request_briefs_set: BTreeMap)> = @@ -1151,7 +1282,10 @@ fn moonriver_rebond_confirm_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -1171,8 +1305,10 @@ fn moonriver_rebond_confirm_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 2_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 2_000_000_000_000_000_000), + ); // set delegator_0 ledger let moonriver_ledger = OneToManyLedger { @@ -1188,7 +1324,10 @@ fn moonriver_rebond_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); DelegatorLedgers::::insert(MOVR, subaccount_0_location, ledger.clone()); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); let query_id = 7; let update_entry_7 = @@ -1214,7 +1353,10 @@ fn moonriver_rebond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 10_000_000_000_000_000_000); @@ -1234,7 +1376,10 @@ fn moonriver_rebond_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); }); } @@ -1249,7 +1394,10 @@ fn moonriver_undelegate_confirm_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -1303,7 +1451,10 @@ fn moonriver_undelegate_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_0_LOCATION, 5_000_000_000_000_000_000); @@ -1319,8 +1470,10 @@ fn moonriver_undelegate_confirm_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set - .insert(VALIDATOR_0_LOCATION, (TimeUnit::Round(24), 5_000_000_000_000_000_000)); + request_briefs_set.insert( + VALIDATOR_0_LOCATION, + (TimeUnit::Round(24), 5_000_000_000_000_000_000), + ); // set delegator_0 ledger let moonriver_ledger = OneToManyLedger { @@ -1335,7 +1488,10 @@ fn moonriver_undelegate_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); // execute revoke confirm let query_id = 9; @@ -1389,7 +1545,10 @@ fn moonriver_undelegate_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let mut delegation_set: BTreeMap> = BTreeMap::new(); delegation_set.insert(VALIDATOR_1_LOCATION, 5_000_000_000_000_000_000); @@ -1409,7 +1568,10 @@ fn moonriver_undelegate_confirm_works() { let ledger = Ledger::ParachainStaking(moonriver_ledger); - assert_eq!(DelegatorLedgers::::get(MOVR, subaccount_0_location), Some(ledger)); + assert_eq!( + DelegatorLedgers::::get(MOVR, subaccount_0_location), + Some(ledger) + ); }); } @@ -1424,7 +1586,10 @@ fn moonriver_transfer_back_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -1435,7 +1600,10 @@ fn moonriver_transfer_back_works() { let exit_account_location = MultiLocation { parents: 0, - interior: X1(Junction::AccountId32 { network: None, id: exit_account_id_32 }), + interior: X1(Junction::AccountId32 { + network: None, + id: exit_account_id_32, + }), }; assert_noop!( @@ -1463,7 +1631,10 @@ fn moonriver_transfer_to_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -1474,7 +1645,10 @@ fn moonriver_transfer_to_works() { let entrance_account_location = MultiLocation { parents: 0, - interior: X1(Junction::AccountId32 { network: None, id: entrance_account_id_32 }), + interior: X1(Junction::AccountId32 { + network: None, + id: entrance_account_id_32, + }), }; assert_noop!( @@ -1501,7 +1675,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { parents: 1, interior: X2( Parachain(2023), - Junction::AccountKey20 { network: None, key: subaccount_0_account_id_20 }, + Junction::AccountKey20 { + network: None, + key: subaccount_0_account_id_20, + }, ), }; @@ -1558,7 +1735,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { let pct = Permill::from_percent(20); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -1576,7 +1756,11 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { // First set base vtoken exchange rate. Should be 1:1. assert_ok!(Currencies::deposit(VMOVR, &ALICE, 100)); - assert_ok!(Slp::increase_token_pool(RuntimeOrigin::signed(ALICE), MOVR, 100)); + assert_ok!(Slp::increase_token_pool( + RuntimeOrigin::signed(ALICE), + MOVR, + 100 + )); // call the charge_host_fee_and_tune_vtoken_exchange_rate assert_ok!(Slp::charge_host_fee_and_tune_vtoken_exchange_rate( @@ -1660,8 +1844,11 @@ fn reset_validators_should_work() { moonriver_setup(); let validator_list_empty = vec![]; - let validator_list_input = - vec![VALIDATOR_0_LOCATION, VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]; + let validator_list_input = vec![ + VALIDATOR_0_LOCATION, + VALIDATOR_0_LOCATION, + VALIDATOR_1_LOCATION, + ]; let validator_list_output = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]).unwrap(); @@ -1671,9 +1858,16 @@ fn reset_validators_should_work() { Error::::ValidatorNotProvided ); - assert_ok!(Slp::reset_validators(RuntimeOrigin::signed(ALICE), MOVR, validator_list_input)); + assert_ok!(Slp::reset_validators( + RuntimeOrigin::signed(ALICE), + MOVR, + validator_list_input + )); - assert_eq!(Validators::::get(MOVR), Some(validator_list_output)); + assert_eq!( + Validators::::get(MOVR), + Some(validator_list_output) + ); }); } @@ -1684,8 +1878,11 @@ fn set_validator_boost_list_should_work() { let validator_list_empty = vec![]; let validator_list_input_1 = vec![VALIDATOR_0_LOCATION]; - let validator_list_input_2 = - vec![VALIDATOR_0_LOCATION, VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]; + let validator_list_input_2 = vec![ + VALIDATOR_0_LOCATION, + VALIDATOR_0_LOCATION, + VALIDATOR_1_LOCATION, + ]; let validator_list_output_1 = BoundedVec::try_from(vec![(VALIDATOR_0_LOCATION, SIX_MONTHS as u64 + 300)]).unwrap(); @@ -1709,7 +1906,10 @@ fn set_validator_boost_list_should_work() { let bounded_validator_list_output_1 = BoundedVec::try_from(validator_list_output_1).unwrap(); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(bounded_validator_list_output_1)); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(bounded_validator_list_output_1) + ); let bounded_validator_0 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION]).unwrap(); assert_eq!(Validators::::get(MOVR), Some(bounded_validator_0)); @@ -1723,10 +1923,16 @@ fn set_validator_boost_list_should_work() { let bounded_validator_list_output_2 = BoundedVec::try_from(validator_list_output_2).unwrap(); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(bounded_validator_list_output_2)); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(bounded_validator_list_output_2) + ); let bounded_validator_0_1 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MOVR), Some(bounded_validator_0_1),); + assert_eq!( + Validators::::get(MOVR), + Some(bounded_validator_0_1), + ); }); } @@ -1743,7 +1949,10 @@ fn add_to_validator_boost_list_should_work() { )]) .unwrap(); let validator_list_output_3 = BoundedVec::try_from(vec![ - (VALIDATOR_0_LOCATION, SIX_MONTHS as u64 + 300 + SIX_MONTHS as u64), + ( + VALIDATOR_0_LOCATION, + SIX_MONTHS as u64 + 300 + SIX_MONTHS as u64, + ), (VALIDATOR_1_LOCATION, SIX_MONTHS as u64 + 400), ]) .unwrap(); @@ -1754,10 +1963,16 @@ fn add_to_validator_boost_list_should_work() { Box::new(VALIDATOR_0_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(validator_list_output_1)); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(validator_list_output_1) + ); let bounded_validator_0 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MOVR), Some(bounded_validator_0.clone())); + assert_eq!( + Validators::::get(MOVR), + Some(bounded_validator_0.clone()) + ); System::set_block_number(400); @@ -1769,7 +1984,10 @@ fn add_to_validator_boost_list_should_work() { assert_eq!(Validators::::get(MOVR), Some(bounded_validator_0)); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(validator_list_output_2)); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(validator_list_output_2) + ); assert_ok!(Slp::add_to_validator_boost_list( RuntimeOrigin::signed(ALICE), @@ -1777,10 +1995,16 @@ fn add_to_validator_boost_list_should_work() { Box::new(VALIDATOR_1_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(validator_list_output_3)); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(validator_list_output_3) + ); let bounded_validator_0_1 = BoundedVec::try_from(vec![VALIDATOR_0_LOCATION, VALIDATOR_1_LOCATION]).unwrap(); - assert_eq!(Validators::::get(MOVR), Some(bounded_validator_0_1),); + assert_eq!( + Validators::::get(MOVR), + Some(bounded_validator_0_1), + ); }); } @@ -1798,7 +2022,10 @@ fn remove_from_validator_boost_list_should_work() { Box::new(VALIDATOR_0_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(validator_list_output.clone())); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(validator_list_output.clone()) + ); assert_ok!(Slp::remove_from_validator_boot_list( RuntimeOrigin::signed(ALICE), @@ -1806,7 +2033,10 @@ fn remove_from_validator_boost_list_should_work() { Box::new(VALIDATOR_1_LOCATION) )); - assert_eq!(ValidatorBoostList::::get(MOVR), Some(validator_list_output)); + assert_eq!( + ValidatorBoostList::::get(MOVR), + Some(validator_list_output) + ); assert_ok!(Slp::remove_from_validator_boot_list( RuntimeOrigin::signed(ALICE), diff --git a/pallets/slp/src/tests/parachain_staking_tests.rs b/pallets/slp/src/tests/parachain_staking_tests.rs index 8dba07be97..83b6e9a305 100644 --- a/pallets/slp/src/tests/parachain_staking_tests.rs +++ b/pallets/slp/src/tests/parachain_staking_tests.rs @@ -55,23 +55,39 @@ fn initialize_parachain_staking_delegator() { Some(mins_and_maxs) )); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), BNC, None,)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + BNC, + None, + )); assert_eq!(DelegatorNextIndex::::get(BNC), 1); }); } fn parachain_staking_setup() { - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; let treasury_account_id_32: [u8; 32] = PalletId(*b"bf/trsry").into_account_truncating(); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_account_id_32, + }), }; // set operate_origins - assert_ok!(Slp::set_operate_origin(RuntimeOrigin::signed(ALICE), BNC, Some(ALICE))); + assert_ok!(Slp::set_operate_origin( + RuntimeOrigin::signed(ALICE), + BNC, + Some(ALICE) + )); // Set OngoingTimeUnitUpdateInterval as 1/3 round(600 blocks per round, 12 seconds per block) assert_ok!(Slp::set_ongoing_time_unit_update_interval( @@ -90,9 +106,15 @@ fn parachain_staking_setup() { )); // Initialize currency delays. - let delay = - Delays { unlock_delay: TimeUnit::Round(24), leave_delegators_delay: TimeUnit::Round(24) }; - assert_ok!(Slp::set_currency_delays(RuntimeOrigin::signed(ALICE), BNC, Some(delay))); + let delay = Delays { + unlock_delay: TimeUnit::Round(24), + leave_delegators_delay: TimeUnit::Round(24), + }; + assert_ok!(Slp::set_currency_delays( + RuntimeOrigin::signed(ALICE), + BNC, + Some(delay) + )); let mins_and_maxs = MinimumsMaximums { delegator_bonded_minimum: 100_000_000_000, @@ -116,7 +138,11 @@ fn parachain_staking_setup() { )); // First to setup index-multilocation relationship of subaccount_0 - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), BNC, None,)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + BNC, + None, + )); // update some BNC balance to treasury account assert_ok!(Currencies::update_balance( @@ -147,165 +173,203 @@ fn parachain_staking_setup() { fn parachain_staking_bond_to_liquidize_works() { env_logger::try_init().unwrap_or(()); - let subaccount_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: ALICE.into() }) }; - - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; - - ExtBuilder::default().init_for_alice_n_bob().build().execute_with(|| { - // environment setup - parachain_staking_setup(); - initialize_parachain_staking_delegator(); - env_logger::try_init().unwrap_or(()); - - DelegatorsIndex2Multilocation::::insert(BNC, 0, subaccount_0_location); - DelegatorsMultilocation2Index::::insert(BNC, subaccount_0_location, 0); - - assert_ok!(ParachainStaking::join_candidates( - RuntimeOrigin::signed(BOB), - 10_000_000_000_000u128, - 10_000_000u32 - )); - assert_ok!(ParachainStaking::join_candidates( - RuntimeOrigin::signed(CHARLIE), - 10_000_000_000_000u128, - 10_000_000u32 - )); - - let entrance_account_id_32: [u8; 32] = PalletId(*b"bf/vtkin").into_account_truncating(); - - let entrance_account_location = MultiLocation { - parents: 0, - interior: X1(AccountId32 { network: None, id: entrance_account_id_32 }), - }; - let entrance_account = AccountId::new(entrance_account_id_32); - assert_eq!(Balances::free_balance(&entrance_account), 100000000000000); - - assert_ok!(Slp::transfer_to( - RuntimeOrigin::signed(ALICE), - BNC, - Box::new(entrance_account_location), - Box::new(subaccount_0_location), - 5_000_000_000_000, - )); - assert_ok!(Slp::bond( - RuntimeOrigin::signed(ALICE), - BNC, - Box::new(subaccount_0_location), - 5_000_000_000_000, - Some(validator_0_location), - None - )); - assert_ok!(Slp::bond_extra( - RuntimeOrigin::signed(ALICE), - BNC, - Box::new(subaccount_0_location), - Some(validator_0_location), - 5_000_000_000_000, - None - )); - assert_ok!(Slp::unbond( - RuntimeOrigin::signed(ALICE), - BNC, - Box::new(subaccount_0_location), - Some(validator_0_location), - 2_000_000_000_000, - None - )); - - let mut delegation_set: BTreeMap> = BTreeMap::new(); - delegation_set.insert(validator_0_location, 10_000_000_000_000); - - let request = OneToManyScheduledRequest { - validator: validator_0_location, - when_executable: TimeUnit::Round(50), - action: OneToManyDelegationAction::Revoke(10_000_000_000_000), - }; - - let mut request_list = Vec::new(); - - // random account to test ordering - let validator_10: [u8; 32] = - hex_literal::hex!["6d6f646c62662f76746b696e0000000000000000000000000000000000000000"] - .into(); - let validator_10_location = MultiLocation { - parents: 0, - interior: X1(AccountId32 { network: None, id: validator_10 }), - }; - let request10 = OneToManyScheduledRequest { - validator: validator_10_location, - when_executable: TimeUnit::Round(50), - action: OneToManyDelegationAction::Revoke(10_000_000_000_000), - }; - - // random account to test ordering - let validator_11: [u8; 32] = - hex_literal::hex!["624d6a004c72a1abcf93131e185515ebe1410e43a301fe1f25d20d8da345376e"] - .into(); - let validator_11_location = MultiLocation { - parents: 0, - interior: X1(AccountId32 { network: None, id: validator_11 }), - }; - let request11 = OneToManyScheduledRequest { - validator: validator_11_location, - when_executable: TimeUnit::Round(50), - action: OneToManyDelegationAction::Revoke(10_000_000_000_000), - }; - request_list.push(request11); - request_list.push(request10); - request_list.push(request); + let subaccount_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: ALICE.into(), + }), + }; - let mut request_briefs_set: BTreeMap)> = - BTreeMap::new(); - request_briefs_set.insert(validator_0_location, (TimeUnit::Round(50), 10_000_000_000_000)); - // set delegator_0 ledger - let parachain_staking_ledger2 = OneToManyLedger { - account: subaccount_0_location, - total: 10_000_000_000_000, - less_total: 10_000_000_000_000, - delegations: delegation_set, - requests: request_list, - request_briefs: request_briefs_set, - status: OneToManyDelegatorStatus::Active, - }; - let ledger2 = Ledger::ParachainStaking(parachain_staking_ledger2); - DelegatorLedgers::::insert(BNC, subaccount_0_location, ledger2.clone()); + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; - System::set_block_number(700_000); - assert_ok!(Slp::update_ongoing_time_unit( - RuntimeOrigin::signed(ALICE), - BNC, - TimeUnit::Round(48) - )); - bifrost_parachain_staking::Round::::set(RoundInfo::new(10000000, 0, 1)); - assert_eq!(Round::::get(), RoundInfo::new(10000000, 0, 1)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(BNC, TimeUnit::Round(1000))); + ExtBuilder::default() + .init_for_alice_n_bob() + .build() + .execute_with(|| { + // environment setup + parachain_staking_setup(); + initialize_parachain_staking_delegator(); + env_logger::try_init().unwrap_or(()); + + DelegatorsIndex2Multilocation::::insert(BNC, 0, subaccount_0_location); + DelegatorsMultilocation2Index::::insert(BNC, subaccount_0_location, 0); + + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(BOB), + 10_000_000_000_000u128, + 10_000_000u32 + )); + assert_ok!(ParachainStaking::join_candidates( + RuntimeOrigin::signed(CHARLIE), + 10_000_000_000_000u128, + 10_000_000u32 + )); + + let entrance_account_id_32: [u8; 32] = PalletId(*b"bf/vtkin").into_account_truncating(); + + let entrance_account_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: entrance_account_id_32, + }), + }; + let entrance_account = AccountId::new(entrance_account_id_32); + assert_eq!(Balances::free_balance(&entrance_account), 100000000000000); + + assert_ok!(Slp::transfer_to( + RuntimeOrigin::signed(ALICE), + BNC, + Box::new(entrance_account_location), + Box::new(subaccount_0_location), + 5_000_000_000_000, + )); + assert_ok!(Slp::bond( + RuntimeOrigin::signed(ALICE), + BNC, + Box::new(subaccount_0_location), + 5_000_000_000_000, + Some(validator_0_location), + None + )); + assert_ok!(Slp::bond_extra( + RuntimeOrigin::signed(ALICE), + BNC, + Box::new(subaccount_0_location), + Some(validator_0_location), + 5_000_000_000_000, + None + )); + assert_ok!(Slp::unbond( + RuntimeOrigin::signed(ALICE), + BNC, + Box::new(subaccount_0_location), + Some(validator_0_location), + 2_000_000_000_000, + None + )); + + let mut delegation_set: BTreeMap> = BTreeMap::new(); + delegation_set.insert(validator_0_location, 10_000_000_000_000); + + let request = OneToManyScheduledRequest { + validator: validator_0_location, + when_executable: TimeUnit::Round(50), + action: OneToManyDelegationAction::Revoke(10_000_000_000_000), + }; + + let mut request_list = Vec::new(); + + // random account to test ordering + let validator_10: [u8; 32] = hex_literal::hex![ + "6d6f646c62662f76746b696e0000000000000000000000000000000000000000" + ] + .into(); + let validator_10_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: validator_10, + }), + }; + let request10 = OneToManyScheduledRequest { + validator: validator_10_location, + when_executable: TimeUnit::Round(50), + action: OneToManyDelegationAction::Revoke(10_000_000_000_000), + }; + + // random account to test ordering + let validator_11: [u8; 32] = hex_literal::hex![ + "624d6a004c72a1abcf93131e185515ebe1410e43a301fe1f25d20d8da345376e" + ] + .into(); + let validator_11_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: validator_11, + }), + }; + let request11 = OneToManyScheduledRequest { + validator: validator_11_location, + when_executable: TimeUnit::Round(50), + action: OneToManyDelegationAction::Revoke(10_000_000_000_000), + }; + request_list.push(request11); + request_list.push(request10); + request_list.push(request); + + let mut request_briefs_set: BTreeMap)> = + BTreeMap::new(); + request_briefs_set.insert( + validator_0_location, + (TimeUnit::Round(50), 10_000_000_000_000), + ); + // set delegator_0 ledger + let parachain_staking_ledger2 = OneToManyLedger { + account: subaccount_0_location, + total: 10_000_000_000_000, + less_total: 10_000_000_000_000, + delegations: delegation_set, + requests: request_list, + request_briefs: request_briefs_set, + status: OneToManyDelegatorStatus::Active, + }; + let ledger2 = Ledger::ParachainStaking(parachain_staking_ledger2); + DelegatorLedgers::::insert(BNC, subaccount_0_location, ledger2.clone()); + + System::set_block_number(700_000); + assert_ok!(Slp::update_ongoing_time_unit( + RuntimeOrigin::signed(ALICE), + BNC, + TimeUnit::Round(48) + )); + bifrost_parachain_staking::Round::::set(RoundInfo::new(10000000, 0, 1)); + assert_eq!(Round::::get(), RoundInfo::new(10000000, 0, 1)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + BNC, + TimeUnit::Round(1000) + )); - // let delegation_scheduled_requests = ParachainStaking::delegation_scheduled_requests(BOB); - // log::debug!("test5{:?}", delegation_scheduled_requests); + // let delegation_scheduled_requests = ParachainStaking::delegation_scheduled_requests(BOB); + // log::debug!("test5{:?}", delegation_scheduled_requests); - assert_ok!(Slp::liquidize( - RuntimeOrigin::signed(ALICE), - BNC, - Box::new(subaccount_0_location), - None, - Some(validator_0_location), - None, - None - )); - }); + assert_ok!(Slp::liquidize( + RuntimeOrigin::signed(ALICE), + BNC, + Box::new(subaccount_0_location), + None, + Some(validator_0_location), + None, + None + )); + }); } #[test] fn parachain_staking_bond_extra_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -350,11 +414,19 @@ fn parachain_staking_bond_extra_works() { fn parachain_staking_unbond_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -399,11 +471,19 @@ fn parachain_staking_unbond_works() { fn parachain_staking_unbond_all_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -446,11 +526,19 @@ fn parachain_staking_unbond_all_works() { fn parachain_staking_rebond_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -468,7 +556,10 @@ fn parachain_staking_rebond_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set.insert(validator_0_location, (TimeUnit::Round(24), 2_000_000_000_000)); + request_briefs_set.insert( + validator_0_location, + (TimeUnit::Round(24), 2_000_000_000_000), + ); // set delegator_0 ledger let parachain_staking_ledger = OneToManyLedger { @@ -504,14 +595,27 @@ fn parachain_staking_rebond_works() { fn parachain_staking_undelegate_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; - let validator_1_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: DAVE.into() }) }; + let validator_1_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: DAVE.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -556,11 +660,19 @@ fn parachain_staking_undelegate_works() { fn parachain_staking_redelegate_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -578,7 +690,10 @@ fn parachain_staking_redelegate_works() { request_list.push(request); let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set.insert(validator_0_location, (TimeUnit::Round(24), 8_000_000_000_000)); + request_briefs_set.insert( + validator_0_location, + (TimeUnit::Round(24), 8_000_000_000_000), + ); // set delegator_0 ledger let parachain_staking_ledger = OneToManyLedger { @@ -613,11 +728,19 @@ fn parachain_staking_redelegate_works() { fn parachain_staking_liquidize_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -637,7 +760,10 @@ fn parachain_staking_liquidize_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set.insert(validator_0_location, (TimeUnit::Round(24), 2_000_000_000_000)); + request_briefs_set.insert( + validator_0_location, + (TimeUnit::Round(24), 2_000_000_000_000), + ); // set delegator_0 ledger let parachain_staking_ledger = OneToManyLedger { @@ -703,9 +829,16 @@ fn parachain_staking_liquidize_works() { let mut request_briefs_set: BTreeMap)> = BTreeMap::new(); - request_briefs_set.insert(validator_0_location, (TimeUnit::Round(50), 10_000_000_000_000)); + request_briefs_set.insert( + validator_0_location, + (TimeUnit::Round(50), 10_000_000_000_000), + ); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), BNC, None,)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + BNC, + None, + )); assert_noop!( Slp::bond( @@ -773,7 +906,10 @@ fn parachain_staking_liquidize_works() { fn parachain_staking_transfer_back_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; ExtBuilder::default().build().execute_with(|| { @@ -783,7 +919,10 @@ fn parachain_staking_transfer_back_works() { let exit_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: exit_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: exit_account_id_32, + }), }; DelegatorsIndex2Multilocation::::insert(BNC, 0, subaccount_0_location); @@ -811,7 +950,10 @@ fn parachain_staking_transfer_back_works() { fn parachain_staking_transfer_to_works() { let subaccount_0_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: CHARLIE.into() }), + interior: X1(AccountId32 { + network: None, + id: CHARLIE.into(), + }), }; ExtBuilder::default().build().execute_with(|| { @@ -822,7 +964,10 @@ fn parachain_staking_transfer_to_works() { let entrance_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: entrance_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: entrance_account_id_32, + }), }; DelegatorsIndex2Multilocation::::insert(BNC, 0, subaccount_0_location); @@ -847,8 +992,13 @@ fn parachain_staking_transfer_to_works() { #[test] fn add_validator_and_remove_validator_works() { - let validator_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: BOB.into() }) }; + let validator_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: BOB.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { let mut valis = vec![]; @@ -900,8 +1050,13 @@ fn add_validator_and_remove_validator_works() { #[test] fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { - let subaccount_0_location = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: ALICE.into() }) }; + let subaccount_0_location = MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: None, + id: ALICE.into(), + }), + }; ExtBuilder::default().build().execute_with(|| { // environment setup @@ -909,14 +1064,21 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { // First set base vtoken exchange rate. Should be 1:1. assert_ok!(Currencies::deposit(VBNC, &ALICE, 1000)); - assert_ok!(Slp::increase_token_pool(RuntimeOrigin::signed(ALICE), BNC, 1000)); + assert_ok!(Slp::increase_token_pool( + RuntimeOrigin::signed(ALICE), + BNC, + 1000 + )); // Set the hosting fee to be 20%, and the beneficiary to be bifrost treasury account. let pct = Permill::from_percent(20); let treasury_account_id_32: [u8; 32] = PalletId(*b"bf/trsry").into_account_truncating(); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_account_id_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -941,7 +1103,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { )); // check token pool, should be 1000 + 1000 = 2000 - assert_eq!(::VtokenMinting::get_token_pool(BNC), 2000); + assert_eq!( + ::VtokenMinting::get_token_pool(BNC), + 2000 + ); // check vBNC issuance, should be 1000 + 20% * 1000 = 1200 assert_eq!(Currencies::total_issuance(VBNC), 1200); }); diff --git a/pallets/slp/src/tests/phala_tests.rs b/pallets/slp/src/tests/phala_tests.rs index 1f8589918b..1cc1687cbf 100644 --- a/pallets/slp/src/tests/phala_tests.rs +++ b/pallets/slp/src/tests/phala_tests.rs @@ -32,17 +32,27 @@ use sp_core::crypto::Ss58Codec; use sp_runtime::traits::AccountIdConversion; // parents 0 means vault, parents 1 means stake_pool -const VALIDATOR_0_LOCATION: MultiLocation = - MultiLocation { parents: 0, interior: X2(GeneralIndex(0), GeneralIndex(0)) }; +const VALIDATOR_0_LOCATION: MultiLocation = MultiLocation { + parents: 0, + interior: X2(GeneralIndex(0), GeneralIndex(0)), +}; const VALIDATOR_0_ACCOUNT_ID_32: [u8; 32] = hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]; const VALIDATOR_0_LOCATION_WRONG: MultiLocation = MultiLocation { parents: 1, - interior: X2(Parachain(2004), AccountId32 { network: None, id: VALIDATOR_0_ACCOUNT_ID_32 }), + interior: X2( + Parachain(2004), + AccountId32 { + network: None, + id: VALIDATOR_0_ACCOUNT_ID_32, + }, + ), }; -const VALIDATOR_1_LOCATION: MultiLocation = - MultiLocation { parents: 0, interior: X2(GeneralIndex(1), GeneralIndex(1)) }; +const VALIDATOR_1_LOCATION: MultiLocation = MultiLocation { + parents: 0, + interior: X2(GeneralIndex(1), GeneralIndex(1)), +}; #[test] fn initialize_phala_delegator_works() { @@ -53,7 +63,10 @@ fn initialize_phala_delegator_works() { .into(); let bifrost_parachain_account_id_32: AccountId = Sibling::from(2001).into_account_truncating(); - assert_eq!(bifrost_parachain_account_id_32_right, bifrost_parachain_account_id_32); + assert_eq!( + bifrost_parachain_account_id_32_right, + bifrost_parachain_account_id_32 + ); // subaccount_id_0: 41YcGwBLwxbFV7VfbF6zYGgUnYbt96dHcA2DWruRJkWtANFD let subaccount_id_0_right: AccountId = @@ -79,7 +92,10 @@ fn initialize_phala_delegator_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_id_0.into() }, + AccountId32 { + network: None, + id: subaccount_id_0.into(), + }, ), }; @@ -104,7 +120,11 @@ fn initialize_phala_delegator_works() { Some(mins_and_maxs) )); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), PHA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + PHA, + None + )); assert_eq!(DelegatorNextIndex::::get(PHA), 1); assert_eq!( DelegatorsIndex2Multilocation::::get(PHA, 0), @@ -130,7 +150,11 @@ fn add_validator_works() { ); assert_noop!( - Slp::add_validator(RuntimeOrigin::signed(ALICE), PHA, Box::new(VALIDATOR_0_LOCATION)), + Slp::add_validator( + RuntimeOrigin::signed(ALICE), + PHA, + Box::new(VALIDATOR_0_LOCATION) + ), Error::::NotExist ); @@ -172,7 +196,13 @@ fn phala_delegate_works() { let subaccount_0_location = MultiLocation { parents: 1, - interior: X2(Parachain(2004), AccountId32 { network: None, id: subaccount_id_0.into() }), + interior: X2( + Parachain(2004), + AccountId32 { + network: None, + id: subaccount_id_0.into(), + }, + ), }; ExtBuilder::default().build().execute_with(|| { @@ -190,7 +220,11 @@ fn phala_delegate_works() { Error::::DelegatorNotExist ); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), PHA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + PHA, + None + )); assert_noop!( Slp::delegate( @@ -274,7 +308,11 @@ fn phala_delegate_works() { fn initialize_preparation_setup() { // set operate_origins - assert_ok!(Slp::set_operate_origin(RuntimeOrigin::signed(ALICE), PHA, Some(ALICE))); + assert_ok!(Slp::set_operate_origin( + RuntimeOrigin::signed(ALICE), + PHA, + Some(ALICE) + )); // Set OngoingTimeUnitUpdateInterval as 1/3 Hour(300 blocks per hour, 12 seconds per block) assert_ok!(Slp::set_ongoing_time_unit_update_interval( @@ -286,12 +324,22 @@ fn initialize_preparation_setup() { System::set_block_number(300); // Initialize ongoing timeunit as 1. - assert_ok!(Slp::update_ongoing_time_unit(RuntimeOrigin::signed(ALICE), PHA, TimeUnit::Hour(1))); + assert_ok!(Slp::update_ongoing_time_unit( + RuntimeOrigin::signed(ALICE), + PHA, + TimeUnit::Hour(1) + )); // Initialize currency delays.21 days = 21 *24 = 504 hours - let delay = - Delays { unlock_delay: TimeUnit::Hour(504), leave_delegators_delay: TimeUnit::Hour(504) }; - assert_ok!(Slp::set_currency_delays(RuntimeOrigin::signed(ALICE), PHA, Some(delay))); + let delay = Delays { + unlock_delay: TimeUnit::Hour(504), + leave_delegators_delay: TimeUnit::Hour(504), + }; + assert_ok!(Slp::set_currency_delays( + RuntimeOrigin::signed(ALICE), + PHA, + Some(delay) + )); let mins_and_maxs = MinimumsMaximums { delegator_bonded_minimum: 1_000_000_000_000, @@ -319,7 +367,10 @@ fn phala_xcm_setup() { let treasury_account_id_32: [u8; 32] = PalletId(*b"bf/trsry").into_account_truncating(); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_account_id_32, + }), }; // update some PHA balance to treasury account @@ -338,35 +389,45 @@ fn phala_xcm_setup() { Some((treasury_location, 1_000_000_000_000)), )); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - PHA, - XcmOperationType::Bond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + PHA, + XcmOperationType::Bond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - PHA, - XcmOperationType::Unbond, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + PHA, + XcmOperationType::Unbond, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - PHA, - XcmOperationType::TransferBack, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + PHA, + XcmOperationType::TransferBack, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - PHA, - XcmOperationType::TransferTo, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + PHA, + XcmOperationType::TransferTo, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); - assert_ok!(::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - PHA, - XcmOperationType::ConvertAsset, - Some((20_000_000_000.into(), 10_000_000_000)), - )); + assert_ok!( + ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( + PHA, + XcmOperationType::ConvertAsset, + Some((20_000_000_000.into(), 10_000_000_000)), + ) + ); } fn phala_setup() { @@ -377,13 +438,23 @@ fn phala_setup() { let subaccount_0_location = MultiLocation { parents: 1, - interior: X2(Parachain(2004), AccountId32 { network: None, id: subaccount_id_0.into() }), + interior: X2( + Parachain(2004), + AccountId32 { + network: None, + id: subaccount_id_0.into(), + }, + ), }; initialize_preparation_setup(); // First to setup index-multilocation relationship of subaccount_0 - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), PHA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + PHA, + None + )); phala_xcm_setup(); @@ -415,13 +486,18 @@ fn phala_bond_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32 }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32, + }, ), }; ExtBuilder::default().build().execute_with(|| { - let share_price_multilocation = - MultiLocation { parents: 1, interior: X2(GeneralIndex(2000), GeneralIndex(1000)) }; + let share_price_multilocation = MultiLocation { + parents: 1, + interior: X2(GeneralIndex(2000), GeneralIndex(1000)), + }; assert_noop!( Slp::bond( @@ -437,7 +513,11 @@ fn phala_bond_works() { // intialize a delegator initialize_preparation_setup(); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), PHA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + PHA, + None + )); assert_noop!( Slp::bond( @@ -540,12 +620,20 @@ fn phala_unbond_works() { let subaccount_0_location = MultiLocation { parents: 1, - interior: X2(Parachain(2004), AccountId32 { network: None, id: subaccount_id_0.into() }), + interior: X2( + Parachain(2004), + AccountId32 { + network: None, + id: subaccount_id_0.into(), + }, + ), }; ExtBuilder::default().build().execute_with(|| { - let share_price_multilocation = - MultiLocation { parents: 1, interior: X2(GeneralIndex(1000), GeneralIndex(1000)) }; + let share_price_multilocation = MultiLocation { + parents: 1, + interior: X2(GeneralIndex(1000), GeneralIndex(1000)), + }; assert_noop!( Slp::unbond( @@ -698,13 +786,18 @@ fn phala_rebond_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; ExtBuilder::default().build().execute_with(|| { - let share_price_multilocation = - MultiLocation { parents: 1, interior: X2(GeneralIndex(2000), GeneralIndex(1000)) }; + let share_price_multilocation = MultiLocation { + parents: 1, + interior: X2(GeneralIndex(2000), GeneralIndex(1000)), + }; // environment setup phala_setup(); @@ -758,7 +851,10 @@ fn phala_undelegate_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -862,7 +958,10 @@ fn phala_redelegate_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -936,7 +1035,10 @@ fn phala_liquidize_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1031,7 +1133,10 @@ fn phala_bond_confirm_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1080,7 +1185,10 @@ fn phala_bond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let ledger_new = PhalaLedger::> { account: subaccount_0_location, @@ -1110,7 +1218,10 @@ fn phala_unbond_confirm_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1158,7 +1269,10 @@ fn phala_unbond_confirm_works() { query_id )); - assert_eq!(DelegatorLedgerXcmUpdateQueue::::get(query_id), None); + assert_eq!( + DelegatorLedgerXcmUpdateQueue::::get(query_id), + None + ); let ledger_new = PhalaLedger::> { account: subaccount_0_location, @@ -1188,7 +1302,10 @@ fn phala_transfer_back_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1201,7 +1318,10 @@ fn phala_transfer_back_works() { let exit_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: exit_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: exit_account_id_32, + }), }; assert_noop!( @@ -1241,7 +1361,10 @@ fn phala_transfer_to_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1254,7 +1377,10 @@ fn phala_transfer_to_works() { let entrance_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: entrance_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: entrance_account_id_32, + }), }; let exit_account_id_32: [u8; 32] = @@ -1263,7 +1389,10 @@ fn phala_transfer_to_works() { let exit_account_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: exit_account_id_32 }), + interior: X1(AccountId32 { + network: None, + id: exit_account_id_32, + }), }; assert_noop!( @@ -1301,7 +1430,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1331,7 +1463,10 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { let pct = Permill::from_percent(20); let treasury_location = MultiLocation { parents: 0, - interior: X1(AccountId32 { network: None, id: treasury_32 }), + interior: X1(AccountId32 { + network: None, + id: treasury_32, + }), }; assert_ok!(Slp::set_hosting_fees( @@ -1349,7 +1484,11 @@ fn charge_host_fee_and_tune_vtoken_exchange_rate_works() { // First set base vtoken exchange rate. Should be 1:1. assert_ok!(Currencies::deposit(VPHA, &ALICE, 100)); - assert_ok!(Slp::increase_token_pool(RuntimeOrigin::signed(ALICE), PHA, 100)); + assert_ok!(Slp::increase_token_pool( + RuntimeOrigin::signed(ALICE), + PHA, + 100 + )); // call the charge_host_fee_and_tune_vtoken_exchange_rate assert_ok!(Slp::charge_host_fee_and_tune_vtoken_exchange_rate( @@ -1387,7 +1526,10 @@ fn add_validator_and_remove_validator_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; @@ -1396,7 +1538,11 @@ fn add_validator_and_remove_validator_works() { initialize_preparation_setup(); - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::signed(ALICE), PHA, None)); + assert_ok!(Slp::initialize_delegator( + RuntimeOrigin::signed(ALICE), + PHA, + None + )); // Set delegator ledger assert_ok!(Slp::add_validator( @@ -1441,7 +1587,10 @@ fn phala_convert_asset_works() { parents: 1, interior: X2( Parachain(2004), - AccountId32 { network: None, id: subaccount_0_account_id_32.into() }, + AccountId32 { + network: None, + id: subaccount_0_account_id_32.into(), + }, ), }; diff --git a/pallets/slpx/src/benchmarking.rs b/pallets/slpx/src/benchmarking.rs index b20ced5ba8..a36525abda 100644 --- a/pallets/slpx/src/benchmarking.rs +++ b/pallets/slpx/src/benchmarking.rs @@ -76,7 +76,10 @@ mod benchmarks { #[extrinsic_call] _(RawOrigin::Root, SupportChain::Astar, address); - assert_eq!(WhitelistAccountId::::get(SupportChain::Astar).first(), None); + assert_eq!( + WhitelistAccountId::::get(SupportChain::Astar).first(), + None + ); } #[benchmark] @@ -84,7 +87,10 @@ mod benchmarks { #[extrinsic_call] _(RawOrigin::Root, CurrencyId::Token2(0), 10u32.into()); - assert_eq!(ExecutionFee::::get(CurrencyId::Token2(0)), Some(10u32.into())); + assert_eq!( + ExecutionFee::::get(CurrencyId::Token2(0)), + Some(10u32.into()) + ); } #[benchmark] @@ -92,7 +98,10 @@ mod benchmarks { #[extrinsic_call] _(RawOrigin::Root, SupportChain::Moonbeam, 10u32.into()); - assert_eq!(TransferToFee::::get(SupportChain::Moonbeam), Some(10u32.into())); + assert_eq!( + TransferToFee::::get(SupportChain::Moonbeam), + Some(10u32.into()) + ); } #[benchmark] @@ -128,7 +137,12 @@ mod benchmarks { fn redeem() { let (caller, receiver) = init_whitelist::(); #[extrinsic_call] - _(RawOrigin::Signed(caller), receiver, VKSM, TargetChain::Astar(receiver)); + _( + RawOrigin::Signed(caller), + receiver, + VKSM, + TargetChain::Astar(receiver), + ); } #[benchmark] diff --git a/pallets/slpx/src/lib.rs b/pallets/slpx/src/lib.rs index 3d3f0d3993..bdbe9b5b5a 100644 --- a/pallets/slpx/src/lib.rs +++ b/pallets/slpx/src/lib.rs @@ -49,7 +49,9 @@ use parity_scale_codec::{Decode, Encode}; use polkadot_parachain_primitives::primitives::{Id, Sibling}; use sp_core::{Hasher, H160, U256}; use sp_runtime::{ - traits::{AccountIdConversion, BlakeTwo256, CheckedSub, UniqueSaturatedFrom}, + traits::{ + AccountIdConversion, BlakeTwo256, BlockNumberProvider, CheckedSub, UniqueSaturatedFrom, + }, BoundedVec, DispatchError, }; use sp_std::{vec, vec::Vec}; @@ -81,6 +83,7 @@ pub mod pallet { weights::WeightMeter, }; use frame_system::ensure_root; + use sp_runtime::traits::BlockNumberProvider; const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); @@ -104,7 +107,8 @@ pub mod pallet { CurrencyIdOf, BalanceOf, >; - + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; /// xtokens xcm transfer interface type XcmTransfer: XcmTransfer, BalanceOf, CurrencyIdOf>; /// Send Xcm @@ -302,7 +306,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_idle(n: BlockNumberFor, limit: Weight) -> Weight { + fn on_idle(_: BlockNumberFor, limit: Weight) -> Weight { let mut weight = Weight::default(); if WeightMeter::with_limit(limit) @@ -312,14 +316,19 @@ pub mod pallet { return weight; } + let current_block_number = T::BlockNumberProvider::current_block_number(); let mut is_handle_xcm_oracle = false; - if let Err(error) = Self::handle_xcm_oracle(n, &mut is_handle_xcm_oracle, &mut weight) { + if let Err(error) = Self::handle_xcm_oracle( + current_block_number, + &mut is_handle_xcm_oracle, + &mut weight, + ) { Self::deposit_event(Event::::XcmOracleFailed { error }); } if !is_handle_xcm_oracle { - let _ = Self::handle_order_queue(n, &mut weight); + let _ = Self::handle_order_queue(current_block_number, &mut weight); } weight } @@ -417,7 +426,10 @@ pub mod pallet { support_chain, |whitelist| -> DispatchResultWithPostInfo { let account = Self::xcm_derivative_account(support_chain, contract_address)?; - ensure!(!whitelist.contains(&account), Error::::AccountAlreadyExists); + ensure!( + !whitelist.contains(&account), + Error::::AccountAlreadyExists + ); whitelist .try_push(account.clone()) .map_err(|_| Error::::WhitelistOverflow)?; @@ -475,7 +487,10 @@ pub mod pallet { // Check the validity of origin T::ControlOrigin::ensure_origin(origin)?; ExecutionFee::::insert(currency_id, execution_fee); - Self::deposit_event(Event::SetExecutionFee { currency_id, execution_fee }); + Self::deposit_event(Event::SetExecutionFee { + currency_id, + execution_fee, + }); Ok(().into()) } @@ -493,7 +508,10 @@ pub mod pallet { // Check the validity of origin T::ControlOrigin::ensure_origin(origin)?; TransferToFee::::insert(support_chain, transfer_to_fee); - Self::deposit_event(Event::SetTransferToFee { support_chain, transfer_to_fee }); + Self::deposit_event(Event::SetTransferToFee { + support_chain, + transfer_to_fee, + }); Ok(().into()) } @@ -511,19 +529,30 @@ pub mod pallet { // Check the validity of origin T::ControlOrigin::ensure_origin(origin)?; // Check in advance to avoid hook errors - currency_id.to_vtoken().map_err(|_| Error::::ErrorConvertVtoken)?; + currency_id + .to_vtoken() + .map_err(|_| Error::::ErrorConvertVtoken)?; let mut currency_list = CurrencyIdList::::get(); if is_support { - ensure!(!currency_list.contains(¤cy_id), Error::::CurrencyAlreadyExists); + ensure!( + !currency_list.contains(¤cy_id), + Error::::CurrencyAlreadyExists + ); currency_list .try_push(currency_id) .map_err(|_| Error::::CurrencyListOverflow)?; } else { - ensure!(currency_list.contains(¤cy_id), Error::::CurrencyNotFound); + ensure!( + currency_list.contains(¤cy_id), + Error::::CurrencyNotFound + ); currency_list.retain(|&x| x != currency_id); } CurrencyIdList::::put(currency_list); - Self::deposit_event(Event::SupportXcmOracle { currency_id, is_support }); + Self::deposit_event(Event::SupportXcmOracle { + currency_id, + is_support, + }); Ok(().into()) } @@ -547,7 +576,7 @@ pub mod pallet { xcm_fee, xcm_weight, period, - last_block: frame_system::Pallet::::block_number(), + last_block: T::BlockNumberProvider::current_block_number(), contract, }); Self::deposit_event(Event::SetXcmOracleConfiguration { @@ -575,16 +604,25 @@ pub mod pallet { let mut currency_list = SupportXcmFeeList::::get(); if is_support { - ensure!(!currency_list.contains(¤cy_id), Error::::CurrencyAlreadyExists); + ensure!( + !currency_list.contains(¤cy_id), + Error::::CurrencyAlreadyExists + ); currency_list .try_push(currency_id) .map_err(|_| Error::::CurrencyListOverflow)?; } else { - ensure!(currency_list.contains(¤cy_id), Error::::CurrencyNotFound); + ensure!( + currency_list.contains(¤cy_id), + Error::::CurrencyNotFound + ); currency_list.retain(|&x| x != currency_id); } SupportXcmFeeList::::put(currency_list); - Self::deposit_event(Event::SetCurrencyToSupportXcmFee { currency_id, is_support }); + Self::deposit_event(Event::SetCurrencyToSupportXcmFee { + currency_id, + is_support, + }); Ok(().into()) } @@ -750,8 +788,8 @@ impl Pallet { fn match_source_chain_id(source_chain_id: u64) -> Option { if source_chain_id == AstarEvmChainId::get() { Some(SupportChain::Astar) - } else if source_chain_id == MoonriverEvmChainId::get() || - source_chain_id == MoonbeamEvmChainId::get() + } else if source_chain_id == MoonriverEvmChainId::get() + || source_chain_id == MoonbeamEvmChainId::get() { Some(SupportChain::Moonbeam) } else { @@ -762,8 +800,9 @@ impl Pallet { /// According to currency_id, return the order type fn order_type(currency_id: CurrencyId) -> Result> { match currency_id { - CurrencyId::Native(_) | CurrencyId::Token(_) | CurrencyId::Token2(_) => - Ok(OrderType::Mint), + CurrencyId::Native(_) | CurrencyId::Token(_) | CurrencyId::Token2(_) => { + Ok(OrderType::Mint) + } CurrencyId::VToken(_) | CurrencyId::VToken2(_) => Ok(OrderType::Redeem), _ => Err(Error::::Unsupported), } @@ -785,24 +824,32 @@ impl Pallet { let location = match support_chain { SupportChain::Astar => { let account_id = Self::h160_to_account_id(&contract_address); - let id: [u8; 32] = - account_id.encode().try_into().map_err(|_| Error::::ErrorEncode)?; + let id: [u8; 32] = account_id + .encode() + .try_into() + .map_err(|_| Error::::ErrorEncode)?; Location::new( 1, - [Parachain(AstarChainId::get()), AccountId32 { network: None, id }], + [ + Parachain(AstarChainId::get()), + AccountId32 { network: None, id }, + ], ) - }, + } SupportChain::Moonbeam => Location::new( 1, [ Parachain(T::VtokenMintingInterface::get_moonbeam_parachain_id()), - AccountKey20 { network: None, key: contract_address.to_fixed_bytes() }, + AccountKey20 { + network: None, + key: contract_address.to_fixed_bytes(), + }, ], ), _ => { ensure!(false, Error::::Unsupported); Location::default() - }, + } }; let raw_account = HashedDescription::<[u8; 32], DescribeFamily>::convert_location( @@ -828,7 +875,7 @@ impl Pallet { let order_type = Self::order_type(currency_id)?; let derivative_account = Self::frontier_derivative_account(&source_chain_caller); let order = Order { - create_block_number: >::block_number(), + create_block_number: T::BlockNumberProvider::current_block_number(), order_type, currency_id, currency_amount, @@ -856,8 +903,12 @@ impl Pallet { xcm_weight: Weight, xcm_fee: u128, ) -> DispatchResult { - let dest = - Location::new(1, [Parachain(T::VtokenMintingInterface::get_moonbeam_parachain_id())]); + let dest = Location::new( + 1, + [Parachain( + T::VtokenMintingInterface::get_moonbeam_parachain_id(), + )], + ); // Moonbeam Native Token let asset = Asset { @@ -867,7 +918,10 @@ impl Pallet { let xcm_message = Xcm(vec![ WithdrawAsset(asset.clone().into()), - BuyExecution { fees: asset, weight_limit: Unlimited }, + BuyExecution { + fees: asset, + weight_limit: Unlimited, + }, Transact { origin_kind: OriginKind::SovereignAccount, require_weight_at_most: xcm_weight, @@ -957,7 +1011,7 @@ impl Pallet { Self::h160_to_account_id(&evm_caller), bifrost_chain_caller, )) - }, + } } } @@ -1008,7 +1062,10 @@ impl Pallet { 1, [ Parachain(T::VtokenMintingInterface::get_moonbeam_parachain_id()), - AccountKey20 { network: None, key: receiver.to_fixed_bytes() }, + AccountKey20 { + network: None, + key: receiver.to_fixed_bytes(), + }, ], ), TargetChain::Hydradx(receiver) => Location::new( @@ -1017,7 +1074,10 @@ impl Pallet { Parachain(HydrationChainId::get()), AccountId32 { network: None, - id: receiver.encode().try_into().map_err(|_| Error::::ErrorEncode)?, + id: receiver + .encode() + .try_into() + .map_err(|_| Error::::ErrorEncode)?, }, ], ), @@ -1027,7 +1087,10 @@ impl Pallet { Parachain(InterlayChainId::get()), AccountId32 { network: None, - id: receiver.encode().try_into().map_err(|_| Error::::ErrorEncode)?, + id: receiver + .encode() + .try_into() + .map_err(|_| Error::::ErrorEncode)?, }, ], ), @@ -1037,7 +1100,10 @@ impl Pallet { Parachain(MantaChainId::get()), AccountId32 { network: None, - id: receiver.encode().try_into().map_err(|_| Error::::ErrorEncode)?, + id: receiver + .encode() + .try_into() + .map_err(|_| Error::::ErrorEncode)?, }, ], ), @@ -1092,8 +1158,10 @@ impl Pallet { .map_err(|_| Error::::ErrorChargeFee)?; match order.order_type { OrderType::Mint => { - let vtoken_id = - order.currency_id.to_vtoken().map_err(|_| Error::::ErrorConvertVtoken)?; + let vtoken_id = order + .currency_id + .to_vtoken() + .map_err(|_| Error::::ErrorConvertVtoken)?; let vtoken_amount = T::VtokenMintingInterface::get_v_currency_amount_by_currency_amount( @@ -1120,13 +1188,13 @@ impl Pallet { &order.target_chain, ) .map_err(|_| Error::::ErrorTransferTo)?; - }, + } OrderType::Redeem => { let redeem_type = match order.target_chain.clone() { TargetChain::Astar(receiver) => { let receiver = Self::h160_to_account_id(&receiver); RedeemType::Astar(receiver) - }, + } TargetChain::Moonbeam(receiver) => RedeemType::Moonbeam(receiver), TargetChain::Hydradx(receiver) => RedeemType::Hydradx(receiver), TargetChain::Interlay(receiver) => RedeemType::Interlay(receiver), @@ -1139,7 +1207,7 @@ impl Pallet { redeem_type, ) .map_err(|_| Error::::ErrorVtokenMiting)?; - }, + } }; Ok(()) } @@ -1173,11 +1241,13 @@ impl Pallet { } match Self::handle_order(&order) { Ok(_) => { - Self::deposit_event(Event::::OrderHandled { order: order.clone() }); - }, + Self::deposit_event(Event::::OrderHandled { + order: order.clone(), + }); + } Err(_) => { Self::deposit_event(Event::::OrderFailed { order }); - }, + } }; *weight = weight.saturating_add(T::DbWeight::get().reads_writes(12, 8)); }; @@ -1202,8 +1272,9 @@ impl Pallet { if let Some(mut config) = configuration { let currency_id = currency_list[0]; let staking_currency_amount = T::VtokenMintingInterface::get_token_pool(currency_id); - let v_currency_id = - currency_id.to_vtoken().map_err(|_| Error::::ErrorConvertVtoken)?; + let v_currency_id = currency_id + .to_vtoken() + .map_err(|_| Error::::ErrorConvertVtoken)?; let v_currency_total_supply = T::MultiCurrency::total_issuance(v_currency_id); if config.last_block + config.period < current_block_number { diff --git a/pallets/slpx/src/migration.rs b/pallets/slpx/src/migration.rs index e2c38cee20..8cd2bac9e9 100644 --- a/pallets/slpx/src/migration.rs +++ b/pallets/slpx/src/migration.rs @@ -36,7 +36,10 @@ impl OnRuntimeUpgrade for BifrostKusamaAddCurrencyToSupportXcmFee #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { let currency_count = SupportXcmFeeList::::get().len(); - ensure!(currency_count == 0, "SupportXcmFeeList post-migrate storage count not match"); + ensure!( + currency_count == 0, + "SupportXcmFeeList post-migrate storage count not match" + ); Ok(sp_std::vec![]) } @@ -44,7 +47,10 @@ impl OnRuntimeUpgrade for BifrostKusamaAddCurrencyToSupportXcmFee #[cfg(feature = "try-runtime")] fn post_upgrade(_cnt: Vec) -> Result<(), TryRuntimeError> { let currency_count_new = SupportXcmFeeList::::get().len(); - ensure!(currency_count_new == 3, "Validators post-migrate storage count not match"); + ensure!( + currency_count_new == 3, + "Validators post-migrate storage count not match" + ); Ok(()) } @@ -62,7 +68,10 @@ impl OnRuntimeUpgrade for BifrostPolkadotAddCurrencyToSupportXcmFee Result, TryRuntimeError> { let currency_count = SupportXcmFeeList::::get().len(); - ensure!(currency_count == 0, "SupportXcmFeeList post-migrate storage count not match"); + ensure!( + currency_count == 0, + "SupportXcmFeeList post-migrate storage count not match" + ); Ok(sp_std::vec![]) } @@ -70,7 +79,10 @@ impl OnRuntimeUpgrade for BifrostPolkadotAddCurrencyToSupportXcmFee) -> Result<(), TryRuntimeError> { let currency_count_new = SupportXcmFeeList::::get().len(); - ensure!(currency_count_new == 5, "Validators post-migrate storage count not match"); + ensure!( + currency_count_new == 5, + "Validators post-migrate storage count not match" + ); Ok(()) } @@ -150,16 +162,28 @@ pub mod v1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::DispatchError> { - log::info!("slpx before migration: version: {:?}", StorageVersion::get::>()); - log::info!("slpx before migration: v0 count: {}", v0::OrderQueue::::get().len()); + log::info!( + "slpx before migration: version: {:?}", + StorageVersion::get::>() + ); + log::info!( + "slpx before migration: v0 count: {}", + v0::OrderQueue::::get().len() + ); Ok(Vec::new()) } #[cfg(feature = "try-runtime")] fn post_upgrade(_: Vec) -> Result<(), sp_runtime::DispatchError> { - log::info!("slpx after migration: version: {:?}", StorageVersion::get::>()); - log::info!("slpx after migration: v1 count: {}", OrderQueue::::get().len()); + log::info!( + "slpx after migration: version: {:?}", + StorageVersion::get::>() + ); + log::info!( + "slpx after migration: v1 count: {}", + OrderQueue::::get().len() + ); Ok(()) } @@ -221,7 +245,9 @@ pub fn migrate_to_v1() -> Weight { }; v1::OrderQueue::::mutate(|order_queue| -> DispatchResultWithPostInfo { - order_queue.try_push(order.clone()).map_err(|_| Error::::ErrorArguments)?; + order_queue + .try_push(order.clone()) + .map_err(|_| Error::::ErrorArguments)?; Ok(().into()) }) .expect("BoundedVec should not overflow"); @@ -253,7 +279,9 @@ pub fn migrate_to_v2() -> Weight { }; OrderQueue::::mutate(|order_queue| -> DispatchResultWithPostInfo { - order_queue.try_push(order.clone()).map_err(|_| Error::::ErrorArguments)?; + order_queue + .try_push(order.clone()) + .map_err(|_| Error::::ErrorArguments)?; Ok(().into()) }) .expect("BoundedVec should not overflow"); diff --git a/pallets/slpx/src/mock.rs b/pallets/slpx/src/mock.rs index 605c72a8c1..b1908b8a3e 100644 --- a/pallets/slpx/src/mock.rs +++ b/pallets/slpx/src/mock.rs @@ -191,6 +191,7 @@ impl bifrost_vtoken_minting::Config for Test { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } parameter_types! { @@ -318,11 +319,14 @@ impl slpx::Config for Test { type ParachainId = ParachainId; type WeightInfo = (); type MaxOrderSize = ConstU32<500>; + type BlockNumberProvider = System; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(0)); ext diff --git a/pallets/slpx/src/tests.rs b/pallets/slpx/src/tests.rs index 762d56562a..a9e83fcba2 100644 --- a/pallets/slpx/src/tests.rs +++ b/pallets/slpx/src/tests.rs @@ -162,7 +162,10 @@ fn remove_whitelist() { SupportChain::Astar, astar_slpx_addr )); - assert_eq!(WhitelistAccountId::::get(SupportChain::Astar).to_vec(), vec![]); + assert_eq!( + WhitelistAccountId::::get(SupportChain::Astar).to_vec(), + vec![] + ); }); } @@ -180,14 +183,21 @@ fn remove_whitelist_account_id_not_in_whitelist() { #[test] fn test_execution_fee_work() { new_test_ext().execute_with(|| { - assert_ok!(Currencies::deposit(CurrencyId::Token2(0), &ALICE, 50 * 1_000_000_000)); + assert_ok!(Currencies::deposit( + CurrencyId::Token2(0), + &ALICE, + 50 * 1_000_000_000 + )); assert_ok!(Slpx::set_execution_fee( RuntimeOrigin::root(), CurrencyId::Token2(0), 10 * 1_000_000_000 )); - assert_eq!(ExecutionFee::::get(CurrencyId::Token2(0)), Some(10 * 1_000_000_000)); + assert_eq!( + ExecutionFee::::get(CurrencyId::Token2(0)), + Some(10 * 1_000_000_000) + ); let balance_exclude_fee = Slpx::charge_execution_fee(CurrencyId::Token2(0), 50 * 1_000_000_000, &ALICE).unwrap(); @@ -198,7 +208,10 @@ fn test_execution_fee_work() { SupportChain::Moonbeam, 10 * 1_000_000_000 )); - assert_eq!(TransferToFee::::get(SupportChain::Moonbeam), Some(10 * 1_000_000_000)); + assert_eq!( + TransferToFee::::get(SupportChain::Moonbeam), + Some(10 * 1_000_000_000) + ); }); } @@ -206,12 +219,18 @@ fn test_execution_fee_work() { fn test_get_default_fee() { new_test_ext().execute_with(|| { assert_eq!(Slpx::get_default_fee(BNC), 10_000_000_000u128); - assert_eq!(Slpx::get_default_fee(CurrencyId::Token(TokenSymbol::KSM)), 10_000_000_000u128); + assert_eq!( + Slpx::get_default_fee(CurrencyId::Token(TokenSymbol::KSM)), + 10_000_000_000u128 + ); assert_eq!( Slpx::get_default_fee(CurrencyId::Token(TokenSymbol::MOVR)), 10_000_000_000_000_000u128 ); - assert_eq!(Slpx::get_default_fee(CurrencyId::VToken(TokenSymbol::KSM)), 10_000_000_000u128); + assert_eq!( + Slpx::get_default_fee(CurrencyId::VToken(TokenSymbol::KSM)), + 10_000_000_000u128 + ); assert_eq!( Slpx::get_default_fee(CurrencyId::VToken(TokenSymbol::MOVR)), 10_000_000_000_000_000u128 @@ -351,13 +370,25 @@ fn test_set_ethereum_call_configration() { #[test] fn test_set_currency_to_support_xcm_fee() { new_test_ext().execute_with(|| { - assert_ok!(Slpx::set_currency_support_xcm_fee(RuntimeOrigin::root(), BNC, true)); + assert_ok!(Slpx::set_currency_support_xcm_fee( + RuntimeOrigin::root(), + BNC, + true + )); assert_eq!(SupportXcmFeeList::::get().to_vec(), vec![BNC]); - assert_ok!(Slpx::set_currency_support_xcm_fee(RuntimeOrigin::root(), KSM, true)); + assert_ok!(Slpx::set_currency_support_xcm_fee( + RuntimeOrigin::root(), + KSM, + true + )); assert_eq!(SupportXcmFeeList::::get().to_vec(), vec![BNC, KSM]); - assert_ok!(Slpx::set_currency_support_xcm_fee(RuntimeOrigin::root(), BNC, false)); + assert_ok!(Slpx::set_currency_support_xcm_fee( + RuntimeOrigin::root(), + BNC, + false + )); assert_eq!(SupportXcmFeeList::::get().to_vec(), vec![KSM]); }) } diff --git a/pallets/stable-asset/Cargo.toml b/pallets/stable-asset/Cargo.toml index 67ae10b8f3..e279182756 100644 --- a/pallets/stable-asset/Cargo.toml +++ b/pallets/stable-asset/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bifrost-stable-asset" -authors = ["Sora Yu "] +authors = ["Liebi Technologies "] description = "Substrate-based runtime version of NUTS stable assets." edition = "2021" version = "0.8.0" diff --git a/pallets/stable-asset/src/lib.rs b/pallets/stable-asset/src/lib.rs index 8477985fcb..10ade71dfd 100644 --- a/pallets/stable-asset/src/lib.rs +++ b/pallets/stable-asset/src/lib.rs @@ -40,7 +40,10 @@ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_core::{U256, U512}; use sp_runtime::{ - traits::{AccountIdConversion, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero}, + traits::{ + AccountIdConversion, BlockNumberProvider, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, + One, Zero, + }, ArithmeticError, DispatchError, SaturatedConversion, }; use sp_std::prelude::*; @@ -291,7 +294,12 @@ pub mod traits { input_asset: Self::AssetId, output_asset: Self::AssetId, input_amount: Self::Balance, - ) -> Option<(StableAssetPoolId, PoolTokenIndex, PoolTokenIndex, Self::Balance)>; + ) -> Option<( + StableAssetPoolId, + PoolTokenIndex, + PoolTokenIndex, + Self::Balance, + )>; /// Get the swap result at exact input amount. /// params: @@ -347,7 +355,7 @@ pub mod pallet { use orml_traits::MultiCurrency; use parity_scale_codec::Codec; use sp_runtime::{ - traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero}, + traits::{BlockNumberProvider, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero}, FixedPointOperand, Permill, }; use sp_std::prelude::*; @@ -394,6 +402,9 @@ pub mod pallet { /// The origin which may create pool or modify pool. type ListingOrigin: EnsureOrigin; + + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::pallet] @@ -634,7 +645,10 @@ pub mod pallet { /// The pool id. pool_id: StableAssetPoolId, /// The token rate info[(currency_id, (denominator, numerator))]. - token_rate: Vec<(T::AssetId, (T::AtLeast64BitUnsigned, T::AtLeast64BitUnsigned))>, + token_rate: Vec<( + T::AssetId, + (T::AtLeast64BitUnsigned, T::AtLeast64BitUnsigned), + )>, }, /// The hardcap of the token rate is configured. TokenRateHardcapConfigured { @@ -789,7 +803,10 @@ pub mod pallet { precision: T::AtLeast64BitUnsigned, ) -> DispatchResult { T::ListingOrigin::ensure_origin(origin.clone())?; - ensure!(T::EnsurePoolAssetId::validate(pool_asset), Error::::InvalidPoolAsset); + ensure!( + T::EnsurePoolAssetId::validate(pool_asset), + Error::::InvalidPoolAsset + ); ::create_pool( pool_asset, assets, @@ -973,7 +990,7 @@ impl Pallet { a1: T::AtLeast64BitUnsigned, t1: BlockNumberFor, ) -> Option { - let current_block = frame_system::Pallet::::block_number(); + let current_block = T::BlockNumberProvider::current_block_number(); if current_block < t1 { let time_diff: u128 = current_block.checked_sub(&t0)?.saturated_into(); let time_diff: T::AtLeast64BitUnsigned = time_diff.into(); @@ -1090,17 +1107,21 @@ impl Pallet { .checked_mul(target_d_u256)? .checked_mul(a_precision_u256)? .checked_div(ann.checked_mul(balance_size)?)?; - let b: U512 = - sum.checked_add(target_d_u256.checked_mul(a_precision_u256)?.checked_div(ann)?)?; + let b: U512 = sum.checked_add( + target_d_u256 + .checked_mul(a_precision_u256)? + .checked_div(ann)?, + )?; let mut prev_y: U512; let mut y: U512 = target_d_u256; for _i in 0..NUMBER_OF_ITERATIONS_TO_CONVERGE { prev_y = y; - y = y - .checked_mul(y)? - .checked_add(c)? - .checked_div(y.checked_mul(two)?.checked_add(b)?.checked_sub(target_d_u256)?)?; + y = y.checked_mul(y)?.checked_add(c)?.checked_div( + y.checked_mul(two)? + .checked_add(b)? + .checked_sub(target_d_u256)?, + )?; if y > prev_y { if y - prev_y <= one { break; @@ -1154,7 +1175,9 @@ impl Pallet { } let result: T::AtLeast64BitUnsigned = balances[i] .checked_add( - &amounts[i].checked_mul(&pool_info.precisions[i]).ok_or(Error::::Math)?, + &amounts[i] + .checked_mul(&pool_info.precisions[i]) + .ok_or(Error::::Math)?, ) .ok_or(Error::::Math)?; balances[i] = result; @@ -1176,7 +1199,9 @@ impl Pallet { .map_err(|_| Error::::Math)? .into(); - mint_amount = mint_amount.checked_sub(&fee_amount).ok_or(Error::::Math)?; + mint_amount = mint_amount + .checked_sub(&fee_amount) + .ok_or(Error::::Math)?; } Ok(MintResult { @@ -1395,8 +1420,9 @@ impl Pallet { .map_err(|_| Error::::Math)? .into(); balances[i] = balance_i.checked_sub(&diff_i).ok_or(Error::::Math)?; - let amounts_i: T::AtLeast64BitUnsigned = - diff_i.checked_div(&pool_info.precisions[i]).ok_or(Error::::Math)?; + let amounts_i: T::AtLeast64BitUnsigned = diff_i + .checked_div(&pool_info.precisions[i]) + .ok_or(Error::::Math)?; amounts.push(amounts_i); } let total_supply: T::AtLeast64BitUnsigned = @@ -1463,9 +1489,13 @@ impl Pallet { } // The pool token amount becomes D - _amount - let y: T::AtLeast64BitUnsigned = - Self::get_y(&balances, i, d.checked_sub(&amount).ok_or(Error::::Math)?, a) - .ok_or(Error::::Math)?; + let y: T::AtLeast64BitUnsigned = Self::get_y( + &balances, + i, + d.checked_sub(&amount).ok_or(Error::::Math)?, + a, + ) + .ok_or(Error::::Math)?; // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors let balance_i: T::AtLeast64BitUnsigned = pool_info.balances[i_usize].into(); let dy: T::AtLeast64BitUnsigned = balance_i @@ -1522,8 +1552,9 @@ impl Pallet { } let balance_i: T::AtLeast64BitUnsigned = balances[i]; // balance = balance + amount * precision - let sub_amount: T::AtLeast64BitUnsigned = - amounts_i.checked_mul(&pool_info.precisions[i]).ok_or(Error::::Math)?; + let sub_amount: T::AtLeast64BitUnsigned = amounts_i + .checked_mul(&pool_info.precisions[i]) + .ok_or(Error::::Math)?; balances[i] = balance_i.checked_sub(&sub_amount).ok_or(Error::::Math)?; } let new_d: T::AtLeast64BitUnsigned = Self::get_d(&balances, a).ok_or(Error::::Math)?; @@ -1532,8 +1563,9 @@ impl Pallet { let mut fee_amount: T::AtLeast64BitUnsigned = zero; if pool_info.redeem_fee > zero { let fee_denominator: T::AtLeast64BitUnsigned = T::FeePrecision::get(); - let div_amount: T::AtLeast64BitUnsigned = - fee_denominator.checked_sub(&pool_info.redeem_fee).ok_or(Error::::Math)?; + let div_amount: T::AtLeast64BitUnsigned = fee_denominator + .checked_sub(&pool_info.redeem_fee) + .ok_or(Error::::Math)?; redeem_amount = u128::try_from( U256::from(redeem_amount.saturated_into::()) .checked_mul(U256::from(fee_denominator.saturated_into::())) @@ -1545,10 +1577,13 @@ impl Pallet { .into(); let sub_amount: T::AtLeast64BitUnsigned = old_d.checked_sub(&new_d).ok_or(Error::::Math)?; - fee_amount = redeem_amount.checked_sub(&sub_amount).ok_or(Error::::Math)?; + fee_amount = redeem_amount + .checked_sub(&sub_amount) + .ok_or(Error::::Math)?; } - let burn_amount: T::AtLeast64BitUnsigned = - redeem_amount.checked_sub(&fee_amount).ok_or(Error::::Math)?; + let burn_amount: T::AtLeast64BitUnsigned = redeem_amount + .checked_sub(&fee_amount) + .ok_or(Error::::Math)?; let total_supply: T::AtLeast64BitUnsigned = old_d.checked_sub(&burn_amount).ok_or(Error::::Math)?; Ok(RedeemMultiResult { @@ -1595,7 +1630,9 @@ impl Pallet { .map_err(|_| Error::::Math)? .into(); } - *balance = balance_of.checked_mul(&pool_info.precisions[i]).ok_or(Error::::Math)?; + *balance = balance_of + .checked_mul(&pool_info.precisions[i]) + .ok_or(Error::::Math)?; } let new_d: T::AtLeast64BitUnsigned = Self::get_d(&balances, a).ok_or(Error::::Math)?; let old_d_div_100: T::AtLeast64BitUnsigned = @@ -1691,8 +1728,10 @@ impl Pallet { .map_err(|_| Error::::Math)? .into(); } - *balance = - balance_of.checked_mul(&pool_info.precisions[i]).ok_or(Error::::Math)?.into(); + *balance = balance_of + .checked_mul(&pool_info.precisions[i]) + .ok_or(Error::::Math)? + .into(); } let mut cloned_stable_asset_info = pool_info.clone(); cloned_stable_asset_info.balances = updated_balances; @@ -1729,8 +1768,10 @@ impl StableAsset for Pallet { } Self::deposit_event(Event::TokenRateSet { pool_id, - token_rate: TokenRateCaches::::iter_prefix(pool_id) - .collect::>(), + token_rate: TokenRateCaches::::iter_prefix(pool_id).collect::>(), }); Ok(()) } @@ -1872,8 +1913,11 @@ impl StableAsset for Pallet { ) -> DispatchResult { let old_balances = pool_info.balances.clone(); let old_total_supply = pool_info.total_supply; - let PendingFeeResult { fee_amount, balances, total_supply } = - Self::get_pending_fee_amount(pool_info)?; + let PendingFeeResult { + fee_amount, + balances, + total_supply, + } = Self::get_pending_fee_amount(pool_info)?; let zero: T::Balance = Zero::zero(); pool_info.total_supply = total_supply; pool_info.balances = balances; @@ -1931,7 +1975,10 @@ impl StableAsset for Pallet { ensure!(assets.len() > 1, Error::::ArgumentsError); let pool_asset_limit = T::PoolAssetLimit::get() as usize; ensure!(assets.len() <= pool_asset_limit, Error::::ArgumentsError); - ensure!(assets.len() == precisions.len(), Error::::ArgumentsMismatch); + ensure!( + assets.len() == precisions.len(), + Error::::ArgumentsMismatch + ); PoolCount::::try_mutate(|pool_count| -> DispatchResult { let pool_id = *pool_count; let swap_id: T::AccountId = T::PalletId::get().into_sub_account_truncating(pool_id); @@ -1940,7 +1987,7 @@ impl StableAsset for Pallet { let balances = sp_std::vec![Zero::zero(); assets.len()]; frame_system::Pallet::::inc_providers(&swap_id); - let current_block = frame_system::Pallet::::block_number(); + let current_block = T::BlockNumberProvider::current_block_number(); *maybe_pool_info = Some(StableAssetPoolInfo { pool_id, pool_asset, @@ -1993,8 +2040,12 @@ impl StableAsset for Pallet { Pools::::try_mutate_exists(pool_id, |maybe_pool_info| -> DispatchResult { let pool_info = maybe_pool_info.as_mut().ok_or(Error::::PoolNotFound)?; Self::collect_yield(pool_id, pool_info)?; - let MintResult { mint_amount, fee_amount, balances, total_supply } = - Self::get_mint_amount(pool_info, &amounts)?; + let MintResult { + mint_amount, + fee_amount, + balances, + total_supply, + } = Self::get_mint_amount(pool_info, &amounts)?; let a: T::AtLeast64BitUnsigned = Self::get_a( pool_info.a, pool_info.a_block, @@ -2133,7 +2184,10 @@ impl StableAsset for Pallet { } = Self::get_redeem_proportion_amount(pool_info, amount)?; let zero: T::Balance = Zero::zero(); for i in 0..amounts.len() { - ensure!(amounts[i] >= min_redeem_amounts[i], Error::::RedeemUnderMin); + ensure!( + amounts[i] >= min_redeem_amounts[i], + Error::::RedeemUnderMin + ); T::Assets::transfer(pool_info.assets[i], &pool_info.account_id, who, amounts[i])?; } if fee_amount > zero { @@ -2275,7 +2329,10 @@ impl StableAsset for Pallet { burn_amount, } = Self::get_redeem_multi_amount(pool_info, &amounts)?; let zero: T::Balance = Zero::zero(); - ensure!(redeem_amount <= max_redeem_amount, Error::::RedeemOverMax); + ensure!( + redeem_amount <= max_redeem_amount, + Error::::RedeemOverMax + ); if fee_amount > zero { T::Assets::transfer( pool_info.pool_asset, @@ -2336,8 +2393,11 @@ impl StableAsset for Pallet { ) -> DispatchResult { Pools::::try_mutate_exists(pool_id, |maybe_pool_info| -> DispatchResult { let pool_info = maybe_pool_info.as_mut().ok_or(Error::::PoolNotFound)?; - ensure!(future_a_block > pool_info.a_block, Error::::ArgumentsError); - let current_block = frame_system::Pallet::::block_number(); + ensure!( + future_a_block > pool_info.a_block, + Error::::ArgumentsError + ); + let current_block = T::BlockNumberProvider::current_block_number(); let initial_a: T::AtLeast64BitUnsigned = Self::get_a( pool_info.a, pool_info.a_block, @@ -2349,7 +2409,11 @@ impl StableAsset for Pallet { pool_info.a_block = current_block; pool_info.future_a = a; pool_info.future_a_block = future_a_block; - Self::deposit_event(Event::AModified { pool_id, value: a, time: future_a_block }); + Self::deposit_event(Event::AModified { + pool_id, + value: a, + time: future_a_block, + }); Ok(()) }) } @@ -2411,7 +2475,12 @@ impl StableAsset for Pallet { input_asset: Self::AssetId, output_asset: Self::AssetId, input_amount: Self::Balance, - ) -> Option<(StableAssetPoolId, PoolTokenIndex, PoolTokenIndex, Self::Balance)> { + ) -> Option<( + StableAssetPoolId, + PoolTokenIndex, + PoolTokenIndex, + Self::Balance, + )> { let mut maybe_best: Option<( StableAssetPoolId, PoolTokenIndex, @@ -2478,8 +2547,9 @@ impl StableAsset for Pallet { ) -> Option> { let pool_info_opt = Self::pool(pool_id); match pool_info_opt { - Some(pool_info) => - Self::get_swap_amount(&pool_info, input_index, output_index, dx_bal).ok(), + Some(pool_info) => { + Self::get_swap_amount(&pool_info, input_index, output_index, dx_bal).ok() + } None => None, } } @@ -2492,8 +2562,9 @@ impl StableAsset for Pallet { ) -> Option> { let pool_info_opt = Self::pool(pool_id); match pool_info_opt { - Some(pool_info) => - Self::get_swap_amount_exact(&pool_info, input_index, output_index, dy_bal), + Some(pool_info) => { + Self::get_swap_amount_exact(&pool_info, input_index, output_index, dy_bal) + } None => None, } } diff --git a/pallets/stable-asset/src/mock.rs b/pallets/stable-asset/src/mock.rs index da1c64a1b8..951677e059 100644 --- a/pallets/stable-asset/src/mock.rs +++ b/pallets/stable-asset/src/mock.rs @@ -128,7 +128,10 @@ impl CreateAssets for TestAssets { let mut d = d.borrow_mut(); let id = AssetId::try_from(d.len()).map_err(|_| DispatchError::Other("Too large id"))?; - d.push(Asset { total: 0, balances: HashMap::new() }); + d.push(Asset { + total: 0, + balances: HashMap::new(), + }); Ok(id) }) @@ -187,15 +190,22 @@ impl MultiCurrency for TestAssets { let i = usize::try_from(asset).map_err(|_| DispatchError::Other("Index out of range"))?; let mut d = d.borrow_mut(); - let a = d.get_mut(i).ok_or(DispatchError::Other("Index out of range"))?; + let a = d + .get_mut(i) + .ok_or(DispatchError::Other("Index out of range"))?; if let Some(x) = a.balances.get_mut(dest) { - *x = x.checked_add(amount).ok_or(DispatchError::Other("Overflow"))?; + *x = x + .checked_add(amount) + .ok_or(DispatchError::Other("Overflow"))?; } else { a.balances.insert(*dest, amount); } - a.total = a.total.checked_add(amount).ok_or(DispatchError::Other("Overflow"))?; + a.total = a + .total + .checked_add(amount) + .ok_or(DispatchError::Other("Overflow"))?; Ok(()) }) @@ -210,13 +220,23 @@ impl MultiCurrency for TestAssets { let i = usize::try_from(asset).map_err(|_| DispatchError::Other("Index out of range"))?; let mut d = d.borrow_mut(); - let a = d.get_mut(i).ok_or(DispatchError::Other("Index out of range"))?; + let a = d + .get_mut(i) + .ok_or(DispatchError::Other("Index out of range"))?; - let x = a.balances.get_mut(dest).ok_or(DispatchError::Other("Not found"))?; + let x = a + .balances + .get_mut(dest) + .ok_or(DispatchError::Other("Not found"))?; - *x = x.checked_sub(amount).ok_or(DispatchError::Other("Overflow"))?; + *x = x + .checked_sub(amount) + .ok_or(DispatchError::Other("Overflow"))?; - a.total = a.total.checked_sub(amount).ok_or(DispatchError::Other("Overflow"))?; + a.total = a + .total + .checked_sub(amount) + .ok_or(DispatchError::Other("Overflow"))?; Ok(()) }) @@ -281,9 +301,13 @@ impl stable_asset::Config for Test { type WeightInfo = (); type ListingOrigin = EnsureStableAsset; type EnsurePoolAssetId = EnsurePoolAssetId; + type BlockNumberProvider = System; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::::default().build_storage().unwrap().into() + frame_system::GenesisConfig::::default() + .build_storage() + .unwrap() + .into() } diff --git a/pallets/stable-asset/src/tests.rs b/pallets/stable-asset/src/tests.rs index 20bb46cfa4..3d34ec3792 100644 --- a/pallets/stable-asset/src/tests.rs +++ b/pallets/stable-asset/src/tests.rs @@ -53,7 +53,10 @@ fn create_pool() -> (i64, i64, i64, u64) { 1, 1000000000000000000u128, )); - assert_ok!(StableAsset::set_token_rate(0, vec![(coin0, (1, 1)), (coin1, (1, 1))])); + assert_ok!(StableAsset::set_token_rate( + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); (coin0, coin1, pool_asset, 8319403528785522541u64) } @@ -228,12 +231,30 @@ fn mint_successful_equal_amounts() { }) ); - assert_eq!(TestAssets::free_balance(coin0, &1), 90000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &1), 90000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin0, &swap_id), 10000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &swap_id), 10000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &1), 199800000000000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &2), 200000000000000u128 - BALANCE_OFF); + assert_eq!( + TestAssets::free_balance(coin0, &1), + 90000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &1), + 90000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin0, &swap_id), + 10000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &swap_id), + 10000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &1), + 199800000000000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &2), + 200000000000000u128 - BALANCE_OFF + ); }); } @@ -268,12 +289,30 @@ fn mint_successful_different_amounts() { }) ); - assert_eq!(TestAssets::free_balance(coin0, &1), 90000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &1), 80000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin0, &swap_id), 10000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &swap_id), 20000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &1), 299606896309149793u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &2), 299906803112262u128 - BALANCE_OFF); + assert_eq!( + TestAssets::free_balance(coin0, &1), + 90000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &1), + 80000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin0, &swap_id), + 10000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &swap_id), + 20000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &1), + 299606896309149793u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &2), + 299906803112262u128 - BALANCE_OFF + ); if let RuntimeEvent::StableAsset(crate::pallet::Event::LiquidityAdded { minter: _, pool_id: _, @@ -344,7 +383,12 @@ fn mint_failed_under_min() { let amounts = vec![10000000u128, 20000000u128]; assert_noop!( - StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 2000000000000000000000000u128), + StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts, + 2000000000000000000000000u128 + ), Error::::MintUnderMin ); }); @@ -356,10 +400,23 @@ fn mint_failed_overflow() { let (coin0, coin1, _pool_asset, _swap_id) = create_pool(); System::set_block_number(2); - assert_ok!(::Assets::deposit(coin0, &1, 10000000000u128)); - assert_ok!(::Assets::deposit(coin1, &1, 20000000000u128)); + assert_ok!(::Assets::deposit( + coin0, + &1, + 10000000000u128 + )); + assert_ok!(::Assets::deposit( + coin1, + &1, + 20000000000u128 + )); let amounts = vec![10000000000u128, 20000000000u128]; - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0u128),); + assert_ok!(StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts, + 0u128 + ),); }); } @@ -371,7 +428,15 @@ fn swap_successful() { let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 0, 1, 5000000u128, 0, 2)); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 0, + 1, + 5000000u128, + 0, + 2 + )); assert_eq!( Pools::::get(0), Some(StableAssetPoolInfo { @@ -394,10 +459,22 @@ fn swap_successful() { precision: 1000000000000000000u128, }) ); - assert_eq!(TestAssets::free_balance(coin0, &1), 85000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &1), 84999301u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin0, &swap_id), 15000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &swap_id), 15000699u128 - BALANCE_OFF); + assert_eq!( + TestAssets::free_balance(coin0, &1), + 85000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &1), + 84999301u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin0, &swap_id), + 15000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &swap_id), + 15000699u128 - BALANCE_OFF + ); if let RuntimeEvent::StableAsset(crate::pallet::Event::TokenSwapped { swapper: _, pool_id: _, @@ -568,12 +645,30 @@ fn redeem_proportion_successful() { precision: 1000000000000000000u128, }) ); - assert_eq!(TestAssets::free_balance(coin0, &1), 93317697u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &1), 86635394u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin0, &swap_id), 6682303u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &swap_id), 13364606u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &1), 199606896309149793u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &2), 799916706598014u128 - BALANCE_OFF); + assert_eq!( + TestAssets::free_balance(coin0, &1), + 93317697u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &1), + 86635394u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin0, &swap_id), + 6682303u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &swap_id), + 13364606u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &1), + 199606896309149793u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &2), + 799916706598014u128 - BALANCE_OFF + ); if let RuntimeEvent::StableAsset(crate::pallet::Event::RedeemedProportion { redeemer: _, pool_id: _, @@ -729,11 +824,23 @@ fn redeem_single_successful() { }) ); assert_eq!(TestAssets::free_balance(coin0, &1), 99503160u128); - assert_eq!(TestAssets::free_balance(coin1, &1), 80000000u128 - BALANCE_OFF); + assert_eq!( + TestAssets::free_balance(coin1, &1), + 80000000u128 - BALANCE_OFF + ); assert_eq!(TestAssets::free_balance(coin0, &swap_id), 496838u128); - assert_eq!(TestAssets::free_balance(coin1, &swap_id), 20000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &1), 199606896309149793u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &2), 799922619246391u128); + assert_eq!( + TestAssets::free_balance(coin1, &swap_id), + 20000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &1), + 199606896309149793u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &2), + 799922619246391u128 + ); if let RuntimeEvent::StableAsset(crate::pallet::Event::RedeemedSingle { redeemer: _, pool_id: _, @@ -895,12 +1002,30 @@ fn redeem_multi_successful() { precision: 1000000000000000000u128, }) ); - assert_eq!(TestAssets::free_balance(coin0, &1), 95000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &1), 85000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin0, &swap_id), 5000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(coin1, &swap_id), 15000000u128 - BALANCE_OFF); - assert_eq!(TestAssets::free_balance(pool_asset, &1), 199031790317593892u128); - assert_eq!(TestAssets::free_balance(pool_asset, &2), 802782333070040u128); + assert_eq!( + TestAssets::free_balance(coin0, &1), + 95000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &1), + 85000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin0, &swap_id), + 5000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(coin1, &swap_id), + 15000000u128 - BALANCE_OFF + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &1), + 199031790317593892u128 + ); + assert_eq!( + TestAssets::free_balance(pool_asset, &2), + 802782333070040u128 + ); if let RuntimeEvent::StableAsset(crate::pallet::Event::RedeemedMulti { redeemer: _, pool_id: _, @@ -1080,13 +1205,27 @@ fn get_mint_amount_same_as_mint() { System::set_block_number(2); let amounts = vec![10000000u128, 20000000u128]; - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts.clone(), 0)); - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts.clone(), + 0 + )); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); let pool_info = Pools::::get(0).unwrap(); - assert_eq!(pool_info.balances, vec![99999990000000000u128, 199999990000000000u128]); assert_eq!( - StableAsset::get_balance_update_amount(&pool_info).unwrap().balances, + pool_info.balances, + vec![99999990000000000u128, 199999990000000000u128] + ); + assert_eq!( + StableAsset::get_balance_update_amount(&pool_info) + .unwrap() + .balances, vec![1000099999990000000000u128, 199999990000000000u128] ); @@ -1130,12 +1269,21 @@ fn get_swap_amount_same_as_swap() { let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0)); - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); let pool_info = Pools::::get(0).unwrap(); - assert_eq!(pool_info.balances, vec![99999990000000000u128, 199999990000000000u128]); assert_eq!( - StableAsset::get_balance_update_amount(&pool_info).unwrap().balances, + pool_info.balances, + vec![99999990000000000u128, 199999990000000000u128] + ); + assert_eq!( + StableAsset::get_balance_update_amount(&pool_info) + .unwrap() + .balances, vec![1000099999990000000000u128, 199999990000000000u128] ); @@ -1149,7 +1297,15 @@ fn get_swap_amount_same_as_swap() { } ); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 0, 1, 5000000u128, 0, 2)); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 0, + 1, + 5000000u128, + 0, + 2 + )); if let RuntimeEvent::StableAsset(crate::pallet::Event::TokenSwapped { swapper: _, pool_id: _, @@ -1179,12 +1335,21 @@ fn get_swap_amount_exact_same_as_swap() { let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0)); - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); let pool_info = Pools::::get(0).unwrap(); - assert_eq!(pool_info.balances, vec![99999990000000000u128, 199999990000000000u128]); assert_eq!( - StableAsset::get_balance_update_amount(&pool_info).unwrap().balances, + pool_info.balances, + vec![99999990000000000u128, 199999990000000000u128] + ); + assert_eq!( + StableAsset::get_balance_update_amount(&pool_info) + .unwrap() + .balances, vec![1000099999990000000000u128, 199999990000000000u128] ); @@ -1198,7 +1363,15 @@ fn get_swap_amount_exact_same_as_swap() { } ); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 0, 1, 4999349u128, 0, 2)); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 0, + 1, + 4999349u128, + 0, + 2 + )); if let RuntimeEvent::StableAsset(crate::pallet::Event::TokenSwapped { swapper: _, pool_id: _, @@ -1228,12 +1401,21 @@ fn get_redeem_proportion_amount_same_as_redeem_proportion() { let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0)); - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); let pool_info = Pools::::get(0).unwrap(); - assert_eq!(pool_info.balances, vec![99999990000000000u128, 199999990000000000u128]); assert_eq!( - StableAsset::get_balance_update_amount(&pool_info).unwrap().balances, + pool_info.balances, + vec![99999990000000000u128, 199999990000000000u128] + ); + assert_eq!( + StableAsset::get_balance_update_amount(&pool_info) + .unwrap() + .balances, vec![1000099999990000000000u128, 199999990000000000u128] ); @@ -1283,12 +1465,21 @@ fn get_redeem_single_amount_same_as_redeem_single() { let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0)); - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); let pool_info = Pools::::get(0).unwrap(); - assert_eq!(pool_info.balances, vec![99999990000000000u128, 199999990000000000u128]); assert_eq!( - StableAsset::get_balance_update_amount(&pool_info).unwrap().balances, + pool_info.balances, + vec![99999990000000000u128, 199999990000000000u128] + ); + assert_eq!( + StableAsset::get_balance_update_amount(&pool_info) + .unwrap() + .balances, vec![1000099999990000000000u128, 199999990000000000u128] ); @@ -1340,12 +1531,21 @@ fn get_redeem_multi_amount_same_as_redeem_multi() { let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts, 0)); - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); let pool_info = Pools::::get(0).unwrap(); - assert_eq!(pool_info.balances, vec![99999990000000000u128, 199999990000000000u128]); assert_eq!( - StableAsset::get_balance_update_amount(&pool_info).unwrap().balances, + pool_info.balances, + vec![99999990000000000u128, 199999990000000000u128] + ); + assert_eq!( + StableAsset::get_balance_update_amount(&pool_info) + .unwrap() + .balances, vec![1000099999990000000000u128, 199999990000000000u128] ); @@ -1394,14 +1594,44 @@ fn swap_should_work_with_unbalance_coin0() { System::set_block_number(2); let amounts = vec![10000000u128, 10000000u128]; - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts.clone(), 0)); + assert_ok!(StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts.clone(), + 0 + )); // increase the balance of coin0 - assert_ok!(::Assets::deposit(coin0, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin0, + &swap_id, + 100_000_000_000 + )); - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts.clone(), 0)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 0, 1, 5000000u128, 0, 2)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 1, 0, 5000000u128, 0, 2)); + assert_ok!(StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts.clone(), + 0 + )); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 0, + 1, + 5000000u128, + 0, + 2 + )); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 1, + 0, + 5000000u128, + 0, + 2 + )); assert_ok!(StableAsset::redeem_proportion( RuntimeOrigin::signed(1), @@ -1441,14 +1671,44 @@ fn swap_should_work_with_unbalance_coin1() { System::set_block_number(2); let amounts = vec![10000000u128, 10000000u128]; - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts.clone(), 0)); + assert_ok!(StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts.clone(), + 0 + )); // increase the balance of coin1 - assert_ok!(::Assets::deposit(coin1, &swap_id, 100_000_000_000)); + assert_ok!(::Assets::deposit( + coin1, + &swap_id, + 100_000_000_000 + )); - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(1), 0, amounts.clone(), 0)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 0, 1, 5000000u128, 0, 2)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(1), 0, 1, 0, 5000000u128, 0, 2)); + assert_ok!(StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts.clone(), + 0 + )); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 0, + 1, + 5000000u128, + 0, + 2 + )); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(1), + 0, + 1, + 0, + 5000000u128, + 0, + 2 + )); assert_ok!(StableAsset::redeem_proportion( RuntimeOrigin::signed(1), diff --git a/pallets/stable-pool/Cargo.toml b/pallets/stable-pool/Cargo.toml index 8aaeaa1381..e19c16038a 100644 --- a/pallets/stable-pool/Cargo.toml +++ b/pallets/stable-pool/Cargo.toml @@ -2,7 +2,7 @@ name = "bifrost-stable-pool" version = "0.8.0" description = "FRAME pallet template for defining custom runtime logic." -authors = ["Sora Yu "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/stable-pool/rpc/Cargo.toml b/pallets/stable-pool/rpc/Cargo.toml index 3c9470c9be..397b95624c 100644 --- a/pallets/stable-pool/rpc/Cargo.toml +++ b/pallets/stable-pool/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-stable-pool-rpc" version = "0.8.0" -authors = ["Sora Yu "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/stable-pool/rpc/runtime-api/Cargo.toml b/pallets/stable-pool/rpc/runtime-api/Cargo.toml index 0993a03470..a2c5d2479c 100644 --- a/pallets/stable-pool/rpc/runtime-api/Cargo.toml +++ b/pallets/stable-pool/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-stable-pool-rpc-runtime-api" version = "0.8.0" -authors = ["Sora Yu "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/stable-pool/rpc/src/lib.rs b/pallets/stable-pool/rpc/src/lib.rs index 05e4906a44..458e977ba4 100644 --- a/pallets/stable-pool/rpc/src/lib.rs +++ b/pallets/stable-pool/rpc/src/lib.rs @@ -60,7 +60,10 @@ pub struct StablePoolRpc { impl StablePoolRpc { pub fn new(client: Arc) -> Self { - Self { client, _marker: PhantomData } + Self { + client, + _marker: PhantomData, + } } } diff --git a/pallets/stable-pool/src/benchmarking.rs b/pallets/stable-pool/src/benchmarking.rs index 9bf4fe9f32..365b1a4808 100644 --- a/pallets/stable-pool/src/benchmarking.rs +++ b/pallets/stable-pool/src/benchmarking.rs @@ -19,33 +19,45 @@ use crate::{Pallet as StablePool, *}; pub use bifrost_primitives::{BNC, DOT, KSM, VDOT}; -use frame_benchmarking::{account, benchmarks, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_support::assert_ok; use frame_system::RawOrigin; use sp_std::vec; -benchmarks! { - create_pool { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn create_pool() -> Result<(), BenchmarkError> { let fee_account: T::AccountId = whitelisted_caller(); let coin0 = DOT; let coin1 = VDOT; - }: _(RawOrigin::Root, - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 10000000u128.into(), - 20000000u128.into(), - 50000000u128.into(), - 10000u128.into(), - fee_account.clone(), - fee_account, - 1000000000000000000u128.into()) - - edit_token_rate { - let fee_account: T::AccountId = account("seed",1,1); + + #[extrinsic_call] + _( + RawOrigin::Root, + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 10000000u128.into(), + 20000000u128.into(), + 50000000u128.into(), + 10000u128.into(), + fee_account.clone(), + fee_account, + 1000000000000000000u128.into(), + ); + + Ok(()) + } + + #[benchmark] + fn edit_token_rate() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = KSM; - assert_ok!( - StablePool::::create_pool( + + assert_ok!(StablePool::::create_pool( RawOrigin::Root.into(), vec![coin0.into(), coin1.into()], vec![1u128.into(), 1u128.into()], @@ -55,16 +67,29 @@ benchmarks! { 10000u128.into(), fee_account.clone(), fee_account.clone(), - 1000000000000000000u128.into()) + 1000000000000000000u128.into() + )); + + #[extrinsic_call] + _( + RawOrigin::Root, + 0, + vec![ + (VDOT.into(), (9u128.into(), 10u128.into())), + (DOT.into(), (1u128.into(), 1u128.into())), + ], ); - }: _(RawOrigin::Root, 0, vec![(VDOT.into(), (9u128.into(), 10u128.into())),(DOT.into(), (1u128.into(), 1u128.into()))]) - config_vtoken_auto_refresh { - let fee_account: T::AccountId = account("seed",1,1); + Ok(()) + } + + #[benchmark] + fn config_vtoken_auto_refresh() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = KSM; - assert_ok!( - StablePool::::create_pool( + + assert_ok!(StablePool::::create_pool( RawOrigin::Root.into(), vec![coin0.into(), coin1.into()], vec![1u128.into(), 1u128.into()], @@ -74,16 +99,22 @@ benchmarks! { 10000u128.into(), fee_account.clone(), fee_account.clone(), - 1000000000000000000u128.into()) - ); - }: _(RawOrigin::Root, VDOT.into(), Permill::from_percent(10)) + 1000000000000000000u128.into() + )); + + #[extrinsic_call] + _(RawOrigin::Root, VDOT.into(), Permill::from_percent(10)); + + Ok(()) + } - remove_vtoken_auto_refresh { - let fee_account: T::AccountId = account("seed",1,1); + #[benchmark] + fn remove_vtoken_auto_refresh() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = KSM; - assert_ok!( - StablePool::::create_pool( + + assert_ok!(StablePool::::create_pool( RawOrigin::Root.into(), vec![coin0.into(), coin1.into()], vec![1u128.into(), 1u128.into()], @@ -93,152 +124,310 @@ benchmarks! { 10000u128.into(), fee_account.clone(), fee_account.clone(), - 1000000000000000000u128.into()) - ); - assert_ok!(StablePool::::config_vtoken_auto_refresh(RawOrigin::Root.into(), VDOT.into(), Permill::from_percent(10))); - }: _(RawOrigin::Root, VDOT.into()) + 1000000000000000000u128.into() + )); - add_liquidity { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + assert_ok!(StablePool::::config_vtoken_auto_refresh( + RawOrigin::Root.into(), + VDOT.into(), + Permill::from_percent(10) + )); + + #[extrinsic_call] + _(RawOrigin::Root, VDOT.into()); + + Ok(()) + } + + #[benchmark] + fn add_liquidity() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = KSM; + T::MultiCurrency::deposit( BNC.into(), &fee_account, - ::Balance::from(100_000_000_000u128.into()) + ::Balance::from(100_000_000_000u128.into()), )?; + T::MultiCurrency::deposit( KSM.into(), &fee_account, - ::Balance::from(100_000_000_000u128.into()) + ::Balance::from(100_000_000_000u128.into()), )?; - let amounts = vec![::Balance::from(10_000_000_000u128.into()), ::Balance::from(10_000_000_000u128.into())]; + + let amounts = vec![ + ::Balance::from(10_000_000_000u128.into()), + ::Balance::from(10_000_000_000u128.into()), + ]; + assert_ok!(StablePool::::create_pool( - RawOrigin::Root.into(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 10000000u128.into(), - 20000000u128.into(), - 50000000u128.into(), - 10000u128.into(), - fee_account.clone(), - fee_account.clone(), - 1000000000000000000u128.into())); - assert_ok!(StablePool::::edit_token_rate(RawOrigin::Root.into(), 0, vec![(BNC.into(), (9u128.into(), 10u128.into())), (KSM.into(), (1u128.into(), 1u128.into()))])); - }: _(RawOrigin::Signed(fee_account), 0, amounts, ::Balance::zero()) - - swap { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + RawOrigin::Root.into(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 10000000u128.into(), + 20000000u128.into(), + 50000000u128.into(), + 10000u128.into(), + fee_account.clone(), + fee_account.clone(), + 1000000000000000000u128.into() + )); + + assert_ok!(StablePool::::edit_token_rate( + RawOrigin::Root.into(), + 0, + vec![ + (BNC.into(), (9u128.into(), 10u128.into())), + (KSM.into(), (1u128.into(), 1u128.into())) + ] + )); + + #[extrinsic_call] + _( + RawOrigin::Signed(fee_account), + 0, + amounts, + ::Balance::zero(), + ); + + Ok(()) + } + + #[benchmark] + fn swap() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; + T::MultiCurrency::deposit( BNC.into(), &fee_account, - ::Balance::from(1000_000_000_000u128.into()) + ::Balance::from(1000_000_000_000u128.into()), )?; - let amounts = vec![::Balance::from(100_000_000_000u128.into()), ::Balance::from(100_000_000u128.into())]; + + let amounts = vec![ + ::Balance::from(100_000_000_000u128.into()), + ::Balance::from(100_000_000u128.into()), + ]; + assert_ok!(StablePool::::create_pool( - RawOrigin::Root.into(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 10000000u128.into(), - 20000000u128.into(), - 50000000u128.into(), - 10000u128.into(), - fee_account.clone(), - fee_account.clone(), - 1000000000000000000u128.into())); - assert_ok!(StablePool::::edit_token_rate(RawOrigin::Root.into(), 0, vec![(BNC.into(), (9u128.into(), 10u128.into()))])); - assert_ok!(StablePool::::add_liquidity(RawOrigin::Signed(fee_account.clone()).into(), 0, amounts, ::Balance::zero())); - }: _(RawOrigin::Signed(fee_account), 0, 0, 1, ::Balance::from(50_000_000_000u128.into()), ::Balance::zero()) - - redeem_proportion { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + RawOrigin::Root.into(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 10000000u128.into(), + 20000000u128.into(), + 50000000u128.into(), + 10000u128.into(), + fee_account.clone(), + fee_account.clone(), + 1000000000000000000u128.into() + )); + + assert_ok!(StablePool::::edit_token_rate( + RawOrigin::Root.into(), + 0, + vec![(BNC.into(), (9u128.into(), 10u128.into()))] + )); + + assert_ok!(StablePool::::add_liquidity( + RawOrigin::Signed(fee_account.clone()).into(), + 0, + amounts, + ::Balance::zero() + )); + + #[extrinsic_call] + _( + RawOrigin::Signed(fee_account), + 0, + 0, + 1, + ::Balance::from(50_000_000_000u128.into()), + ::Balance::zero(), + ); + + Ok(()) + } + + #[benchmark] + fn redeem_proportion() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; T::MultiCurrency::deposit( BNC.into(), &fee_account, - ::Balance::from(1000_000_000_000u128.into()) + ::Balance::from(1000_000_000_000u128.into()), )?; - let amounts = vec![::Balance::from(100_000_000_000u128.into()), ::Balance::from(100_000_000u128.into())]; + + let amounts = vec![ + ::Balance::from(100_000_000_000u128.into()), + ::Balance::from(100_000_000u128.into()), + ]; + assert_ok!(StablePool::::create_pool( - RawOrigin::Root.into(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 0u128.into(), - 0u128.into(), - 0u128.into(), - 220u128.into(), - fee_account.clone(), - fee_account.clone(), - 1000000000000u128.into())); - assert_ok!(StablePool::::edit_token_rate(RawOrigin::Root.into(), 0, vec![(BNC.into(), (9u128.into(), 10u128.into()))])); - assert_ok!(StablePool::::add_liquidity(RawOrigin::Signed(fee_account.clone()).into(), 0, amounts, ::Balance::zero())); - // assert_ok!(StablePool::::swap(RawOrigin::Signed(fee_account.clone()).into(), 0, 0, 1, ::Balance::from(50_000_000_000u128.into()), ::Balance::zero())); - }: _(RawOrigin::Signed(fee_account), 0, ::Balance::from(5_000_000u128.into()), vec![::Balance::zero(), ::Balance::zero()]) - - redeem_single { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + RawOrigin::Root.into(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 0u128.into(), + 0u128.into(), + 0u128.into(), + 220u128.into(), + fee_account.clone(), + fee_account.clone(), + 1000000000000u128.into() + )); + + assert_ok!(StablePool::::edit_token_rate( + RawOrigin::Root.into(), + 0, + vec![(BNC.into(), (9u128.into(), 10u128.into()))] + )); + + assert_ok!(StablePool::::add_liquidity( + RawOrigin::Signed(fee_account.clone()).into(), + 0, + amounts, + ::Balance::zero() + )); + + #[extrinsic_call] + _( + RawOrigin::Signed(fee_account), + 0, + ::Balance::from(5_000_000u128.into()), + vec![ + ::Balance::zero(), + ::Balance::zero(), + ], + ); + + Ok(()) + } + + #[benchmark] + fn redeem_single() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; + T::MultiCurrency::deposit( BNC.into(), &fee_account, - ::Balance::from(1000_000_000_000u128.into()) + ::Balance::from(1000_000_000_000u128.into()), )?; - let amounts = vec![::Balance::from(100_000_000_000u128.into()), ::Balance::from(100_000_000u128.into())]; + + let amounts = vec![ + ::Balance::from(100_000_000_000u128.into()), + ::Balance::from(100_000_000u128.into()), + ]; + assert_ok!(StablePool::::create_pool( - RawOrigin::Root.into(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 0u128.into(), - 0u128.into(), - 0u128.into(), - 220u128.into(), - fee_account.clone(), - fee_account.clone(), - 1000000000000u128.into())); - assert_ok!(StablePool::::edit_token_rate(RawOrigin::Root.into(), 0, vec![(BNC.into(), (9u128.into(), 10u128.into()))])); - assert_ok!(StablePool::::add_liquidity(RawOrigin::Signed(fee_account.clone()).into(), 0, amounts, ::Balance::zero())); - }: _(RawOrigin::Signed(fee_account), 0, ::Balance::from(5_000_000u128.into()), 0, ::Balance::zero(), 2) - - redeem_multi { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + RawOrigin::Root.into(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 0u128.into(), + 0u128.into(), + 0u128.into(), + 220u128.into(), + fee_account.clone(), + fee_account.clone(), + 1000000000000u128.into() + )); + + assert_ok!(StablePool::::edit_token_rate( + RawOrigin::Root.into(), + 0, + vec![(BNC.into(), (9u128.into(), 10u128.into()))] + )); + + assert_ok!(StablePool::::add_liquidity( + RawOrigin::Signed(fee_account.clone()).into(), + 0, + amounts, + ::Balance::zero() + )); + + #[extrinsic_call] + _( + RawOrigin::Signed(fee_account), + 0, + ::Balance::from(5_000_000u128.into()), + 0, + ::Balance::zero(), + 2, + ); + + Ok(()) + } + + #[benchmark] + fn redeem_multi() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; + T::MultiCurrency::deposit( BNC.into(), &fee_account, - ::Balance::from(1000_000_000_000u128.into()) + ::Balance::from(1000_000_000_000u128.into()), )?; - let amounts = vec![::Balance::from(100_000_000_000u128.into()), ::Balance::from(100_000_000_000u128.into())]; + + let amounts = vec![ + ::Balance::from(100_000_000_000u128.into()), + ::Balance::from(100_000_000_000u128.into()), + ]; + assert_ok!(StablePool::::create_pool( - RawOrigin::Root.into(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 0u128.into(), - 0u128.into(), - 0u128.into(), - 220u128.into(), - fee_account.clone(), - fee_account.clone(), - 1000000000000u128.into())); - assert_ok!(StablePool::::edit_token_rate(RawOrigin::Root.into(), 0, vec![(BNC.into(), (9u128.into(), 10u128.into()))])); - assert_ok!(StablePool::::add_liquidity(RawOrigin::Signed(fee_account.clone()).into(), 0, amounts, ::Balance::zero())); - let redeem_amounts = vec![::Balance::from(90_000_000u128.into()), ::Balance::from(90_000_000u128.into())]; - }: _(RawOrigin::Signed(fee_account), 0, redeem_amounts, ::Balance::from(200_000_000_000u128.into())) - - modify_a { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + RawOrigin::Root.into(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 0u128.into(), + 0u128.into(), + 0u128.into(), + 220u128.into(), + fee_account.clone(), + fee_account.clone(), + 1000000000000u128.into() + )); + + assert_ok!(StablePool::::edit_token_rate( + RawOrigin::Root.into(), + 0, + vec![(BNC.into(), (9u128.into(), 10u128.into()))] + )); + + assert_ok!(StablePool::::add_liquidity( + RawOrigin::Signed(fee_account.clone()).into(), + 0, + amounts, + ::Balance::zero() + )); + + let redeem_amounts = vec![ + ::Balance::from(90_000_000u128.into()), + ::Balance::from(90_000_000u128.into()), + ]; + + #[extrinsic_call] + _( + RawOrigin::Signed(fee_account), + 0, + redeem_amounts, + ::Balance::from(200_000_000_000u128.into()), + ); + + Ok(()) + } + + #[benchmark] + fn modify_a() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; + assert_ok!(StablePool::::create_pool( RawOrigin::Root.into(), vec![coin0.into(), coin1.into()], @@ -249,14 +438,21 @@ benchmarks! { 220u128.into(), fee_account.clone(), fee_account.clone(), - 1000000000000u128.into())); - }: _(RawOrigin::Root, 0, 9u128.into(), 9u32.into()) + 1000000000000u128.into() + )); - modify_fees { - let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + #[extrinsic_call] + _(RawOrigin::Root, 0, 9u128.into(), 9u32.into()); + + Ok(()) + } + + #[benchmark] + fn modify_fees() -> Result<(), BenchmarkError> { + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; + assert_ok!(StablePool::::create_pool( RawOrigin::Root.into(), vec![coin0.into(), coin1.into()], @@ -267,14 +463,28 @@ benchmarks! { 220u128.into(), fee_account.clone(), fee_account.clone(), - 1000000000000u128.into())); - }: _(RawOrigin::Root, 0, Some(1000u128.into()), Some(1000u128.into()), Some(1000u128.into())) + 1000000000000u128.into() + )); + + #[extrinsic_call] + _( + RawOrigin::Root, + 0, + Some(1000u128.into()), + Some(1000u128.into()), + Some(1000u128.into()), + ); + + Ok(()) + } - modify_recipients { + #[benchmark] + fn modify_recipients() -> Result<(), BenchmarkError> { let test_account: T::AccountId = whitelisted_caller(); - let fee_account: T::AccountId = account("seed",1,1); + let fee_account: T::AccountId = account("seed", 1, 1); let coin0 = BNC; let coin1 = BNC; + assert_ok!(StablePool::::create_pool( RawOrigin::Root.into(), vec![coin0.into(), coin1.into()], @@ -285,8 +495,31 @@ benchmarks! { 220u128.into(), fee_account.clone(), fee_account.clone(), - 1000000000000u128.into())); - }: _(RawOrigin::Root, 0, Some(test_account.clone()), Some(test_account)) + 1000000000000u128.into() + )); + + #[extrinsic_call] + _( + RawOrigin::Root, + 0, + Some(test_account.clone()), + Some(test_account), + ); + + Ok(()) + } - impl_benchmark_test_suite!(StablePool, crate::mock::ExtBuilder::default().build(), crate::mock::Test); + // This line generates test cases for benchmarking, and could be run by: + // `cargo test -p pallet-example-basic --all-features`, you will see one line per case: + // `test benchmarking::bench_sort_vector ... ok` + // `test benchmarking::bench_accumulate_dummy ... ok` + // `test benchmarking::bench_set_dummy_benchmark ... ok` in the result. + // + // The line generates three steps per benchmark, with repeat=1 and the three steps are + // [low, mid, high] of the range. + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Test + ); } diff --git a/pallets/stable-pool/src/lib.rs b/pallets/stable-pool/src/lib.rs index ba79161298..ded1d80606 100644 --- a/pallets/stable-pool/src/lib.rs +++ b/pallets/stable-pool/src/lib.rs @@ -268,9 +268,9 @@ pub mod pallet { // Ensure that the provided fees are within valid limits ensure!( - mint_fee.map(|x| x < fee_denominator).unwrap_or(true) && - swap_fee.map(|x| x < fee_denominator).unwrap_or(true) && - redeem_fee.map(|x| x < fee_denominator).unwrap_or(true), + mint_fee.map(|x| x < fee_denominator).unwrap_or(true) + && swap_fee.map(|x| x < fee_denominator).unwrap_or(true) + && redeem_fee.map(|x| x < fee_denominator).unwrap_or(true), bifrost_stable_asset::Error::::ArgumentsError ); @@ -410,7 +410,12 @@ impl Pallet { fn ensure_can_refresh( token_in: AssetIdOf, token_out: AssetIdOf, - ) -> Option<(AssetIdOf, AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf, Permill)> { + ) -> Option<( + AssetIdOf, + AtLeast64BitUnsignedOf, + AtLeast64BitUnsignedOf, + Permill, + )> { if let Some(hardcap) = Self::get_token_rate_hardcap(token_in) { if T::CurrencyIdConversion::convert_to_token(token_in).ok() == Some(token_out) { return Some(( @@ -496,8 +501,12 @@ impl Pallet { )?; } T::StableAsset::collect_yield(pool_id, &mut pool_info)?; - let MintResult { mint_amount, fee_amount, balances, total_supply } = - bifrost_stable_asset::Pallet::::get_mint_amount(&pool_info, &amounts)?; + let MintResult { + mint_amount, + fee_amount, + balances, + total_supply, + } = bifrost_stable_asset::Pallet::::get_mint_amount(&pool_info, &amounts)?; let a = T::StableAsset::get_a( pool_info.a, pool_info.a_block, @@ -511,8 +520,8 @@ impl Pallet { continue; } ensure!( - amounts_old[i] >= - Self::downscale( + amounts_old[i] + >= Self::downscale( *amount, pool_id, *pool_info @@ -597,8 +606,8 @@ impl Pallet { let zero = Zero::zero(); for i in 0..amounts.len() { ensure!( - amounts[i] >= - *min_redeem_amounts + amounts[i] + >= *min_redeem_amounts .get(i as usize) .ok_or(bifrost_stable_asset::Error::::ArgumentsMismatch)?, bifrost_stable_asset::Error::::RedeemUnderMin @@ -674,13 +683,18 @@ impl Pallet { .ok_or(bifrost_stable_asset::Error::::ArgumentsMismatch)?, )?; } - let RedeemMultiResult { redeem_amount, fee_amount, balances, total_supply, burn_amount } = - bifrost_stable_asset::Pallet::::get_redeem_multi_amount( - &mut pool_info, - &new_amounts, - )?; + let RedeemMultiResult { + redeem_amount, + fee_amount, + balances, + total_supply, + burn_amount, + } = bifrost_stable_asset::Pallet::::get_redeem_multi_amount(&mut pool_info, &new_amounts)?; let zero: T::Balance = Zero::zero(); - ensure!(redeem_amount <= max_redeem_amount, Error::::RedeemOverMax); + ensure!( + redeem_amount <= max_redeem_amount, + Error::::RedeemOverMax + ); if fee_amount > zero { ::Assets::transfer( pool_info.pool_asset, @@ -745,8 +759,13 @@ impl Pallet { T::StableAsset::pool(pool_id).ok_or(bifrost_stable_asset::Error::::PoolNotFound)?; T::StableAsset::collect_yield(pool_id, &mut pool_info)?; - let RedeemSingleResult { mut dy, fee_amount, total_supply, balances, redeem_amount } = - bifrost_stable_asset::Pallet::::get_redeem_single_amount(&mut pool_info, amount, i)?; + let RedeemSingleResult { + mut dy, + fee_amount, + total_supply, + balances, + redeem_amount, + } = bifrost_stable_asset::Pallet::::get_redeem_single_amount(&mut pool_info, amount, i)?; dy = Self::downscale( dy, pool_id, @@ -758,8 +777,14 @@ impl Pallet { let i_usize = i as usize; let pool_size = pool_info.assets.len(); let asset_length_usize = asset_length as usize; - ensure!(asset_length_usize == pool_size, bifrost_stable_asset::Error::::ArgumentsError); - ensure!(dy >= min_redeem_amount, bifrost_stable_asset::Error::::RedeemUnderMin); + ensure!( + asset_length_usize == pool_size, + bifrost_stable_asset::Error::::ArgumentsError + ); + ensure!( + dy >= min_redeem_amount, + bifrost_stable_asset::Error::::RedeemUnderMin + ); if fee_amount > Zero::zero() { T::MultiCurrency::transfer( pool_info.pool_asset, @@ -823,13 +848,17 @@ impl Pallet { .ok_or(bifrost_stable_asset::Error::::ArgumentsMismatch)?; T::StableAsset::collect_yield(pool_id, &mut pool_info)?; let dx = Self::upscale(amount, pool_id, token_in)?; - let SwapResult { dx: _, dy, y, balance_i } = - bifrost_stable_asset::Pallet::::get_swap_amount( - &pool_info, - currency_id_in, - currency_id_out, - dx, - )?; + let SwapResult { + dx: _, + dy, + y, + balance_i, + } = bifrost_stable_asset::Pallet::::get_swap_amount( + &pool_info, + currency_id_in, + currency_id_out, + dx, + )?; let downscale_out = Self::downscale(dy, pool_id, token_out)?; ensure!(downscale_out >= min_dy, Error::::SwapUnderMin); @@ -1044,12 +1073,12 @@ impl Pallet { currency_id_out: &AssetIdOf, ) -> Option<(StableAssetPoolId, PoolTokenIndex, PoolTokenIndex)> { Pools::::iter().find_map(|(pool_id, pool_info)| { - if pool_info.assets.get(0) == Some(currency_id_in) && - pool_info.assets.get(1) == Some(currency_id_out) + if pool_info.assets.get(0) == Some(currency_id_in) + && pool_info.assets.get(1) == Some(currency_id_out) { Some((pool_id, 0, 1)) - } else if pool_info.assets.get(0) == Some(currency_id_out) && - pool_info.assets.get(1) == Some(currency_id_in) + } else if pool_info.assets.get(0) == Some(currency_id_out) + && pool_info.assets.get(1) == Some(currency_id_in) { Some((pool_id, 1, 0)) } else { diff --git a/pallets/stable-pool/src/mock.rs b/pallets/stable-pool/src/mock.rs index 20dcfac754..1196288bc8 100644 --- a/pallets/stable-pool/src/mock.rs +++ b/pallets/stable-pool/src/mock.rs @@ -240,6 +240,7 @@ impl bifrost_stable_asset::Config for Test { type WeightInfo = (); type ListingOrigin = EnsureSignedBy; type EnsurePoolAssetId = EnsurePoolAssetId; + type BlockNumberProvider = System; } impl bifrost_stable_pool::Config for Test { @@ -289,6 +290,7 @@ impl bifrost_vtoken_minting::Config for Test { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } pub struct Slp; @@ -331,7 +333,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -364,7 +368,10 @@ impl ExtBuilder { // Build genesis storage according to the mock runtime. pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap().into(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap() + .into(); bifrost_asset_registry::GenesisConfig:: { currency: vec![ @@ -410,3 +417,8 @@ impl ExtBuilder { t.into() } } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/stable-pool/src/tests.rs b/pallets/stable-pool/src/tests.rs index a6277a30a9..b2d16c6098 100644 --- a/pallets/stable-pool/src/tests.rs +++ b/pallets/stable-pool/src/tests.rs @@ -85,13 +85,31 @@ fn create_movr_pool() -> (CurrencyId, CurrencyId, CurrencyId, u128) { } fn init() -> (CurrencyId, CurrencyId, CurrencyId, u128) { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint(Some(3).into(), DOT, 100_000_000, BoundedVec::default(), None)); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); let (coin0, coin1, pool_asset, swap_id) = create_pool(); System::set_block_number(2); let amounts = vec![10000000u128, 20000000u128]; assert_ok!(StableAsset::mint(RuntimeOrigin::signed(3), 0, amounts, 0)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(3), 0, 0, 1, 5000000u128, 0, 2)); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(3), + 0, + 0, + 1, + 5000000u128, + 0, + 2 + )); assert_eq!(Tokens::free_balance(DOT, &3), 85000000u128 - BALANCE_OFF); (coin0, coin1, pool_asset, swap_id) } @@ -99,936 +117,1152 @@ fn init() -> (CurrencyId, CurrencyId, CurrencyId, u128) { #[test] fn modify_a_argument_error_failed() { env_logger::try_init().unwrap_or(()); - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (_coin0, _coin1, _pool_asset, _swap_id) = create_pool(); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (_coin0, _coin1, _pool_asset, _swap_id) = create_pool(); - assert_noop!( - StableAsset::modify_a(RuntimeOrigin::signed(1), 0, 100, 0), - bifrost_stable_asset::Error::::ArgumentsError - ); - }); + assert_noop!( + StableAsset::modify_a(RuntimeOrigin::signed(1), 0, 100, 0), + bifrost_stable_asset::Error::::ArgumentsError + ); + }); } #[test] fn calc() { env_logger::try_init().unwrap_or(()); - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (_coin0, _coin1, _pool_asset, _swap_id) = create_pool(); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (_coin0, _coin1, _pool_asset, _swap_id) = create_pool(); - assert_noop!( - StableAsset::modify_a(RuntimeOrigin::signed(1), 0, 100, 0), - bifrost_stable_asset::Error::::ArgumentsError - ); - }); + assert_noop!( + StableAsset::modify_a(RuntimeOrigin::signed(1), 0, 100, 0), + bifrost_stable_asset::Error::::ArgumentsError + ); + }); } #[test] fn create_pool_successful() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let coin0 = DOT; - let coin1 = VDOT; - assert_eq!(PoolCount::::get(), 0); - assert_ok!(StablePool::create_pool( - RuntimeOrigin::root(), - vec![coin0, coin1], - vec![1u128, 1u128], - 1u128, - 1u128, - 1u128, - 1u128, - 1, - 1, - 1000000000000000000u128, - )); - assert_eq!( - Pools::::get(0), - Some(StableAssetPoolInfo { - pool_id: 0, - pool_asset: CurrencyId::BLP(0), - assets: vec![coin0, coin1], - precisions: vec![1u128, 1u128], - mint_fee: 1u128, - swap_fee: 1u128, - redeem_fee: 1u128, - total_supply: 0u128, - a: 1u128, - a_block: 0, - future_a: 1u128, - future_a_block: 0, - balances: vec![0, 0], - fee_recipient: 1, - account_id: 30160825295207673652903702381u128, - yield_recipient: 1, - precision: 1000000000000000000u128, - }) - ); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let coin0 = DOT; + let coin1 = VDOT; + assert_eq!(PoolCount::::get(), 0); + assert_ok!(StablePool::create_pool( + RuntimeOrigin::root(), + vec![coin0, coin1], + vec![1u128, 1u128], + 1u128, + 1u128, + 1u128, + 1u128, + 1, + 1, + 1000000000000000000u128, + )); + assert_eq!( + Pools::::get(0), + Some(StableAssetPoolInfo { + pool_id: 0, + pool_asset: CurrencyId::BLP(0), + assets: vec![coin0, coin1], + precisions: vec![1u128, 1u128], + mint_fee: 1u128, + swap_fee: 1u128, + redeem_fee: 1u128, + total_supply: 0u128, + a: 1u128, + a_block: 0, + future_a: 1u128, + future_a_block: 0, + balances: vec![0, 0], + fee_recipient: 1, + account_id: 30160825295207673652903702381u128, + yield_recipient: 1, + precision: 1000000000000000000u128, + }) + ); + }); } #[test] fn mint_successful_equal_amounts() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint( - Some(3).into(), - DOT, - 100_000_000, - BoundedVec::default(), - None - )); - let (coin0, coin1, pool_asset, swap_id) = create_pool(); - System::set_block_number(2); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); - let amounts = vec![10000000u128, 10000000u128]; - assert_noop!( - StableAsset::mint( + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_minimum_mint( RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); + let (coin0, coin1, pool_asset, swap_id) = create_pool(); + System::set_block_number(2); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), 0, - amounts.clone(), - 2000000000000000000000000u128 - ), - bifrost_stable_asset::Error::::MintUnderMin - ); - assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); - // assert_ok!(StableAsset::mint(RuntimeOrigin::signed(3), 0, amounts.clone(), 0)); - assert_eq!( - Pools::::get(0), - Some(StableAssetPoolInfo { - pool_id: 0, - pool_asset, - assets: vec![coin0, coin1], - precisions: vec![10000000000u128, 10000000000u128], - mint_fee: 10000000u128, - swap_fee: 20000000u128, - redeem_fee: 50000000u128, - total_supply: 200000000000000000u128, - a: 10000u128, - a_block: 0, - future_a: 10000u128, - future_a_block: 0, - balances: vec![100000000000000000u128, 100000000000000000u128], - fee_recipient: 2, - account_id: swap_id, - yield_recipient: 1, - precision: 1000000000000000000u128, - }) - ); + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); + let amounts = vec![10000000u128, 10000000u128]; + assert_noop!( + StableAsset::mint( + RuntimeOrigin::signed(1), + 0, + amounts.clone(), + 2000000000000000000000000u128 + ), + bifrost_stable_asset::Error::::MintUnderMin + ); + assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); + // assert_ok!(StableAsset::mint(RuntimeOrigin::signed(3), 0, amounts.clone(), 0)); + assert_eq!( + Pools::::get(0), + Some(StableAssetPoolInfo { + pool_id: 0, + pool_asset, + assets: vec![coin0, coin1], + precisions: vec![10000000000u128, 10000000000u128], + mint_fee: 10000000u128, + swap_fee: 20000000u128, + redeem_fee: 50000000u128, + total_supply: 200000000000000000u128, + a: 10000u128, + a_block: 0, + future_a: 10000u128, + future_a_block: 0, + balances: vec![100000000000000000u128, 100000000000000000u128], + fee_recipient: 2, + account_id: swap_id, + yield_recipient: 1, + precision: 1000000000000000000u128, + }) + ); - assert_eq!(Tokens::free_balance(coin0, &3), 90000000u128 + BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &3), 90000000u128 + BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin0, &swap_id), 10000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &swap_id), 10000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(pool_asset, &3), 199800000000000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(pool_asset, &2), 200000000000000u128 - BALANCE_OFF); - // fee_recipient - }); + assert_eq!(Tokens::free_balance(coin0, &3), 90000000u128 + BALANCE_OFF); + assert_eq!(Tokens::free_balance(coin1, &3), 90000000u128 + BALANCE_OFF); + assert_eq!( + Tokens::free_balance(coin0, &swap_id), + 10000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(coin1, &swap_id), + 10000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(pool_asset, &3), + 199800000000000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(pool_asset, &2), + 200000000000000u128 - BALANCE_OFF + ); + // fee_recipient + }); } #[test] fn swap_successful() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint( - Some(3).into(), - DOT, - 100_000_000, - BoundedVec::default(), - None - )); - let (coin0, coin1, pool_asset, swap_id) = create_pool(); - System::set_block_number(2); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); + let (coin0, coin1, pool_asset, swap_id) = create_pool(); + System::set_block_number(2); - let amounts = vec![10000000u128, 20000000u128]; - assert_ok!(StableAsset::mint(RuntimeOrigin::signed(3), 0, amounts, 0)); - assert_ok!(StableAsset::swap(RuntimeOrigin::signed(3), 0, 0, 1, 5000000u128, 0, 2)); - assert_eq!( - Pools::::get(0), - Some(StableAssetPoolInfo { - pool_id: 0, - pool_asset, - assets: vec![coin0, coin1], - precisions: vec![10000000000u128, 10000000000u128], - mint_fee: 10000000u128, - swap_fee: 20000000u128, - redeem_fee: 50000000u128, - total_supply: 300006989999594867u128, - a: 10000u128, - a_block: 0, - future_a: 10000u128, - future_a_block: 0, - balances: vec![150000000000000000u128, 150006990000000000u128], - fee_recipient: 2, - account_id: swap_id, - yield_recipient: 1, - precision: 1000000000000000000u128, - }) - ); - assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &3), 84999301u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin0, &swap_id), 15000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &swap_id), 15000699u128 - BALANCE_OFF); - }); + let amounts = vec![10000000u128, 20000000u128]; + assert_ok!(StableAsset::mint(RuntimeOrigin::signed(3), 0, amounts, 0)); + assert_ok!(StableAsset::swap( + RuntimeOrigin::signed(3), + 0, + 0, + 1, + 5000000u128, + 0, + 2 + )); + assert_eq!( + Pools::::get(0), + Some(StableAssetPoolInfo { + pool_id: 0, + pool_asset, + assets: vec![coin0, coin1], + precisions: vec![10000000000u128, 10000000000u128], + mint_fee: 10000000u128, + swap_fee: 20000000u128, + redeem_fee: 50000000u128, + total_supply: 300006989999594867u128, + a: 10000u128, + a_block: 0, + future_a: 10000u128, + future_a_block: 0, + balances: vec![150000000000000000u128, 150006990000000000u128], + fee_recipient: 2, + account_id: swap_id, + yield_recipient: 1, + precision: 1000000000000000000u128, + }) + ); + assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); + assert_eq!(Tokens::free_balance(coin1, &3), 84999301u128 - BALANCE_OFF); + assert_eq!( + Tokens::free_balance(coin0, &swap_id), + 15000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(coin1, &swap_id), + 15000699u128 - BALANCE_OFF + ); + }); } #[test] fn get_swap_output_amount() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); - System::set_block_number(2); - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint( - Some(3).into(), - DOT, - 100_000_000, - BoundedVec::default(), - None - )); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); + System::set_block_number(2); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); - let (coin0, coin1, pool_asset, swap_id) = create_pool(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); - let amounts = vec![10000000u128, 20000000u128]; - assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); - assert_eq!(StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), Some(4999301)); - assert_noop!( - StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 4999302), - Error::::SwapUnderMin - ); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 4999301)); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] - )); - assert_eq!(StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), Some(4485945)); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); - assert_eq!(StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), Some(4980724)); - assert_noop!( - StablePool::on_swap(&3u128, 0, 1, 1, 5000000u128, 0), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_noop!( - StablePool::on_swap(&3u128, 3, 0, 1, 5000000u128, 0), - bifrost_stable_asset::Error::::PoolNotFound - ); - assert_noop!( - StablePool::on_swap(&3u128, 0, 2, 1, 5000000u128, 0), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_noop!( - StablePool::on_swap(&3u128, 0, 0, 2, 5000000u128, 0), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_noop!( - StablePool::on_swap(&3u128, 0, 0, 1, 0u128, 0), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_noop!( - StablePool::on_swap(&3u128, 0, 0, 1, 500000000u128, 0u128), - orml_tokens::Error::::BalanceTooLow - ); - assert_eq!( - Pools::::get(0), - Some(StableAssetPoolInfo { - pool_id: 0, - pool_asset, - assets: vec![coin0, coin1], - precisions: vec![10000000000u128, 10000000000u128], - mint_fee: 10000000u128, - swap_fee: 20000000u128, - redeem_fee: 50000000u128, - total_supply: 300006989999594867u128, - a: 10000u128, - a_block: 2, - future_a: 10000u128, - future_a_block: 2, - balances: vec![150000000000000000u128, 150006990000000000u128], - fee_recipient: 2, - account_id: swap_id, - yield_recipient: 1, - precision: 1000000000000000000u128, - }) - ); - assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &3), 84999301u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin0, &swap_id), 15000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &swap_id), 15000699u128 - BALANCE_OFF); - }); + let (coin0, coin1, pool_asset, swap_id) = create_pool(); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); + let amounts = vec![10000000u128, 20000000u128]; + assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); + assert_eq!( + StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), + Some(4999301) + ); + assert_noop!( + StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 4999302), + Error::::SwapUnderMin + ); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 4999301)); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] + )); + assert_eq!( + StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), + Some(4485945) + ); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); + assert_eq!( + StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), + Some(4980724) + ); + assert_noop!( + StablePool::on_swap(&3u128, 0, 1, 1, 5000000u128, 0), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_noop!( + StablePool::on_swap(&3u128, 3, 0, 1, 5000000u128, 0), + bifrost_stable_asset::Error::::PoolNotFound + ); + assert_noop!( + StablePool::on_swap(&3u128, 0, 2, 1, 5000000u128, 0), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_noop!( + StablePool::on_swap(&3u128, 0, 0, 2, 5000000u128, 0), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_noop!( + StablePool::on_swap(&3u128, 0, 0, 1, 0u128, 0), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_noop!( + StablePool::on_swap(&3u128, 0, 0, 1, 500000000u128, 0u128), + orml_tokens::Error::::BalanceTooLow + ); + assert_eq!( + Pools::::get(0), + Some(StableAssetPoolInfo { + pool_id: 0, + pool_asset, + assets: vec![coin0, coin1], + precisions: vec![10000000000u128, 10000000000u128], + mint_fee: 10000000u128, + swap_fee: 20000000u128, + redeem_fee: 50000000u128, + total_supply: 300006989999594867u128, + a: 10000u128, + a_block: 2, + future_a: 10000u128, + future_a_block: 2, + balances: vec![150000000000000000u128, 150006990000000000u128], + fee_recipient: 2, + account_id: swap_id, + yield_recipient: 1, + precision: 1000000000000000000u128, + }) + ); + assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); + assert_eq!(Tokens::free_balance(coin1, &3), 84999301u128 - BALANCE_OFF); + assert_eq!( + Tokens::free_balance(coin0, &swap_id), + 15000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(coin1, &swap_id), + 15000699u128 - BALANCE_OFF + ); + }); } #[test] fn mint_swap_redeem1() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint( - Some(3).into(), - DOT, - 100_000_000, - BoundedVec::default(), - None - )); - assert_ok!(Tokens::set_balance(RuntimeOrigin::root(), 3, VDOT, 90_000_000, 0)); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); + assert_ok!(Tokens::set_balance( + RuntimeOrigin::root(), + 3, + VDOT, + 90_000_000, + 0 + )); - let (coin0, coin1, _pool_asset, swap_id) = create_pool(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] - )); - System::set_block_number(2); + let (coin0, coin1, _pool_asset, swap_id) = create_pool(); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] + )); + System::set_block_number(2); - let amounts = vec![10_000_000u128, 20_000_000u128]; - assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &3), 74502743u128 - BALANCE_OFF); // 90_000_000 - 22_222_222 + 4_502_743 - assert_eq!(Tokens::free_balance(coin0, &swap_id), 15000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &swap_id), 15497257u128 - BALANCE_OFF); - assert_ok!(StablePool::on_swap(&4u128, 0, 0, 1, 15_000_000u128, 0)); - assert_ok!(StablePool::on_swap(&1u128, 0, 0, 1, 500_000_000u128, 0)); - assert_noop!( - StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0]), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_ok!(StablePool::redeem_proportion_inner(&3, 0, 15_000_000_000_000u128, vec![0, 0])); - }); + let amounts = vec![10_000_000u128, 20_000_000u128]; + assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); + assert_eq!(Tokens::free_balance(coin1, &3), 74502743u128 - BALANCE_OFF); // 90_000_000 - 22_222_222 + 4_502_743 + assert_eq!( + Tokens::free_balance(coin0, &swap_id), + 15000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(coin1, &swap_id), + 15497257u128 - BALANCE_OFF + ); + assert_ok!(StablePool::on_swap(&4u128, 0, 0, 1, 15_000_000u128, 0)); + assert_ok!(StablePool::on_swap(&1u128, 0, 0, 1, 500_000_000u128, 0)); + assert_noop!( + StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0]), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_ok!(StablePool::redeem_proportion_inner( + &3, + 0, + 15_000_000_000_000u128, + vec![0, 0] + )); + }); } #[test] fn mint_swap_redeem2() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint( - Some(3).into(), - DOT, - 100_000_000, - BoundedVec::default(), - None - )); - assert_ok!(Tokens::set_balance(RuntimeOrigin::root(), 3, VDOT, 90_000_000, 0)); - let (coin0, coin1, pool_asset, swap_id) = create_pool2(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] - )); - let amounts = vec![10_000_000u128, 20_000_000u128]; - assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); - assert_eq!(Tokens::free_balance(coin1, &3), 70_000_000 - BALANCE_OFF); // 90_000_000 - 20_000_000 - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &3), 74502743u128 - BALANCE_OFF); // 90_000_000 - 20_000_000 + 4502743 - assert_eq!(Tokens::free_balance(coin0, &swap_id), 15000000u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(coin1, &swap_id), 15497257u128 - BALANCE_OFF); - assert_eq!(Tokens::free_balance(pool_asset, &3), 32176560); - assert_eq!(Tokens::free_balance(pool_asset, &2), 42231); - assert_eq!(Tokens::free_balance(pool_asset, &1), 0); - assert_eq!( - Tokens::free_balance(pool_asset, &2) + Tokens::free_balance(pool_asset, &3), - ::MultiCurrency::total_issuance(pool_asset) - ); - assert_noop!( - StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0]), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_noop!( - StablePool::redeem_proportion_inner(&3, 0, 0u128, vec![0u128, 0u128]), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_noop!( - StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0, 0, 0]), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_noop!( - StablePool::redeem_proportion_inner( + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); + assert_ok!(Tokens::set_balance( + RuntimeOrigin::root(), + 3, + VDOT, + 90_000_000, + 0 + )); + let (coin0, coin1, pool_asset, swap_id) = create_pool2(); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] + )); + let amounts = vec![10_000_000u128, 20_000_000u128]; + assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); + assert_eq!(Tokens::free_balance(coin1, &3), 70_000_000 - BALANCE_OFF); // 90_000_000 - 20_000_000 + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); + assert_eq!(Tokens::free_balance(coin1, &3), 74502743u128 - BALANCE_OFF); // 90_000_000 - 20_000_000 + 4502743 + assert_eq!( + Tokens::free_balance(coin0, &swap_id), + 15000000u128 - BALANCE_OFF + ); + assert_eq!( + Tokens::free_balance(coin1, &swap_id), + 15497257u128 - BALANCE_OFF + ); + assert_eq!(Tokens::free_balance(pool_asset, &3), 32176560); + assert_eq!(Tokens::free_balance(pool_asset, &2), 42231); + assert_eq!(Tokens::free_balance(pool_asset, &1), 0); + assert_eq!( + Tokens::free_balance(pool_asset, &2) + Tokens::free_balance(pool_asset, &3), + ::MultiCurrency::total_issuance(pool_asset) + ); + assert_noop!( + StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0]), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_noop!( + StablePool::redeem_proportion_inner(&3, 0, 0u128, vec![0u128, 0u128]), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_noop!( + StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0, 0, 0]), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_noop!( + StablePool::redeem_proportion_inner( + &3, + 0, + 15_000_000u128, + vec![100000000000000000u128, 0] + ), + bifrost_stable_asset::Error::::RedeemUnderMin + ); + assert_noop!( + StablePool::redeem_proportion_inner(&3, 3, 15_000_000u128, vec![0, 0]), + bifrost_stable_asset::Error::::PoolNotFound + ); + let pool_account: u128 = StableAssetPalletId::get().into_account_truncating(); + assert_eq!(Tokens::free_balance(coin0, &pool_account), 15000000); + assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); + assert_ok!(StablePool::redeem_proportion_inner( &3, 0, - 15_000_000u128, - vec![100000000000000000u128, 0] - ), - bifrost_stable_asset::Error::::RedeemUnderMin - ); - assert_noop!( - StablePool::redeem_proportion_inner(&3, 3, 15_000_000u128, vec![0, 0]), - bifrost_stable_asset::Error::::PoolNotFound - ); - let pool_account: u128 = StableAssetPalletId::get().into_account_truncating(); - assert_eq!(Tokens::free_balance(coin0, &pool_account), 15000000); - assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); - assert_ok!(StablePool::redeem_proportion_inner(&3, 0, 32176560, vec![0, 0])); - assert_eq!(Tokens::free_balance(pool_asset, &2), 203114); - assert_eq!(Tokens::free_balance(coin0, &pool_account), 94563); - let free = 85000000 + 15000000 - 94563; // 99905437 - assert_eq!(Tokens::free_balance(coin0, &3), free); - }); + 32176560, + vec![0, 0] + )); + assert_eq!(Tokens::free_balance(pool_asset, &2), 203114); + assert_eq!(Tokens::free_balance(coin0, &pool_account), 94563); + let free = 85000000 + 15000000 - 94563; // 99905437 + assert_eq!(Tokens::free_balance(coin0, &3), free); + }); } #[test] fn mint_swap_redeem_for_precisions() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0)); - assert_ok!(VtokenMinting::mint( - Some(3).into(), - DOT, - 100_000_000, - BoundedVec::default(), - None - )); - assert_ok!(Tokens::set_balance(RuntimeOrigin::root(), 3, VDOT, 90_000_000, 0)); - let (coin0, coin1, _pool_asset, _swap_id) = create_pool2(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] - )); - let amounts = vec![10_000_000u128, 20_000_000u128]; - assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); - assert_eq!(Tokens::free_balance(coin1, &3), 70_000_000 - BALANCE_OFF); // 90_000_000 - 20_000_000 - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); - assert_noop!( - StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0]), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_ok!(StablePool::redeem_proportion_inner(&3, 0, 32176560, vec![0, 0])); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(1), + DOT, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(3).into(), + DOT, + 100_000_000, + BoundedVec::default(), + None + )); + assert_ok!(Tokens::set_balance( + RuntimeOrigin::root(), + 3, + VDOT, + 90_000_000, + 0 + )); + let (coin0, coin1, _pool_asset, _swap_id) = create_pool2(); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))] + )); + let amounts = vec![10_000_000u128, 20_000_000u128]; + assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0)); + assert_eq!(Tokens::free_balance(coin1, &3), 70_000_000 - BALANCE_OFF); // 90_000_000 - 20_000_000 + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!(Tokens::free_balance(coin0, &3), 85000000u128 - BALANCE_OFF); + assert_noop!( + StablePool::redeem_proportion_inner(&3, 0, 15_000_000u128, vec![0]), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_ok!(StablePool::redeem_proportion_inner( + &3, + 0, + 32176560, + vec![0, 0] + )); + }); } #[test] fn redeem_single() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let coin0 = DOT; - let coin1 = VDOT; - let pool_asset = CurrencyId::BLP(0); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let coin0 = DOT; + let coin1 = VDOT; + let pool_asset = CurrencyId::BLP(0); - assert_ok!(::MultiCurrency::deposit( - coin0.into(), - &6, - 1_000_000_000_000u128 - )); - assert_ok!(::MultiCurrency::deposit( - coin1.into(), - &6, - 1_000_000_000_000u128 - )); - assert_eq!(Tokens::free_balance(coin0, &6), 1_000_000_000_000u128); + assert_ok!(::MultiCurrency::deposit( + coin0.into(), + &6, + 1_000_000_000_000u128 + )); + assert_ok!(::MultiCurrency::deposit( + coin1.into(), + &6, + 1_000_000_000_000u128 + )); + assert_eq!(Tokens::free_balance(coin0, &6), 1_000_000_000_000u128); - let amounts = vec![100_000_000_000u128, 100_000_000_000u128]; - assert_ok!(StablePool::create_pool( - RuntimeOrigin::root(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 0u128.into(), - 0u128.into(), - 0u128.into(), - 220u128.into(), - 5, - 5, - 1000000000000u128.into() - )); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(DOT, (1, 1)), (VDOT, (10, 11))] - )); - assert_ok!(StablePool::add_liquidity(RuntimeOrigin::signed(6).into(), 0, amounts, 0)); - assert_eq!(Tokens::free_balance(coin0, &6), 900_000_000_000u128); - assert_eq!(Tokens::free_balance(coin1, &6), 900_000_000_000u128); - assert_eq!(Tokens::free_balance(pool_asset, &6), 209_955_833_377); - assert_ok!(StablePool::redeem_single( - RuntimeOrigin::signed(6).into(), - 0, - 5_000_000_000u128, - 0, - 0, - 2 - )); - assert_noop!( - StablePool::redeem_single(RuntimeOrigin::signed(6), 0, 0u128, 0, 0u128, 2), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_noop!( - StablePool::redeem_single( - RuntimeOrigin::signed(6), + let amounts = vec![100_000_000_000u128, 100_000_000_000u128]; + assert_ok!(StablePool::create_pool( + RuntimeOrigin::root(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 0u128.into(), + 0u128.into(), + 0u128.into(), + 220u128.into(), + 5, + 5, + 1000000000000u128.into() + )); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), 0, - 1000000000000000000u128, + vec![(DOT, (1, 1)), (VDOT, (10, 11))] + )); + assert_ok!(StablePool::add_liquidity( + RuntimeOrigin::signed(6).into(), 0, - 0u128, - 2 - ), - bifrost_stable_asset::Error::::Math - ); - assert_noop!( - StablePool::redeem_single( - RuntimeOrigin::signed(6), + amounts, + 0 + )); + assert_eq!(Tokens::free_balance(coin0, &6), 900_000_000_000u128); + assert_eq!(Tokens::free_balance(coin1, &6), 900_000_000_000u128); + assert_eq!(Tokens::free_balance(pool_asset, &6), 209_955_833_377); + assert_ok!(StablePool::redeem_single( + RuntimeOrigin::signed(6).into(), 0, 5_000_000_000u128, 0, - 6_000_000_000u128, + 0, 2 - ), - bifrost_stable_asset::Error::::RedeemUnderMin - ); - assert_noop!( - StablePool::redeem_single( - RuntimeOrigin::signed(6), + )); + assert_noop!( + StablePool::redeem_single(RuntimeOrigin::signed(6), 0, 0u128, 0, 0u128, 2), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_noop!( + StablePool::redeem_single( + RuntimeOrigin::signed(6), + 0, + 1000000000000000000u128, + 0, + 0u128, + 2 + ), + bifrost_stable_asset::Error::::Math + ); + assert_noop!( + StablePool::redeem_single( + RuntimeOrigin::signed(6), + 0, + 5_000_000_000u128, + 0, + 6_000_000_000u128, + 2 + ), + bifrost_stable_asset::Error::::RedeemUnderMin + ); + assert_noop!( + StablePool::redeem_single( + RuntimeOrigin::signed(6), + 0, + 100000000000000000u128, + 3, + 0u128, + 2 + ), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_noop!( + StablePool::redeem_single( + RuntimeOrigin::signed(6), + 3, + 100000000000000000u128, + 3, + 0u128, + 2 + ), + bifrost_stable_asset::Error::::PoolNotFound + ); + assert_eq!(Tokens::free_balance(pool_asset, &6), 204_955_833_377); + assert_eq!(Tokens::free_balance(coin0, &6), 904_942_938_280); + assert_eq!(Tokens::free_balance(coin1, &6), 900_000_000_000u128); + assert_ok!(StablePool::redeem_single( + RuntimeOrigin::signed(6).into(), + 0, + 5_000_000_000u128, + 1, 0, - 100000000000000000u128, - 3, - 0u128, 2 - ), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_noop!( - StablePool::redeem_single( - RuntimeOrigin::signed(6), - 3, - 100000000000000000u128, - 3, - 0u128, + )); + assert_eq!(Tokens::free_balance(coin1, &6), 904_596_263_064); + assert_noop!( + StablePool::modify_fees( + RuntimeOrigin::root(), + 0, + Some(10_000_000_000), + Some(10_000_000_000), + Some(10_000_000_000) + ), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_ok!(StablePool::modify_fees( + RuntimeOrigin::root(), + 0, + Some(9_999_999_999), + Some(9_999_999_999), + Some(9_999_999_999), + )); + assert_ok!(StablePool::redeem_single( + RuntimeOrigin::signed(6).into(), + 0, + 5_000_000_000u128, + 1, + 0, 2 - ), - bifrost_stable_asset::Error::::PoolNotFound - ); - assert_eq!(Tokens::free_balance(pool_asset, &6), 204_955_833_377); - assert_eq!(Tokens::free_balance(coin0, &6), 904_942_938_280); - assert_eq!(Tokens::free_balance(coin1, &6), 900_000_000_000u128); - assert_ok!(StablePool::redeem_single( - RuntimeOrigin::signed(6).into(), - 0, - 5_000_000_000u128, - 1, - 0, - 2 - )); - assert_eq!(Tokens::free_balance(coin1, &6), 904_596_263_064); - assert_noop!( - StablePool::modify_fees( + )); + assert_eq!(Tokens::free_balance(coin1, &6), 904_596_263_064); + assert_ok!(StablePool::modify_fees( RuntimeOrigin::root(), 0, - Some(10_000_000_000), - Some(10_000_000_000), - Some(10_000_000_000) - ), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_ok!(StablePool::modify_fees( - RuntimeOrigin::root(), - 0, - Some(9_999_999_999), - Some(9_999_999_999), - Some(9_999_999_999), - )); - assert_ok!(StablePool::redeem_single( - RuntimeOrigin::signed(6).into(), - 0, - 5_000_000_000u128, - 1, - 0, - 2 - )); - assert_eq!(Tokens::free_balance(coin1, &6), 904_596_263_064); - assert_ok!(StablePool::modify_fees( - RuntimeOrigin::root(), - 0, - Some(9_999_999_999), - Some(9_999_999_999), - Some(999_999_999), - )); - assert_ok!(StablePool::redeem_single( - RuntimeOrigin::signed(6).into(), - 0, - 5_000_000_000u128, - 1, - 0, - 2 - )); - assert_eq!(Tokens::free_balance(coin1, &6), 908_716_032_298); - }); + Some(9_999_999_999), + Some(9_999_999_999), + Some(999_999_999), + )); + assert_ok!(StablePool::redeem_single( + RuntimeOrigin::signed(6).into(), + 0, + 5_000_000_000u128, + 1, + 0, + 2 + )); + assert_eq!(Tokens::free_balance(coin1, &6), 908_716_032_298); + }); } #[test] fn redeem_multi() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let coin0 = DOT; - let coin1 = VDOT; - let pool_asset = CurrencyId::BLP(0); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let coin0 = DOT; + let coin1 = VDOT; + let pool_asset = CurrencyId::BLP(0); - assert_ok!(::MultiCurrency::deposit( - coin0.into(), - &6, - 1_000_000_000_000u128 - )); - assert_ok!(::MultiCurrency::deposit( - coin1.into(), - &6, - 1_000_000_000_000u128 - )); - assert_eq!(Tokens::free_balance(coin0, &6), 1_000_000_000_000u128); + assert_ok!(::MultiCurrency::deposit( + coin0.into(), + &6, + 1_000_000_000_000u128 + )); + assert_ok!(::MultiCurrency::deposit( + coin1.into(), + &6, + 1_000_000_000_000u128 + )); + assert_eq!(Tokens::free_balance(coin0, &6), 1_000_000_000_000u128); - let amounts = vec![100_000_000_000u128, 100_000_000_000u128]; - assert_ok!(StablePool::create_pool( - RuntimeOrigin::root(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 0u128.into(), - 0u128.into(), - 0u128.into(), - 220u128.into(), - 5, - 5, - 1000000000000u128.into() - )); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(DOT, (1, 1)), (VDOT, (10, 11))] - )); - - assert_noop!( - StablePool::add_liquidity( - RuntimeOrigin::signed(6), + let amounts = vec![100_000_000_000u128, 100_000_000_000u128]; + assert_ok!(StablePool::create_pool( + RuntimeOrigin::root(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 0u128.into(), + 0u128.into(), + 0u128.into(), + 220u128.into(), + 5, + 5, + 1000000000000u128.into() + )); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), 0, - amounts.clone(), - 2000000000000000000000000u128 - ), - Error::::MintUnderMin - ); - let amounts2 = vec![10000000u128, 20000000u128, 20000000u128]; - assert_noop!( - StablePool::add_liquidity(RuntimeOrigin::signed(1), 0, amounts2.clone(), 0), - bifrost_stable_asset::Error::::ArgumentsMismatch - ); - assert_noop!( - StablePool::add_liquidity(RuntimeOrigin::signed(1), 3, amounts2, 0), - bifrost_stable_asset::Error::::PoolNotFound - ); - let amounts_has_zero = vec![0u128, 20000000u128]; - assert_noop!( - StablePool::add_liquidity(RuntimeOrigin::signed(1), 0, amounts_has_zero, 0), - bifrost_stable_asset::Error::::ArgumentsError - ); - assert_ok!(StablePool::add_liquidity(RuntimeOrigin::signed(6).into(), 0, amounts, 0)); - assert_eq!(Tokens::free_balance(coin0, &6), 900_000_000_000u128); - assert_eq!(Tokens::free_balance(coin1, &6), 900_000_000_000u128); - assert_eq!(Tokens::free_balance(pool_asset, &6), 209_955_833_377); + vec![(DOT, (1, 1)), (VDOT, (10, 11))] + )); - assert_noop!( - StablePool::redeem_multi( - RuntimeOrigin::signed(1), + assert_noop!( + StablePool::add_liquidity( + RuntimeOrigin::signed(6), + 0, + amounts.clone(), + 2000000000000000000000000u128 + ), + Error::::MintUnderMin + ); + let amounts2 = vec![10000000u128, 20000000u128, 20000000u128]; + assert_noop!( + StablePool::add_liquidity(RuntimeOrigin::signed(1), 0, amounts2.clone(), 0), + bifrost_stable_asset::Error::::ArgumentsMismatch + ); + assert_noop!( + StablePool::add_liquidity(RuntimeOrigin::signed(1), 3, amounts2, 0), + bifrost_stable_asset::Error::::PoolNotFound + ); + let amounts_has_zero = vec![0u128, 20000000u128]; + assert_noop!( + StablePool::add_liquidity(RuntimeOrigin::signed(1), 0, amounts_has_zero, 0), + bifrost_stable_asset::Error::::ArgumentsError + ); + assert_ok!(StablePool::add_liquidity( + RuntimeOrigin::signed(6).into(), 0, - vec![200_000_000_000u128, 200_000_000_000u128], - 1100000000000000000u128, - ), - bifrost_stable_asset::Error::::Math - ); - assert_noop!( - StablePool::redeem_multi( - RuntimeOrigin::signed(1), + amounts, + 0 + )); + assert_eq!(Tokens::free_balance(coin0, &6), 900_000_000_000u128); + assert_eq!(Tokens::free_balance(coin1, &6), 900_000_000_000u128); + assert_eq!(Tokens::free_balance(pool_asset, &6), 209_955_833_377); + + assert_noop!( + StablePool::redeem_multi( + RuntimeOrigin::signed(1), + 0, + vec![200_000_000_000u128, 200_000_000_000u128], + 1100000000000000000u128, + ), + bifrost_stable_asset::Error::::Math + ); + assert_noop!( + StablePool::redeem_multi( + RuntimeOrigin::signed(1), + 0, + vec![20_000_000_000u128, 20_000_000_000u128], + 1_000_000_000u128, + ), + Error::::RedeemOverMax + ); + assert_ok!(StablePool::redeem_multi( + RuntimeOrigin::signed(6).into(), 0, - vec![20_000_000_000u128, 20_000_000_000u128], - 1_000_000_000u128, - ), - Error::::RedeemOverMax - ); - assert_ok!(StablePool::redeem_multi( - RuntimeOrigin::signed(6).into(), - 0, - vec![5_000_000_000, 5_000_000_000], - 12_000_000_000u128, - )); - assert_eq!(Tokens::free_balance(coin1, &6), 905_000_000_000); - assert_eq!(Tokens::free_balance(coin0, &6), 905_000_000_000); - assert_eq!(Tokens::free_balance(pool_asset, &6), 199_458_041_709); - }); + vec![5_000_000_000, 5_000_000_000], + 12_000_000_000u128, + )); + assert_eq!(Tokens::free_balance(coin1, &6), 905_000_000_000); + assert_eq!(Tokens::free_balance(coin0, &6), 905_000_000_000); + assert_eq!(Tokens::free_balance(pool_asset, &6), 199_458_041_709); + }); } #[test] fn bnc_add_liquidity_should_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let coin0 = BNC; - let coin1 = VBNC; - let pool_asset = CurrencyId::BLP(0); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let coin0 = BNC; + let coin1 = VBNC; + let pool_asset = CurrencyId::BLP(0); - assert_ok!(::MultiCurrency::deposit( - coin1.into(), - &6, - 1_000_000_000_000u128 - )); - assert_eq!(Tokens::free_balance(coin1, &6), 1_000_000_000_000u128); - assert_ok!(::MultiCurrency::deposit( - coin1.into(), - &6, - 1_000_000_000_000u128 - )); - assert_eq!(Tokens::free_balance(coin1, &6), 2_000_000_000_000u128); - assert_eq!(Balances::free_balance(&6), 100_000_000_000_000); + assert_ok!(::MultiCurrency::deposit( + coin1.into(), + &6, + 1_000_000_000_000u128 + )); + assert_eq!(Tokens::free_balance(coin1, &6), 1_000_000_000_000u128); + assert_ok!(::MultiCurrency::deposit( + coin1.into(), + &6, + 1_000_000_000_000u128 + )); + assert_eq!(Tokens::free_balance(coin1, &6), 2_000_000_000_000u128); + assert_eq!(Balances::free_balance(&6), 100_000_000_000_000); - let amounts = vec![100_000_000_000u128, 100_000_000_000u128]; - assert_ok!(StablePool::create_pool( - RuntimeOrigin::root(), - vec![coin0.into(), coin1.into()], - vec![1u128.into(), 1u128.into()], - 0u128.into(), - 0u128.into(), - 0u128.into(), - 220u128.into(), - 5, - 5, - 1000000000000u128.into() - )); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(BNC, (1, 1)), (VBNC, (10, 11))] - )); - assert_eq!(Tokens::free_balance(pool_asset, &6), 0); - assert_ok!(StablePool::add_liquidity(RuntimeOrigin::signed(6).into(), 0, amounts, 0)); - assert_eq!(Tokens::free_balance(pool_asset, &6), 209_955_833_377); - }); + let amounts = vec![100_000_000_000u128, 100_000_000_000u128]; + assert_ok!(StablePool::create_pool( + RuntimeOrigin::root(), + vec![coin0.into(), coin1.into()], + vec![1u128.into(), 1u128.into()], + 0u128.into(), + 0u128.into(), + 0u128.into(), + 220u128.into(), + 5, + 5, + 1000000000000u128.into() + )); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(BNC, (1, 1)), (VBNC, (10, 11))] + )); + assert_eq!(Tokens::free_balance(pool_asset, &6), 0); + assert_ok!(StablePool::add_liquidity( + RuntimeOrigin::signed(6).into(), + 0, + amounts, + 0 + )); + assert_eq!(Tokens::free_balance(pool_asset, &6), 209_955_833_377); + }); } #[test] fn edit_token_rate() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_noop!( - StablePool::edit_token_rate( + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_noop!( + StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(BNC, (1, 1)), (VBNC, (10, 11))] + ), + bifrost_stable_asset::Error::::ArgumentsError + ); + let (_coin0, _coin1, _pool_asset, _swap_id) = create_pool2(); + assert_ok!(StablePool::edit_token_rate( RuntimeOrigin::root(), 0, vec![(BNC, (1, 1)), (VBNC, (10, 11))] - ), - bifrost_stable_asset::Error::::ArgumentsError - ); - let (_coin0, _coin1, _pool_asset, _swap_id) = create_pool2(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(BNC, (1, 1)), (VBNC, (10, 11))] - )); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(VBNC, (10, 11)), (BNC, (1, 1))] - ); + )); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(VBNC, (10, 11)), (BNC, (1, 1))] + ); - assert_ok!(StablePool::edit_token_rate(RuntimeOrigin::root(), 0, vec![(VBNC, (10, 12))])); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(VBNC, (10, 12)), (BNC, (1, 1))] - ); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(VBNC, (10, 12))] + )); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(VBNC, (10, 12)), (BNC, (1, 1))] + ); - assert_ok!(StablePool::edit_token_rate(RuntimeOrigin::root(), 0, vec![])); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![] - ); - assert_ok!(StablePool::edit_token_rate(RuntimeOrigin::root(), 0, vec![(VBNC, (10, 12))])); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(VBNC, (10, 12))] - ); - }); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![] + )); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![] + ); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(VBNC, (10, 12))] + )); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(VBNC, (10, 12))] + ); + }); } #[test] fn redeem_movr() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (coin0, coin1, pool_asset, _swap_id) = create_movr_pool(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (90_000_000, 100_000_000))] - )); - let amounts = vec![million_unit(100_000), million_unit(200_000)]; - assert_ok!(StablePool::mint_inner(&0, 0, amounts, 0)); - assert_eq!(Tokens::free_balance(pool_asset, &0), 321765598211330627258732); - assert_ok!(StablePool::redeem_proportion_inner(&0, 0, million_unit(300_000), vec![0, 0])); - assert_eq!(Tokens::free_balance(pool_asset, &0), 21765598211330627258732); - assert_eq!(Tokens::free_balance(coin0, &0), 992676625984156921892393); - assert_eq!(Tokens::free_balance(coin1, &0), 985353251968313843784786); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (coin0, coin1, pool_asset, _swap_id) = create_movr_pool(); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (90_000_000, 100_000_000))] + )); + let amounts = vec![million_unit(100_000), million_unit(200_000)]; + assert_ok!(StablePool::mint_inner(&0, 0, amounts, 0)); + assert_eq!( + Tokens::free_balance(pool_asset, &0), + 321765598211330627258732 + ); + assert_ok!(StablePool::redeem_proportion_inner( + &0, + 0, + million_unit(300_000), + vec![0, 0] + )); + assert_eq!( + Tokens::free_balance(pool_asset, &0), + 21765598211330627258732 + ); + assert_eq!(Tokens::free_balance(coin0, &0), 992676625984156921892393); + assert_eq!(Tokens::free_balance(coin1, &0), 985353251968313843784786); + }); } #[test] fn config_vtoken_auto_refresh_should_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (coin0, coin1, _pool_asset, _swap_id) = init(); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (coin0, coin1, _pool_asset, _swap_id) = init(); - assert_ok!(StablePool::config_vtoken_auto_refresh( - RuntimeOrigin::root(), - VDOT, - Permill::from_percent(10) - )); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); - assert_ok!(Currencies::deposit(VDOT, &3, 100)); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (1, 1))] - ); - assert_ok!(::VtokenMinting::increase_token_pool(DOT, 1000)); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (100000100, 100001000))] - ); + assert_ok!(StablePool::config_vtoken_auto_refresh( + RuntimeOrigin::root(), + VDOT, + Permill::from_percent(10) + )); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); + assert_ok!(Currencies::deposit(VDOT, &3, 100)); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (1, 1))] + ); + assert_ok!(::VtokenMinting::increase_token_pool( + DOT, 1000 + )); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (100000100, 100001000))] + ); - assert_eq!(Tokens::free_balance(DOT, &3), 75000000u128 - BALANCE_OFF); - }); + assert_eq!(Tokens::free_balance(DOT, &3), 75000000u128 - BALANCE_OFF); + }); } #[test] fn over_the_hardcap_should_not_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (coin0, coin1, _pool_asset, _swap_id) = init(); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (coin0, coin1, _pool_asset, _swap_id) = init(); - assert_ok!(StablePool::config_vtoken_auto_refresh( - RuntimeOrigin::root(), - VDOT, - Permill::from_percent(10) - )); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); + assert_ok!(StablePool::config_vtoken_auto_refresh( + RuntimeOrigin::root(), + VDOT, + Permill::from_percent(10) + )); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); - assert_ok!(::VtokenMinting::increase_token_pool(DOT, 20_000_000)); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (1, 1))] - ); + assert_ok!(::VtokenMinting::increase_token_pool( + DOT, 20_000_000 + )); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (1, 1))] + ); - assert_ok!(StablePool::config_vtoken_auto_refresh( - RuntimeOrigin::root(), - VDOT, - Permill::from_percent(20) - )); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (100000000, 120000000))] - ); + assert_ok!(StablePool::config_vtoken_auto_refresh( + RuntimeOrigin::root(), + VDOT, + Permill::from_percent(20) + )); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (100000000, 120000000))] + ); - assert_eq!(Tokens::free_balance(DOT, &3), 75000000u128 - BALANCE_OFF); - }); + assert_eq!(Tokens::free_balance(DOT, &3), 75000000u128 - BALANCE_OFF); + }); } #[test] fn not_config_vtoken_auto_refresh_should_not_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (coin0, coin1, _pool_asset, _swap_id) = init(); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (coin0, coin1, _pool_asset, _swap_id) = init(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); - assert_ok!(::VtokenMinting::increase_token_pool(DOT, 1000)); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (1, 1))] - ); - assert_eq!(Tokens::free_balance(DOT, &3), 80000000u128 - BALANCE_OFF); - }); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); + assert_ok!(::VtokenMinting::increase_token_pool( + DOT, 1000 + )); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (1, 1))] + ); + assert_eq!(Tokens::free_balance(DOT, &3), 80000000u128 - BALANCE_OFF); + }); } #[test] fn config_vtoken_auto_refresh_should_not_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - assert_noop!( - StablePool::config_vtoken_auto_refresh( - RuntimeOrigin::root(), - DOT, - Permill::from_percent(20) - ), - bifrost_stable_asset::Error::::ArgumentsError - ); - }); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + assert_noop!( + StablePool::config_vtoken_auto_refresh( + RuntimeOrigin::root(), + DOT, + Permill::from_percent(20) + ), + bifrost_stable_asset::Error::::ArgumentsError + ); + }); } #[test] fn remove_vtoken_auto_refresh_should_work() { - ExtBuilder::default().new_test_ext().build().execute_with(|| { - let (coin0, coin1, _pool_asset, _swap_id) = init(); - assert_ok!(StablePool::edit_token_rate( - RuntimeOrigin::root(), - 0, - vec![(coin0, (1, 1)), (coin1, (1, 1))] - )); - assert_ok!(StablePool::config_vtoken_auto_refresh( - RuntimeOrigin::root(), - VDOT, - Permill::from_percent(20) - )); - assert_ok!(::VtokenMinting::increase_token_pool(DOT, 20_000_000)); + ExtBuilder::default() + .new_test_ext() + .build() + .execute_with(|| { + let (coin0, coin1, _pool_asset, _swap_id) = init(); + assert_ok!(StablePool::edit_token_rate( + RuntimeOrigin::root(), + 0, + vec![(coin0, (1, 1)), (coin1, (1, 1))] + )); + assert_ok!(StablePool::config_vtoken_auto_refresh( + RuntimeOrigin::root(), + VDOT, + Permill::from_percent(20) + )); + assert_ok!(::VtokenMinting::increase_token_pool( + DOT, 20_000_000 + )); - assert_ok!(StablePool::remove_vtoken_auto_refresh(RuntimeOrigin::root(), VDOT)); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (1, 1))] - ); + assert_ok!(StablePool::remove_vtoken_auto_refresh( + RuntimeOrigin::root(), + VDOT + )); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (1, 1))] + ); - assert_ok!(StablePool::config_vtoken_auto_refresh( - RuntimeOrigin::root(), - VDOT, - Permill::from_percent(20) - )); - assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); - assert_eq!( - bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, - (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), - )>>(), - vec![(coin0, (1, 1)), (coin1, (100000000, 120000000))] - ); - }); + assert_ok!(StablePool::config_vtoken_auto_refresh( + RuntimeOrigin::root(), + VDOT, + Permill::from_percent(20) + )); + assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0)); + assert_eq!( + bifrost_stable_asset::TokenRateCaches::::iter_prefix(0).collect::, + (AtLeast64BitUnsignedOf, AtLeast64BitUnsignedOf), + )>>(), + vec![(coin0, (1, 1)), (coin1, (100000000, 120000000))] + ); + }); } diff --git a/pallets/stable-pool/src/traits.rs b/pallets/stable-pool/src/traits.rs index 5b69979ba9..c7233d5cca 100644 --- a/pallets/stable-pool/src/traits.rs +++ b/pallets/stable-pool/src/traits.rs @@ -110,7 +110,14 @@ impl StablePoolHandler for Pallet { amount: Self::Balance, min_dy: Self::Balance, ) -> DispatchResult { - Self::on_swap(who, pool_id, currency_id_in, currency_id_out, amount, min_dy) + Self::on_swap( + who, + pool_id, + currency_id_in, + currency_id_out, + amount, + min_dy, + ) } fn redeem_single( diff --git a/pallets/stable-pool/src/weights.rs b/pallets/stable-pool/src/weights.rs index 3c0cf79167..b86cc5f344 100644 --- a/pallets/stable-pool/src/weights.rs +++ b/pallets/stable-pool/src/weights.rs @@ -24,9 +24,9 @@ //! Autogenerated weights for bifrost_stable_pool //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-11-26, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` //! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 // Executed Command: @@ -36,7 +36,7 @@ // --chain=bifrost-kusama-local // --steps=50 // --repeat=20 -// --pallet=bifrost_stable_pool +// --pallet=bifrost_stable-pool // --extrinsic=* // --execution=wasm // --wasm-execution=compiled @@ -69,33 +69,33 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { - /// Storage: StableAsset PoolCount (r:1 w:1) - /// Proof Skipped: StableAsset PoolCount (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:1) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `StableAsset::PoolCount` (r:1 w:1) + /// Proof: `StableAsset::PoolCount` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:1) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn create_pool() -> Weight { // Proof Size summary in bytes: - // Measured: `663` - // Estimated: `4128` - // Minimum execution time: 87_500_000 picoseconds. - Weight::from_parts(89_559_000, 4128) + // Measured: `413` + // Estimated: `3878` + // Minimum execution time: 18_988_000 picoseconds. + Weight::from_parts(19_996_000, 3878) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } - /// Storage: StableAsset PoolCount (r:1 w:0) - /// Proof Skipped: StableAsset PoolCount (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: StableAsset TokenRateCaches (r:3 w:2) - /// Proof Skipped: StableAsset TokenRateCaches (max_values: None, max_size: None, mode: Measured) + /// Storage: `StableAsset::PoolCount` (r:1 w:0) + /// Proof: `StableAsset::PoolCount` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `StableAsset::TokenRateCaches` (r:3 w:2) + /// Proof: `StableAsset::TokenRateCaches` (`max_values`: None, `max_size`: None, mode: `Measured`) fn edit_token_rate() -> Weight { // Proof Size summary in bytes: // Measured: `258` // Estimated: `8673` - // Minimum execution time: 68_594_000 picoseconds. - Weight::from_parts(69_659_000, 8673) + // Minimum execution time: 17_652_000 picoseconds. + Weight::from_parts(18_259_000, 8673) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -105,10 +105,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_383_000 picoseconds. - Weight::from_parts(12_724_000, 0) - .saturating_add(Weight::from_parts(0, 0)) - .saturating_add(RocksDbWeight::get().writes(1)) + // Minimum execution time: 4_632_000 picoseconds. + Weight::from_parts(4_853_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `StableAsset::TokenRateHardcap` (r:0 w:1) /// Proof: `StableAsset::TokenRateHardcap` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -116,146 +115,147 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_453_000 picoseconds. - Weight::from_parts(12_564_000, 0) - .saturating_add(Weight::from_parts(0, 0)) - .saturating_add(RocksDbWeight::get().writes(1)) + // Minimum execution time: 4_554_000 picoseconds. + Weight::from_parts(4_807_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) - /// Storage: StableAsset TokenRateCaches (r:2 w:0) - /// Proof Skipped: StableAsset TokenRateCaches (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: Tokens Accounts (r:3 w:3) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `StableAsset::TokenRateCaches` (r:2 w:0) + /// Proof: `StableAsset::TokenRateCaches` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:3 w:3) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:2 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `2557` + // Measured: `1488` // Estimated: `8769` - // Minimum execution time: 416_124_000 picoseconds. - Weight::from_parts(426_362_000, 8769) + // Minimum execution time: 122_609_000 picoseconds. + Weight::from_parts(127_984_000, 8769) .saturating_add(RocksDbWeight::get().reads(11_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: StableAsset TokenRateCaches (r:1 w:0) - /// Proof Skipped: StableAsset TokenRateCaches (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:1 w:1) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `StableAsset::TokenRateCaches` (r:1 w:0) + /// Proof: `StableAsset::TokenRateCaches` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) + /// Storage: `StableAsset::TokenRateHardcap` (r:1 w:0) + /// Proof: `StableAsset::TokenRateHardcap` (`max_values`: None, `max_size`: None, mode: `Measured`) fn swap() -> Weight { // Proof Size summary in bytes: - // Measured: `2239` + // Measured: `1399` // Estimated: `6196` - // Minimum execution time: 366_396_000 picoseconds. - Weight::from_parts(378_337_000, 6196) - .saturating_add(RocksDbWeight::get().reads(7_u64)) + // Minimum execution time: 111_540_000 picoseconds. + Weight::from_parts(115_438_000, 6196) + .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: StableAsset TokenRateCaches (r:1 w:0) - /// Proof Skipped: StableAsset TokenRateCaches (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:1 w:1) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `StableAsset::TokenRateCaches` (r:1 w:0) + /// Proof: `StableAsset::TokenRateCaches` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn redeem_proportion() -> Weight { // Proof Size summary in bytes: - // Measured: `2239` + // Measured: `1399` // Estimated: `6196` - // Minimum execution time: 350_451_000 picoseconds. - Weight::from_parts(357_994_000, 6196) + // Minimum execution time: 105_276_000 picoseconds. + Weight::from_parts(109_130_000, 6196) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: StableAsset TokenRateCaches (r:1 w:0) - /// Proof Skipped: StableAsset TokenRateCaches (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:1 w:1) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `StableAsset::TokenRateCaches` (r:1 w:0) + /// Proof: `StableAsset::TokenRateCaches` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn redeem_single() -> Weight { // Proof Size summary in bytes: - // Measured: `2239` + // Measured: `1399` // Estimated: `6196` - // Minimum execution time: 297_040_000 picoseconds. - Weight::from_parts(304_546_000, 6196) + // Minimum execution time: 87_950_000 picoseconds. + Weight::from_parts(90_586_000, 6196) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: StableAsset TokenRateCaches (r:1 w:0) - /// Proof Skipped: StableAsset TokenRateCaches (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:1 w:1) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `StableAsset::TokenRateCaches` (r:1 w:0) + /// Proof: `StableAsset::TokenRateCaches` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn redeem_multi() -> Weight { // Proof Size summary in bytes: - // Measured: `2239` + // Measured: `1399` // Estimated: `6196` - // Minimum execution time: 353_506_000 picoseconds. - Weight::from_parts(363_290_000, 6196) + // Minimum execution time: 107_490_000 picoseconds. + Weight::from_parts(110_310_000, 6196) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) fn modify_a() -> Weight { // Proof Size summary in bytes: // Measured: `446` // Estimated: `3911` - // Minimum execution time: 43_656_000 picoseconds. - Weight::from_parts(44_538_000, 3911) + // Minimum execution time: 8_656_000 picoseconds. + Weight::from_parts(9_385_000, 3911) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) fn modify_fees() -> Weight { // Proof Size summary in bytes: // Measured: `446` // Estimated: `3911` - // Minimum execution time: 41_403_000 picoseconds. - Weight::from_parts(41_816_000, 3911) + // Minimum execution time: 8_520_000 picoseconds. + Weight::from_parts(8_857_000, 3911) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: StableAsset Pools (r:1 w:1) - /// Proof Skipped: StableAsset Pools (max_values: None, max_size: None, mode: Measured) + /// Storage: `StableAsset::Pools` (r:1 w:1) + /// Proof: `StableAsset::Pools` (`max_values`: None, `max_size`: None, mode: `Measured`) fn modify_recipients() -> Weight { // Proof Size summary in bytes: // Measured: `446` // Estimated: `3911` - // Minimum execution time: 41_495_000 picoseconds. - Weight::from_parts(42_190_000, 3911) + // Minimum execution time: 8_551_000 picoseconds. + Weight::from_parts(8_736_000, 3911) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/pallets/system-staking/Cargo.toml b/pallets/system-staking/Cargo.toml index d6ed5d30ac..a1cf5302fd 100644 --- a/pallets/system-staking/Cargo.toml +++ b/pallets/system-staking/Cargo.toml @@ -2,7 +2,7 @@ name = "bifrost-system-staking" version = "4.0.0-dev" description = "System staking pallet" -authors = ["Akagi201 "] +authors = ["Liebi Technologies "] homepage = "https://github.com/bifrost-io/bifrost" edition = "2021" publish = false @@ -24,6 +24,7 @@ sp-arithmetic = { workspace = true } orml-traits = { workspace = true } sp-runtime = { workspace = true } bifrost-primitives = { workspace = true } +bifrost-vtoken-minting = { workspace = true } [dev-dependencies] sp-core = { workspace = true } @@ -34,7 +35,6 @@ orml-tokens = { workspace = true } orml-xtokens = { workspace = true } orml-traits = { workspace = true } hex-literal = { workspace = true } -bifrost-vtoken-minting = { workspace = true } bifrost-slp = { workspace = true } bifrost-farming = { workspace = true } bifrost-asset-registry = { workspace = true } diff --git a/pallets/system-staking/src/benchmarking.rs b/pallets/system-staking/src/benchmarking.rs index d40ef8b1a5..b2978c8991 100644 --- a/pallets/system-staking/src/benchmarking.rs +++ b/pallets/system-staking/src/benchmarking.rs @@ -17,9 +17,9 @@ // along with this program. If not, see . #![cfg(feature = "runtime-benchmarks")] -use crate::{Pallet as SystemStaking, *}; -use bifrost_primitives::{CurrencyId, PoolId, TokenSymbol}; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; +use crate::{Config, Pallet as SystemStaking, *}; +use bifrost_primitives::{CurrencyId, PoolId, TokenSymbol, *}; +use frame_benchmarking::v2::*; use frame_support::{ assert_ok, sp_runtime::{traits::UniqueSaturatedFrom, Perbill, Permill}, @@ -28,10 +28,12 @@ use frame_support::{ use frame_system::{Pallet as System, RawOrigin}; use sp_std::vec; -benchmarks! { - on_initialize { - const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); - const MOVR: CurrencyId = CurrencyId::Token(TokenSymbol::MOVR); +#[benchmarks(where T: Config + bifrost_vtoken_minting::Config)] +mod benchmarks { + use super::*; + + #[benchmark] + fn on_initialize() -> Result<(), BenchmarkError> { assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), KSM, @@ -42,6 +44,7 @@ benchmarks! { Some(vec![1 as PoolId]), Some(vec![Perbill::from_percent(100)]), )); + assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), MOVR, @@ -52,23 +55,41 @@ benchmarks! { Some(vec![1 as PoolId]), Some(vec![Perbill::from_percent(100)]), )); - System::::set_block_number( - System::::block_number() + 1u32.into() - ); + + System::::set_block_number(System::::block_number() + 1u32.into()); SystemStaking::::on_initialize(System::::block_number()); - System::::set_block_number( - System::::block_number() + 1u32.into() - ); + System::::set_block_number(System::::block_number() + 1u32.into()); SystemStaking::::on_initialize(System::::block_number()); - }:{SystemStaking::::on_initialize(System::::block_number());} + #[block] + { + SystemStaking::::on_initialize(System::::block_number()); + } - token_config { + Ok(()) + } + + #[benchmark] + fn token_config() -> Result<(), BenchmarkError> { const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); let token_amount = BalanceOf::::unique_saturated_from(1000u128); let pool_id = PoolId::from(1u32); - }: _(RawOrigin::Root, KSM, Some(BlockNumberFor::::from(1u32)), Some(Permill::from_percent(80)),Some(false),Some(token_amount),Some(vec![pool_id]),Some(vec![Perbill::from_percent(100)])) + #[extrinsic_call] + _( + RawOrigin::Root, + KSM, + Some(BlockNumberFor::::from(1u32)), + Some(Permill::from_percent(80)), + Some(false), + Some(token_amount), + Some(vec![pool_id]), + Some(vec![Perbill::from_percent(100)]), + ); + + Ok(()) + } - refresh_token_info { + #[benchmark] + fn refresh_token_info() -> Result<(), BenchmarkError> { const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), @@ -80,10 +101,14 @@ benchmarks! { Some(vec![1 as PoolId]), Some(vec![Perbill::from_percent(100)]), )); - }: _(RawOrigin::Root,KSM) + #[extrinsic_call] + _(RawOrigin::Root, KSM); - payout { - const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); + Ok(()) + } + + #[benchmark] + fn payout() -> Result<(), BenchmarkError> { assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), KSM, @@ -94,13 +119,29 @@ benchmarks! { Some(vec![1 as PoolId]), Some(vec![Perbill::from_percent(100)]), )); + let caller: T::AccountId = whitelisted_caller(); - assert_ok!(T::MultiCurrency::deposit(KSM, &caller, BalanceOf::::unique_saturated_from(1000u128))); - assert_ok!(T::VtokenMintingInterface::mint(caller, KSM, BalanceOf::::unique_saturated_from(1000u128), BoundedVec::default(),None)); - }: _(RawOrigin::Root,KSM) + assert_ok!(::MultiCurrency::deposit( + KSM, + &caller, + BalanceOf::::unique_saturated_from(1_000_000_000_000_000u128).into() + )); + assert_ok!(T::VtokenMintingInterface::mint( + caller, + KSM, + BalanceOf::::unique_saturated_from(10_000_000_000u128), + BoundedVec::default(), + None + )); - on_redeem_success { - const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); + #[extrinsic_call] + _(RawOrigin::Root, KSM); + + Ok(()) + } + + #[benchmark] + fn on_redeem_success() -> Result<(), BenchmarkError> { assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), KSM, @@ -113,10 +154,16 @@ benchmarks! { )); let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); - }:{SystemStaking::::on_redeem_success(KSM,caller,token_amount);} + #[block] + { + SystemStaking::::on_redeem_success(KSM, caller, token_amount); + } - on_redeemed { - const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); + Ok(()) + } + + #[benchmark] + fn on_redeemed() -> Result<(), BenchmarkError> { assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), KSM, @@ -130,10 +177,16 @@ benchmarks! { let caller: T::AccountId = whitelisted_caller(); let token_amount = BalanceOf::::unique_saturated_from(1000u128); let fee_amount = BalanceOf::::unique_saturated_from(1000u128); - }:{SystemStaking::::on_redeemed(caller,KSM,token_amount,token_amount,fee_amount);} + #[block] + { + SystemStaking::::on_redeemed(caller, KSM, token_amount, token_amount, fee_amount); + } - delete_token { - const KSM: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); + Ok(()) + } + + #[benchmark] + fn delete_token() -> Result<(), BenchmarkError> { assert_ok!(SystemStaking::::token_config( RawOrigin::Root.into(), KSM, @@ -144,11 +197,16 @@ benchmarks! { Some(vec![1 as PoolId]), Some(vec![Perbill::from_percent(100)]), )); - }: _(RawOrigin::Root,KSM) -} -impl_benchmark_test_suite!( - SystemStaking, - crate::mock::ExtBuilder::default().one_hundred_for_alice_n_bob().build(), - crate::mock::Runtime -); + #[extrinsic_call] + _(RawOrigin::Root, KSM); + + Ok(()) + } + + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); +} diff --git a/pallets/system-staking/src/lib.rs b/pallets/system-staking/src/lib.rs index 13d32627c2..1121a184bc 100644 --- a/pallets/system-staking/src/lib.rs +++ b/pallets/system-staking/src/lib.rs @@ -27,7 +27,7 @@ use frame_system::pallet_prelude::BlockNumberFor; use orml_traits::MultiCurrency; pub use pallet::*; use sp_runtime::{ - traits::{AccountIdConversion, Saturating, Zero}, + traits::{AccountIdConversion, BlockNumberProvider, Saturating, Zero}, BoundedVec, }; use sp_std::vec::Vec; @@ -77,7 +77,7 @@ pub mod pallet { type WeightInfo: WeightInfo; /// The interface to call Farming module functions. - type FarmingInfo: FarmingInfo, CurrencyIdOf>; + type FarmingInfo: FarmingInfo, CurrencyIdOf, AccountIdOf>; /// The interface to call VtokenMinting module functions. type VtokenMintingInterface: VtokenMintingInterface< @@ -106,6 +106,9 @@ pub mod pallet { /// This value is set to 1500 in the runtime configuration. #[pallet::constant] type BlocksPerRound: Get; + + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); @@ -142,7 +145,11 @@ pub mod pallet { /// - `current`: The index of the current round. /// - `first`: The block number at which this round started. /// - `length`: The length of the round in blocks. - NewRound { current: RoundIndex, first: BlockNumberFor, length: u32 }, + NewRound { + current: RoundIndex, + first: BlockNumberFor, + length: u32, + }, /// Configuration of a token has been changed. /// /// - `token`: The identifier of the token whose configuration changed. @@ -283,6 +290,8 @@ pub mod pallet { vfree: BalanceOf, shadow: BalanceOf, }, + /// payout error + PayoutFailed { token: CurrencyIdOf }, } #[pallet::error] @@ -303,9 +312,10 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: BlockNumberFor) -> Weight { + fn on_initialize(_: BlockNumberFor) -> Weight { // Get token list let token_list = TokenList::::get(); + let current_block_number = T::BlockNumberProvider::current_block_number(); //Get round info, if can't find it in the storage, a new one will be created. let mut round = if let Some(round) = >::get() { @@ -317,11 +327,11 @@ pub mod pallet { // New round start // Current blockNumber - BlockNumber of Round Start >= Length of Round - if round.should_update(n) { + if round.should_update(current_block_number) { // Mutate round // Set current round index -= 1 // BlockNumber of Round Start = Current blockNumber - round.update(n); + round.update(current_block_number); >::put(round); // Iterate through the token list @@ -353,8 +363,14 @@ pub mod pallet { if let Some(token_info) = TokenStatus::::get(i) { // Current blockNumber - BlockNumber of Round Start == // token_info.current_config.exec_delay ===> true - if round.check_delay(n, token_info.current_config.exec_delay) { + if round.check_delay(current_block_number, token_info.current_config.exec_delay) + { Self::process_token_info(pallet_account.clone(), token_info, i).ok(); + + if let Err(_) = Self::do_payout(i) { + log::error!("System staking auto payout failed, token: {:?}", i); + Self::deposit_event(Event::PayoutFailed { token: i }); + } } } } @@ -442,7 +458,9 @@ pub mod pallet { // If it is a new token, add it to the token list if new_token { let mut token_list = TokenList::::get(); - token_list.try_push(token).map_err(|_| Error::::ExceedMaxTokenLen)?; + token_list + .try_push(token) + .map_err(|_| Error::::ExceedMaxTokenLen)?; >::put(token_list); } @@ -515,51 +533,7 @@ pub mod pallet { pub fn payout(origin: OriginFor, token: CurrencyIdOf) -> DispatchResultWithPostInfo { T::EnsureConfirmAsGovernance::ensure_origin(origin)?; - let token_info = >::get(&token).ok_or(Error::::TokenInfoNotFound)?; - - // token_id convert to vtoken_id - let vtoken_id = token.to_vtoken().map_err(|_| Error::::TokenInfoNotFound)?; - - let pallet_account: AccountIdOf = T::PalletId::get().into_account_truncating(); - - // Calculate the revenue generated by vtoken - let vfree_amount = T::MultiCurrency::free_balance(vtoken_id, &pallet_account); - let free_amount = T::VtokenMintingInterface::get_currency_amount_by_v_currency_amount( - token, - vtoken_id, - vfree_amount, - )?; - let token_amount = free_amount.saturating_sub(token_info.system_shadow_amount); - - // Calculate the number of benefits converted to vtoken - let vtoken_amount = - T::VtokenMintingInterface::get_v_currency_amount_by_currency_amount( - token, - vtoken_id, - token_amount, - )?; - - // Transfer vtoken(benefits) to BenefitReceivingAccount - T::MultiCurrency::transfer( - vtoken_id, - &pallet_account, - &T::BenefitReceivingAccount::get(), - vtoken_amount, - ) - .map_err(|_| Error::::PayoutFailed)?; - - Self::deposit_event(Event::Payout { - token, - vtoken: vtoken_id, - from: pallet_account, - to: T::BenefitReceivingAccount::get(), - amount: vtoken_amount, - vfree: vfree_amount, - free: free_amount, - shadow: token_info.system_shadow_amount, - }); - - Ok(().into()) + Self::do_payout(token) } } } @@ -573,8 +547,8 @@ impl Pallet { // Query farming info let mut farming_staking_amount = BalanceOf::::zero(); for i in 0..token_info.current_config.farming_poolids.len() { - farming_staking_amount = farming_staking_amount + - token_info.current_config.lptoken_rates[i].mul_floor( + farming_staking_amount = farming_staking_amount + + token_info.current_config.lptoken_rates[i].mul_floor( // TODO: get_token_shares T::FarmingInfo::get_token_shares( token_info.current_config.farming_poolids[i], @@ -609,12 +583,16 @@ impl Pallet { // Check stakable_amount > (system_shadow_amount - pending_redeem_amount) ===> mint vksm , // update system_shadow_amount+=mint_amount - if stakable_amount > - token_info.system_shadow_amount.saturating_sub(token_info.pending_redeem_amount) + if stakable_amount + > token_info + .system_shadow_amount + .saturating_sub(token_info.pending_redeem_amount) { // mint_amount = stakable_amount - (system_shadow_amount - pending_redeem_amount) let mint_amount = stakable_amount.saturating_sub( - token_info.system_shadow_amount.saturating_sub(token_info.pending_redeem_amount), + token_info + .system_shadow_amount + .saturating_sub(token_info.pending_redeem_amount), ); // Deposit mint_amount ksm to pallet_account @@ -643,8 +621,10 @@ impl Pallet { }); // Check stakable_amount < (system_shadow_amount - pending_redeem_amount) ===> redeem vksm , // update pending_redeem_amount += token_amount - } else if stakable_amount < - token_info.system_shadow_amount.saturating_sub(token_info.pending_redeem_amount) + } else if stakable_amount + < token_info + .system_shadow_amount + .saturating_sub(token_info.pending_redeem_amount) { // redeem_amount = system_shadow_amount - pending_redeem_amount - stakable_amount let redeem_amount = token_info @@ -683,6 +663,55 @@ impl Pallet { Ok(().into()) } + fn do_payout(token: CurrencyIdOf) -> DispatchResultWithPostInfo { + let token_info = >::get(&token).ok_or(Error::::TokenInfoNotFound)?; + + // token_id convert to vtoken_id + let vtoken_id = token + .to_vtoken() + .map_err(|_| Error::::TokenInfoNotFound)?; + + let pallet_account: AccountIdOf = T::PalletId::get().into_account_truncating(); + + // Calculate the revenue generated by vtoken + let vfree_amount = T::MultiCurrency::free_balance(vtoken_id, &pallet_account); + let free_amount = T::VtokenMintingInterface::get_currency_amount_by_v_currency_amount( + token, + vtoken_id, + vfree_amount, + )?; + let token_amount = free_amount.saturating_sub(token_info.system_shadow_amount); + + // Calculate the number of benefits converted to vtoken + let vtoken_amount = T::VtokenMintingInterface::get_v_currency_amount_by_currency_amount( + token, + vtoken_id, + token_amount, + )?; + + // Transfer vtoken(benefits) to BenefitReceivingAccount + T::MultiCurrency::transfer( + vtoken_id, + &pallet_account, + &T::BenefitReceivingAccount::get(), + vtoken_amount, + ) + .map_err(|_| Error::::PayoutFailed)?; + + Self::deposit_event(Event::Payout { + token, + vtoken: vtoken_id, + from: pallet_account, + to: T::BenefitReceivingAccount::get(), + amount: vtoken_amount, + vfree: vfree_amount, + free: free_amount, + shadow: token_info.system_shadow_amount, + }); + + Ok(().into()) + } + // vTokenMinting on_initialize_update_ledger , update pending_redeem_amount -= token_amount , // update system_shadow_amount -= token_amount pub fn on_redeem_success( @@ -704,8 +733,9 @@ impl Pallet { }; // pending_redeem_amount -= token_amount - token_info.pending_redeem_amount = - token_info.pending_redeem_amount.saturating_sub(token_amount); + token_info.pending_redeem_amount = token_info + .pending_redeem_amount + .saturating_sub(token_amount); // Destroy token match T::MultiCurrency::withdraw(token_id, &to, token_amount) { @@ -720,7 +750,7 @@ impl Pallet { }); token_info.system_shadow_amount = token_info.system_shadow_amount.saturating_sub(token_amount); - }, + } Err(error) => { log::warn!("{:?} withdraw error: {:?}", &token_id, error); Self::deposit_event(Event::WithdrawFailed { @@ -731,7 +761,7 @@ impl Pallet { system_shadow_amount: token_info.system_shadow_amount, pending_redeem_amount: token_info.pending_redeem_amount, }); - }, + } } >::insert(&token_id, token_info); T::WeightInfo::on_redeem_success() @@ -768,8 +798,9 @@ impl Pallet { }; // pending_redeem_amount += token_amount - token_info.pending_redeem_amount = - token_info.pending_redeem_amount.saturating_add(token_amount); + token_info.pending_redeem_amount = token_info + .pending_redeem_amount + .saturating_add(token_amount); >::insert(&token_id, token_info.clone()); diff --git a/pallets/system-staking/src/migrations/v1.rs b/pallets/system-staking/src/migrations/v1.rs index 4468a16ae7..6f5af6a9a0 100644 --- a/pallets/system-staking/src/migrations/v1.rs +++ b/pallets/system-staking/src/migrations/v1.rs @@ -18,11 +18,9 @@ use crate::*; use frame_support::{ - ensure, pallet_prelude::StorageVersion, traits::{GetStorageVersion, OnRuntimeUpgrade}, }; -use parity_scale_codec::{Decode, Encode}; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -100,6 +98,7 @@ impl OnRuntimeUpgrade for MigrateToV1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { + use parity_scale_codec::Encode; let cnt = TokenStatus::::iter().count(); // print out the pre-migrate storage count log::info!(target: LOG_TARGET, "TokenStatus pre-migrate storage count: {:?}", cnt); @@ -108,6 +107,8 @@ impl OnRuntimeUpgrade for MigrateToV1 { #[cfg(feature = "try-runtime")] fn post_upgrade(cnt: Vec) -> Result<(), TryRuntimeError> { + use frame_support::ensure; + use parity_scale_codec::Decode; let new_count = TokenStatus::::iter().count(); let old_count: u64 = Decode::decode(&mut cnt.as_slice()) diff --git a/pallets/system-staking/src/mock.rs b/pallets/system-staking/src/mock.rs index b70453057f..32163566d6 100644 --- a/pallets/system-staking/src/mock.rs +++ b/pallets/system-staking/src/mock.rs @@ -202,6 +202,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } ord_parameter_types! { @@ -272,6 +273,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = (); type AssetIdMaps = AssetIdMaps; type TreasuryAccount = TreasuryAccount; + type BlockNumberProvider = System; } parameter_types! { @@ -296,6 +298,7 @@ impl bifrost_farming::Config for Runtime { type BlockNumberToBalance = ConvertInto; type WhitelistMaximumLimit = WhitelistMaximumLimit; type GaugeRewardIssuer = FarmingGaugeRewardIssuerPalletId; + type BlockNumberProvider = System; } parameter_types! { @@ -317,6 +320,7 @@ impl system_staking::Config for Runtime { type BlocksPerRound = BlocksPerRound; type MaxTokenLen = MaxTokenLen; type MaxFarmingPoolIdLen = MaxFarmingPoolIdLen; + type BlockNumberProvider = System; } parameter_types! { @@ -396,7 +400,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -423,7 +429,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self @@ -473,3 +481,8 @@ pub(crate) fn roll_to(n: u64) -> u64 { } num_blocks } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/system-staking/src/tests.rs b/pallets/system-staking/src/tests.rs index cabff83e54..68c297b228 100644 --- a/pallets/system-staking/src/tests.rs +++ b/pallets/system-staking/src/tests.rs @@ -28,369 +28,451 @@ use sp_std::{collections::btree_map::BTreeMap, prelude::*}; #[test] fn token_config_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(BlockNumberFor::::from(1u32)), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - None, - None, - )); - let token_info = >::get(KSM).unwrap(); - assert_eq!(token_info.new_config.add_or_sub, false); - assert_eq!(token_info.new_config.exec_delay, 1); - assert_eq!(token_info.new_config.system_stakable_farming_rate, Permill::from_percent(80)); - assert_eq!(token_info.new_config.system_stakable_base, 100); - assert_eq!(token_info.new_config.farming_poolids, Vec::::new()); - assert_eq!(token_info.new_config.lptoken_rates, Vec::::new()); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(BlockNumberFor::::from(1u32)), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + None, + None, + )); + let token_info = >::get(KSM).unwrap(); + assert_eq!(token_info.new_config.add_or_sub, false); + assert_eq!(token_info.new_config.exec_delay, 1); + assert_eq!( + token_info.new_config.system_stakable_farming_rate, + Permill::from_percent(80) + ); + assert_eq!(token_info.new_config.system_stakable_base, 100); + assert_eq!(token_info.new_config.farming_poolids, Vec::::new()); + assert_eq!(token_info.new_config.lptoken_rates, Vec::::new()); + }); } #[test] fn delete_token_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(1), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - None, - None, - )); - - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - MOVR, - Some(2), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - None, - None, - )); - - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - MOVR, - Some(2), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - None, - None, - )); - - assert_ok!(SystemStaking::delete_token(RuntimeOrigin::root(), MOVR,)); - - assert!(>::get(MOVR).is_none()); - assert!(>::get(KSM).is_some()); - let token_list = >::get(); - assert_eq!(token_list.len(), 1); - assert!(!token_list.clone().into_inner().contains(&MOVR)); - assert!(token_list.into_inner().contains(&KSM)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(1), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + None, + None, + )); + + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + MOVR, + Some(2), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + None, + None, + )); + + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + MOVR, + Some(2), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + None, + None, + )); + + assert_ok!(SystemStaking::delete_token(RuntimeOrigin::root(), MOVR,)); + + assert!(>::get(MOVR).is_none()); + assert!(>::get(KSM).is_some()); + let token_list = >::get(); + assert_eq!(token_list.len(), 1); + assert!(!token_list.clone().into_inner().contains(&MOVR)); + assert!(token_list.into_inner().contains(&KSM)); + }); } #[test] fn round_info_should_correct() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - System::set_block_number(System::block_number() + 1000); - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(1), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - None, - None, - )); - roll_one_block(); - assert_eq!(Round::::get().unwrap().length, 5); - assert_eq!(Round::::get().unwrap().current, 1); - assert_eq!(Round::::get().unwrap().first, 1001); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + System::set_block_number(System::block_number() + 1000); + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(1), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + None, + None, + )); + roll_one_block(); + assert_eq!(Round::::get().unwrap().length, 5); + assert_eq!(Round::::get().unwrap().current, 1); + assert_eq!(Round::::get().unwrap().first, 1001); + }); } #[test] fn refresh_token_info_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_farming_no_gauge(); - asset_registry(); - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 10)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - assert_ok!(VtokenMinting::set_minimum_redeem(RuntimeOrigin::signed(ALICE), VKSM, 10)); - - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(1), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - Some(vec![pid]), - Some(vec![Perbill::from_percent(100)]), - )); - - assert_ok!(SystemStaking::refresh_token_info(RuntimeOrigin::root(), KSM)); - let token_info = >::get(KSM).unwrap(); - assert_eq!(token_info.new_config, token_info.current_config); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, _tokens) = init_farming_no_gauge(); + asset_registry(); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 10 + )); + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::set_minimum_redeem( + RuntimeOrigin::signed(ALICE), + VKSM, + 10 + )); + + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(1), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + Some(vec![pid]), + Some(vec![Perbill::from_percent(100)]), + )); + + assert_ok!(SystemStaking::refresh_token_info( + RuntimeOrigin::root(), + KSM + )); + let token_info = >::get(KSM).unwrap(); + assert_eq!(token_info.new_config, token_info.current_config); + }); } #[test] fn payout_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_farming_no_gauge(); - asset_registry(); - - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 0)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(1), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - Some(vec![pid]), - Some(vec![Perbill::from_percent(100)]), - )); - - assert_ok!(VtokenMinting::mint( - RuntimeOrigin::signed(ALICE), - KSM, - 1000, - BoundedVec::default(), - Some(0u32), - )); - - let pallet_account = ::PalletId::get().into_account_truncating(); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 100); - - assert_ok!(SystemStaking::payout(RuntimeOrigin::root(), KSM)); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 1); - - let treasury_balance = Currencies::free_balance(VKSM, &TreasuryAccount::get()); - assert_eq!(treasury_balance, 99); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, _tokens) = init_farming_no_gauge(); + asset_registry(); + + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 0 + )); + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(1), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + Some(vec![pid]), + Some(vec![Perbill::from_percent(100)]), + )); + + assert_ok!(VtokenMinting::mint( + RuntimeOrigin::signed(ALICE), + KSM, + 1000, + BoundedVec::default(), + Some(0u32), + )); + + let pallet_account = ::PalletId::get().into_account_truncating(); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 100); + + assert_ok!(SystemStaking::payout(RuntimeOrigin::root(), KSM)); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 1); + + let treasury_balance = Currencies::free_balance(VKSM, &TreasuryAccount::get()); + assert_eq!(treasury_balance, 99); + }); } #[test] fn payout_should_fail() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 0)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - - assert_ok!(VtokenMinting::mint( - RuntimeOrigin::signed(ALICE), - KSM, - 1000, - BoundedVec::default(), - Some(0u32), - )); - - assert_noop!( - SystemStaking::payout(RuntimeOrigin::root(), KSM), - Error::::TokenInfoNotFound - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 0 + )); + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + + assert_ok!(VtokenMinting::mint( + RuntimeOrigin::signed(ALICE), + KSM, + 1000, + BoundedVec::default(), + Some(0u32), + )); + + assert_noop!( + SystemStaking::payout(RuntimeOrigin::root(), KSM), + Error::::TokenInfoNotFound + ); + }); } #[test] fn on_redeem_success_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - - let pallet_account = ::PalletId::get().into_account_truncating(); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 100); - - SystemStaking::on_redeem_success(VKSM, pallet_account.clone(), 10); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 90); - let mut token_info = >::get(VKSM).unwrap(); - assert_eq!(token_info.pending_redeem_amount, 0); - assert_eq!(token_info.system_shadow_amount, 0); - - token_info.pending_redeem_amount = 100; - token_info.system_shadow_amount = 100; - >::insert(&VKSM, token_info.clone()); - assert_eq!(token_info.pending_redeem_amount, 100); - assert_eq!(token_info.system_shadow_amount, 100); - - SystemStaking::on_redeem_success(VKSM, pallet_account.clone(), 90); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 0); - let token_info = >::get(VKSM).unwrap(); - assert_eq!(token_info.pending_redeem_amount, 10); - assert_eq!(token_info.system_shadow_amount, 10); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + + let pallet_account = ::PalletId::get().into_account_truncating(); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 100); + + SystemStaking::on_redeem_success(VKSM, pallet_account.clone(), 10); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 90); + let mut token_info = >::get(VKSM).unwrap(); + assert_eq!(token_info.pending_redeem_amount, 0); + assert_eq!(token_info.system_shadow_amount, 0); + + token_info.pending_redeem_amount = 100; + token_info.system_shadow_amount = 100; + >::insert(&VKSM, token_info.clone()); + assert_eq!(token_info.pending_redeem_amount, 100); + assert_eq!(token_info.system_shadow_amount, 100); + + SystemStaking::on_redeem_success(VKSM, pallet_account.clone(), 90); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 0); + let token_info = >::get(VKSM).unwrap(); + assert_eq!(token_info.pending_redeem_amount, 10); + assert_eq!(token_info.system_shadow_amount, 10); + }); } #[test] fn on_refund_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - - let pallet_account = ::PalletId::get().into_account_truncating(); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 100); - - SystemStaking::on_refund(VKSM, pallet_account.clone(), 10); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 90); - let mut token_info = >::get(VKSM).unwrap(); - assert_eq!(token_info.pending_redeem_amount, 0); - assert_eq!(token_info.system_shadow_amount, 0); - - token_info.pending_redeem_amount = 100; - token_info.system_shadow_amount = 100; - >::insert(&VKSM, token_info.clone()); - assert_eq!(token_info.pending_redeem_amount, 100); - assert_eq!(token_info.system_shadow_amount, 100); - - SystemStaking::on_refund(VKSM, pallet_account.clone(), 90); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 0); - let token_info = >::get(VKSM).unwrap(); - assert_eq!(token_info.pending_redeem_amount, 10); - assert_eq!(token_info.system_shadow_amount, 10); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + + let pallet_account = ::PalletId::get().into_account_truncating(); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 100); + + SystemStaking::on_refund(VKSM, pallet_account.clone(), 10); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 90); + let mut token_info = >::get(VKSM).unwrap(); + assert_eq!(token_info.pending_redeem_amount, 0); + assert_eq!(token_info.system_shadow_amount, 0); + + token_info.pending_redeem_amount = 100; + token_info.system_shadow_amount = 100; + >::insert(&VKSM, token_info.clone()); + assert_eq!(token_info.pending_redeem_amount, 100); + assert_eq!(token_info.system_shadow_amount, 100); + + SystemStaking::on_refund(VKSM, pallet_account.clone(), 90); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 0); + let token_info = >::get(VKSM).unwrap(); + assert_eq!(token_info.pending_redeem_amount, 10); + assert_eq!(token_info.system_shadow_amount, 10); + }); } #[test] fn on_redeemed_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - asset_registry(); - - let pallet_account = ::PalletId::get().into_account_truncating(); - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 100); - - SystemStaking::on_redeemed(pallet_account.clone(), VKSM, 10, 0, 0); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 100); - let mut token_info = >::get(VKSM).unwrap(); - assert_eq!(token_info.pending_redeem_amount, 10); - - token_info.pending_redeem_amount = 100; - >::insert(&VKSM, token_info.clone()); - assert_eq!(token_info.pending_redeem_amount, 100); - - SystemStaking::on_redeemed(pallet_account.clone(), VKSM, 10, 0, 0); - - let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); - assert_eq!(pallet_vfree_balance, 100); - let token_info = >::get(VKSM).unwrap(); - assert_eq!(token_info.pending_redeem_amount, 110); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + asset_registry(); + + let pallet_account = ::PalletId::get().into_account_truncating(); + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 100); + + SystemStaking::on_redeemed(pallet_account.clone(), VKSM, 10, 0, 0); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 100); + let mut token_info = >::get(VKSM).unwrap(); + assert_eq!(token_info.pending_redeem_amount, 10); + + token_info.pending_redeem_amount = 100; + >::insert(&VKSM, token_info.clone()); + assert_eq!(token_info.pending_redeem_amount, 100); + + SystemStaking::on_redeemed(pallet_account.clone(), VKSM, 10, 0, 0); + + let pallet_vfree_balance = Currencies::free_balance(VKSM, &pallet_account); + assert_eq!(pallet_vfree_balance, 100); + let token_info = >::get(VKSM).unwrap(); + assert_eq!(token_info.pending_redeem_amount, 110); + }); } #[test] fn round_process_token() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_farming_no_gauge(); - asset_registry(); - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 10)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - assert_ok!(VtokenMinting::set_minimum_redeem(RuntimeOrigin::signed(ALICE), VKSM, 10)); - - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(1), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - Some(vec![pid]), - Some(vec![Perbill::from_percent(100)]), - )); - - roll_to(5); // round start - roll_to(6); // delay exec - - let token_info = >::get(KSM).unwrap(); - assert!(token_info.system_shadow_amount > 0); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, _tokens) = init_farming_no_gauge(); + asset_registry(); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 10 + )); + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::set_minimum_redeem( + RuntimeOrigin::signed(ALICE), + VKSM, + 10 + )); + + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(1), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + Some(vec![pid]), + Some(vec![Perbill::from_percent(100)]), + )); + + roll_to(5); // round start + roll_to(6); // delay exec + + let token_info = >::get(KSM).unwrap(); + assert!(token_info.system_shadow_amount > 0); + }); } #[test] fn round_process_token_rollback() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (pid, _tokens) = init_farming_no_gauge(); - asset_registry(); - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 10000)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - assert_ok!(VtokenMinting::set_minimum_redeem(RuntimeOrigin::signed(ALICE), VKSM, 10000)); - - assert_ok!(SystemStaking::token_config( - RuntimeOrigin::root(), - KSM, - Some(1), - Some(Permill::from_percent(80)), - Some(false), - Some(100), - Some(vec![pid]), - Some(vec![Perbill::from_percent(100)]), - )); - - roll_to(5); // round start - roll_to(6); // delay exec - - let token_info = >::get(KSM).unwrap(); - assert!(token_info.system_shadow_amount == 0); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (pid, _tokens) = init_farming_no_gauge(); + asset_registry(); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 10000 + )); + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::set_minimum_redeem( + RuntimeOrigin::signed(ALICE), + VKSM, + 10000 + )); + + assert_ok!(SystemStaking::token_config( + RuntimeOrigin::root(), + KSM, + Some(1), + Some(Permill::from_percent(80)), + Some(false), + Some(100), + Some(vec![pid]), + Some(vec![Perbill::from_percent(100)]), + )); + + roll_to(5); // round start + roll_to(6); // delay exec + + let token_info = >::get(KSM).unwrap(); + assert!(token_info.system_shadow_amount == 0); + }); } fn init_farming_no_gauge() -> (PoolId, BalanceOf) { let mut tokens_proportion_map = BTreeMap::, Perbill>::new(); - tokens_proportion_map.entry(KSM).or_insert(Perbill::from_percent(100)); + tokens_proportion_map + .entry(KSM) + .or_insert(Perbill::from_percent(100)); let tokens_proportion = vec![(KSM, Perbill::from_percent(100))]; let tokens = 1000; let basic_rewards = vec![(KSM, 1000)]; @@ -400,7 +482,7 @@ fn init_farming_no_gauge() -> (PoolId, BalanceOf) { RuntimeOrigin::signed(ALICE), tokens_proportion.clone(), basic_rewards.clone(), - Some((1000, gauge_basic_rewards)), + Some(gauge_basic_rewards), 0, 0, 10, @@ -410,7 +492,11 @@ fn init_farming_no_gauge() -> (PoolId, BalanceOf) { let pid = 0; let charge_rewards = vec![(KSM, 100000)]; - assert_ok!(Farming::charge(RuntimeOrigin::signed(BOB), pid, charge_rewards, false)); + assert_ok!(Farming::charge( + RuntimeOrigin::signed(BOB), + pid, + charge_rewards, + )); assert_ok!(Farming::deposit(RuntimeOrigin::signed(ALICE), pid, tokens)); (pid, tokens) } @@ -421,8 +507,14 @@ fn asset_registry() { ( currency_id, AssetMetadata { - name: currency_id.name().map(|s| s.as_bytes().to_vec()).unwrap_or_default(), - symbol: currency_id.symbol().map(|s| s.as_bytes().to_vec()).unwrap_or_default(), + name: currency_id + .name() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), + symbol: currency_id + .symbol() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), decimals: currency_id.decimals().unwrap_or_default(), minimal_balance: *minimal_balance, }, diff --git a/pallets/system-staking/src/types.rs b/pallets/system-staking/src/types.rs index d0ce958211..517fced675 100644 --- a/pallets/system-staking/src/types.rs +++ b/pallets/system-staking/src/types.rs @@ -38,7 +38,11 @@ impl< > RoundInfo { pub fn new(current: RoundIndex, first: B, length: u32) -> RoundInfo { - RoundInfo { current, first, length } + RoundInfo { + current, + first, + length, + } } /// Check if the round should be updated pub fn should_update(&self, now: B) -> bool { diff --git a/pallets/system-staking/src/weights.rs b/pallets/system-staking/src/weights.rs index 4c03afc00b..a77ed9999d 100644 --- a/pallets/system-staking/src/weights.rs +++ b/pallets/system-staking/src/weights.rs @@ -24,9 +24,9 @@ //! Autogenerated weights for bifrost_system_staking //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.1 +//! DATE: 2024-12-18, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` //! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 // Executed Command: @@ -36,7 +36,7 @@ // --chain=bifrost-kusama-local // --steps=50 // --repeat=20 -// --pallet=bifrost_system_staking +// --pallet=bifrost-system-staking // --extrinsic=* // --execution=wasm // --wasm-execution=compiled @@ -64,86 +64,86 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { - /// Storage: SystemStaking TokenList (r:1 w:0) - /// Proof Skipped: SystemStaking TokenList (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: SystemStaking Round (r:1 w:0) - /// Proof Skipped: SystemStaking Round (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: SystemStaking TokenStatus (r:2 w:0) - /// Proof Skipped: SystemStaking TokenStatus (max_values: None, max_size: None, mode: Measured) + /// Storage: `SystemStaking::TokenList` (r:1 w:0) + /// Proof: `SystemStaking::TokenList` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `SystemStaking::Round` (r:1 w:0) + /// Proof: `SystemStaking::Round` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `SystemStaking::TokenStatus` (r:2 w:0) + /// Proof: `SystemStaking::TokenStatus` (`max_values`: None, `max_size`: None, mode: `Measured`) fn on_initialize() -> Weight { // Proof Size summary in bytes: // Measured: `445` // Estimated: `6385` - // Minimum execution time: 30_023_000 picoseconds. - Weight::from_parts(30_834_000, 6385) + // Minimum execution time: 8_769_000 picoseconds. + Weight::from_parts(9_831_000, 6385) .saturating_add(RocksDbWeight::get().reads(4_u64)) } - /// Storage: SystemStaking TokenStatus (r:1 w:1) - /// Proof Skipped: SystemStaking TokenStatus (max_values: None, max_size: None, mode: Measured) - /// Storage: SystemStaking TokenList (r:1 w:1) - /// Proof Skipped: SystemStaking TokenList (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: `SystemStaking::TokenStatus` (r:1 w:1) + /// Proof: `SystemStaking::TokenStatus` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `SystemStaking::TokenList` (r:1 w:1) + /// Proof: `SystemStaking::TokenList` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn token_config() -> Weight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 44_695_000 picoseconds. - Weight::from_parts(45_801_000, 3574) + // Minimum execution time: 9_370_000 picoseconds. + Weight::from_parts(10_254_000, 3574) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: SystemStaking TokenStatus (r:1 w:1) - /// Proof Skipped: SystemStaking TokenStatus (max_values: None, max_size: None, mode: Measured) - /// Storage: Farming PoolInfos (r:1 w:0) - /// Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) + /// Storage: `SystemStaking::TokenStatus` (r:1 w:1) + /// Proof: `SystemStaking::TokenStatus` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::PoolInfos` (r:1 w:0) + /// Proof: `Farming::PoolInfos` (`max_values`: None, `max_size`: None, mode: `Measured`) fn refresh_token_info() -> Weight { // Proof Size summary in bytes: - // Measured: `403` - // Estimated: `3868` - // Minimum execution time: 56_032_000 picoseconds. - Weight::from_parts(57_981_000, 3868) + // Measured: `370` + // Estimated: `3835` + // Minimum execution time: 14_641_000 picoseconds. + Weight::from_parts(27_074_000, 3835) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: SystemStaking TokenStatus (r:1 w:0) - /// Proof Skipped: SystemStaking TokenStatus (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:1 w:0) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: VtokenMinting TokenPool (r:1 w:0) - /// Proof: VtokenMinting TokenPool (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:1 w:0) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `SystemStaking::TokenStatus` (r:1 w:0) + /// Proof: `SystemStaking::TokenStatus` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Tokens::Accounts` (r:1 w:0) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `VtokenMinting::TokenPool` (r:1 w:0) + /// Proof: `VtokenMinting::TokenPool` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:0) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn payout() -> Weight { // Proof Size summary in bytes: - // Measured: `1190` - // Estimated: `4655` - // Minimum execution time: 71_558_000 picoseconds. - Weight::from_parts(72_649_000, 4655) + // Measured: `550` + // Estimated: `4015` + // Minimum execution time: 16_437_000 picoseconds. + Weight::from_parts(17_241_000, 4015) .saturating_add(RocksDbWeight::get().reads(4_u64)) } fn on_redeem_success() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_672_000 picoseconds. - Weight::from_parts(2_317_000, 0) + // Minimum execution time: 201_000 picoseconds. + Weight::from_parts(243_000, 0) } fn on_redeemed() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_053_000 picoseconds. - Weight::from_parts(2_416_000, 0) + // Minimum execution time: 234_000 picoseconds. + Weight::from_parts(282_000, 0) } - /// Storage: SystemStaking TokenList (r:1 w:1) - /// Proof Skipped: SystemStaking TokenList (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: SystemStaking TokenStatus (r:0 w:1) - /// Proof Skipped: SystemStaking TokenStatus (max_values: None, max_size: None, mode: Measured) + /// Storage: `SystemStaking::TokenList` (r:1 w:1) + /// Proof: `SystemStaking::TokenList` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `SystemStaking::TokenStatus` (r:0 w:1) + /// Proof: `SystemStaking::TokenStatus` (`max_values`: None, `max_size`: None, mode: `Measured`) fn delete_token() -> Weight { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1654` - // Minimum execution time: 24_359_000 picoseconds. - Weight::from_parts(25_049_000, 1654) + // Minimum execution time: 5_654_000 picoseconds. + Weight::from_parts(5_826_000, 1654) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/pallets/token-issuer/Cargo.toml b/pallets/token-issuer/Cargo.toml index 200dafad43..771311a920 100644 --- a/pallets/token-issuer/Cargo.toml +++ b/pallets/token-issuer/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-token-issuer" version = "0.8.0" -authors = ["Herry Ho "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/token-issuer/src/lib.rs b/pallets/token-issuer/src/lib.rs index 1dcff37472..3275a8fda4 100644 --- a/pallets/token-issuer/src/lib.rs +++ b/pallets/token-issuer/src/lib.rs @@ -132,7 +132,7 @@ pub mod pallet { match IssueWhiteList::::get(currency_id) { None => { issue_vec = vec![account.clone()]; - }, + } Some(issue_whitelist) => { issue_vec = issue_whitelist.into_inner(); ensure!(!issue_vec.contains(&account), Error::::NotAllowed); @@ -142,7 +142,7 @@ pub mod pallet { ); issue_vec.push(account.clone()); - }, + } } issue_whitelist_new = @@ -168,7 +168,7 @@ pub mod pallet { issue_list.retain(|x| x.clone() != account); Self::deposit_event(Event::RemovedFromIssueList(account, currency_id)); Ok(()) - }, + } _ => Err(Error::::NotExist), } })?; @@ -190,7 +190,7 @@ pub mod pallet { match TransferWhiteList::::get(currency_id) { None => { transfer_vec = vec![account.clone()]; - }, + } Some(transfer_whitelist) => { transfer_vec = transfer_whitelist.into_inner(); ensure!(!transfer_vec.contains(&account), Error::::NotAllowed); @@ -200,7 +200,7 @@ pub mod pallet { ); transfer_vec.push(account.clone()); - }, + } } transfer_whitelist_new = @@ -231,7 +231,7 @@ pub mod pallet { currency_id, )); Ok(()) - }, + } _ => Err(Error::::NotExist), } }, @@ -276,7 +276,10 @@ pub mod pallet { let transfer_whitelist = TransferWhiteList::::get(currency_id).ok_or(Error::::NotAllowed)?; - ensure!(transfer_whitelist.contains(&transferrer), Error::::NotAllowed); + ensure!( + transfer_whitelist.contains(&transferrer), + Error::::NotAllowed + ); let balance = T::MultiCurrency::free_balance(currency_id, &transferrer); ensure!(balance >= amount, Error::::NotEnoughBalance); diff --git a/pallets/token-issuer/src/mock.rs b/pallets/token-issuer/src/mock.rs index 4764c9e600..2873e44976 100644 --- a/pallets/token-issuer/src/mock.rs +++ b/pallets/token-issuer/src/mock.rs @@ -166,7 +166,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -196,7 +198,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/token-issuer/src/tests.rs b/pallets/token-issuer/src/tests.rs index aae47d9d6b..a9e5407bb4 100644 --- a/pallets/token-issuer/src/tests.rs +++ b/pallets/token-issuer/src/tests.rs @@ -31,134 +31,171 @@ fn initialize_charlie_as_issue_whitelist_member() { CHARLIE )); // Issue some ZLK to Charlie's account - assert_ok!(TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), CHARLIE, ZLK, 1000)); + assert_ok!(TokenIssuer::issue( + RuntimeOrigin::signed(CHARLIE), + CHARLIE, + ZLK, + 1000 + )); } #[test] fn add_to_issue_whitelist_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - // Charlie is not allowed to issue ZLK. - assert_noop!( - TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), - Error::::NotAllowed - ); - // Chalie is added to the issue whitelist to have the ability of issuing ZLK. - assert_ok!(TokenIssuer::add_to_issue_whitelist( - pallet_collective::RawOrigin::Members(2, 3).into(), - ZLK, - CHARLIE - )); - - let bounded_list = BoundedVec::try_from(vec![CHARLIE]).unwrap(); - assert_eq!(IssueWhiteList::::get(ZLK), Some(bounded_list)); - // Charlie succuessfully issue 800 unit of ZLK to Alice account - assert_ok!(TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800)); - assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + // Charlie is not allowed to issue ZLK. + assert_noop!( + TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), + Error::::NotAllowed + ); + // Chalie is added to the issue whitelist to have the ability of issuing ZLK. + assert_ok!(TokenIssuer::add_to_issue_whitelist( + pallet_collective::RawOrigin::Members(2, 3).into(), + ZLK, + CHARLIE + )); + + let bounded_list = BoundedVec::try_from(vec![CHARLIE]).unwrap(); + assert_eq!(IssueWhiteList::::get(ZLK), Some(bounded_list)); + // Charlie succuessfully issue 800 unit of ZLK to Alice account + assert_ok!(TokenIssuer::issue( + RuntimeOrigin::signed(CHARLIE), + ALICE, + ZLK, + 800 + )); + assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); + }); } #[test] fn remove_from_issue_whitelist_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - // Charlie is not in the issue whitelist - assert_noop!( - TokenIssuer::remove_from_issue_whitelist( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + // Charlie is not in the issue whitelist + assert_noop!( + TokenIssuer::remove_from_issue_whitelist( + pallet_collective::RawOrigin::Members(2, 3).into(), + ZLK, + CHARLIE + ), + Error::::NotExist + ); + // Add Charlie + assert_ok!(TokenIssuer::add_to_issue_whitelist( pallet_collective::RawOrigin::Members(2, 3).into(), ZLK, CHARLIE - ), - Error::::NotExist - ); - // Add Charlie - assert_ok!(TokenIssuer::add_to_issue_whitelist( - pallet_collective::RawOrigin::Members(2, 3).into(), - ZLK, - CHARLIE - )); - - // Charlie succuessfully issue 800 unit of ZLK to Alice account - assert_ok!(TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800)); - assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); - - // Successfully remove Charlie - assert_ok!(TokenIssuer::remove_from_issue_whitelist( - pallet_collective::RawOrigin::Members(2, 3).into(), - ZLK, - CHARLIE - )); - // Charlie is no longer able to issue token to any account - assert_noop!( - TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), - Error::::NotAllowed - ); - }); + )); + + // Charlie succuessfully issue 800 unit of ZLK to Alice account + assert_ok!(TokenIssuer::issue( + RuntimeOrigin::signed(CHARLIE), + ALICE, + ZLK, + 800 + )); + assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); + + // Successfully remove Charlie + assert_ok!(TokenIssuer::remove_from_issue_whitelist( + pallet_collective::RawOrigin::Members(2, 3).into(), + ZLK, + CHARLIE + )); + // Charlie is no longer able to issue token to any account + assert_noop!( + TokenIssuer::issue(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), + Error::::NotAllowed + ); + }); } #[test] fn add_to_transfer_whitelist_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - initialize_charlie_as_issue_whitelist_member(); - - // Charlie is not allowed to transfer ZLK. - assert_noop!( - TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), - Error::::NotAllowed - ); - // Chalie is added to the transfer whitelist to have the ability of transferring ZLK. - assert_ok!(TokenIssuer::add_to_transfer_whitelist( - pallet_collective::RawOrigin::Members(2, 3).into(), - ZLK, - CHARLIE - )); - - let bounded_list = BoundedVec::try_from(vec![CHARLIE]).unwrap(); - assert_eq!(TransferWhiteList::::get(ZLK), Some(bounded_list)); - // Charlie succuessfully transfer 800 unit of ZLK to Alice account - assert_ok!(TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800)); - assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); - // exceed balance - assert_noop!( - TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 300), - Error::::NotEnoughBalance - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + initialize_charlie_as_issue_whitelist_member(); + + // Charlie is not allowed to transfer ZLK. + assert_noop!( + TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), + Error::::NotAllowed + ); + // Chalie is added to the transfer whitelist to have the ability of transferring ZLK. + assert_ok!(TokenIssuer::add_to_transfer_whitelist( + pallet_collective::RawOrigin::Members(2, 3).into(), + ZLK, + CHARLIE + )); + + let bounded_list = BoundedVec::try_from(vec![CHARLIE]).unwrap(); + assert_eq!(TransferWhiteList::::get(ZLK), Some(bounded_list)); + // Charlie succuessfully transfer 800 unit of ZLK to Alice account + assert_ok!(TokenIssuer::transfer( + RuntimeOrigin::signed(CHARLIE), + ALICE, + ZLK, + 800 + )); + assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); + // exceed balance + assert_noop!( + TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 300), + Error::::NotEnoughBalance + ); + }); } #[test] fn remove_from_transfer_whitelist_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - initialize_charlie_as_issue_whitelist_member(); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + initialize_charlie_as_issue_whitelist_member(); + + // Charlie is not in the transfer whitelist + assert_noop!( + TokenIssuer::remove_from_transfer_whitelist( + pallet_collective::RawOrigin::Members(2, 3).into(), + ZLK, + CHARLIE + ), + Error::::NotExist + ); + // Add Charlie + assert_ok!(TokenIssuer::add_to_transfer_whitelist( + pallet_collective::RawOrigin::Members(2, 3).into(), + ZLK, + CHARLIE + )); + + // Charlie succuessfully transfer 800 unit of ZLK to Alice account + assert_ok!(TokenIssuer::transfer( + RuntimeOrigin::signed(CHARLIE), + ALICE, + ZLK, + 800 + )); + assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); - // Charlie is not in the transfer whitelist - assert_noop!( - TokenIssuer::remove_from_transfer_whitelist( + // Successfully remove Charlie + assert_ok!(TokenIssuer::remove_from_transfer_whitelist( pallet_collective::RawOrigin::Members(2, 3).into(), ZLK, CHARLIE - ), - Error::::NotExist - ); - // Add Charlie - assert_ok!(TokenIssuer::add_to_transfer_whitelist( - pallet_collective::RawOrigin::Members(2, 3).into(), - ZLK, - CHARLIE - )); - - // Charlie succuessfully transfer 800 unit of ZLK to Alice account - assert_ok!(TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800)); - assert_eq!(Tokens::free_balance(ZLK, &ALICE), 800); - - // Successfully remove Charlie - assert_ok!(TokenIssuer::remove_from_transfer_whitelist( - pallet_collective::RawOrigin::Members(2, 3).into(), - ZLK, - CHARLIE - )); - // Charlie is no longer able to transfer token to any account - assert_noop!( - TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), - Error::::NotAllowed - ); - }); + )); + // Charlie is no longer able to transfer token to any account + assert_noop!( + TokenIssuer::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, ZLK, 800), + Error::::NotAllowed + ); + }); } diff --git a/pallets/traits/Cargo.toml b/pallets/traits/Cargo.toml index 517f3b1274..3d42ccdeb4 100644 --- a/pallets/traits/Cargo.toml +++ b/pallets/traits/Cargo.toml @@ -1,5 +1,5 @@ [package] -authors = ["Parallel Team", "Liebi Technologies "] +authors = ["Liebi Technologies "] edition = "2021" name = "pallet-traits" version = "0.8.0" diff --git a/pallets/traits/src/evm.rs b/pallets/traits/src/evm.rs index 5360ab31e7..9df4eaa0c3 100644 --- a/pallets/traits/src/evm.rs +++ b/pallets/traits/src/evm.rs @@ -15,3 +15,27 @@ pub trait InspectEvmAccounts { /// Returns `True` if the address is allowed to deploy smart contracts. fn can_deploy_contracts(evm_address: EvmAddress) -> bool; } + +impl, EvmAddress: Default> InspectEvmAccounts + for () +{ + fn evm_address(_account_id: &impl AsRef<[u8; 32]>) -> EvmAddress { + EvmAddress::default() + } + + fn convert_account_id(_evm_address: EvmAddress) -> AccountId { + [0u8; 32].into() + } + + fn bound_account_id(_evm_address: EvmAddress) -> Option { + None + } + + fn account_id(_evm_address: EvmAddress) -> AccountId { + [0u8; 32].into() + } + + fn can_deploy_contracts(_evm_address: EvmAddress) -> bool { + false + } +} diff --git a/pallets/traits/src/lend_market.rs b/pallets/traits/src/lend_market.rs index 88fab107d6..7cf018f54b 100644 --- a/pallets/traits/src/lend_market.rs +++ b/pallets/traits/src/lend_market.rs @@ -1,16 +1,20 @@ -// Copyright 2021 Parallel Finance Developer. -// This file is part of Parallel Finance. +// This file is part of Bifrost. -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . use bifrost_primitives::{Rate, Ratio}; use parity_scale_codec::{Decode, Encode}; diff --git a/pallets/vbnc-convert/src/benchmarking.rs b/pallets/vbnc-convert/src/benchmarking.rs index b3ff9e3212..531d94cc5a 100644 --- a/pallets/vbnc-convert/src/benchmarking.rs +++ b/pallets/vbnc-convert/src/benchmarking.rs @@ -58,11 +58,21 @@ mod benchmarks { #[extrinsic_call] Pallet::::charge_vbnc_p(RawOrigin::Signed(caller.clone()), amount); - assert_eq!(T::MultiCurrency::free_balance(VBNC_P, &caller), Zero::zero()); - assert_eq!(T::MultiCurrency::free_balance(VBNC_P, &vbnc_pool_account), amount); + assert_eq!( + T::MultiCurrency::free_balance(VBNC_P, &caller), + Zero::zero() + ); + assert_eq!( + T::MultiCurrency::free_balance(VBNC_P, &vbnc_pool_account), + amount + ); Ok(()) } - impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext_benchmark(), crate::mock::Runtime); + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/vbnc-convert/src/lib.rs b/pallets/vbnc-convert/src/lib.rs index 39573b4b3d..98d9de21c1 100644 --- a/pallets/vbnc-convert/src/lib.rs +++ b/pallets/vbnc-convert/src/lib.rs @@ -134,7 +134,10 @@ pub mod pallet { Self::ensure_pool_balance_enough(VBNC_P, vbnc_p_amount)?; let existential_deposit = T::MultiCurrency::minimum_balance(VBNC_P); - ensure!(vbnc_p_amount >= existential_deposit, Error::::LessThanExistentialDeposit); + ensure!( + vbnc_p_amount >= existential_deposit, + Error::::LessThanExistentialDeposit + ); // transfer vBNC-p from pool to user let vbnc_pool_account = Self::vbnc_p_pool_account(); @@ -144,7 +147,10 @@ pub mod pallet { T::MultiCurrency::withdraw(currency, &who, value)?; // deposit event - Self::deposit_event(Event::VBNCPConverted { to: who, value: vbnc_p_amount }); + Self::deposit_event(Event::VBNCPConverted { + to: who, + value: vbnc_p_amount, + }); Ok(()) } diff --git a/pallets/vbnc-convert/src/mock.rs b/pallets/vbnc-convert/src/mock.rs index 88d8cc86ed..cee4326f5b 100644 --- a/pallets/vbnc-convert/src/mock.rs +++ b/pallets/vbnc-convert/src/mock.rs @@ -173,10 +173,14 @@ impl bifrost_vbnc_convert::Config for Runtime { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - pallet_balances::GenesisConfig:: { balances: vec![(BOB, 10)] } - .assimilate_storage(&mut t) + let mut t = frame_system::GenesisConfig::::default() + .build_storage() .unwrap(); + pallet_balances::GenesisConfig:: { + balances: vec![(BOB, 10)], + } + .assimilate_storage(&mut t) + .unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/pallets/vbnc-convert/src/tests.rs b/pallets/vbnc-convert/src/tests.rs index 91193e00e0..60a2bbb6c2 100644 --- a/pallets/vbnc-convert/src/tests.rs +++ b/pallets/vbnc-convert/src/tests.rs @@ -31,16 +31,30 @@ use frame_support::{assert_noop, assert_ok}; fn convert_to_vbnc_p_should_work() { new_test_ext().execute_with(|| { assert_ok!(Tokens::deposit(VBNC, &BOB, 5000)); - assert_ok!(Tokens::deposit(VBNC_P, &VBNCConvert::vbnc_p_pool_account(), 5000)); - - assert_ok!(VBNCConvert::convert_to_vbnc_p(RuntimeOrigin::signed(BOB), VBNC, 1000)); + assert_ok!(Tokens::deposit( + VBNC_P, + &VBNCConvert::vbnc_p_pool_account(), + 5000 + )); + + assert_ok!(VBNCConvert::convert_to_vbnc_p( + RuntimeOrigin::signed(BOB), + VBNC, + 1000 + )); System::assert_last_event(RuntimeEvent::VBNCConvert(Event::VBNCPConverted { to: BOB, value: 1000, })); - assert_eq!(::MultiCurrency::free_balance(VBNC, &BOB,), 4000); - assert_eq!(::MultiCurrency::free_balance(VBNC_P, &BOB,), 1000); + assert_eq!( + ::MultiCurrency::free_balance(VBNC, &BOB,), + 4000 + ); + assert_eq!( + ::MultiCurrency::free_balance(VBNC_P, &BOB,), + 1000 + ); assert_eq!( ::MultiCurrency::free_balance( VBNC_P, @@ -94,7 +108,11 @@ fn convert_to_vbnc_p_should_fail_with_pool_balance_poor() { fn convert_to_vbnc_p_should_fail_with_less_than_existential_depositr() { new_test_ext().execute_with(|| { assert_ok!(Tokens::deposit(VBNC, &BOB, 500)); - assert_ok!(Tokens::deposit(VBNC_P, &VBNCConvert::vbnc_p_pool_account(), 500)); + assert_ok!(Tokens::deposit( + VBNC_P, + &VBNCConvert::vbnc_p_pool_account(), + 500 + )); assert_noop!( VBNCConvert::convert_to_vbnc_p(RuntimeOrigin::signed(BOB), VBNC, 1), @@ -114,7 +132,10 @@ fn charge_vbnc_should_work() { value: 100, })); - assert_eq!(::MultiCurrency::free_balance(VBNC_P, &BOB), 400); + assert_eq!( + ::MultiCurrency::free_balance(VBNC_P, &BOB), + 400 + ); assert_eq!( ::MultiCurrency::free_balance( VBNC_P, diff --git a/pallets/vesting/Cargo.toml b/pallets/vesting/Cargo.toml index 8937da2f01..513632935e 100644 --- a/pallets/vesting/Cargo.toml +++ b/pallets/vesting/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vesting" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/vesting/src/lib.rs b/pallets/vesting/src/lib.rs index c70f2754a8..f7d34941e2 100644 --- a/pallets/vesting/src/lib.rs +++ b/pallets/vesting/src/lib.rs @@ -72,8 +72,8 @@ use scale_info::TypeInfo; use sp_runtime::{ codec::{Decode, Encode, MaxEncodedLen}, traits::{ - AtLeast32BitUnsigned, Bounded, Convert, MaybeSerializeDeserialize, One, Saturating, - StaticLookup, Zero, + AtLeast32BitUnsigned, BlockNumberProvider, Bounded, Convert, MaybeSerializeDeserialize, + One, Saturating, StaticLookup, Zero, }, DispatchError, RuntimeDebug, }; @@ -131,13 +131,16 @@ impl VestingAction { &self, schedules: Vec, BlockNumberFor>>, ) -> impl Iterator, BlockNumberFor>> + '_ { - schedules.into_iter().enumerate().filter_map(move |(index, schedule)| { - if self.should_remove(index) { - None - } else { - Some(schedule) - } - }) + schedules + .into_iter() + .enumerate() + .filter_map(move |(index, schedule)| { + if self.should_remove(index) { + None + } else { + Some(schedule) + } + }) } } @@ -177,6 +180,9 @@ pub mod pallet { /// the unvested amount. type UnvestedFundsAllowedWithdrawReasons: Get; + /// Provider for the block number. + type BlockNumberProvider: BlockNumberProvider>; + /// Maximum number of vesting schedules an account may have at a given moment. const MAX_VESTING_SCHEDULES: u32; } @@ -192,7 +198,10 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn integrity_test() { - assert!(T::MAX_VESTING_SCHEDULES > 0, "`MaxVestingSchedules` must ge greater than 0"); + assert!( + T::MAX_VESTING_SCHEDULES > 0, + "`MaxVestingSchedules` must ge greater than 0" + ); } } @@ -226,7 +235,12 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { - pub vesting: Vec<(T::AccountId, BlockNumberFor, BlockNumberFor, BalanceOf)>, + pub vesting: Vec<( + T::AccountId, + BlockNumberFor, + BlockNumberFor, + BalanceOf, + )>, } #[pallet::genesis_build] @@ -244,7 +258,10 @@ pub mod pallet { // * liquid - Number of units which can be spent before vesting begins for &(ref who, begin, length, liquid) in self.vesting.iter() { let balance = T::Currency::free_balance(who); - assert!(!balance.is_zero(), "Currencies must be init'd before vesting"); + assert!( + !balance.is_zero(), + "Currencies must be init'd before vesting" + ); // Total genesis `balance` minus `liquid` equals funds locked for vesting let locked = balance.saturating_sub(liquid); let length_as_balance = T::BlockNumberToBalance::convert(length); @@ -270,7 +287,10 @@ pub mod pallet { pub enum Event { /// The amount vested has been updated. This could indicate a change in funds available. /// The balance given is the amount which is left unvested (and thus locked). - VestingUpdated { account: T::AccountId, unvested: BalanceOf }, + VestingUpdated { + account: T::AccountId, + unvested: BalanceOf, + }, /// An \[account\] has become fully vested. VestingCompleted { account: T::AccountId }, } @@ -423,18 +443,27 @@ pub mod pallet { let index = index as usize; Self::do_vest(target.clone())?; let schedules = Vesting::::get(&target).ok_or(Error::::NotVesting)?; - ensure!(schedules.len() > index, Error::::ScheduleIndexOutOfBounds); - ensure!(schedules[index].per_block() != per_block, Error::::SamePerBlock); + ensure!( + schedules.len() > index, + Error::::ScheduleIndexOutOfBounds + ); + ensure!( + schedules[index].per_block() != per_block, + Error::::SamePerBlock + ); let absolute_start = VestingStartAt::::get().ok_or(Error::::VestingStartAtNotSet)?; - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let old_start_at = absolute_start.saturating_add(schedules[index].starting_block()); let remained_vesting = schedules[index].locked_at::(now, Some(old_start_at)); - ensure!(remained_vesting <= schedules[index].locked(), Error::::WrongLockedAmount); + ensure!( + remained_vesting <= schedules[index].locked(), + Error::::WrongLockedAmount + ); let mut new_start_offset = schedules[index].starting_block(); if now > old_start_at { @@ -507,8 +536,10 @@ pub mod pallet { let schedule2_index = schedule2_index as usize; let schedules = Vesting::::get(&who).ok_or(Error::::NotVesting)?; - let merge_action = - VestingAction::Merge { index1: schedule1_index, index2: schedule2_index }; + let merge_action = VestingAction::Merge { + index1: schedule1_index, + index2: schedule2_index, + }; let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), merge_action)?; @@ -523,7 +554,7 @@ pub mod pallet { impl Pallet { fn check_cliff(who: T::AccountId) -> DispatchResult { if let Some(cliff_block) = Cliff::::get(who.clone()) { - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); ensure!(cliff_block < now, Error::::WrongCliffVesting); Cliff::::remove(who); }; @@ -547,7 +578,10 @@ impl Pallet { let now_as_balance = T::BlockNumberToBalance::convert(now); // Check if one or both schedules have ended. - match (schedule1_ending_block <= now_as_balance, schedule2_ending_block <= now_as_balance) { + match ( + schedule1_ending_block <= now_as_balance, + schedule2_ending_block <= now_as_balance, + ) { // If both schedules have ended, we don't merge and exit early. (true, true) => return None, // If one schedule has ended, we treat the one that has not ended as the new @@ -555,7 +589,7 @@ impl Pallet { (true, false) => return Some(schedule2), (false, true) => return Some(schedule1), // If neither schedule has ended don't exit early. - _ => {}, + _ => {} } let locked = schedule1 @@ -571,7 +605,9 @@ impl Pallet { ); let ending_block = schedule1_ending_block.max(schedule2_ending_block); - let starting_block = now.max(schedule1.starting_block()).max(schedule2.starting_block()); + let starting_block = now + .max(schedule1.starting_block()) + .max(schedule2.starting_block()); let per_block = { let duration = ending_block @@ -581,7 +617,10 @@ impl Pallet { }; let schedule = VestingInfo::new(locked, per_block, starting_block); - debug_assert!(schedule.is_valid(), "merge_vesting_info schedule validation check failed"); + debug_assert!( + schedule.is_valid(), + "merge_vesting_info schedule validation check failed" + ); Some(schedule) } @@ -593,7 +632,10 @@ impl Pallet { schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { // Validate user inputs. - ensure!(schedule.locked() >= T::MinVestedTransfer::get(), Error::::AmountLow); + ensure!( + schedule.locked() >= T::MinVestedTransfer::get(), + Error::::AmountLow + ); if !schedule.is_valid() { return Err(Error::::InvalidScheduleParams.into()); }; @@ -622,7 +664,10 @@ impl Pallet { schedule.per_block(), schedule.starting_block(), ); - debug_assert!(res.is_ok(), "Failed to add a schedule when we had to succeed."); + debug_assert!( + res.is_ok(), + "Failed to add a schedule when we had to succeed." + ); Ok(()) } @@ -640,8 +685,11 @@ impl Pallet { fn report_schedule_updates( schedules: Vec, BlockNumberFor>>, action: VestingAction, - ) -> (Vec, BlockNumberFor>>, BalanceOf) { - let now = >::block_number(); + ) -> ( + Vec, BlockNumberFor>>, + BalanceOf, + ) { + let now = T::BlockNumberProvider::current_block_number(); let mut total_locked_now: BalanceOf = Zero::zero(); let filtered_schedules = action @@ -665,7 +713,9 @@ impl Pallet { fn write_lock(who: &T::AccountId, total_locked_now: BalanceOf) { if total_locked_now.is_zero() { T::Currency::remove_lock(VESTING_ID, who); - Self::deposit_event(Event::::VestingCompleted { account: who.clone() }); + Self::deposit_event(Event::::VestingCompleted { + account: who.clone(), + }); } else { let reasons = WithdrawReasons::except(T::UnvestedFundsAllowedWithdrawReasons::get()); T::Currency::set_lock(VESTING_ID, who, total_locked_now, reasons); @@ -684,7 +734,9 @@ impl Pallet { let schedules: BoundedVec< VestingInfo, BlockNumberFor>, MaxVestingSchedulesGet, - > = schedules.try_into().map_err(|_| Error::::AtMaxVestingSchedules)?; + > = schedules + .try_into() + .map_err(|_| Error::::AtMaxVestingSchedules)?; if schedules.len() == 0 { Vesting::::remove(&who); @@ -713,13 +765,26 @@ impl Pallet { fn exec_action( schedules: Vec, BlockNumberFor>>, action: VestingAction, - ) -> Result<(Vec, BlockNumberFor>>, BalanceOf), DispatchError> { + ) -> Result< + ( + Vec, BlockNumberFor>>, + BalanceOf, + ), + DispatchError, + > { let (schedules, locked_now) = match action { - VestingAction::Merge { index1: idx1, index2: idx2 } => { + VestingAction::Merge { + index1: idx1, + index2: idx2, + } => { // The schedule index is based off of the schedule ordering prior to filtering out // any schedules that may be ending at this block. - let schedule1 = *schedules.get(idx1).ok_or(Error::::ScheduleIndexOutOfBounds)?; - let schedule2 = *schedules.get(idx2).ok_or(Error::::ScheduleIndexOutOfBounds)?; + let schedule1 = *schedules + .get(idx1) + .ok_or(Error::::ScheduleIndexOutOfBounds)?; + let schedule2 = *schedules + .get(idx2) + .ok_or(Error::::ScheduleIndexOutOfBounds)?; // The length of `schedules` decreases by 2 here since we filter out 2 schedules. // Thus we know below that we can push the new merged schedule without error @@ -727,7 +792,7 @@ impl Pallet { let (mut schedules, mut locked_now) = Self::report_schedule_updates(schedules.to_vec(), action); - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); if let Some(new_schedule) = Self::merge_vesting_info(now, schedule1, schedule2) { // Merging created a new schedule so we: // 1) need to add it to the accounts vesting schedule collection, @@ -742,13 +807,13 @@ impl Pallet { } // In the None case there was no new schedule to account for. (schedules, locked_now) - }, + } _ => Self::report_schedule_updates(schedules.to_vec(), action), }; debug_assert!( - locked_now > Zero::zero() && schedules.len() > 0 || - locked_now == Zero::zero() && schedules.len() == 0 + locked_now > Zero::zero() && schedules.len() > 0 + || locked_now == Zero::zero() && schedules.len() == 0 ); Ok((schedules, locked_now)) @@ -765,7 +830,7 @@ where /// Get the amount that is currently being vested and cannot be transferred out of this account. fn vesting_balance(who: &T::AccountId) -> Option> { if let Some(v) = Vesting::::get(who) { - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let total_locked_now = v.iter().fold(Zero::zero(), |total, schedule| { let start_at = VestingStartAt::::get() .map(|st| st.saturating_add(schedule.starting_block())); @@ -811,7 +876,10 @@ where // NOTE: we must push the new schedule so that `exec_action` // will give the correct new locked amount. - ensure!(schedules.try_push(vesting_schedule).is_ok(), Error::::AtMaxVestingSchedules); + ensure!( + schedules.try_push(vesting_schedule).is_ok(), + Error::::AtMaxVestingSchedules + ); let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), VestingAction::Passive)?; @@ -846,7 +914,9 @@ where /// Remove a vesting schedule for a given account. fn remove_vesting_schedule(who: &T::AccountId, schedule_index: u32) -> DispatchResult { let schedules = Vesting::::get(who).ok_or(Error::::NotVesting)?; - let remove_action = VestingAction::Remove { index: schedule_index as usize }; + let remove_action = VestingAction::Remove { + index: schedule_index as usize, + }; let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), remove_action)?; diff --git a/pallets/vesting/src/mock.rs b/pallets/vesting/src/mock.rs index 8ed458342d..2ef0de716c 100644 --- a/pallets/vesting/src/mock.rs +++ b/pallets/vesting/src/mock.rs @@ -79,6 +79,7 @@ impl Config for Test { type MinVestedTransfer = MinVestedTransfer; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; type WeightInfo = (); + type BlockNumberProvider = System; } pub struct ExtBuilder { @@ -88,7 +89,10 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { existential_deposit: 1, vesting_genesis_config: None } + Self { + existential_deposit: 1, + vesting_genesis_config: None, + } } } @@ -105,7 +109,9 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ (1, 10 * self.existential_deposit), diff --git a/pallets/vesting/src/tests.rs b/pallets/vesting/src/tests.rs index ce02da117c..79a0a08876 100644 --- a/pallets/vesting/src/tests.rs +++ b/pallets/vesting/src/tests.rs @@ -47,375 +47,472 @@ const DAVE: u64 = 4; #[test] fn check_vesting_status() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - let user1_free_balance = Balances::free_balance(&ALICE); - let user2_free_balance = Balances::free_balance(&BOB); - let user3_free_balance = Balances::free_balance(&CHAR); - assert_eq!(user1_free_balance, ALICE_INIT_BALANCE); // Account 1 has free balance - assert_eq!(user2_free_balance, BOB_INIT_BALANCE); // Account 2 has free balance - assert_eq!(user3_free_balance, CHAR_INIT_BALANCE); // Account 3 has free balance - - let s = Balances::locks(ALICE).to_vec()[0].amount; - println!("{:?}", s); - println!("{:?}", b"vesting "); - - let user1_vesting_schedule = VestingInfo::new( - ALICE_INIT_LOCKED, // 10 * ED - 5 * ED - ALICE_PER_BLOCK, // Vesting over 10 blocks - 0u64, - ); - let user2_vesting_schedule = VestingInfo::new( - BOB_INIT_LOCKED, // 20 * ED - BOB_PER_BLOCK, // Vesting over 20 blocks - 10u64, - ); - let user3_vesting_schedule = VestingInfo::new( - CHAR_INIT_LOCKED, // 30 * ED - ED * 5 - CHAR_PER_BLOCK, // Vesting over 20 blocks - 10u64, - ); - assert_eq!(vesting::::get(&ALICE).unwrap().to_vec(), vec![user1_vesting_schedule]); - assert_eq!(vesting::::get(&BOB).unwrap().to_vec(), vec![user2_vesting_schedule]); - assert_eq!(vesting::::get(&CHAR).unwrap().to_vec(), vec![user3_vesting_schedule]); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + let user1_free_balance = Balances::free_balance(&ALICE); + let user2_free_balance = Balances::free_balance(&BOB); + let user3_free_balance = Balances::free_balance(&CHAR); + assert_eq!(user1_free_balance, ALICE_INIT_BALANCE); // Account 1 has free balance + assert_eq!(user2_free_balance, BOB_INIT_BALANCE); // Account 2 has free balance + assert_eq!(user3_free_balance, CHAR_INIT_BALANCE); // Account 3 has free balance + + let s = Balances::locks(ALICE).to_vec()[0].amount; + println!("{:?}", s); + println!("{:?}", b"vesting "); + + let user1_vesting_schedule = VestingInfo::new( + ALICE_INIT_LOCKED, // 10 * ED - 5 * ED + ALICE_PER_BLOCK, // Vesting over 10 blocks + 0u64, + ); + let user2_vesting_schedule = VestingInfo::new( + BOB_INIT_LOCKED, // 20 * ED + BOB_PER_BLOCK, // Vesting over 20 blocks + 10u64, + ); + let user3_vesting_schedule = VestingInfo::new( + CHAR_INIT_LOCKED, // 30 * ED - ED * 5 + CHAR_PER_BLOCK, // Vesting over 20 blocks + 10u64, + ); + assert_eq!( + vesting::::get(&ALICE).unwrap().to_vec(), + vec![user1_vesting_schedule] + ); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user2_vesting_schedule] + ); + assert_eq!( + vesting::::get(&CHAR).unwrap().to_vec(), + vec![user3_vesting_schedule] + ); + }); } #[test] fn vesting_balance_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - // not set start_at , all return init_locked - assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); - - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - - // current block 1 - assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED - ALICE_PER_BLOCK)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); - - //set block to 10 - System::set_block_number(10); - assert_eq!(System::block_number(), 10); - - assert_eq!(Vesting::vesting_balance(&ALICE), Some(0)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); - - //set block to 30 - System::set_block_number(30); - assert_eq!(System::block_number(), 30); - - assert_eq!(Vesting::vesting_balance(&ALICE), Some(0)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(0)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(0)); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + // not set start_at , all return init_locked + assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); + + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + + // current block 1 + assert_eq!( + Vesting::vesting_balance(&ALICE), + Some(ALICE_INIT_LOCKED - ALICE_PER_BLOCK) + ); + assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); + + //set block to 10 + System::set_block_number(10); + assert_eq!(System::block_number(), 10); + + assert_eq!(Vesting::vesting_balance(&ALICE), Some(0)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); + + //set block to 30 + System::set_block_number(30); + assert_eq!(System::block_number(), 30); + + assert_eq!(Vesting::vesting_balance(&ALICE), Some(0)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(0)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(0)); + }) } #[test] fn vesting_balance_with_start_at_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - // not set start_at , all return init_locked - assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); - - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 1)); - - // current block 1 - assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); - - //set block to 10 - System::set_block_number(10); - assert_eq!(System::block_number(), 10); - - //set start_at to 3 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 3)); - - assert_eq!(Vesting::vesting_balance(&ALICE), Some(3 * ALICE_PER_BLOCK)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); - - //set block to 30 - System::set_block_number(30); - assert_eq!(System::block_number(), 30); - - assert_eq!(Vesting::vesting_balance(&ALICE), Some(0)); - assert_eq!(Vesting::vesting_balance(&BOB), Some(3 * BOB_PER_BLOCK)); - assert_eq!(Vesting::vesting_balance(&CHAR), Some(3 * CHAR_PER_BLOCK)); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + // not set start_at , all return init_locked + assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); + + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 1)); + + // current block 1 + assert_eq!(Vesting::vesting_balance(&ALICE), Some(ALICE_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); + + //set block to 10 + System::set_block_number(10); + assert_eq!(System::block_number(), 10); + + //set start_at to 3 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 3)); + + assert_eq!(Vesting::vesting_balance(&ALICE), Some(3 * ALICE_PER_BLOCK)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(BOB_INIT_LOCKED)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(CHAR_INIT_LOCKED)); + + //set block to 30 + System::set_block_number(30); + assert_eq!(System::block_number(), 30); + + assert_eq!(Vesting::vesting_balance(&ALICE), Some(0)); + assert_eq!(Vesting::vesting_balance(&BOB), Some(3 * BOB_PER_BLOCK)); + assert_eq!(Vesting::vesting_balance(&CHAR), Some(3 * CHAR_PER_BLOCK)); + }) } #[test] fn vested_transfer_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - let user1_vesting_schedule_1 = VestingInfo::new(ALICE_INIT_LOCKED, ALICE_PER_BLOCK, 0u64); - let user1_vesting_schedule_2 = VestingInfo::new(10000, 1000, 15); - - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - ALICE, - user1_vesting_schedule_2 - )); - assert_eq!( - vesting::::get(&ALICE).unwrap().to_vec(), - vec![user1_vesting_schedule_1, user1_vesting_schedule_2] - ); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + let user1_vesting_schedule_1 = + VestingInfo::new(ALICE_INIT_LOCKED, ALICE_PER_BLOCK, 0u64); + let user1_vesting_schedule_2 = VestingInfo::new(10000, 1000, 15); + + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + ALICE, + user1_vesting_schedule_2 + )); + assert_eq!( + vesting::::get(&ALICE).unwrap().to_vec(), + vec![user1_vesting_schedule_1, user1_vesting_schedule_2] + ); + }) } #[test] fn do_vest_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - //check alice - let alice_locked_1 = Balances::locks(ALICE).to_vec()[0].amount; - assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); - let alice_locked_2 = Balances::locks(ALICE).to_vec()[0].amount; - - assert_eq!(alice_locked_1 - 5 * ALICE_PER_BLOCK, alice_locked_2); - - // vested transfer to alice - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - ALICE, - VestingInfo::new(10000, 1000, 2,) - )); - //check start block is 2 , add locked = 10000 - 3 * 1000 - assert_eq!( - Vesting::vesting_balance(&ALICE), - Some(ALICE_INIT_LOCKED - 5 * ALICE_PER_BLOCK + 10000 - 3 * 1000) - ); - let alice_locked_3 = Balances::locks(ALICE).to_vec()[0].amount; - assert_eq!(alice_locked_2 + 10000 - 3 * 1000, alice_locked_3); - assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); - let alice_locked_4 = Balances::locks(ALICE).to_vec()[0].amount; - assert_eq!(alice_locked_3, alice_locked_4); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + //check alice + let alice_locked_1 = Balances::locks(ALICE).to_vec()[0].amount; + assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); + let alice_locked_2 = Balances::locks(ALICE).to_vec()[0].amount; + + assert_eq!(alice_locked_1 - 5 * ALICE_PER_BLOCK, alice_locked_2); + + // vested transfer to alice + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + ALICE, + VestingInfo::new(10000, 1000, 2,) + )); + //check start block is 2 , add locked = 10000 - 3 * 1000 + assert_eq!( + Vesting::vesting_balance(&ALICE), + Some(ALICE_INIT_LOCKED - 5 * ALICE_PER_BLOCK + 10000 - 3 * 1000) + ); + let alice_locked_3 = Balances::locks(ALICE).to_vec()[0].amount; + assert_eq!(alice_locked_2 + 10000 - 3 * 1000, alice_locked_3); + assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); + let alice_locked_4 = Balances::locks(ALICE).to_vec()[0].amount; + assert_eq!(alice_locked_3, alice_locked_4); + }) } #[test] fn do_vest_with_cliff_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - assert_ok!(Vesting::force_set_cliff(RawOrigin::Root.into(), ALICE, 4)); - assert_eq!(Cliff::::get(ALICE), Some(4)); - - //set block to 4 - System::set_block_number(4); - assert_eq!(System::block_number(), 4); - - assert_noop!( - Vesting::vest(RawOrigin::Signed(ALICE).into()), - Error::::WrongCliffVesting - ); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - //check alice - let alice_locked_1 = Balances::locks(ALICE).to_vec()[0].amount; - assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); - let alice_locked_2 = Balances::locks(ALICE).to_vec()[0].amount; - assert_eq!(alice_locked_1 - 5 * ALICE_PER_BLOCK, alice_locked_2); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + assert_ok!(Vesting::force_set_cliff(RawOrigin::Root.into(), ALICE, 4)); + assert_eq!(Cliff::::get(ALICE), Some(4)); + + //set block to 4 + System::set_block_number(4); + assert_eq!(System::block_number(), 4); + + assert_noop!( + Vesting::vest(RawOrigin::Signed(ALICE).into()), + Error::::WrongCliffVesting + ); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + //check alice + let alice_locked_1 = Balances::locks(ALICE).to_vec()[0].amount; + assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); + let alice_locked_2 = Balances::locks(ALICE).to_vec()[0].amount; + assert_eq!(alice_locked_1 - 5 * ALICE_PER_BLOCK, alice_locked_2); + }) } #[test] fn do_vest_with_start_at_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 3 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 3)); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - //check alice - let alice_locked_1 = Balances::locks(ALICE).to_vec()[0].amount; - assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); - let alice_locked_2 = Balances::locks(ALICE).to_vec()[0].amount; - assert_eq!(alice_locked_1 - 2 * ALICE_PER_BLOCK, alice_locked_2); - - //set start_at to 3 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 5)); - - //set block to 10 - System::set_block_number(10); - assert_eq!(System::block_number(), 10); - //check alice - let alice_locked_3 = Balances::locks(ALICE).to_vec()[0].amount; - assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); - let alice_locked_4 = Balances::locks(ALICE).to_vec()[0].amount; - - //check current locked = 5 * alice_pre_block , before vest 2 * alice_pre_block , now vest 3 - // * alice_pre_block - assert_eq!(alice_locked_3 - 3 * ALICE_PER_BLOCK, alice_locked_4); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 3 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 3)); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + //check alice + let alice_locked_1 = Balances::locks(ALICE).to_vec()[0].amount; + assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); + let alice_locked_2 = Balances::locks(ALICE).to_vec()[0].amount; + assert_eq!(alice_locked_1 - 2 * ALICE_PER_BLOCK, alice_locked_2); + + //set start_at to 3 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 5)); + + //set block to 10 + System::set_block_number(10); + assert_eq!(System::block_number(), 10); + //check alice + let alice_locked_3 = Balances::locks(ALICE).to_vec()[0].amount; + assert_ok!(Vesting::vest(RawOrigin::Signed(ALICE).into())); + let alice_locked_4 = Balances::locks(ALICE).to_vec()[0].amount; + + //check current locked = 5 * alice_pre_block , before vest 2 * alice_pre_block , now vest 3 + // * alice_pre_block + assert_eq!(alice_locked_3 - 3 * ALICE_PER_BLOCK, alice_locked_4); + }) } #[test] fn set_vesting_per_block_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - //check bob - let alice_locked_1 = Balances::locks(BOB).to_vec()[0].amount; - assert_eq!(alice_locked_1, BOB_INIT_LOCKED); - - //set vesting_per_block to 100 - assert_ok!(Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 0, 100)); - - //check result start_at 10 > now 5 => 10 start_at - let user_vesting_schedule_1 = VestingInfo::new(20000, 100, 10); - assert_eq!(vesting::::get(&BOB).unwrap().to_vec(), vec![user_vesting_schedule_1]); - - //set block to 15 - System::set_block_number(15); - assert_eq!(System::block_number(), 15); - - let bob_locked_1 = Balances::locks(BOB).to_vec()[0].amount; - - //set vesting_per_block to 10 - assert_ok!(Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 0, 10)); - - //check result start_at 10 < now 15 => now 15 - absolute_start 0 - //old_start_at = old_start_block 10 + absolute_start 0 - //remained_vesting = 20000 - 5 * 100 - let user_vesting_schedule_2 = VestingInfo::new(20000 - 5 * 100, 10, 15); - assert_eq!(vesting::::get(&BOB).unwrap().to_vec(), vec![user_vesting_schedule_2]); - let bob_locked_2 = Balances::locks(BOB).to_vec()[0].amount; - assert_eq!(bob_locked_1 - 5 * 100, bob_locked_2); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + //check bob + let alice_locked_1 = Balances::locks(BOB).to_vec()[0].amount; + assert_eq!(alice_locked_1, BOB_INIT_LOCKED); + + //set vesting_per_block to 100 + assert_ok!(Vesting::set_vesting_per_block( + RawOrigin::Root.into(), + BOB, + 0, + 100 + )); + + //check result start_at 10 > now 5 => 10 start_at + let user_vesting_schedule_1 = VestingInfo::new(20000, 100, 10); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_1] + ); + + //set block to 15 + System::set_block_number(15); + assert_eq!(System::block_number(), 15); + + let bob_locked_1 = Balances::locks(BOB).to_vec()[0].amount; + + //set vesting_per_block to 10 + assert_ok!(Vesting::set_vesting_per_block( + RawOrigin::Root.into(), + BOB, + 0, + 10 + )); + + //check result start_at 10 < now 15 => now 15 - absolute_start 0 + //old_start_at = old_start_block 10 + absolute_start 0 + //remained_vesting = 20000 - 5 * 100 + let user_vesting_schedule_2 = VestingInfo::new(20000 - 5 * 100, 10, 15); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_2] + ); + let bob_locked_2 = Balances::locks(BOB).to_vec()[0].amount; + assert_eq!(bob_locked_1 - 5 * 100, bob_locked_2); + }) } #[test] fn set_vesting_per_block_with_start_at_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 2 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - //check bob - let alice_locked_1 = Balances::locks(BOB).to_vec()[0].amount; - assert_eq!(alice_locked_1, BOB_INIT_LOCKED); - - //set vesting_per_block to 100 - assert_ok!(Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 0, 100)); - - //check result old_start_at 12 > now 5 => 10 start_at - let user_vesting_schedule_1 = VestingInfo::new(20000, 100, 10); - assert_eq!(vesting::::get(&BOB).unwrap().to_vec(), vec![user_vesting_schedule_1]); - - //set block to 15 - System::set_block_number(15); - assert_eq!(System::block_number(), 15); - - let bob_locked_1 = Balances::locks(BOB).to_vec()[0].amount; - - //set vesting_per_block to 10 - assert_ok!(Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 0, 10)); - - //old_start_at = old_start_block 10 + absolute_start 2 - //old_start_at 12 < now 15 => now 15 - absolute_start 2 = 13 - //remained_vesting = 20000 - 3 * 100 - let user_vesting_schedule_2 = VestingInfo::new(20000 - 3 * 100, 10, 13); - assert_eq!(vesting::::get(&BOB).unwrap().to_vec(), vec![user_vesting_schedule_2]); - let bob_locked_2 = Balances::locks(BOB).to_vec()[0].amount; - assert_eq!(bob_locked_1 - 3 * 100, bob_locked_2); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 2 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + //check bob + let alice_locked_1 = Balances::locks(BOB).to_vec()[0].amount; + assert_eq!(alice_locked_1, BOB_INIT_LOCKED); + + //set vesting_per_block to 100 + assert_ok!(Vesting::set_vesting_per_block( + RawOrigin::Root.into(), + BOB, + 0, + 100 + )); + + //check result old_start_at 12 > now 5 => 10 start_at + let user_vesting_schedule_1 = VestingInfo::new(20000, 100, 10); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_1] + ); + + //set block to 15 + System::set_block_number(15); + assert_eq!(System::block_number(), 15); + + let bob_locked_1 = Balances::locks(BOB).to_vec()[0].amount; + + //set vesting_per_block to 10 + assert_ok!(Vesting::set_vesting_per_block( + RawOrigin::Root.into(), + BOB, + 0, + 10 + )); + + //old_start_at = old_start_block 10 + absolute_start 2 + //old_start_at 12 < now 15 => now 15 - absolute_start 2 = 13 + //remained_vesting = 20000 - 3 * 100 + let user_vesting_schedule_2 = VestingInfo::new(20000 - 3 * 100, 10, 13); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_2] + ); + let bob_locked_2 = Balances::locks(BOB).to_vec()[0].amount; + assert_eq!(bob_locked_1 - 3 * 100, bob_locked_2); + }) } #[test] fn repeatedly_set_vesting_per_block_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); - - let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); - let user_vesting_schedule_2 = VestingInfo::new(10000, 1000, 12); - let user_vesting_schedule_3 = VestingInfo::new(10000, 1000, 20); - - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - BOB, - user_vesting_schedule_2 - )); - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - BOB, - user_vesting_schedule_3 - )); - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![user_vesting_schedule_1, user_vesting_schedule_2, user_vesting_schedule_3] - ); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - //check bob - let alice_locked_1 = Balances::locks(BOB).to_vec()[0].amount; - assert_eq!(alice_locked_1, 40000); - - //error OutOfBounds - assert_noop!( - Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 3, 100), - Error::::ScheduleIndexOutOfBounds - ); - //set vesting_per_block to 100 - assert_ok!(Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 1, 100)); - - //check result old_start_at 12 > now 5 => 12 start_at - let new_user_vesting_schedule_1 = VestingInfo::new(10000, 100, 12); - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![user_vesting_schedule_1, new_user_vesting_schedule_1, user_vesting_schedule_3] - ); - - //set block to 15 - System::set_block_number(15); - assert_eq!(System::block_number(), 15); - - let bob_locked_1 = Balances::locks(BOB).to_vec()[0].amount; - - //set vesting_per_block to 10 - assert_ok!(Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 0, 10)); - - //old_start_at = old_start_block 10 + absolute_start 2 - //old_start_block 12 < now 15 => now 15 - absolute_start 2 = 13 - //remained_vesting = 20000 - 3 * 1000 - let new_user_vesting_schedule_2 = VestingInfo::new(20000 - 3 * 1000, 10, 13); - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![new_user_vesting_schedule_2, new_user_vesting_schedule_1, user_vesting_schedule_3] - ); - - let bob_locked_2 = Balances::locks(BOB).to_vec()[0].amount; - assert_eq!(bob_locked_1 - 3 * 1000 - 100, bob_locked_2); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); + + let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); + let user_vesting_schedule_2 = VestingInfo::new(10000, 1000, 12); + let user_vesting_schedule_3 = VestingInfo::new(10000, 1000, 20); + + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + BOB, + user_vesting_schedule_2 + )); + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + BOB, + user_vesting_schedule_3 + )); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![ + user_vesting_schedule_1, + user_vesting_schedule_2, + user_vesting_schedule_3 + ] + ); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + //check bob + let alice_locked_1 = Balances::locks(BOB).to_vec()[0].amount; + assert_eq!(alice_locked_1, 40000); + + //error OutOfBounds + assert_noop!( + Vesting::set_vesting_per_block(RawOrigin::Root.into(), BOB, 3, 100), + Error::::ScheduleIndexOutOfBounds + ); + //set vesting_per_block to 100 + assert_ok!(Vesting::set_vesting_per_block( + RawOrigin::Root.into(), + BOB, + 1, + 100 + )); + + //check result old_start_at 12 > now 5 => 12 start_at + let new_user_vesting_schedule_1 = VestingInfo::new(10000, 100, 12); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![ + user_vesting_schedule_1, + new_user_vesting_schedule_1, + user_vesting_schedule_3 + ] + ); + + //set block to 15 + System::set_block_number(15); + assert_eq!(System::block_number(), 15); + + let bob_locked_1 = Balances::locks(BOB).to_vec()[0].amount; + + //set vesting_per_block to 10 + assert_ok!(Vesting::set_vesting_per_block( + RawOrigin::Root.into(), + BOB, + 0, + 10 + )); + + //old_start_at = old_start_block 10 + absolute_start 2 + //old_start_block 12 < now 15 => now 15 - absolute_start 2 = 13 + //remained_vesting = 20000 - 3 * 1000 + let new_user_vesting_schedule_2 = VestingInfo::new(20000 - 3 * 1000, 10, 13); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![ + new_user_vesting_schedule_2, + new_user_vesting_schedule_1, + user_vesting_schedule_3 + ] + ); + + let bob_locked_2 = Balances::locks(BOB).to_vec()[0].amount; + assert_eq!(bob_locked_1 - 3 * 1000 - 100, bob_locked_2); + }) } /* @@ -435,200 +532,230 @@ return bigger #[test] fn merge_schedules_has_not_started_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); - - let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); - let user_vesting_schedule_2 = VestingInfo::new(20000, 1000, 12); - - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - BOB, - user_vesting_schedule_2 - )); - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![user_vesting_schedule_1, user_vesting_schedule_2] - ); - - //set block to 5 - System::set_block_number(5); - assert_eq!(System::block_number(), 5); - - // ending_block = 32 - // starting_block = 12 - // locked = 40000 - // per_block = 40000 / 20 = 2000 - assert_ok!(Vesting::merge_schedules(RawOrigin::Signed(BOB).into(), 0, 1)); - - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![VestingInfo::new(BOB_INIT_LOCKED * 2, 2000, 12)] - ); - assert_eq!(40000, Balances::locks(BOB).to_vec()[0].amount); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); + + let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); + let user_vesting_schedule_2 = VestingInfo::new(20000, 1000, 12); + + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + BOB, + user_vesting_schedule_2 + )); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_1, user_vesting_schedule_2] + ); + + //set block to 5 + System::set_block_number(5); + assert_eq!(System::block_number(), 5); + + // ending_block = 32 + // starting_block = 12 + // locked = 40000 + // per_block = 40000 / 20 = 2000 + assert_ok!(Vesting::merge_schedules( + RawOrigin::Signed(BOB).into(), + 0, + 1 + )); + + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![VestingInfo::new(BOB_INIT_LOCKED * 2, 2000, 12)] + ); + assert_eq!(40000, Balances::locks(BOB).to_vec()[0].amount); + }) } #[test] fn merge_ongoing_schedules_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); - - let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); - let user_vesting_schedule_2 = VestingInfo::new(20000, 1000, 40); - - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - BOB, - user_vesting_schedule_2 - )); - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![user_vesting_schedule_1, user_vesting_schedule_2] - ); - - //set block to 50 - System::set_block_number(50); - assert_eq!(System::block_number(), 50); - - // ending_block = 60 - // starting_block = 40 - // locked = 40000 - // per_block = 40000 / 20 = 2000 - assert_ok!(Vesting::merge_schedules(RawOrigin::Signed(BOB).into(), 0, 1)); - - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![VestingInfo::new(BOB_INIT_LOCKED, 1000, 40)] - ); - assert_eq!(12000, Balances::locks(BOB).to_vec()[0].amount); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); + + let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); + let user_vesting_schedule_2 = VestingInfo::new(20000, 1000, 40); + + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + BOB, + user_vesting_schedule_2 + )); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_1, user_vesting_schedule_2] + ); + + //set block to 50 + System::set_block_number(50); + assert_eq!(System::block_number(), 50); + + // ending_block = 60 + // starting_block = 40 + // locked = 40000 + // per_block = 40000 / 20 = 2000 + assert_ok!(Vesting::merge_schedules( + RawOrigin::Signed(BOB).into(), + 0, + 1 + )); + + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![VestingInfo::new(BOB_INIT_LOCKED, 1000, 40)] + ); + assert_eq!(12000, Balances::locks(BOB).to_vec()[0].amount); + }) } #[test] fn merge_finished_schedules_should_work() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - //set start_at to 0 - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); - - let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); - let user_vesting_schedule_2 = VestingInfo::new(20000, 1000, 40); - - assert_ok!(Vesting::vested_transfer( - RawOrigin::Signed(DAVE).into(), - BOB, - user_vesting_schedule_2 - )); - assert_eq!( - vesting::::get(&BOB).unwrap().to_vec(), - vec![user_vesting_schedule_1, user_vesting_schedule_2] - ); - - //set block to 60 - System::set_block_number(60); - assert_eq!(System::block_number(), 60); - - //None - assert_ok!(Vesting::merge_schedules(RawOrigin::Signed(BOB).into(), 0, 1)); - - assert_eq!(vesting::::get(&BOB), None); - assert_eq!(0, Balances::locks(BOB).to_vec().len()); - }) + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + //set start_at to 0 + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 2)); + + let user_vesting_schedule_1 = VestingInfo::new(BOB_INIT_LOCKED, BOB_PER_BLOCK, 10u64); + let user_vesting_schedule_2 = VestingInfo::new(20000, 1000, 40); + + assert_ok!(Vesting::vested_transfer( + RawOrigin::Signed(DAVE).into(), + BOB, + user_vesting_schedule_2 + )); + assert_eq!( + vesting::::get(&BOB).unwrap().to_vec(), + vec![user_vesting_schedule_1, user_vesting_schedule_2] + ); + + //set block to 60 + System::set_block_number(60); + assert_eq!(System::block_number(), 60); + + //None + assert_ok!(Vesting::merge_schedules( + RawOrigin::Signed(BOB).into(), + 0, + 1 + )); + + assert_eq!(vesting::::get(&BOB), None); + assert_eq!(0, Balances::locks(BOB).to_vec().len()); + }) } #[test] fn merge_schedules_that_have_not_started() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // Vest over 20 blocks. - 10, - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - assert_eq!(Balances::usable_balance(&2), 0); - - // Add a schedule that is identical to the one that already exists. - assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched0)); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched0]); - assert_eq!(Balances::usable_balance(&2), 0); - assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - - // Since we merged identical schedules, the new schedule finishes at the same - // time as the original, just with double the amount. - let sched1 = VestingInfo::new( - sched0.locked() * 2, - sched0.per_block() * 2, - 10, // Starts at the block the schedules are merged/ - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched1]); - - assert_eq!(Balances::usable_balance(&2), 0); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // Vest over 20 blocks. + 10, + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + assert_eq!(Balances::usable_balance(&2), 0); + + // Add a schedule that is identical to the one that already exists. + assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched0)); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched0]); + assert_eq!(Balances::usable_balance(&2), 0); + assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + + // Since we merged identical schedules, the new schedule finishes at the same + // time as the original, just with double the amount. + let sched1 = VestingInfo::new( + sched0.locked() * 2, + sched0.per_block() * 2, + 10, // Starts at the block the schedules are merged/ + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched1]); + + assert_eq!(Balances::usable_balance(&2), 0); + }); } #[test] fn merge_ongoing_schedules() { // Merging two schedules that have started will vest both before merging. - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // Vest over 20 blocks. - 10, - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - - let sched1 = VestingInfo::new( - ED * 10, - ED, // Vest over 10 blocks. - sched0.starting_block() + 5, // Start at block 15. - ); - assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1]); - - // assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - // assert_eq!(vesting::::get(&2).unwrap(), vec![]); - - // Got to half way through the second schedule where both schedules are actively vesting. - let cur_block = 20; - System::set_block_number(cur_block); - - // Account 2 has no usable balances prior to the merge because they have not unlocked - // with `vest` yet. - assert_eq!(Balances::usable_balance(&2), 0); - - assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - - // Merging schedules un-vests all pre-existing schedules prior to merging, which is - // reflected in account 2's updated usable balance. - let sched0_vested_now = sched0.per_block() * (cur_block - sched0.starting_block()); - let sched1_vested_now = sched1.per_block() * (cur_block - sched1.starting_block()); - assert_eq!(Balances::usable_balance(&2), sched0_vested_now + sched1_vested_now); - - // The locked amount is the sum of what both schedules have locked at the current block. - let sched2_locked = sched1 - .locked_at::(cur_block, Some(15)) - .saturating_add(sched0.locked_at::(cur_block, Some(10))); - // End block of the new schedule is the greater of either merged schedule. - let sched2_end = sched1 - .ending_block_as_balance::() - .max(sched0.ending_block_as_balance::()); - let sched2_duration = sched2_end - cur_block; - // Based off the new schedules total locked and its duration, we can calculate the - // amount to unlock per block. - let sched2_per_block = sched2_locked / sched2_duration; - - let sched2 = VestingInfo::new(sched2_locked, sched2_per_block, cur_block); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched2]); - - // And just to double check, we assert the new merged schedule we be cleaned up as expected. - System::set_block_number(30); - vest_and_assert_no_vesting::(2); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // Vest over 20 blocks. + 10, + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + + let sched1 = VestingInfo::new( + ED * 10, + ED, // Vest over 10 blocks. + sched0.starting_block() + 5, // Start at block 15. + ); + assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1]); + + // assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + // assert_eq!(vesting::::get(&2).unwrap(), vec![]); + + // Got to half way through the second schedule where both schedules are actively vesting. + let cur_block = 20; + System::set_block_number(cur_block); + + // Account 2 has no usable balances prior to the merge because they have not unlocked + // with `vest` yet. + assert_eq!(Balances::usable_balance(&2), 0); + + assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + + // Merging schedules un-vests all pre-existing schedules prior to merging, which is + // reflected in account 2's updated usable balance. + let sched0_vested_now = sched0.per_block() * (cur_block - sched0.starting_block()); + let sched1_vested_now = sched1.per_block() * (cur_block - sched1.starting_block()); + assert_eq!( + Balances::usable_balance(&2), + sched0_vested_now + sched1_vested_now + ); + + // The locked amount is the sum of what both schedules have locked at the current block. + let sched2_locked = sched1 + .locked_at::(cur_block, Some(15)) + .saturating_add(sched0.locked_at::(cur_block, Some(10))); + // End block of the new schedule is the greater of either merged schedule. + let sched2_end = sched1 + .ending_block_as_balance::() + .max(sched0.ending_block_as_balance::()); + let sched2_duration = sched2_end - cur_block; + // Based off the new schedules total locked and its duration, we can calculate the + // amount to unlock per block. + let sched2_per_block = sched2_locked / sched2_duration; + + let sched2 = VestingInfo::new(sched2_locked, sched2_per_block, cur_block); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched2]); + + // And just to double check, we assert the new merged schedule we be cleaned up as expected. + System::set_block_number(30); + vest_and_assert_no_vesting::(2); + }); } /// Calls vest, and asserts that there is no entry for `account` @@ -647,326 +774,364 @@ where fn merging_shifts_other_schedules_index() { // Schedules being merged are filtered out, schedules to the right of any merged // schedule shift left and the merged schedule is always last. - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - let sched0 = VestingInfo::new( - ED * 10, - ED, // Vesting over 10 blocks. - 10, - ); - let sched1 = VestingInfo::new( - ED * 11, - ED, // Vesting over 11 blocks. - 11, - ); - let sched2 = VestingInfo::new( - ED * 12, - ED, // Vesting over 12 blocks. - 12, - ); - - // Account 3 starts out with no schedules, - assert_eq!(vesting::::get(&3), None); - // and some usable balance. - let usable_balance = Balances::usable_balance(&3); - assert_eq!(usable_balance, 30 * ED); - - let cur_block = 1; - assert_eq!(System::block_number(), cur_block); - - // Transfer the above 3 schedules to account 3. - assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched0)); - assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched1)); - assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched2)); - - // With no schedules vested or merged they are in the order they are created - assert_eq!(vesting::::get(&3).unwrap(), vec![sched0, sched1, sched2]); - // and the usable balance has not changed. - assert_eq!(usable_balance, Balances::usable_balance(&3)); - - assert_ok!(Vesting::merge_schedules(Some(3).into(), 0, 2)); - - // Create the merged schedule of sched0 & sched2. - // The merged schedule will have the max possible starting block, - let sched3_start = sched1.starting_block().max(sched2.starting_block()); - // `locked` equal to the sum of the two schedules locked through the current block, - let sched3_locked = sched2.locked_at::(cur_block, Some(sched2.starting_block())) + - sched0.locked_at::(cur_block, Some(sched0.starting_block())); - // and will end at the max possible block. - let sched3_end = sched2 - .ending_block_as_balance::() - .max(sched0.ending_block_as_balance::()); - let sched3_duration = sched3_end - sched3_start; - let sched3_per_block = sched3_locked / sched3_duration; - let sched3 = VestingInfo::new(sched3_locked, sched3_per_block, sched3_start); - - // The not touched schedule moves left and the new merged schedule is appended. - assert_eq!(vesting::::get(&3).unwrap(), vec![sched1, sched3]); - // The usable balance hasn't changed since none of the schedules have started. - assert_eq!(Balances::usable_balance(&3), usable_balance); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + let sched0 = VestingInfo::new( + ED * 10, + ED, // Vesting over 10 blocks. + 10, + ); + let sched1 = VestingInfo::new( + ED * 11, + ED, // Vesting over 11 blocks. + 11, + ); + let sched2 = VestingInfo::new( + ED * 12, + ED, // Vesting over 12 blocks. + 12, + ); + + // Account 3 starts out with no schedules, + assert_eq!(vesting::::get(&3), None); + // and some usable balance. + let usable_balance = Balances::usable_balance(&3); + assert_eq!(usable_balance, 30 * ED); + + let cur_block = 1; + assert_eq!(System::block_number(), cur_block); + + // Transfer the above 3 schedules to account 3. + assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched0)); + assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched1)); + assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched2)); + + // With no schedules vested or merged they are in the order they are created + assert_eq!( + vesting::::get(&3).unwrap(), + vec![sched0, sched1, sched2] + ); + // and the usable balance has not changed. + assert_eq!(usable_balance, Balances::usable_balance(&3)); + + assert_ok!(Vesting::merge_schedules(Some(3).into(), 0, 2)); + + // Create the merged schedule of sched0 & sched2. + // The merged schedule will have the max possible starting block, + let sched3_start = sched1.starting_block().max(sched2.starting_block()); + // `locked` equal to the sum of the two schedules locked through the current block, + let sched3_locked = sched2 + .locked_at::(cur_block, Some(sched2.starting_block())) + + sched0.locked_at::(cur_block, Some(sched0.starting_block())); + // and will end at the max possible block. + let sched3_end = sched2 + .ending_block_as_balance::() + .max(sched0.ending_block_as_balance::()); + let sched3_duration = sched3_end - sched3_start; + let sched3_per_block = sched3_locked / sched3_duration; + let sched3 = VestingInfo::new(sched3_locked, sched3_per_block, sched3_start); + + // The not touched schedule moves left and the new merged schedule is appended. + assert_eq!(vesting::::get(&3).unwrap(), vec![sched1, sched3]); + // The usable balance hasn't changed since none of the schedules have started. + assert_eq!(Balances::usable_balance(&3), usable_balance); + }); } #[test] fn merge_ongoing_and_yet_to_be_started_schedules() { // Merge an ongoing schedule that has had `vest` called and a schedule that has not already // started. - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // Vesting over 20 blocks - 10, - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - - // Fast forward to half way through the life of sched1. - let mut cur_block = - (sched0.starting_block() + sched0.ending_block_as_balance::()) / 2; - assert_eq!(cur_block, 20); - System::set_block_number(cur_block); - - // Prior to vesting there is no usable balance. - let mut usable_balance = 0; - assert_eq!(Balances::usable_balance(&2), usable_balance); - // Vest the current schedules (which is just sched0 now). - Vesting::vest(Some(2).into()).unwrap(); - - // After vesting the usable balance increases by the unlocked amount. - let sched0_vested_now = sched0.locked() - - sched0.locked_at::(cur_block, Some(sched0.starting_block())); - usable_balance += sched0_vested_now; - assert_eq!(Balances::usable_balance(&2), usable_balance); - - // Go forward a block. - cur_block += 1; - System::set_block_number(cur_block); - - // And add a schedule that starts after this block, but before sched0 finishes. - let sched1 = VestingInfo::new( - ED * 10, - 1, // Vesting over 256 * 10 (2560) blocks - cur_block + 1, - ); - assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); - - // Merge the schedules before sched1 starts. - assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - // After merging, the usable balance only changes by the amount sched0 vested since we - // last called `vest` (which is just 1 block). The usable balance is not affected by - // sched1 because it has not started yet. - usable_balance += sched0.per_block(); - assert_eq!(Balances::usable_balance(&2), usable_balance); - - // The resulting schedule will have the later starting block of the two, - let sched2_start = sched1.starting_block(); - // `locked` equal to the sum of the two schedules locked through the current block, - let sched2_locked = sched0.locked_at::(cur_block, Some(sched0.starting_block())) + - sched1.locked_at::(cur_block, Some(sched1.starting_block())); - // and will end at the max possible block. - let sched2_end = sched0 - .ending_block_as_balance::() - .max(sched1.ending_block_as_balance::()); - let sched2_duration = sched2_end - sched2_start; - let sched2_per_block = sched2_locked / sched2_duration; - - let sched2 = VestingInfo::new(sched2_locked, sched2_per_block, sched2_start); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched2]); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // Vesting over 20 blocks + 10, + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + + // Fast forward to half way through the life of sched1. + let mut cur_block = + (sched0.starting_block() + sched0.ending_block_as_balance::()) / 2; + assert_eq!(cur_block, 20); + System::set_block_number(cur_block); + + // Prior to vesting there is no usable balance. + let mut usable_balance = 0; + assert_eq!(Balances::usable_balance(&2), usable_balance); + // Vest the current schedules (which is just sched0 now). + Vesting::vest(Some(2).into()).unwrap(); + + // After vesting the usable balance increases by the unlocked amount. + let sched0_vested_now = sched0.locked() + - sched0.locked_at::(cur_block, Some(sched0.starting_block())); + usable_balance += sched0_vested_now; + assert_eq!(Balances::usable_balance(&2), usable_balance); + + // Go forward a block. + cur_block += 1; + System::set_block_number(cur_block); + + // And add a schedule that starts after this block, but before sched0 finishes. + let sched1 = VestingInfo::new( + ED * 10, + 1, // Vesting over 256 * 10 (2560) blocks + cur_block + 1, + ); + assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); + + // Merge the schedules before sched1 starts. + assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + // After merging, the usable balance only changes by the amount sched0 vested since we + // last called `vest` (which is just 1 block). The usable balance is not affected by + // sched1 because it has not started yet. + usable_balance += sched0.per_block(); + assert_eq!(Balances::usable_balance(&2), usable_balance); + + // The resulting schedule will have the later starting block of the two, + let sched2_start = sched1.starting_block(); + // `locked` equal to the sum of the two schedules locked through the current block, + let sched2_locked = sched0 + .locked_at::(cur_block, Some(sched0.starting_block())) + + sched1.locked_at::(cur_block, Some(sched1.starting_block())); + // and will end at the max possible block. + let sched2_end = sched0 + .ending_block_as_balance::() + .max(sched1.ending_block_as_balance::()); + let sched2_duration = sched2_end - sched2_start; + let sched2_per_block = sched2_locked / sched2_duration; + + let sched2 = VestingInfo::new(sched2_locked, sched2_per_block, sched2_start); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched2]); + }); } #[test] fn merge_finished_and_ongoing_schedules() { // If a schedule finishes by the current block we treat the ongoing schedule, // without any alterations, as the merged one. - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // Vesting over 20 blocks. - 10, - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - - let sched1 = VestingInfo::new( - ED * 40, - ED, // Vesting over 40 blocks. - 10, - ); - assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); - - // Transfer a 3rd schedule, so we can demonstrate how schedule indices change. - // (We are not merging this schedule.) - let sched2 = VestingInfo::new( - ED * 30, - ED, // Vesting over 30 blocks. - 10, - ); - assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched2)); - - // The schedules are in expected order prior to merging. - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1, sched2]); - - // Fast forward to sched0's end block. - let cur_block = sched0.ending_block_as_balance::(); - System::set_block_number(cur_block); - assert_eq!(System::block_number(), 30); - - // Prior to `merge_schedules` and with no vest/vest_other called the user has no usable - // balance. - assert_eq!(Balances::usable_balance(&2), 0); - assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - - // sched2 is now the first, since sched0 & sched1 get filtered out while "merging". - // sched1 gets treated like the new merged schedule by getting pushed onto back - // of the vesting schedules vec. Note: sched0 finished at the current block. - assert_eq!(vesting::::get(&2).unwrap(), vec![sched2, sched1]); - - // sched0 has finished, so its funds are fully unlocked. - let sched0_unlocked_now = sched0.locked(); - // The remaining schedules are ongoing, so their funds are partially unlocked. - let sched1_unlocked_now = sched1.locked() - - sched1.locked_at::(cur_block, Some(sched1.starting_block())); - let sched2_unlocked_now = sched2.locked() - - sched2.locked_at::(cur_block, Some(sched2.starting_block())); - - // Since merging also vests all the schedules, the users usable balance after merging - // includes all pre-existing schedules unlocked through the current block, including - // schedules not merged. - assert_eq!( - Balances::usable_balance(&2), - sched0_unlocked_now + sched1_unlocked_now + sched2_unlocked_now - ); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // Vesting over 20 blocks. + 10, + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + + let sched1 = VestingInfo::new( + ED * 40, + ED, // Vesting over 40 blocks. + 10, + ); + assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); + + // Transfer a 3rd schedule, so we can demonstrate how schedule indices change. + // (We are not merging this schedule.) + let sched2 = VestingInfo::new( + ED * 30, + ED, // Vesting over 30 blocks. + 10, + ); + assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched2)); + + // The schedules are in expected order prior to merging. + assert_eq!( + vesting::::get(&2).unwrap(), + vec![sched0, sched1, sched2] + ); + + // Fast forward to sched0's end block. + let cur_block = sched0.ending_block_as_balance::(); + System::set_block_number(cur_block); + assert_eq!(System::block_number(), 30); + + // Prior to `merge_schedules` and with no vest/vest_other called the user has no usable + // balance. + assert_eq!(Balances::usable_balance(&2), 0); + assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + + // sched2 is now the first, since sched0 & sched1 get filtered out while "merging". + // sched1 gets treated like the new merged schedule by getting pushed onto back + // of the vesting schedules vec. Note: sched0 finished at the current block. + assert_eq!(vesting::::get(&2).unwrap(), vec![sched2, sched1]); + + // sched0 has finished, so its funds are fully unlocked. + let sched0_unlocked_now = sched0.locked(); + // The remaining schedules are ongoing, so their funds are partially unlocked. + let sched1_unlocked_now = sched1.locked() + - sched1.locked_at::(cur_block, Some(sched1.starting_block())); + let sched2_unlocked_now = sched2.locked() + - sched2.locked_at::(cur_block, Some(sched2.starting_block())); + + // Since merging also vests all the schedules, the users usable balance after merging + // includes all pre-existing schedules unlocked through the current block, including + // schedules not merged. + assert_eq!( + Balances::usable_balance(&2), + sched0_unlocked_now + sched1_unlocked_now + sched2_unlocked_now + ); + }); } #[test] fn merge_finishing_schedules_does_not_create_a_new_one() { // If both schedules finish by the current block we don't create new one - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // 20 block duration. - 10, - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - - // Create sched1 and transfer it to account 2. - let sched1 = VestingInfo::new( - ED * 30, - ED, // 30 block duration. - 10, - ); - assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched1)); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1]); - - let all_scheds_end = sched0 - .ending_block_as_balance::() - .max(sched1.ending_block_as_balance::()); - - assert_eq!(all_scheds_end, 40); - System::set_block_number(all_scheds_end); - - // Prior to merge_schedules and with no vest/vest_other called the user has no usable - // balance. - assert_eq!(Balances::usable_balance(&2), 0); - - // Merge schedule 0 and 1. - assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - // The user no longer has any more vesting schedules because they both ended at the - // block they where merged, - assert!(!>::contains_key(&2)); - // and their usable balance has increased by the total amount locked in the merged - // schedules. - assert_eq!(Balances::usable_balance(&2), sched0.locked() + sched1.locked()); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // 20 block duration. + 10, + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + + // Create sched1 and transfer it to account 2. + let sched1 = VestingInfo::new( + ED * 30, + ED, // 30 block duration. + 10, + ); + assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched1)); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1]); + + let all_scheds_end = sched0 + .ending_block_as_balance::() + .max(sched1.ending_block_as_balance::()); + + assert_eq!(all_scheds_end, 40); + System::set_block_number(all_scheds_end); + + // Prior to merge_schedules and with no vest/vest_other called the user has no usable + // balance. + assert_eq!(Balances::usable_balance(&2), 0); + + // Merge schedule 0 and 1. + assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + // The user no longer has any more vesting schedules because they both ended at the + // block they where merged, + assert!(!>::contains_key(&2)); + // and their usable balance has increased by the total amount locked in the merged + // schedules. + assert_eq!( + Balances::usable_balance(&2), + sched0.locked() + sched1.locked() + ); + }); } #[test] fn merge_finished_and_yet_to_be_started_schedules() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // 20 block duration. - 10, // Ends at block 30 - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - - let sched1 = VestingInfo::new( - ED * 30, - ED * 2, // 30 block duration. - 35, - ); - assert_ok!(Vesting::vested_transfer(Some(13).into(), 2, sched1)); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1]); - - let sched2 = VestingInfo::new( - ED * 40, - ED, // 40 block duration. - 30, - ); - // Add a 3rd schedule to demonstrate how sched1 shifts. - assert_ok!(Vesting::vested_transfer(Some(13).into(), 2, sched2)); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1, sched2]); - - System::set_block_number(30); - - // At block 30, sched0 has finished unlocking while sched1 and sched2 are still fully - // locked, - assert_eq!(Vesting::vesting_balance(&2), Some(sched1.locked() + sched2.locked())); - // but since we have not vested usable balance is still 0. - assert_eq!(Balances::usable_balance(&2), 0); - - // Merge schedule 0 and 1. - assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); - - // sched0 is removed since it finished, and sched1 is removed and then pushed on the back - // because it is treated as the merged schedule - assert_eq!(vesting::::get(&2).unwrap(), vec![sched2, sched1]); - - // The usable balance is updated because merging fully unlocked sched0. - assert_eq!(Balances::usable_balance(&2), sched0.locked()); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // 20 block duration. + 10, // Ends at block 30 + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + + let sched1 = VestingInfo::new( + ED * 30, + ED * 2, // 30 block duration. + 35, + ); + assert_ok!(Vesting::vested_transfer(Some(13).into(), 2, sched1)); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched1]); + + let sched2 = VestingInfo::new( + ED * 40, + ED, // 40 block duration. + 30, + ); + // Add a 3rd schedule to demonstrate how sched1 shifts. + assert_ok!(Vesting::vested_transfer(Some(13).into(), 2, sched2)); + assert_eq!( + vesting::::get(&2).unwrap(), + vec![sched0, sched1, sched2] + ); + + System::set_block_number(30); + + // At block 30, sched0 has finished unlocking while sched1 and sched2 are still fully + // locked, + assert_eq!( + Vesting::vesting_balance(&2), + Some(sched1.locked() + sched2.locked()) + ); + // but since we have not vested usable balance is still 0. + assert_eq!(Balances::usable_balance(&2), 0); + + // Merge schedule 0 and 1. + assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); + + // sched0 is removed since it finished, and sched1 is removed and then pushed on the back + // because it is treated as the merged schedule + assert_eq!(vesting::::get(&2).unwrap(), vec![sched2, sched1]); + + // The usable balance is updated because merging fully unlocked sched0. + assert_eq!(Balances::usable_balance(&2), sched0.locked()); + }); } #[test] fn merge_schedules_throws_proper_errors() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - // Account 2 should already have a vesting schedule. - let sched0 = VestingInfo::new( - ED * 20, - ED, // 20 block duration. - 10, - ); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); - - // Account 2 only has 1 vesting schedule. - assert_noop!( - Vesting::merge_schedules(Some(2).into(), 0, 1), - Error::::ScheduleIndexOutOfBounds - ); - - // Account 4 has 0 vesting schedules. - assert_eq!(vesting::::get(&4), None); - assert_noop!(Vesting::merge_schedules(Some(4).into(), 0, 1), Error::::NotVesting); - - // There are enough schedules to merge but an index is non-existent. - Vesting::vested_transfer(Some(3).into(), 2, sched0).unwrap(); - assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched0]); - assert_noop!( - Vesting::merge_schedules(Some(2).into(), 0, 2), - Error::::ScheduleIndexOutOfBounds - ); - - // It is a storage noop with no errors if the indexes are the same. - assert_storage_noop!(Vesting::merge_schedules(Some(2).into(), 0, 0).unwrap()); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + // Account 2 should already have a vesting schedule. + let sched0 = VestingInfo::new( + ED * 20, + ED, // 20 block duration. + 10, + ); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0]); + + // Account 2 only has 1 vesting schedule. + assert_noop!( + Vesting::merge_schedules(Some(2).into(), 0, 1), + Error::::ScheduleIndexOutOfBounds + ); + + // Account 4 has 0 vesting schedules. + assert_eq!(vesting::::get(&4), None); + assert_noop!( + Vesting::merge_schedules(Some(4).into(), 0, 1), + Error::::NotVesting + ); + + // There are enough schedules to merge but an index is non-existent. + Vesting::vested_transfer(Some(3).into(), 2, sched0).unwrap(); + assert_eq!(vesting::::get(&2).unwrap(), vec![sched0, sched0]); + assert_noop!( + Vesting::merge_schedules(Some(2).into(), 0, 2), + Error::::ScheduleIndexOutOfBounds + ); + + // It is a storage noop with no errors if the indexes are the same. + assert_storage_noop!(Vesting::merge_schedules(Some(2).into(), 0, 0).unwrap()); + }); } #[test] @@ -974,8 +1139,12 @@ fn merge_schedules_throws_proper_errors() { fn multiple_schedules_from_genesis_config_errors() { // MaxVestingSchedules is 3, but this config has 4 for account 12 so we panic when building // from genesis. - let vesting_config = - vec![(12, 10, 20, ED), (12, 10, 20, ED), (12, 10, 20, ED), (12, 10, 20, ED)]; + let vesting_config = vec![ + (12, 10, 20, ED), + (12, 10, 20, ED), + (12, 10, 20, ED), + (12, 10, 20, ED), + ]; ExtBuilder::default() .existential_deposit(ED) .vesting_genesis_config(vesting_config) @@ -984,44 +1153,56 @@ fn multiple_schedules_from_genesis_config_errors() { #[test] fn build_genesis_has_storage_version_v1() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - assert_eq!(StorageVersion::::get(), Releases::V1); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + assert_eq!(StorageVersion::::get(), Releases::V1); + }); } #[test] fn merge_vesting_handles_per_block_0() { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - const ED: u64 = 256; - assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); - let sched0 = VestingInfo::new( - ED, 0, // Vesting over 256 blocks. - 1, - ); - assert_eq!(sched0.ending_block_as_balance::(), 257); - let sched1 = VestingInfo::new( - ED * 2, - 0, // Vesting over 512 blocks. - 10, - ); - assert_eq!(sched1.ending_block_as_balance::(), 512u64 + 10); - - let merged = VestingInfo::new(764, 1, 10); - assert_eq!(Vesting::merge_vesting_info(5, sched0, sched1), Some(merged)); - }); + ExtBuilder::default() + .existential_deposit(ED) + .build() + .execute_with(|| { + const ED: u64 = 256; + assert_ok!(Vesting::init_vesting_start_at(RawOrigin::Root.into(), 0)); + let sched0 = VestingInfo::new( + ED, 0, // Vesting over 256 blocks. + 1, + ); + assert_eq!(sched0.ending_block_as_balance::(), 257); + let sched1 = VestingInfo::new( + ED * 2, + 0, // Vesting over 512 blocks. + 10, + ); + assert_eq!(sched1.ending_block_as_balance::(), 512u64 + 10); + + let merged = VestingInfo::new(764, 1, 10); + assert_eq!(Vesting::merge_vesting_info(5, sched0, sched1), Some(merged)); + }); } #[test] fn vesting_info_validate_works() { let min_transfer = ::MinVestedTransfer::get(); // Does not check for min transfer. - assert_eq!(VestingInfo::new(min_transfer - 1, 1u64, 10u64).is_valid(), true); + assert_eq!( + VestingInfo::new(min_transfer - 1, 1u64, 10u64).is_valid(), + true + ); // `locked` cannot be 0. assert_eq!(VestingInfo::new(0, 1u64, 10u64).is_valid(), false); // `per_block` cannot be 0. - assert_eq!(VestingInfo::new(min_transfer + 1, 0u64, 10u64).is_valid(), false); + assert_eq!( + VestingInfo::new(min_transfer + 1, 0u64, 10u64).is_valid(), + false + ); // With valid inputs it does not error. assert_eq!(VestingInfo::new(min_transfer, 1u64, 10u64).is_valid(), true); @@ -1074,27 +1255,36 @@ fn per_block_works() { // When an accounts free balance + schedule.locked is less than ED, the vested transfer will fail. #[test] fn vested_transfer_less_than_existential_deposit_fails() { - ExtBuilder::default().existential_deposit(4 * ED).build().execute_with(|| { - // MinVestedTransfer is less the ED. - assert!( - ::Currency::minimum_balance() > - ::MinVestedTransfer::get() - ); - - let sched = - VestingInfo::new(::MinVestedTransfer::get() as u64, 1u64, 10u64); - // The new account balance with the schedule's locked amount would be less than ED. - assert!( - Balances::free_balance(&99) + sched.locked() < + ExtBuilder::default() + .existential_deposit(4 * ED) + .build() + .execute_with(|| { + // MinVestedTransfer is less the ED. + assert!( ::Currency::minimum_balance() - ); - - // vested_transfer fails. - assert_noop!(Vesting::vested_transfer(Some(3).into(), 99, sched), TokenError::BelowMinimum,); - // force_vested_transfer fails. - assert_noop!( - Vesting::force_vested_transfer(RawOrigin::Root.into(), 3, 99, sched), - TokenError::BelowMinimum, - ); - }); + > ::MinVestedTransfer::get() + ); + + let sched = VestingInfo::new( + ::MinVestedTransfer::get() as u64, + 1u64, + 10u64, + ); + // The new account balance with the schedule's locked amount would be less than ED. + assert!( + Balances::free_balance(&99) + sched.locked() + < ::Currency::minimum_balance() + ); + + // vested_transfer fails. + assert_noop!( + Vesting::vested_transfer(Some(3).into(), 99, sched), + TokenError::BelowMinimum, + ); + // force_vested_transfer fails. + assert_noop!( + Vesting::force_vested_transfer(RawOrigin::Root.into(), 3, 99, sched), + TokenError::BelowMinimum, + ); + }); } diff --git a/pallets/vesting/src/vesting_info.rs b/pallets/vesting/src/vesting_info.rs index 1ee61fa17d..f4e72d0177 100644 --- a/pallets/vesting/src/vesting_info.rs +++ b/pallets/vesting/src/vesting_info.rs @@ -40,7 +40,11 @@ where per_block: Balance, starting_block: BlockNumber, ) -> VestingInfo { - VestingInfo { locked, per_block, starting_block } + VestingInfo { + locked, + per_block, + starting_block, + } } /// Validate parameters for `VestingInfo`. Note that this does not check @@ -101,8 +105,8 @@ where // the block after starting. One::one() } else { - self.locked / self.per_block() + - if (self.locked % self.per_block()).is_zero() { + self.locked / self.per_block() + + if (self.locked % self.per_block()).is_zero() { Zero::zero() } else { // `per_block` does not perfectly divide `locked`, so we need an extra block to diff --git a/pallets/vstoken-conversion/Cargo.toml b/pallets/vstoken-conversion/Cargo.toml index 43d858ab6b..60129b86f1 100644 --- a/pallets/vstoken-conversion/Cargo.toml +++ b/pallets/vstoken-conversion/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vstoken-conversion" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/vstoken-conversion/src/benchmarking.rs b/pallets/vstoken-conversion/src/benchmarking.rs index ec947163ca..06eeecb78d 100644 --- a/pallets/vstoken-conversion/src/benchmarking.rs +++ b/pallets/vstoken-conversion/src/benchmarking.rs @@ -20,7 +20,7 @@ #![cfg(feature = "runtime-benchmarks")] use bifrost_primitives::{CurrencyId, TokenSymbol}; -use frame_benchmarking::v1::{account, benchmarks, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::{ assert_ok, traits::{EnsureOrigin, Get}, @@ -36,106 +36,174 @@ use crate::{ pub const VS_BOND: CurrencyId = CurrencyId::VSBond(TokenSymbol::BNC, 2001, 0, 8); pub const VS_KSM: CurrencyId = CurrencyId::VSToken(TokenSymbol::KSM); -benchmarks! { - set_exchange_fee { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let fee: VstokenConversionExchangeFee> = - VstokenConversionExchangeFee { - vstoken_exchange_fee: 10u32.into(), - vsbond_exchange_fee_of_vstoken: 10u32.into(), - }; - }: _(origin,fee) - - set_exchange_rate { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let fee: VstokenConversionExchangeFee> = - VstokenConversionExchangeFee { - vstoken_exchange_fee: 10u32.into(), - vsbond_exchange_fee_of_vstoken: 10u32.into(), - }; +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn set_exchange_fee() -> Result<(), BenchmarkError> { + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let fee: VstokenConversionExchangeFee> = VstokenConversionExchangeFee { + vstoken_exchange_fee: 10u32.into(), + vsbond_exchange_fee_of_vstoken: 10u32.into(), + }; + + #[extrinsic_call] + _(origin as ::RuntimeOrigin, fee); + + Ok(()) + } + + #[benchmark] + fn set_exchange_rate() -> Result<(), BenchmarkError> { + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let rate: VstokenConversionExchangeRate = VstokenConversionExchangeRate { vsbond_convert_to_vstoken: Percent::from_percent(5), vstoken_convert_to_vsbond: Percent::from_percent(5), }; - }: _(origin,1,rate) - - set_relaychain_lease { - let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - }: _(origin,1) - - vsbond_convert_to_vstoken { - let test_account: T::AccountId = account("seed",1,1); - let fee: VstokenConversionExchangeFee> = - VstokenConversionExchangeFee { - vstoken_exchange_fee: 10u32.into(), - vsbond_exchange_fee_of_vstoken: 10u32.into(), - }; + + #[extrinsic_call] + _( + origin as ::RuntimeOrigin, + 1, + rate, + ); + + Ok(()) + } + + #[benchmark] + fn set_relaychain_lease() -> Result<(), BenchmarkError> { + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + + #[extrinsic_call] + _(origin as ::RuntimeOrigin, 1); + + Ok(()) + } + + #[benchmark] + fn vsbond_convert_to_vstoken() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); + let fee: VstokenConversionExchangeFee> = VstokenConversionExchangeFee { + vstoken_exchange_fee: 10u32.into(), + vsbond_exchange_fee_of_vstoken: 10u32.into(), + }; let rate: VstokenConversionExchangeRate = VstokenConversionExchangeRate { vsbond_convert_to_vstoken: Percent::from_percent(95), vstoken_convert_to_vsbond: Percent::from_percent(95), }; - assert_ok!( - VstokenConversion::::set_exchange_fee( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - fee - )); - - assert_ok!( - VstokenConversion::::set_exchange_rate( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - 8, - rate - )); - - assert_ok!( - VstokenConversion::::set_relaychain_lease( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - 1 - )); + + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + + // Setup initial conditions + assert_ok!(VstokenConversion::::set_exchange_fee( + origin.clone() as ::RuntimeOrigin, + fee + )); + assert_ok!(VstokenConversion::::set_exchange_rate( + origin.clone() as ::RuntimeOrigin, + 8, + rate + )); + assert_ok!(VstokenConversion::::set_relaychain_lease( + origin as ::RuntimeOrigin, + 1 + )); let vsbond_account: T::AccountId = ::VsbondAccount::get().into_account_truncating(); - T::MultiCurrency::deposit(VS_KSM, &vsbond_account, BalanceOf::::unique_saturated_from(1000000000000u128))?; - T::MultiCurrency::deposit(VS_BOND, &test_account, BalanceOf::::unique_saturated_from(1000000000000u128))?; - }: _(RawOrigin::Signed(test_account),VS_BOND,BalanceOf::::unique_saturated_from(100000000000u128),BalanceOf::::unique_saturated_from(10000000000u128)) - - vstoken_convert_to_vsbond { - let test_account: T::AccountId = account("seed",1,1); - let fee: VstokenConversionExchangeFee> = - VstokenConversionExchangeFee { - vstoken_exchange_fee: 10u32.into(), - vsbond_exchange_fee_of_vstoken: 10u32.into(), - }; + T::MultiCurrency::deposit( + VS_KSM, + &vsbond_account, + BalanceOf::::unique_saturated_from(1000000000000u128), + )?; + T::MultiCurrency::deposit( + VS_BOND, + &test_account, + BalanceOf::::unique_saturated_from(1000000000000u128), + )?; + + #[extrinsic_call] + _( + RawOrigin::Signed(test_account), + VS_BOND, + BalanceOf::::unique_saturated_from(100000000000u128), + BalanceOf::::unique_saturated_from(10000000000u128), + ); + + Ok(()) + } + + #[benchmark] + fn vstoken_convert_to_vsbond() -> Result<(), BenchmarkError> { + let test_account: T::AccountId = account("seed", 1, 1); + let fee: VstokenConversionExchangeFee> = VstokenConversionExchangeFee { + vstoken_exchange_fee: 10u32.into(), + vsbond_exchange_fee_of_vstoken: 10u32.into(), + }; let rate: VstokenConversionExchangeRate = VstokenConversionExchangeRate { vsbond_convert_to_vstoken: Percent::from_percent(5), vstoken_convert_to_vsbond: Percent::from_percent(5), }; - assert_ok!( - VstokenConversion::::set_exchange_fee( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - fee - )); - - assert_ok!( - VstokenConversion::::set_exchange_rate( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - 8, - rate - )); - - assert_ok!( - VstokenConversion::::set_relaychain_lease( - T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - 1 - )); + + let origin = + T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + + // Setup initial conditions + assert_ok!(VstokenConversion::::set_exchange_fee( + origin.clone() as ::RuntimeOrigin, + fee + )); + assert_ok!(VstokenConversion::::set_exchange_rate( + origin.clone() as ::RuntimeOrigin, + 8, + rate + )); + assert_ok!(VstokenConversion::::set_relaychain_lease( + origin as ::RuntimeOrigin, + 1 + )); let vsbond_account: T::AccountId = ::VsbondAccount::get().into_account_truncating(); - T::MultiCurrency::deposit(VS_BOND, &vsbond_account, BalanceOf::::unique_saturated_from(100000000000000u128))?; - T::MultiCurrency::deposit(VS_KSM, &test_account, BalanceOf::::unique_saturated_from(100000000000000u128))?; - - }: _(RawOrigin::Signed(test_account),VS_BOND,BalanceOf::::unique_saturated_from(1000000000000u128),BalanceOf::::unique_saturated_from(100000000000u128)) - - - impl_benchmark_test_suite!(VstokenConversion,crate::mock::ExtBuilder::default().build(),crate::mock::Runtime); + T::MultiCurrency::deposit( + VS_BOND, + &vsbond_account, + BalanceOf::::unique_saturated_from(100000000000000u128), + )?; + T::MultiCurrency::deposit( + VS_KSM, + &test_account, + BalanceOf::::unique_saturated_from(100000000000000u128), + )?; + + #[extrinsic_call] + _( + RawOrigin::Signed(test_account), + VS_BOND, + BalanceOf::::unique_saturated_from(1000000000000u128), + BalanceOf::::unique_saturated_from(100000000000u128), + ); + + Ok(()) + } + + // This line generates test cases for benchmarking, and could be run by: + // `cargo test -p pallet-example-basic --all-features`, you will see one line per case: + // `test benchmarking::bench_sort_vector ... ok` + // `test benchmarking::bench_accumulate_dummy ... ok` + // `test benchmarking::bench_set_dummy_benchmark ... ok` in the result. + // + // The line generates three steps per benchmark, with repeat=1 and the three steps are + // [low, mid, high] of the range. + impl_benchmark_test_suite!( + Pallet, + crate::mock::new_test_ext_benchmark(), + crate::mock::Runtime + ); } diff --git a/pallets/vstoken-conversion/src/lib.rs b/pallets/vstoken-conversion/src/lib.rs index 26b0866796..e822235e92 100644 --- a/pallets/vstoken-conversion/src/lib.rs +++ b/pallets/vstoken-conversion/src/lib.rs @@ -169,7 +169,10 @@ pub mod pallet { let exchanger = ensure_signed(origin)?; let user_vsbond_balance = T::MultiCurrency::free_balance(vs_bond_currency_id, &exchanger); - ensure!(user_vsbond_balance >= vsbond_amount, Error::::NotEnoughBalance); + ensure!( + user_vsbond_balance >= vsbond_amount, + Error::::NotEnoughBalance + ); ensure!( minimum_vstoken >= T::MultiCurrency::minimum_balance(T::RelayCurrencyId::get()), Error::::NotEnoughBalance @@ -178,9 +181,9 @@ pub mod pallet { // Calculate lease let relay_lease = RelaychainLease::::get(); let mut remaining_due_lease: i32 = match vs_bond_currency_id { - CurrencyId::VSBond(TokenSymbol::KSM, .., expire_lease) | - CurrencyId::VSBond(TokenSymbol::BNC, .., expire_lease) | - CurrencyId::VSBond2(.., expire_lease) => { + CurrencyId::VSBond(TokenSymbol::KSM, .., expire_lease) + | CurrencyId::VSBond(TokenSymbol::BNC, .., expire_lease) + | CurrencyId::VSBond2(.., expire_lease) => { let mut remaining_due_lease: i32 = (expire_lease as i64 - relay_lease as i64) .try_into() .map_err(|_| Error::::CalculationOverflow)?; @@ -188,7 +191,7 @@ pub mod pallet { .checked_add(1i32) .ok_or(Error::::CalculationOverflow)?; remaining_due_lease - }, + } _ => return Err(Error::::NotSupportTokenType.into()), }; ensure!(remaining_due_lease <= 9i32, Error::::NotSupportTokenType); @@ -203,7 +206,10 @@ pub mod pallet { .checked_sub(&exchange_fee.vsbond_exchange_fee_of_vstoken) .ok_or(Error::::CalculationOverflow)?; let vstoken_balance = exchange_rate.vsbond_convert_to_vstoken * vsbond_balance; - ensure!(vstoken_balance >= minimum_vstoken, Error::::NotEnoughBalance); + ensure!( + vstoken_balance >= minimum_vstoken, + Error::::NotEnoughBalance + ); T::MultiCurrency::transfer( vs_bond_currency_id, @@ -247,7 +253,10 @@ pub mod pallet { .map_err(|_| Error::::NotSupportTokenType)?; let user_vstoken_balance = T::MultiCurrency::free_balance(vs_token_currency_id, &exchanger); - ensure!(user_vstoken_balance >= vstoken_amount, Error::::NotEnoughBalance); + ensure!( + user_vstoken_balance >= vstoken_amount, + Error::::NotEnoughBalance + ); ensure!( minimum_vsbond >= T::MultiCurrency::minimum_balance(currency_id), Error::::NotEnoughBalance @@ -256,9 +265,9 @@ pub mod pallet { // Calculate lease let relay_lease = RelaychainLease::::get(); let mut remaining_due_lease: i32 = match currency_id { - CurrencyId::VSBond(TokenSymbol::KSM, .., expire_lease) | - CurrencyId::VSBond(TokenSymbol::BNC, .., expire_lease) | - CurrencyId::VSBond2(.., expire_lease) => { + CurrencyId::VSBond(TokenSymbol::KSM, .., expire_lease) + | CurrencyId::VSBond(TokenSymbol::BNC, .., expire_lease) + | CurrencyId::VSBond2(.., expire_lease) => { let mut remaining_due_lease: i32 = (expire_lease as i64 - relay_lease as i64) .try_into() .map_err(|_| Error::::CalculationOverflow)?; @@ -266,7 +275,7 @@ pub mod pallet { .checked_add(1i32) .ok_or(Error::::CalculationOverflow)?; remaining_due_lease - }, + } _ => return Err(Error::::NotSupportTokenType.into()), }; ensure!(remaining_due_lease <= 9i32, Error::::NotSupportTokenType); @@ -288,7 +297,10 @@ pub mod pallet { let vsbond_balance = exchange_rate .vstoken_convert_to_vsbond .saturating_reciprocal_mul(vstoken_balance); - ensure!(vsbond_balance >= minimum_vsbond, Error::::NotEnoughBalance); + ensure!( + vsbond_balance >= minimum_vsbond, + Error::::NotEnoughBalance + ); T::MultiCurrency::transfer( currency_id, @@ -341,7 +353,10 @@ pub mod pallet { *old_exchange_rate = exchange_rate.clone(); }); - Self::deposit_event(Event::ExchangeRateSet { lease, exchange_rate }); + Self::deposit_event(Event::ExchangeRateSet { + lease, + exchange_rate, + }); Ok(()) } diff --git a/pallets/vstoken-conversion/src/mock.rs b/pallets/vstoken-conversion/src/mock.rs index 46e56b292d..b08d25d0d4 100644 --- a/pallets/vstoken-conversion/src/mock.rs +++ b/pallets/vstoken-conversion/src/mock.rs @@ -158,7 +158,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -182,7 +184,9 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self @@ -209,3 +213,8 @@ impl ExtBuilder { t.into() } } + +#[cfg(feature = "runtime-benchmarks")] +pub fn new_test_ext_benchmark() -> sp_io::TestExternalities { + ExtBuilder::default().build() +} diff --git a/pallets/vstoken-conversion/src/tests.rs b/pallets/vstoken-conversion/src/tests.rs index c1eb850ad5..6c6736393b 100644 --- a/pallets/vstoken-conversion/src/tests.rs +++ b/pallets/vstoken-conversion/src/tests.rs @@ -29,130 +29,162 @@ use crate::{mock::*, *}; #[test] fn vsksm_convert_to_vsbond() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - const EXCHANGE_FEE: VstokenConversionExchangeFee> = - VstokenConversionExchangeFee { - vstoken_exchange_fee: 10, - vsbond_exchange_fee_of_vstoken: 10, + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + const EXCHANGE_FEE: VstokenConversionExchangeFee> = + VstokenConversionExchangeFee { + vstoken_exchange_fee: 10, + vsbond_exchange_fee_of_vstoken: 10, + }; + assert_ok!(VstokenConversion::set_exchange_fee( + RuntimeOrigin::signed(ALICE), + EXCHANGE_FEE + )); + pub const EXCHANGE_RATE_PERCENTAGE: Percent = Percent::from_percent(5); + const EXCHANGE_RATE: VstokenConversionExchangeRate = VstokenConversionExchangeRate { + vsbond_convert_to_vstoken: EXCHANGE_RATE_PERCENTAGE, + // vsbond_convert_to_vsksm: EXCHANGE_RATE_PERCENTAGE, + vstoken_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE, + // vsdot_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE, }; - assert_ok!(VstokenConversion::set_exchange_fee(RuntimeOrigin::signed(ALICE), EXCHANGE_FEE)); - pub const EXCHANGE_RATE_PERCENTAGE: Percent = Percent::from_percent(5); - const EXCHANGE_RATE: VstokenConversionExchangeRate = VstokenConversionExchangeRate { - vsbond_convert_to_vstoken: EXCHANGE_RATE_PERCENTAGE, - // vsbond_convert_to_vsksm: EXCHANGE_RATE_PERCENTAGE, - vstoken_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE, - // vsdot_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE, - }; - assert_ok!(VstokenConversion::set_relaychain_lease(RuntimeOrigin::signed(ALICE), 1)); - assert_noop!( - VstokenConversion::vstoken_convert_to_vsbond( - Some(BOB).into(), - VSBOND_BNC_2001_0_8, - 1000, + assert_ok!(VstokenConversion::set_relaychain_lease( + RuntimeOrigin::signed(ALICE), 1 - ), - Error::::NotEnoughBalance - ); - assert_noop!( - VstokenConversion::vstoken_convert_to_vsbond( + )); + assert_noop!( + VstokenConversion::vstoken_convert_to_vsbond( + Some(BOB).into(), + VSBOND_BNC_2001_0_8, + 1000, + 1 + ), + Error::::NotEnoughBalance + ); + assert_noop!( + VstokenConversion::vstoken_convert_to_vsbond( + Some(BOB).into(), + VSBOND_BNC_2001_0_8, + 100, + 1 + ), + Error::::CalculationOverflow + ); + assert_ok!(VstokenConversion::set_exchange_rate( + RuntimeOrigin::signed(ALICE), + 8, + EXCHANGE_RATE + )); + assert_eq!(ExchangeRate::::get(8), EXCHANGE_RATE); + assert_noop!( + VstokenConversion::vstoken_convert_to_vsbond( + Some(BOB).into(), + VSBOND_BNC_2001_0_8, + 100, + 1 + ), + orml_tokens::Error::::BalanceTooLow + ); + assert_noop!( + VstokenConversion::vstoken_convert_to_vsbond(Some(BOB).into(), KSM, 100, 1), + Error::::NotSupportTokenType + ); + let vsbond_account: AccountId = + ::VsbondAccount::get().into_account_truncating(); + assert_ok!(>::deposit( + VSBOND_BNC_2001_0_8, + &vsbond_account, + 10000 + )); + assert_ok!(VstokenConversion::vstoken_convert_to_vsbond( Some(BOB).into(), VSBOND_BNC_2001_0_8, 100, 1 - ), - Error::::CalculationOverflow - ); - assert_ok!(VstokenConversion::set_exchange_rate( - RuntimeOrigin::signed(ALICE), - 8, - EXCHANGE_RATE - )); - assert_eq!(ExchangeRate::::get(8), EXCHANGE_RATE); - assert_noop!( - VstokenConversion::vstoken_convert_to_vsbond( + )); + assert_eq!(Tokens::free_balance(VSKSM, &BOB), 0); + assert_eq!( + Tokens::free_balance(VSBOND_BNC_2001_0_8, &vsbond_account), + 8200 + ); + assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &BOB), 1900); + + assert_ok!(>::deposit( + VSKSM, &BOB, 1000 + )); + pub const EXCHANGE_RATE_PERCENTAGE_0: Percent = Percent::from_percent(100); + const EXCHANGE_RATE_0: VstokenConversionExchangeRate = VstokenConversionExchangeRate { + vsbond_convert_to_vstoken: EXCHANGE_RATE_PERCENTAGE_0, + vstoken_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE_0, + }; + assert_ok!(VstokenConversion::set_relaychain_lease( + RuntimeOrigin::signed(ALICE), + 11 + )); + assert_ok!(VstokenConversion::set_exchange_rate( + RuntimeOrigin::signed(ALICE), + -2, + EXCHANGE_RATE_0 + )); + assert_ok!(VstokenConversion::vstoken_convert_to_vsbond( Some(BOB).into(), VSBOND_BNC_2001_0_8, 100, 1 - ), - orml_tokens::Error::::BalanceTooLow - ); - assert_noop!( - VstokenConversion::vstoken_convert_to_vsbond(Some(BOB).into(), KSM, 100, 1), - Error::::NotSupportTokenType - ); - let vsbond_account: AccountId = - ::VsbondAccount::get().into_account_truncating(); - assert_ok!(>::deposit( - VSBOND_BNC_2001_0_8, - &vsbond_account, - 10000 - )); - assert_ok!(VstokenConversion::vstoken_convert_to_vsbond( - Some(BOB).into(), - VSBOND_BNC_2001_0_8, - 100, - 1 - )); - assert_eq!(Tokens::free_balance(VSKSM, &BOB), 0); - assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &vsbond_account), 8200); - assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &BOB), 1900); - - assert_ok!(>::deposit(VSKSM, &BOB, 1000)); - pub const EXCHANGE_RATE_PERCENTAGE_0: Percent = Percent::from_percent(100); - const EXCHANGE_RATE_0: VstokenConversionExchangeRate = VstokenConversionExchangeRate { - vsbond_convert_to_vstoken: EXCHANGE_RATE_PERCENTAGE_0, - vstoken_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE_0, - }; - assert_ok!(VstokenConversion::set_relaychain_lease(RuntimeOrigin::signed(ALICE), 11)); - assert_ok!(VstokenConversion::set_exchange_rate( - RuntimeOrigin::signed(ALICE), - -2, - EXCHANGE_RATE_0 - )); - assert_ok!(VstokenConversion::vstoken_convert_to_vsbond( - Some(BOB).into(), - VSBOND_BNC_2001_0_8, - 100, - 1 - )); - assert_eq!(Tokens::free_balance(VSKSM, &BOB), 900); - assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &vsbond_account), 8110); - assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &BOB), 1990); - }); + )); + assert_eq!(Tokens::free_balance(VSKSM, &BOB), 900); + assert_eq!( + Tokens::free_balance(VSBOND_BNC_2001_0_8, &vsbond_account), + 8110 + ); + assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &BOB), 1990); + }); } #[test] fn vsbond_convert_to_vsksm() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - const EXCHANGE_FEE: VstokenConversionExchangeFee> = - VstokenConversionExchangeFee { - vstoken_exchange_fee: 10, - vsbond_exchange_fee_of_vstoken: 10, + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + const EXCHANGE_FEE: VstokenConversionExchangeFee> = + VstokenConversionExchangeFee { + vstoken_exchange_fee: 10, + vsbond_exchange_fee_of_vstoken: 10, + }; + assert_ok!(VstokenConversion::set_exchange_fee( + RuntimeOrigin::signed(ALICE), + EXCHANGE_FEE + )); + const EXCHANGE_RATE_PERCENTAGE: Percent = Percent::from_percent(5); + const EXCHANGE_RATE: VstokenConversionExchangeRate = VstokenConversionExchangeRate { + vsbond_convert_to_vstoken: EXCHANGE_RATE_PERCENTAGE, + vstoken_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE, }; - assert_ok!(VstokenConversion::set_exchange_fee(RuntimeOrigin::signed(ALICE), EXCHANGE_FEE)); - const EXCHANGE_RATE_PERCENTAGE: Percent = Percent::from_percent(5); - const EXCHANGE_RATE: VstokenConversionExchangeRate = VstokenConversionExchangeRate { - vsbond_convert_to_vstoken: EXCHANGE_RATE_PERCENTAGE, - vstoken_convert_to_vsbond: EXCHANGE_RATE_PERCENTAGE, - }; - assert_ok!(VstokenConversion::set_relaychain_lease(RuntimeOrigin::signed(ALICE), 1)); - assert_ok!(VstokenConversion::set_exchange_rate( - RuntimeOrigin::signed(ALICE), - 8, - EXCHANGE_RATE - )); - assert_eq!(ExchangeRate::::get(8), EXCHANGE_RATE); - let vsbond_account: AccountId = - ::VsbondAccount::get().into_account_truncating(); - assert_ok!(VstokenConversion::vsbond_convert_to_vstoken( - Some(BOB).into(), - VSBOND_BNC_2001_0_8, - 100, - 1 - )); - assert_eq!(Tokens::free_balance(VSKSM, &BOB), 104); - assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &vsbond_account), 100); - assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &BOB), 0); - }); + assert_ok!(VstokenConversion::set_relaychain_lease( + RuntimeOrigin::signed(ALICE), + 1 + )); + assert_ok!(VstokenConversion::set_exchange_rate( + RuntimeOrigin::signed(ALICE), + 8, + EXCHANGE_RATE + )); + assert_eq!(ExchangeRate::::get(8), EXCHANGE_RATE); + let vsbond_account: AccountId = + ::VsbondAccount::get().into_account_truncating(); + assert_ok!(VstokenConversion::vsbond_convert_to_vstoken( + Some(BOB).into(), + VSBOND_BNC_2001_0_8, + 100, + 1 + )); + assert_eq!(Tokens::free_balance(VSKSM, &BOB), 104); + assert_eq!( + Tokens::free_balance(VSBOND_BNC_2001_0_8, &vsbond_account), + 100 + ); + assert_eq!(Tokens::free_balance(VSBOND_BNC_2001_0_8, &BOB), 0); + }); } diff --git a/pallets/vstoken-conversion/src/weights.rs b/pallets/vstoken-conversion/src/weights.rs index e1e22dee8d..a06986fcb4 100644 --- a/pallets/vstoken-conversion/src/weights.rs +++ b/pallets/vstoken-conversion/src/weights.rs @@ -24,9 +24,9 @@ //! Autogenerated weights for bifrost_vstoken_conversion //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-12-03, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `mjl-legion`, CPU: `12th Gen Intel(R) Core(TM) i9-12900H` //! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 // Executed Command: @@ -36,7 +36,7 @@ // --chain=bifrost-kusama-local // --steps=50 // --repeat=20 -// --pallet=bifrost_vstoken_conversion +// --pallet=bifrost_vstoken-conversion // --extrinsic=* // --execution=wasm // --wasm-execution=compiled @@ -62,82 +62,82 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { - /// Storage: VstokenConversion ExchangeFee (r:1 w:1) - /// Proof: VstokenConversion ExchangeFee (max_values: Some(1), max_size: Some(32), added: 527, mode: MaxEncodedLen) + /// Storage: `VstokenConversion::ExchangeFee` (r:1 w:1) + /// Proof: `VstokenConversion::ExchangeFee` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn set_exchange_fee() -> Weight { // Proof Size summary in bytes: - // Measured: `180` + // Measured: `213` // Estimated: `1517` - // Minimum execution time: 30_744_000 picoseconds. - Weight::from_parts(31_166_000, 1517) + // Minimum execution time: 19_049_000 picoseconds. + Weight::from_parts(21_188_000, 1517) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: VstokenConversion ExchangeRate (r:1 w:1) - /// Proof: VstokenConversion ExchangeRate (max_values: None, max_size: Some(14), added: 2489, mode: MaxEncodedLen) + /// Storage: `VstokenConversion::ExchangeRate` (r:1 w:1) + /// Proof: `VstokenConversion::ExchangeRate` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) fn set_exchange_rate() -> Weight { // Proof Size summary in bytes: - // Measured: `180` + // Measured: `213` // Estimated: `3479` - // Minimum execution time: 30_215_000 picoseconds. - Weight::from_parts(31_148_000, 3479) + // Minimum execution time: 21_707_000 picoseconds. + Weight::from_parts(23_228_000, 3479) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: VstokenConversion RelaychainLease (r:1 w:1) - /// Proof: VstokenConversion RelaychainLease (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: `VstokenConversion::RelaychainLease` (r:1 w:1) + /// Proof: `VstokenConversion::RelaychainLease` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn set_relaychain_lease() -> Weight { // Proof Size summary in bytes: - // Measured: `180` + // Measured: `213` // Estimated: `1489` - // Minimum execution time: 28_293_000 picoseconds. - Weight::from_parts(29_337_000, 1489) + // Minimum execution time: 19_567_000 picoseconds. + Weight::from_parts(20_639_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: Tokens Accounts (r:4 w:4) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: VstokenConversion RelaychainLease (r:1 w:0) - /// Proof: VstokenConversion RelaychainLease (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: VstokenConversion ExchangeRate (r:1 w:0) - /// Proof: VstokenConversion ExchangeRate (max_values: None, max_size: Some(14), added: 2489, mode: MaxEncodedLen) - /// Storage: VstokenConversion ExchangeFee (r:1 w:0) - /// Proof: VstokenConversion ExchangeFee (max_values: Some(1), max_size: Some(32), added: 527, mode: MaxEncodedLen) - /// Storage: System Account (r:3 w:3) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:2 w:2) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `Tokens::Accounts` (r:4 w:4) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:2 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `VstokenConversion::RelaychainLease` (r:1 w:0) + /// Proof: `VstokenConversion::RelaychainLease` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `VstokenConversion::ExchangeRate` (r:1 w:0) + /// Proof: `VstokenConversion::ExchangeRate` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `VstokenConversion::ExchangeFee` (r:1 w:0) + /// Proof: `VstokenConversion::ExchangeFee` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:3) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:2 w:2) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn vsbond_convert_to_vstoken() -> Weight { // Proof Size summary in bytes: - // Measured: `2336` + // Measured: `1461` // Estimated: `11362` - // Minimum execution time: 258_393_000 picoseconds. - Weight::from_parts(262_031_000, 11362) + // Minimum execution time: 186_527_000 picoseconds. + Weight::from_parts(201_205_000, 11362) .saturating_add(RocksDbWeight::get().reads(14_u64)) .saturating_add(RocksDbWeight::get().writes(9_u64)) } - /// Storage: Tokens Accounts (r:4 w:4) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:0) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - /// Storage: VstokenConversion RelaychainLease (r:1 w:0) - /// Proof: VstokenConversion RelaychainLease (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: VstokenConversion ExchangeRate (r:1 w:0) - /// Proof: VstokenConversion ExchangeRate (max_values: None, max_size: Some(14), added: 2489, mode: MaxEncodedLen) - /// Storage: VstokenConversion ExchangeFee (r:1 w:0) - /// Proof: VstokenConversion ExchangeFee (max_values: Some(1), max_size: Some(32), added: 527, mode: MaxEncodedLen) - /// Storage: System Account (r:3 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:1 w:1) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(38), added: 2513, mode: MaxEncodedLen) + /// Storage: `Tokens::Accounts` (r:4 w:4) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:2 w:0) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `VstokenConversion::RelaychainLease` (r:1 w:0) + /// Proof: `VstokenConversion::RelaychainLease` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `VstokenConversion::ExchangeRate` (r:1 w:0) + /// Proof: `VstokenConversion::ExchangeRate` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `VstokenConversion::ExchangeFee` (r:1 w:0) + /// Proof: `VstokenConversion::ExchangeFee` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(38), added: 2513, mode: `MaxEncodedLen`) fn vstoken_convert_to_vsbond() -> Weight { // Proof Size summary in bytes: - // Measured: `2327` + // Measured: `1453` // Estimated: `11362` - // Minimum execution time: 244_708_000 picoseconds. - Weight::from_parts(247_427_000, 11362) + // Minimum execution time: 181_662_000 picoseconds. + Weight::from_parts(188_009_000, 11362) .saturating_add(RocksDbWeight::get().reads(13_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } diff --git a/pallets/vtoken-minting/Cargo.toml b/pallets/vtoken-minting/Cargo.toml index 4226b370e4..2aaad43cdd 100644 --- a/pallets/vtoken-minting/Cargo.toml +++ b/pallets/vtoken-minting/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vtoken-minting" version = "0.8.0" -authors = ["Kadokura "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/vtoken-minting/rpc/Cargo.toml b/pallets/vtoken-minting/rpc/Cargo.toml index 080396f47b..764628f5c0 100644 --- a/pallets/vtoken-minting/rpc/Cargo.toml +++ b/pallets/vtoken-minting/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vtoken-minting-rpc" version = "0.8.0" -authors = ["Tiebing "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/vtoken-minting/rpc/runtime-api/Cargo.toml b/pallets/vtoken-minting/rpc/runtime-api/Cargo.toml index a18515f8d2..adc4b4a4ea 100644 --- a/pallets/vtoken-minting/rpc/runtime-api/Cargo.toml +++ b/pallets/vtoken-minting/rpc/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vtoken-minting-rpc-runtime-api" version = "0.8.0" -authors = ["Tiebing "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/vtoken-minting/rpc/src/lib.rs b/pallets/vtoken-minting/rpc/src/lib.rs index 7c412626f4..5215607fdb 100644 --- a/pallets/vtoken-minting/rpc/src/lib.rs +++ b/pallets/vtoken-minting/rpc/src/lib.rs @@ -60,7 +60,10 @@ pub struct VtokenMintingRpc { impl VtokenMintingRpc { pub fn new(client: Arc) -> Self { - Self { client, _marker: PhantomData } + Self { + client, + _marker: PhantomData, + } } } diff --git a/pallets/vtoken-minting/src/benchmarking.rs b/pallets/vtoken-minting/src/benchmarking.rs index 1812968894..7e648206eb 100644 --- a/pallets/vtoken-minting/src/benchmarking.rs +++ b/pallets/vtoken-minting/src/benchmarking.rs @@ -24,7 +24,7 @@ use bifrost_primitives::{CurrencyId, TokenSymbol, VtokenMintingOperator, VKSM}; use frame_benchmarking::v1::{benchmarks, whitelisted_caller, BenchmarkError}; use frame_support::{assert_ok, sp_runtime::traits::UniqueSaturatedFrom}; use frame_system::RawOrigin; - +use sp_runtime::Vec; benchmarks! { set_minimum_mint { let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; @@ -100,7 +100,7 @@ benchmarks! { // assert_ok!(VtokenMinting::::set_minimum_redeem(RawOrigin::Root.into(), VKSM, vtoken_amount)); T::MultiCurrency::deposit(KSM, &caller, token_amount)?; assert_ok!(VtokenMinting::::mint(RawOrigin::Signed(caller.clone()).into(), KSM, token_amount,BoundedVec::default(), None)); - }: _(RawOrigin::Signed(caller.clone()), VKSM, redeem_amount) + }: _(RawOrigin::Signed(caller.clone()), None, VKSM, redeem_amount) rebond { let caller: T::AccountId = whitelisted_caller(); @@ -117,7 +117,7 @@ benchmarks! { T::MultiCurrency::deposit(KSM, &caller, token_amount)?; T::MultiCurrency::deposit(VKSM, &caller, redeem_amount)?; assert_ok!(VtokenMinting::::mint(RawOrigin::Signed(caller.clone()).into(), KSM, mint_amount,BoundedVec::default(), None)); - assert_ok!(VtokenMinting::::redeem(RawOrigin::Signed(caller.clone()).into(), VKSM, redeem_amount)); + assert_ok!(VtokenMinting::::redeem(RawOrigin::Signed(caller.clone()).into(), None, VKSM, redeem_amount)); assert_ok!(VtokenMinting::::add_support_rebond_token(T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, KSM)); }: _(RawOrigin::Signed(caller), KSM, rebond_amount) @@ -136,8 +136,21 @@ benchmarks! { T::MultiCurrency::deposit(KSM, &caller, token_amount)?; T::MultiCurrency::deposit(VKSM, &caller, redeem_amount)?; assert_ok!(VtokenMinting::::mint(RawOrigin::Signed(caller.clone()).into(), KSM, mint_amount,BoundedVec::default(), None)); - assert_ok!(VtokenMinting::::redeem(RawOrigin::Signed(caller.clone()).into(), VKSM, redeem_amount)); + assert_ok!(VtokenMinting::::redeem(RawOrigin::Signed(caller.clone()).into(), None, VKSM, redeem_amount)); assert_ok!(VtokenMinting::::add_support_rebond_token(T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, KSM)); + let time_unit = TimeUnit::Era(1); + let total_locked_amount: BalanceOf = 10_000u32.into(); + + let mut unlock_ids_native = Vec::new(); + for id in 0..1000 { + unlock_ids_native.push(id); + } + let unlock_ids = BoundedVec::try_from(unlock_ids_native).expect("UnlockId list exceeds MaximumUnlockIdOfTimeUnit"); + TimeUnitUnlockLedger::::insert( + time_unit.clone(), + KSM, + (total_locked_amount, unlock_ids.clone(), KSM), + ); let unlock_id:UnlockId = 0; }: _(RawOrigin::Signed(caller), KSM, unlock_id) diff --git a/pallets/vtoken-minting/src/impls.rs b/pallets/vtoken-minting/src/impls.rs index 55bddc782c..a55c939607 100644 --- a/pallets/vtoken-minting/src/impls.rs +++ b/pallets/vtoken-minting/src/impls.rs @@ -16,21 +16,18 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -// Ensure we're `no_std` when compiling for Wasm. -#![cfg_attr(not(feature = "std"), no_std)] - use crate::{ AccountIdOf, BalanceOf, Config, CurrencyIdOf, Error, Event, Fees, HookIterationLimit, MinTimeUnit, MinimumMint, MinimumRedeem, MintWithLockBlocks, OnRedeemSuccess, OngoingTimeUnit, - Pallet, RedeemTo, TimeUnitUnlockLedger, TokenPool, TokenUnlockLedger, TokenUnlockNextId, - UnlockDuration, UnlockId, UnlockingTotal, UserUnlockLedger, VtokenIncentiveCoef, - VtokenLockLedger, WeightInfo, + Pallet, RedeemTo, SupportedEth, TimeUnitUnlockLedger, TokenPool, TokenUnlockLedger, + TokenUnlockNextId, UnlockDuration, UnlockId, UnlockingTotal, UserUnlockLedger, + VtokenIncentiveCoef, VtokenLockLedger, WeightInfo, }; use bb_bnc::traits::BbBNCInterface; use bifrost_primitives::{ currency::BNC, AstarChainId, CurrencyId, CurrencyIdExt, HydrationChainId, InterlayChainId, MantaChainId, RedeemType, SlpxOperator, TimeUnit, VTokenMintRedeemProvider, - VTokenSupplyProvider, VtokenMintingInterface, VtokenMintingOperator, FIL, + VTokenSupplyProvider, VtokenMintingInterface, VtokenMintingOperator, FIL, V_WETH, }; use frame_support::{ pallet_prelude::{DispatchResultWithPostInfo, *}, @@ -44,6 +41,7 @@ use frame_support::{ use frame_system::pallet_prelude::*; use orml_traits::{MultiCurrency, MultiLockableCurrency, XcmTransfer}; use sp_core::U256; +use sp_runtime::traits::BlockNumberProvider; use sp_runtime::{helpers_128bit::multiply_by_rational_with_rounding, Rounding}; use sp_std::{vec, vec::Vec}; use xcm::{prelude::*, v4::Location}; @@ -72,14 +70,16 @@ impl Pallet { TokenPool::::mutate(currency_id, |token_pool_amount| -> DispatchResult { match operation { Operation::Set => *token_pool_amount = *currency_amount, - Operation::Add => + Operation::Add => { *token_pool_amount = token_pool_amount .checked_add(currency_amount) - .ok_or(Error::::CalculationOverflow)?, - Operation::Sub => + .ok_or(Error::::CalculationOverflow)? + } + Operation::Sub => { *token_pool_amount = token_pool_amount .checked_sub(currency_amount) - .ok_or(Error::::CalculationOverflow)?, + .ok_or(Error::::CalculationOverflow)? + } } Ok(()) }) @@ -98,14 +98,16 @@ impl Pallet { UnlockingTotal::::mutate(currency_id, |unlocking_total_amount| -> DispatchResult { match operation { Operation::Set => *unlocking_total_amount = *currency_amount, - Operation::Add => + Operation::Add => { *unlocking_total_amount = unlocking_total_amount .checked_add(currency_amount) - .ok_or(Error::::CalculationOverflow)?, - Operation::Sub => + .ok_or(Error::::CalculationOverflow)? + } + Operation::Sub => { *unlocking_total_amount = unlocking_total_amount .checked_sub(currency_amount) - .ok_or(Error::::CalculationOverflow)?, + .ok_or(Error::::CalculationOverflow)? + } } Ok(()) }) @@ -139,10 +141,11 @@ impl Pallet { redeem_type, )); Ok(false) - }, + } Operation::Sub => { - let (_, total_locked_amount, _, _) = - value.as_mut().ok_or(Error::::TimeUnitUnlockLedgerNotFound)?; + let (_, total_locked_amount, _, _) = value + .as_mut() + .ok_or(Error::::TimeUnitUnlockLedgerNotFound)?; if currency_amount >= total_locked_amount { *value = None; @@ -153,7 +156,7 @@ impl Pallet { .ok_or(Error::::CalculationOverflow)?; Ok(false) } - }, + } }) } @@ -177,19 +180,22 @@ impl Pallet { match operation { Operation::Set | Operation::Add => match unlocking_ledger { Some((total_locked, ledger_list, _token_id)) => { - ledger_list.try_push(*unlock_id).map_err(|_| Error::::TooManyRedeems)?; + ledger_list + .try_push(*unlock_id) + .map_err(|_| Error::::TooManyRedeems)?; *total_locked = total_locked .checked_add(¤cy_amount) .ok_or(Error::::CalculationOverflow)?; - }, - None => + } + None => { *unlocking_ledger = Some(( *currency_amount, BoundedVec::try_from(vec![*unlock_id]) .map_err(|_| Error::::TooManyRedeems)?, *currency_id, - )), + )) + } }, Operation::Sub => { let (total_locked_amount, ledger_list, _) = unlocking_ledger @@ -206,7 +212,7 @@ impl Pallet { ledger_list.retain(|x| x != unlock_id); } } - }, + } } Ok(()) }) @@ -232,19 +238,21 @@ impl Pallet { match operation { Operation::Set | Operation::Add => match user_unlock_ledger { Some((total_locked, ledger_list)) => { - ledger_list.try_push(*unlock_id).map_err(|_| Error::::TooManyRedeems)?; + ledger_list + .try_push(*unlock_id) + .map_err(|_| Error::::TooManyRedeems)?; *total_locked = total_locked .checked_add(¤cy_amount) .ok_or(Error::::CalculationOverflow)?; - }, + } None => { *user_unlock_ledger = Some(( *currency_amount, BoundedVec::try_from(vec![*unlock_id]) .map_err(|_| Error::::TooManyRedeems)?, )); - }, + } }, Operation::Sub => { let (total_locked_amount, ledger_list) = user_unlock_ledger @@ -261,7 +269,7 @@ impl Pallet { ledger_list.retain(|x| x != unlock_id); } } - }, + } } Ok(()) }) @@ -334,8 +342,9 @@ impl Pallet { // Charging fees T::MultiCurrency::transfer(currency_id, minter, &T::FeeAccount::get(), mint_fee)?; - let currency_amount = - currency_amount.checked_sub(&mint_fee).ok_or(Error::::CalculationOverflow)?; + let currency_amount = currency_amount + .checked_sub(&mint_fee) + .ok_or(Error::::CalculationOverflow)?; let v_currency_amount = Self::get_v_currency_amount_by_currency_amount( currency_id, v_currency_id, @@ -494,14 +503,17 @@ impl Pallet { 1, [ Parachain(T::MoonbeamChainId::get()), - AccountKey20 { network: None, key: receiver.to_fixed_bytes() }, + AccountKey20 { + network: None, + key: receiver.to_fixed_bytes(), + }, ], ), RedeemTo::Moonbeam(receiver), ), RedeemType::Native => { unreachable!() - }, + } }; if redeem_currency_id == FIL { let assets = vec![ @@ -550,7 +562,10 @@ impl Pallet { if let Some((_total_locked, ledger_list, currency_id)) = TimeUnitUnlockLedger::::get(&time_unit, currency) { - for unlock_id in ledger_list.iter().take(HookIterationLimit::::get() as usize) { + for unlock_id in ledger_list + .iter() + .take(HookIterationLimit::::get() as usize) + { if let Some((account, unlock_amount, time_unit, redeem_type)) = TokenUnlockLedger::::get(currency_id, unlock_id) { @@ -579,8 +594,9 @@ impl Pallet { UnlockDuration::::get(currency).ok_or(Error::::UnlockDurationNotFound)?; let ongoing_time = OngoingTimeUnit::::get(currency).ok_or(Error::::OngoingTimeUnitNotSet)?; - let result_time_unit = - ongoing_time.add(unlock_duration).ok_or(Error::::CalculationOverflow)?; + let result_time_unit = ongoing_time + .add(unlock_duration) + .ok_or(Error::::CalculationOverflow)?; if result_time_unit.gt(time_unit) { *time_unit = time_unit.clone().add_one(); } @@ -602,7 +618,14 @@ impl Pallet { currency_amount >= MinimumMint::::get(currency_id), Error::::BelowMinimumMint ); - let v_currency_id = currency_id.to_vtoken().map_err(|_| Error::::NotSupportTokenType)?; + + let v_currency_id = if SupportedEth::::get().contains(¤cy_id) { + V_WETH + } else { + currency_id + .to_vtoken() + .map_err(|_| Error::::NotSupportTokenType)? + }; let (currency_amount_excluding_fee, v_currency_amount, mint_fee) = Self::mint_without_transfer(&minter, v_currency_id, currency_id, currency_amount)?; @@ -632,11 +655,24 @@ impl Pallet { pub fn do_redeem( redeemer: AccountIdOf, + currency_id: Option>, v_currency_id: CurrencyIdOf, v_currency_amount: BalanceOf, redeem_type: RedeemType>, ) -> DispatchResultWithPostInfo { - let currency_id = v_currency_id.to_token().map_err(|_| Error::::NotSupportTokenType)?; + let currency_id = match currency_id { + Some(currency_id) => { + ensure!( + SupportedEth::::get().contains(¤cy_id), + Error::::NotSupportTokenType + ); + currency_id + } + None => v_currency_id + .to_token() + .map_err(|_| Error::::NotSupportTokenType)?, + }; + ensure!( v_currency_amount >= MinimumRedeem::::get(v_currency_id), Error::::BelowMinimumRedeem @@ -698,7 +734,9 @@ impl Pallet { }); // Increase the next unlock id - *next_id = next_id.checked_add(1).ok_or(Error::::CalculationOverflow)?; + *next_id = next_id + .checked_add(1) + .ok_or(Error::::CalculationOverflow)?; T::ChannelCommission::record_redeem_amount(v_currency_id, v_currency_amount)?; let extra_weight = T::OnRedeemSuccess::on_redeemed( @@ -741,7 +779,7 @@ impl Pallet { // get the vtoken lock duration from VtokenIncentiveCoef let lock_duration = MintWithLockBlocks::::get(v_currency_id) .ok_or(Error::::IncentiveLockBlocksNotSet)?; - let current_block = frame_system::Pallet::::block_number(); + let current_block = T::BlockNumberProvider::current_block_number(); let due_block = current_block .checked_add(&lock_duration) .ok_or(Error::::CalculationOverflow)?; @@ -759,13 +797,14 @@ impl Pallet { lock_records .try_push((v_currency_amount, due_block)) .map_err(|_| Error::::TooManyLocks)?; - }, - None => + } + None => { *v_token_lock_ledger = Some(( v_currency_amount, BoundedVec::try_from(vec![(v_currency_amount, due_block)]) .map_err(|_| Error::::TooManyLocks)?, - )), + )) + } } // extend the locked amount to be new_lock_total @@ -788,19 +827,29 @@ impl Pallet { // get the vtoken pool balance let vtoken_pool_balance = T::MultiCurrency::free_balance(v_currency_id, &Self::incentive_pool_account()); - ensure!(vtoken_pool_balance > BalanceOf::::zero(), Error::::NotEnoughBalance); + ensure!( + vtoken_pool_balance > BalanceOf::::zero(), + Error::::NotEnoughBalance + ); // get current block number - let current_block_number: BlockNumberFor = frame_system::Pallet::::block_number(); + let current_block_number: BlockNumberFor = + T::BlockNumberProvider::current_block_number(); // get the veBNC total amount let vebnc_total_issuance = T::BbBNC::total_supply(current_block_number) .map_err(|_| Error::::VeBNCCheckingError)?; - ensure!(vebnc_total_issuance > BalanceOf::::zero(), Error::::BalanceZero); + ensure!( + vebnc_total_issuance > BalanceOf::::zero(), + Error::::BalanceZero + ); // get the veBNC balance of the minter let minter_vebnc_balance = T::BbBNC::balance_of(minter, None).map_err(|_| Error::::VeBNCCheckingError)?; - ensure!(minter_vebnc_balance > BalanceOf::::zero(), Error::::NotEnoughBalance); + ensure!( + minter_vebnc_balance > BalanceOf::::zero(), + Error::::NotEnoughBalance + ); // get the percentage of the veBNC balance of the minter to the total veBNC amount and // get the square root of the percentage @@ -821,18 +870,23 @@ impl Pallet { // calculate the incentive amount, but mind the overflow // incentive_amount = vtoken_pool_balance * incentive_coef * v_currency_amount * // sqrt_percentage / v_currency_total_issuance - let incentive_amount = - U256::from(percentage.mul_ceil(vtoken_pool_balance).saturated_into::()) - .checked_mul(U256::from(incentive_coef)) - .and_then(|x| x.checked_mul(U256::from(v_currency_amount.saturated_into::()))) - // .and_then(|x| x.checked_mul(percentage)) - .and_then(|x| { - x.checked_div(U256::from(v_currency_total_issuance.saturated_into::())) - }) - // first turn into u128,then use unique_saturated_into BalanceOf - .map(|x| x.saturated_into::()) - .map(|x| x.unique_saturated_into()) - .ok_or(Error::::CalculationOverflow)?; + let incentive_amount = U256::from( + percentage + .mul_ceil(vtoken_pool_balance) + .saturated_into::(), + ) + .checked_mul(U256::from(incentive_coef)) + .and_then(|x| x.checked_mul(U256::from(v_currency_amount.saturated_into::()))) + // .and_then(|x| x.checked_mul(percentage)) + .and_then(|x| { + x.checked_div(U256::from( + v_currency_total_issuance.saturated_into::(), + )) + }) + // first turn into u128,then use unique_saturated_into BalanceOf + .map(|x| x.saturated_into::()) + .map(|x| x.unique_saturated_into()) + .ok_or(Error::::CalculationOverflow)?; Ok(incentive_amount) } @@ -842,7 +896,15 @@ impl VtokenMintingOperator, AccountIdOf, for Pallet { fn get_token_pool(currency_id: CurrencyId) -> BalanceOf { - TokenPool::::get(currency_id) + if SupportedEth::::get().contains(¤cy_id) { + let mut token_pool_amount = BalanceOf::::zero(); + SupportedEth::::get().iter().for_each(|¤cy_id| { + token_pool_amount += TokenPool::::get(currency_id); + }); + token_pool_amount + } else { + TokenPool::::get(currency_id) + } } fn increase_token_pool( @@ -893,7 +955,12 @@ impl VtokenMintingOperator, AccountIdOf, fn get_token_unlock_ledger( currency_id: CurrencyId, index: u32, - ) -> Option<(AccountIdOf, BalanceOf, TimeUnit, RedeemType>)> { + ) -> Option<( + AccountIdOf, + BalanceOf, + TimeUnit, + RedeemType>, + )> { TokenUnlockLedger::::get(currency_id, index) } @@ -920,7 +987,13 @@ impl VtokenMintingInterface, CurrencyIdOf, BalanceO v_currency_id: CurrencyIdOf, v_currency_amount: BalanceOf, ) -> DispatchResultWithPostInfo { - Self::do_redeem(exchanger, v_currency_id, v_currency_amount, RedeemType::Native) + Self::do_redeem( + exchanger, + None, + v_currency_id, + v_currency_amount, + RedeemType::Native, + ) } fn slpx_redeem( @@ -929,7 +1002,13 @@ impl VtokenMintingInterface, CurrencyIdOf, BalanceO v_currency_amount: BalanceOf, redeem_type: RedeemType>, ) -> DispatchResultWithPostInfo { - Self::do_redeem(exchanger, v_currency_id, v_currency_amount, redeem_type) + Self::do_redeem( + exchanger, + None, + v_currency_id, + v_currency_amount, + redeem_type, + ) } fn get_v_currency_amount_by_currency_amount( @@ -937,7 +1016,11 @@ impl VtokenMintingInterface, CurrencyIdOf, BalanceO v_currency_id: CurrencyIdOf, currency_amount: BalanceOf, ) -> Result, DispatchError> { - let token_pool_amount = TokenPool::::get(currency_id); + let token_pool_amount = as VtokenMintingInterface< + AccountIdOf, + CurrencyIdOf, + BalanceOf, + >>::get_token_pool(currency_id); let v_currency_total_issuance = T::MultiCurrency::total_issuance(v_currency_id); if BalanceOf::::zero().eq(&token_pool_amount) { @@ -966,7 +1049,11 @@ impl VtokenMintingInterface, CurrencyIdOf, BalanceO v_currency_id: CurrencyIdOf, v_currency_amount: BalanceOf, ) -> Result, DispatchError> { - let token_pool_amount = TokenPool::::get(currency_id); + let token_pool_amount = as VtokenMintingInterface< + AccountIdOf, + CurrencyIdOf, + BalanceOf, + >>::get_token_pool(currency_id); let v_currency_total_issuance = T::MultiCurrency::total_issuance(v_currency_id); if BalanceOf::::zero().eq(&v_currency_total_issuance) { @@ -988,7 +1075,15 @@ impl VtokenMintingInterface, CurrencyIdOf, BalanceO } fn get_token_pool(currency_id: CurrencyId) -> BalanceOf { - TokenPool::::get(currency_id) + if SupportedEth::::get().contains(¤cy_id) { + let mut token_pool_amount = BalanceOf::::zero(); + SupportedEth::::get().iter().for_each(|¤cy_id| { + token_pool_amount += TokenPool::::get(currency_id); + }); + token_pool_amount + } else { + TokenPool::::get(currency_id) + } } fn get_moonbeam_parachain_id() -> u32 { diff --git a/pallets/vtoken-minting/src/lib.rs b/pallets/vtoken-minting/src/lib.rs index 849633dab2..a6f27f6633 100644 --- a/pallets/vtoken-minting/src/lib.rs +++ b/pallets/vtoken-minting/src/lib.rs @@ -42,7 +42,7 @@ use bifrost_primitives::{ use frame_support::{ pallet_prelude::{DispatchResultWithPostInfo, *}, sp_runtime::{ - traits::{CheckedAdd, CheckedSub, Saturating, Zero}, + traits::{BlockNumberProvider, CheckedAdd, CheckedSub, Saturating, Zero}, DispatchError, Permill, }, traits::LockIdentifier, @@ -134,6 +134,8 @@ pub mod pallet { #[pallet::constant] type MoonbeamChainId: Get; + /// The current block number provider. + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::event] @@ -284,12 +286,19 @@ pub mod pallet { incentive_vtoken_amount: BalanceOf, }, /// Incentive coefficient set. - VtokenIncentiveCoefSet { v_currency_id: CurrencyIdOf, coefficient: Option }, + VtokenIncentiveCoefSet { + v_currency_id: CurrencyIdOf, + coefficient: Option, + }, /// Incentive lock blocks set. VtokenIncentiveLockBlocksSet { v_currency_id: CurrencyIdOf, blocks: Option>, }, + /// Set Supported eths. + SupportedEthSet { + eths: BoundedVec>, + }, } #[pallet::error] @@ -451,6 +460,10 @@ pub mod pallet { #[pallet::storage] pub type HookIterationLimit = StorageValue<_, u32, ValueQuery>; + #[pallet::storage] + pub type SupportedEth = + StorageValue<_, BoundedVec>, ValueQuery>; + //【vtoken -> Blocks】, the locked blocks for each vtoken when minted in an incentive mode #[pallet::storage] pub type MintWithLockBlocks = @@ -470,7 +483,10 @@ pub mod pallet { AccountIdOf, Blake2_128Concat, CurrencyId, - (BalanceOf, BoundedVec<(BalanceOf, BlockNumberFor), T::MaxLockRecords>), + ( + BalanceOf, + BoundedVec<(BalanceOf, BlockNumberFor), T::MaxLockRecords>, + ), OptionQuery, >; @@ -488,7 +504,7 @@ pub mod pallet { "Received invalid justification for {:?}", err, ); - }, + } } } @@ -529,11 +545,18 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::redeem())] pub fn redeem( origin: OriginFor, + currency_id: Option>, v_currency_id: CurrencyIdOf, v_currency_amount: BalanceOf, ) -> DispatchResultWithPostInfo { let redeemer = ensure_signed(origin)?; - Self::do_redeem(redeemer, v_currency_id, v_currency_amount, RedeemType::Native) + Self::do_redeem( + redeemer, + currency_id, + v_currency_id, + v_currency_amount, + RedeemType::Native, + ) } /// Already redeemed currency by burning v_currency. But need to wait for the unlock period. @@ -550,13 +573,17 @@ pub mod pallet { currency_amount: BalanceOf, ) -> DispatchResult { let rebonder = ensure_signed(origin)?; - let v_currency_id = - currency_id.to_vtoken().map_err(|_| Error::::NotSupportTokenType)?; + let v_currency_id = currency_id + .to_vtoken() + .map_err(|_| Error::::NotSupportTokenType)?; let (user_unlock_amount, unlock_id_list) = UserUnlockLedger::::get(&rebonder, currency_id) .ok_or(Error::::UserUnlockLedgerNotFound)?; - ensure!(user_unlock_amount >= currency_amount, Error::::NotEnoughBalanceToUnlock); + ensure!( + user_unlock_amount >= currency_amount, + Error::::NotEnoughBalanceToUnlock + ); let mut temp_currency_amount = currency_amount; for unlock_id in unlock_id_list.into_iter().rev() { @@ -599,7 +626,7 @@ pub mod pallet { .checked_add(¤cy_amount) .ok_or(Error::::CalculationOverflow)?; Ok(()) - }, + } None => Err(Error::::InvalidRebondToken), } })?; @@ -627,8 +654,9 @@ pub mod pallet { ) -> DispatchResult { let rebonder = ensure_signed(origin)?; - let v_currency_id = - currency_id.to_vtoken().map_err(|_| Error::::NotSupportTokenType)?; + let v_currency_id = currency_id + .to_vtoken() + .map_err(|_| Error::::NotSupportTokenType)?; let (who, unlock_amount, time_unit, _) = TokenUnlockLedger::::get(currency_id, unlock_id) @@ -655,7 +683,7 @@ pub mod pallet { .checked_add(¤cy_amount) .ok_or(Error::::CalculationOverflow)?; Ok(()) - }, + } None => Err(Error::::InvalidRebondToken), } })?; @@ -688,7 +716,10 @@ pub mod pallet { *old_unlock_duration = Some(unlock_duration.clone()); }); - Self::deposit_event(Event::UnlockDurationSet { currency_id, unlock_duration }); + Self::deposit_event(Event::UnlockDurationSet { + currency_id, + unlock_duration, + }); Ok(()) } @@ -709,7 +740,10 @@ pub mod pallet { *old_amount = minimum_amount; }); - Self::deposit_event(Event::MinimumMintSet { currency_id, minimum_amount }); + Self::deposit_event(Event::MinimumMintSet { + currency_id, + minimum_amount, + }); Ok(()) } @@ -731,7 +765,10 @@ pub mod pallet { *old_amount = minimum_amount; }); - Self::deposit_event(Event::MinimumRedeemSet { currency_id, minimum_amount }); + Self::deposit_event(Event::MinimumRedeemSet { + currency_id, + minimum_amount, + }); Ok(()) } @@ -753,7 +790,7 @@ pub mod pallet { *maybe_value = Some(BalanceOf::::zero()); Self::deposit_event(Event::SupportRebondTokenAdded { currency_id }); Ok(()) - }, + } } }) } @@ -775,7 +812,7 @@ pub mod pallet { *maybe_value = None; Self::deposit_event(Event::SupportRebondTokenRemoved { currency_id }); Ok(()) - }, + } None => Err(Error::::InvalidRebondToken.into()), } }) @@ -796,7 +833,10 @@ pub mod pallet { Fees::::mutate(|fees| *fees = (mint_fee, redeem_fee)); - Self::deposit_event(Event::FeeSet { mint_fee, redeem_fee }); + Self::deposit_event(Event::FeeSet { + mint_fee, + redeem_fee, + }); Ok(()) } @@ -830,7 +870,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; Self::update_unlocking_total(¤cy_id, ¤cy_amount, Operation::Set)?; - Self::deposit_event(Event::UnlockingTotalSet { currency_id, currency_amount }); + Self::deposit_event(Event::UnlockingTotalSet { + currency_id, + currency_amount, + }); Ok(()) } @@ -851,7 +894,10 @@ pub mod pallet { *old_time_unit = time_unit.clone() }); - Self::deposit_event(Event::MinTimeUnitSet { currency_id, time_unit }); + Self::deposit_event(Event::MinTimeUnitSet { + currency_id, + time_unit, + }); Ok(()) } @@ -872,7 +918,10 @@ pub mod pallet { *old_time_unit = Some(time_unit.clone()) }); - Self::deposit_event(Event::SetOngoingTimeUnit { currency_id, time_unit }); + Self::deposit_event(Event::SetOngoingTimeUnit { + currency_id, + time_unit, + }); Ok(()) } @@ -894,16 +943,23 @@ pub mod pallet { .map_err(|_| Error::::NotEnoughBalance)?; // check whether the currency_id is supported - ensure!(MinimumMint::::contains_key(currency_id), Error::::NotSupportTokenType); + ensure!( + MinimumMint::::contains_key(currency_id), + Error::::NotSupportTokenType + ); // check whether the user has veBNC let vebnc_balance = T::BbBNC::balance_of(&minter, None).map_err(|_| Error::::VeBNCCheckingError)?; - ensure!(vebnc_balance > BalanceOf::::zero(), Error::::NotEnoughBalance); + ensure!( + vebnc_balance > BalanceOf::::zero(), + Error::::NotEnoughBalance + ); // check whether the vtoken coefficient is set - let v_currency_id = - currency_id.to_vtoken().map_err(|_| Error::::NotSupportTokenType)?; + let v_currency_id = currency_id + .to_vtoken() + .map_err(|_| Error::::NotSupportTokenType)?; ensure!( VtokenIncentiveCoef::::contains_key(v_currency_id), @@ -915,11 +971,19 @@ pub mod pallet { let vtoken_pool_balance = T::MultiCurrency::free_balance(v_currency_id, &incentive_pool_account); - ensure!(vtoken_pool_balance > BalanceOf::::zero(), Error::::NotEnoughBalance); + ensure!( + vtoken_pool_balance > BalanceOf::::zero(), + Error::::NotEnoughBalance + ); // mint vtoken - let vtoken_minted = - Self::do_mint(minter.clone(), currency_id, currency_amount, remark, channel_id)?; + let vtoken_minted = Self::do_mint( + minter.clone(), + currency_id, + currency_amount, + remark, + channel_id, + )?; // lock vtoken and record the lock Self::lock_vtoken_for_incentive_minting(minter.clone(), v_currency_id, vtoken_minted)?; @@ -971,7 +1035,7 @@ pub mod pallet { &unlocker, v_currency_id, |maybe_ledger| -> Result<(), Error> { - let current_block = frame_system::Pallet::::block_number(); + let current_block = T::BlockNumberProvider::current_block_number(); if let Some(ref mut ledger) = maybe_ledger { // check the total locked amount @@ -999,7 +1063,10 @@ pub mod pallet { } // check the unlock amount - ensure!(unlock_amount > BalanceOf::::zero(), Error::::NoUnlockRecord); + ensure!( + unlock_amount > BalanceOf::::zero(), + Error::::NoUnlockRecord + ); let remaining_locked_amount = total_locked .checked_sub(&unlock_amount) @@ -1092,5 +1159,22 @@ pub mod pallet { Ok(()) } + + /// Set Supported eths. + /// Parameters: + /// - `eths`: The supported eths. + #[pallet::call_index(18)] + #[pallet::weight(T::DbWeight::get().writes(1u64))] + pub fn set_supported_eth( + origin: OriginFor, + eths: BoundedVec>, + ) -> DispatchResult { + T::ControlOrigin::ensure_origin(origin)?; + + SupportedEth::::put(eths.clone()); + Self::deposit_event(Event::SupportedEthSet { eths }); + + Ok(()) + } } } diff --git a/pallets/vtoken-minting/src/mock.rs b/pallets/vtoken-minting/src/mock.rs index 1e8e4df821..5031e3587d 100644 --- a/pallets/vtoken-minting/src/mock.rs +++ b/pallets/vtoken-minting/src/mock.rs @@ -26,7 +26,7 @@ use bifrost_asset_registry::AssetIdMaps; use bifrost_primitives::{ currency::{BNC, DOT, FIL, KSM, MOVR, VBNC, VFIL, VKSM, VMOVR}, BifrostEntranceAccount, BifrostExitAccount, BifrostFeeAccount, CurrencyId, CurrencyIdMapping, - IncentivePoolAccount, MockXcmTransfer, MoonbeamChainId, SlpxOperator, KUSD, + IncentivePoolAccount, MockXcmTransfer, MoonbeamChainId, SlpxOperator, KUSD, V_WETH, WETH, }; use bifrost_runtime_common::{micro, milli}; use frame_support::{derive_impl, ord_parameter_types, parameter_types, traits::Nothing}; @@ -124,6 +124,9 @@ orml_traits::parameter_type_with_key! { &VKSM => 0, &FIL => 0, &VFIL => 0, + &V_WETH => 0, + &WETH => 0, + &VFIL => 0, &MOVR => 1 * micro::(MOVR), // MOVR has a decimals of 10e18 &VMOVR => 1 * micro::(MOVR), // MOVR has a decimals of 10e18 &VBNC => 10 * milli::(NativeCurrencyId::get()), // 0.01 BNC @@ -183,6 +186,7 @@ impl vtoken_minting::Config for Runtime { type XcmTransfer = MockXcmTransfer; type MoonbeamChainId = MoonbeamChainId; type ChannelCommission = (); + type BlockNumberProvider = System; } ord_parameter_types! { @@ -208,7 +212,9 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { endowed_accounts: vec![] } + Self { + endowed_accounts: vec![], + } } } @@ -227,12 +233,16 @@ impl ExtBuilder { (BOB, MOVR, 1000000000000000000000), (BOB, VFIL, 1000), (BOB, FIL, 100000000000000000000000), + (BOB, WETH, 1000000000000000000000), (CHARLIE, MOVR, 100000000000000000000000), + (CHARLIE, WETH, 100000000000000000000000), ]) } pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: self diff --git a/pallets/vtoken-minting/src/tests.rs b/pallets/vtoken-minting/src/tests.rs index 791eddc4f9..d47bc9d30e 100644 --- a/pallets/vtoken-minting/src/tests.rs +++ b/pallets/vtoken-minting/src/tests.rs @@ -23,711 +23,1141 @@ use crate::{mock::*, DispatchError::Module, *}; use bifrost_primitives::{ currency::{BNC, FIL, KSM, MOVR, VBNC, VFIL, VKSM, VMOVR}, - VtokenMintingOperator, + VtokenMintingOperator, V_WETH, WETH, }; use frame_support::{assert_noop, assert_ok, sp_runtime::Permill, BoundedVec}; use sp_runtime::ModuleError; #[test] fn mint_bnc() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - BNC, - 95000000000, - BoundedVec::default(), - None - )); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - BNC, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::increase_token_pool(BNC, 70000000000)); - // assert_eq!(TokenPool::::get(BNC), 70000000000); - assert_ok!(VtokenMinting::update_ongoing_time_unit(BNC, TimeUnit::Era(1))); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 95000000000); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VBNC, 20000000000)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + BNC, + 95000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + BNC, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::increase_token_pool(BNC, 70000000000)); + // assert_eq!(TokenPool::::get(BNC), 70000000000); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + BNC, + TimeUnit::Era(1) + )); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 95000000000); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + None, + VBNC, + 20000000000 + )); + }); } #[test] fn redeem_bnc() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - // AssetIdMaps::::register_vtoken_metadata(TokenSymbol::BNC) - // .expect("VToken register"); - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), BNC, 0)); - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - BNC, - 100000000000, - BoundedVec::default(), - None - )); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - BNC, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::increase_token_pool(BNC, 70000000000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(BNC, TimeUnit::Era(1))); - assert_eq!(Tokens::free_balance(VBNC, &BOB), 100000000000); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VBNC, 20000000000)); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + // AssetIdMaps::::register_vtoken_metadata(TokenSymbol::BNC) + // .expect("VToken register"); + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + BNC, + 0 + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + BNC, + 100000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + BNC, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::increase_token_pool(BNC, 70000000000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + BNC, + TimeUnit::Era(1) + )); + assert_eq!(Tokens::free_balance(VBNC, &BOB), 100000000000); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + None, + VBNC, + 20000000000 + )); + }); } #[test] fn mint() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 200)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_noop!( - VtokenMinting::mint(Some(BOB).into(), KSM, 100, BoundedVec::default(), None), - Error::::BelowMinimumMint - ); - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - KSM, - 100000000000, - BoundedVec::default(), - None - )); - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - MOVR, - 100000000000000000000, - BoundedVec::default(), - None - )); - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - MOVR, - 100000000000000000000, - BoundedVec::default(), - None - )); - assert_eq!(TokenPool::::get(MOVR), 190000000000000000000); - assert_eq!(TokenPool::::get(KSM), 95000000000); - assert_eq!(MinimumMint::::get(KSM), 200); - assert_eq!(Tokens::total_issuance(VKSM), 95000001000); - - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_eq!(Tokens::free_balance(KSM, &entrance_account), 95000000000); - let fee_account: AccountId = ::FeeAccount::get(); - assert_eq!(Tokens::free_balance(KSM, &fee_account), 5000000000); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 200 + )); + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_noop!( + VtokenMinting::mint(Some(BOB).into(), KSM, 100, BoundedVec::default(), None), + Error::::BelowMinimumMint + ); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 100000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + MOVR, + 100000000000000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + MOVR, + 100000000000000000000, + BoundedVec::default(), + None + )); + assert_eq!(TokenPool::::get(MOVR), 190000000000000000000); + assert_eq!(TokenPool::::get(KSM), 95000000000); + assert_eq!(MinimumMint::::get(KSM), 200); + assert_eq!(Tokens::total_issuance(VKSM), 95000001000); + + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_eq!(Tokens::free_balance(KSM, &entrance_account), 95000000000); + let fee_account: AccountId = ::FeeAccount::get(); + assert_eq!(Tokens::free_balance(KSM, &fee_account), 5000000000); + }); } #[test] fn redeem() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - pub const FEE: Permill = Permill::from_percent(2); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - assert_ok!(VtokenMinting::set_minimum_redeem(RuntimeOrigin::signed(ALICE), VKSM, 90)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 1000, BoundedVec::default(), None)); - assert_noop!( - VtokenMinting::redeem(Some(BOB).into(), VKSM, 80), - Error::::BelowMinimumRedeem - ); - assert_noop!( - VtokenMinting::redeem(Some(BOB).into(), KSM, 80), - Error::::NotSupportTokenType - ); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 100)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 200)); - assert_eq!(TokenPool::::get(KSM), 1686); // 1000 + 980 - 98 - 196 - assert_eq!(UnlockingTotal::::get(KSM), 294); // 98 + 196 - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - MOVR, - TimeUnit::Round(1) - )); - assert_ok!(VtokenMinting::update_ongoing_time_unit(MOVR, TimeUnit::Round(1))); - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - MOVR, - 300000000000000000000, - BoundedVec::default(), - None - )); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VMOVR, 20000000000000000000)); - assert_ok!(VtokenMinting::add_support_rebond_token(RuntimeOrigin::signed(ALICE), MOVR)); - assert_ok!(VtokenMinting::rebond(Some(BOB).into(), MOVR, 19000000000000000000)); - assert_ok!(VtokenMinting::set_min_time_unit( - RuntimeOrigin::signed(ALICE), - MOVR, - TimeUnit::Round(1) - )); - assert_eq!(MinTimeUnit::::get(MOVR), TimeUnit::Round(1)); - assert_ok!(VtokenMinting::set_unlocking_total(RuntimeOrigin::signed(ALICE), MOVR, 1000)); - assert_eq!(UnlockingTotal::::get(MOVR), 1000); - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_eq!(Tokens::free_balance(KSM, &entrance_account), 980); - let mut ledger_list_origin = BoundedVec::default(); - assert_ok!(ledger_list_origin.try_push(0)); - assert_ok!(ledger_list_origin.try_push(1)); - assert_eq!( - UserUnlockLedger::::get(BOB, KSM), - Some((294, ledger_list_origin.clone())) - ); - assert_eq!( - TokenUnlockLedger::::get(KSM, 0), - Some((BOB, 98, TimeUnit::Era(2), RedeemType::Native)) - ); - let mut ledger_list_origin2 = BoundedVec::default(); - assert_ok!(ledger_list_origin2.try_push(0)); - assert_ok!(ledger_list_origin2.try_push(1)); - assert_eq!( - TimeUnitUnlockLedger::::get(TimeUnit::Era(2), KSM), - Some((294, ledger_list_origin2, KSM)) - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + pub const FEE: Permill = Permill::from_percent(2); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::set_minimum_redeem( + RuntimeOrigin::signed(ALICE), + VKSM, + 90 + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 1000, + BoundedVec::default(), + None + )); + assert_noop!( + VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 80), + Error::::BelowMinimumRedeem + ); + assert_noop!( + VtokenMinting::redeem(Some(BOB).into(), None, KSM, 80), + Error::::NotSupportTokenType + ); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 100)); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 200)); + assert_eq!(TokenPool::::get(KSM), 1686); // 1000 + 980 - 98 - 196 + assert_eq!(UnlockingTotal::::get(KSM), 294); // 98 + 196 + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + MOVR, + TimeUnit::Round(1) + )); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + MOVR, + TimeUnit::Round(1) + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + MOVR, + 300000000000000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + None, + VMOVR, + 20000000000000000000 + )); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + MOVR + )); + assert_ok!(VtokenMinting::rebond( + Some(BOB).into(), + MOVR, + 19000000000000000000 + )); + assert_ok!(VtokenMinting::set_min_time_unit( + RuntimeOrigin::signed(ALICE), + MOVR, + TimeUnit::Round(1) + )); + assert_eq!(MinTimeUnit::::get(MOVR), TimeUnit::Round(1)); + assert_ok!(VtokenMinting::set_unlocking_total( + RuntimeOrigin::signed(ALICE), + MOVR, + 1000 + )); + assert_eq!(UnlockingTotal::::get(MOVR), 1000); + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_eq!(Tokens::free_balance(KSM, &entrance_account), 980); + let mut ledger_list_origin = BoundedVec::default(); + assert_ok!(ledger_list_origin.try_push(0)); + assert_ok!(ledger_list_origin.try_push(1)); + assert_eq!( + UserUnlockLedger::::get(BOB, KSM), + Some((294, ledger_list_origin.clone())) + ); + assert_eq!( + TokenUnlockLedger::::get(KSM, 0), + Some((BOB, 98, TimeUnit::Era(2), RedeemType::Native)) + ); + let mut ledger_list_origin2 = BoundedVec::default(); + assert_ok!(ledger_list_origin2.try_push(0)); + assert_ok!(ledger_list_origin2.try_push(1)); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Era(2), KSM), + Some((294, ledger_list_origin2, KSM)) + ); + }); } #[test] fn rebond() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - pub const FEE: Permill = Permill::from_percent(0); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(0) - )); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - let mut ledger_list_origin = BoundedVec::default(); - assert_ok!(ledger_list_origin.try_push(0)); - let mut ledger_list_origin2 = BoundedVec::default(); - assert_ok!(ledger_list_origin2.try_push(0)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 200, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 100, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 200)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 100)); - assert_eq!( - TokenUnlockLedger::::get(KSM, 1), - Some((BOB, 100, TimeUnit::Era(1), RedeemType::Native)) - ); - assert_noop!( - VtokenMinting::rebond(Some(BOB).into(), KSM, 100), - Error::::InvalidRebondToken - ); - assert_ok!(VtokenMinting::add_support_rebond_token(RuntimeOrigin::signed(ALICE), KSM)); - assert_ok!(VtokenMinting::rebond(Some(BOB).into(), KSM, 200)); - assert_eq!( - TimeUnitUnlockLedger::::get(TimeUnit::Era(1), KSM), - Some((100, ledger_list_origin.clone(), KSM)) - ); - assert_eq!( - UserUnlockLedger::::get(BOB, KSM), - Some((100, ledger_list_origin2.clone())) - ); - assert_eq!( - TokenUnlockLedger::::get(KSM, 0), - Some((BOB, 100, TimeUnit::Era(1), RedeemType::Native)) - ); - assert_eq!(TokenUnlockLedger::::get(KSM, 1), None); - assert_eq!(TokenPool::::get(KSM), 1200); - assert_eq!(UnlockingTotal::::get(KSM), 100); // 200 + 100 - 200 - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_eq!(Tokens::free_balance(KSM, &entrance_account), 300); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + pub const FEE: Permill = Permill::from_percent(0); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(0) + )); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + let mut ledger_list_origin = BoundedVec::default(); + assert_ok!(ledger_list_origin.try_push(0)); + let mut ledger_list_origin2 = BoundedVec::default(); + assert_ok!(ledger_list_origin2.try_push(0)); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 200, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 200)); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 100)); + assert_eq!( + TokenUnlockLedger::::get(KSM, 1), + Some((BOB, 100, TimeUnit::Era(1), RedeemType::Native)) + ); + assert_noop!( + VtokenMinting::rebond(Some(BOB).into(), KSM, 100), + Error::::InvalidRebondToken + ); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + KSM + )); + assert_ok!(VtokenMinting::rebond(Some(BOB).into(), KSM, 200)); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Era(1), KSM), + Some((100, ledger_list_origin.clone(), KSM)) + ); + assert_eq!( + UserUnlockLedger::::get(BOB, KSM), + Some((100, ledger_list_origin2.clone())) + ); + assert_eq!( + TokenUnlockLedger::::get(KSM, 0), + Some((BOB, 100, TimeUnit::Era(1), RedeemType::Native)) + ); + assert_eq!(TokenUnlockLedger::::get(KSM, 1), None); + assert_eq!(TokenPool::::get(KSM), 1200); + assert_eq!(UnlockingTotal::::get(KSM), 100); // 200 + 100 - 200 + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_eq!(Tokens::free_balance(KSM, &entrance_account), 300); + }); } #[test] fn movr() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_ok!(VtokenMinting::set_hook_iteration_limit(RuntimeOrigin::signed(ALICE), 10)); - assert_ok!(VtokenMinting::set_min_time_unit( - RuntimeOrigin::signed(ALICE), - MOVR, - TimeUnit::Round(1) - )); - pub const FEE: Permill = Permill::from_percent(2); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_ok!(VtokenMinting::set_hook_iteration_limit( + RuntimeOrigin::signed(ALICE), + 10 + )); + assert_ok!(VtokenMinting::set_min_time_unit( + RuntimeOrigin::signed(ALICE), + MOVR, + TimeUnit::Round(1) + )); + pub const FEE: Permill = Permill::from_percent(2); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + MOVR, + TimeUnit::Round(1) + )); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + MOVR, + TimeUnit::Round(1) + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + MOVR, + 300000000000000000000, + BoundedVec::default(), + None + )); + assert_eq!( + Tokens::free_balance(MOVR, &entrance_account), + 294000000000000000000 + ); + assert_eq!(Tokens::free_balance(VMOVR, &BOB), 294000000000000000000); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + None, + VMOVR, + 200000000000000000000 + )); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + None, + VMOVR, + 80000000000000000000 + )); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + None, + VMOVR, + 10000000000000000000 + )); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + assert_eq!(MinTimeUnit::::get(MOVR), TimeUnit::Round(2)); + assert_eq!( + OngoingTimeUnit::::get(MOVR), + Some(TimeUnit::Round(1)) + ); + assert_eq!(Tokens::free_balance(MOVR, &BOB), 984200000000000000000); + assert_eq!(TokenUnlockLedger::::get(MOVR, 0), None); + assert_ok!(VtokenMinting::mint( + Some(CHARLIE).into(), + MOVR, + 30000000000000000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem( + Some(CHARLIE).into(), + None, + VMOVR, + 20000000000000000000000 + )); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + MOVR + )); + assert_eq!(TokenUnlockLedger::::get(MOVR, 0), None); + assert_eq!(TokenUnlockLedger::::get(MOVR, 1), None); + assert_eq!(TokenUnlockLedger::::get(MOVR, 2), None); + assert_eq!(TokenUnlockNextId::::get(MOVR), 4); + assert_ok!(VtokenMinting::rebond( + Some(CHARLIE).into(), + MOVR, + 19000000000000000000000 + )); + assert_ok!(VtokenMinting::rebond_by_unlock_id( + Some(CHARLIE).into(), + MOVR, + 3 + )); + assert_eq!(UnlockingTotal::::get(MOVR), 0); + }); +} + +#[test] +fn set_supported_eths() { + ExtBuilder::default().build().execute_with(|| { + assert_ok!(VtokenMinting::set_supported_eth( RuntimeOrigin::signed(ALICE), - MOVR, - TimeUnit::Round(1) - )); - assert_ok!(VtokenMinting::update_ongoing_time_unit(MOVR, TimeUnit::Round(1))); - assert_ok!(VtokenMinting::mint( - Some(BOB).into(), - MOVR, - 300000000000000000000, - BoundedVec::default(), - None + vec![WETH].try_into().unwrap() )); - assert_eq!(Tokens::free_balance(MOVR, &entrance_account), 294000000000000000000); - assert_eq!(Tokens::free_balance(VMOVR, &BOB), 294000000000000000000); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VMOVR, 200000000000000000000)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VMOVR, 80000000000000000000)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VMOVR, 10000000000000000000)); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - assert_eq!(MinTimeUnit::::get(MOVR), TimeUnit::Round(2)); - assert_eq!(OngoingTimeUnit::::get(MOVR), Some(TimeUnit::Round(1))); - assert_eq!(Tokens::free_balance(MOVR, &BOB), 984200000000000000000); - assert_eq!(TokenUnlockLedger::::get(MOVR, 0), None); - assert_ok!(VtokenMinting::mint( - Some(CHARLIE).into(), - MOVR, - 30000000000000000000000, - BoundedVec::default(), - None - )); - assert_ok!(VtokenMinting::redeem(Some(CHARLIE).into(), VMOVR, 20000000000000000000000)); - assert_ok!(VtokenMinting::add_support_rebond_token(RuntimeOrigin::signed(ALICE), MOVR)); - assert_eq!(TokenUnlockLedger::::get(MOVR, 0), None); - assert_eq!(TokenUnlockLedger::::get(MOVR, 1), None); - assert_eq!(TokenUnlockLedger::::get(MOVR, 2), None); - assert_eq!(TokenUnlockNextId::::get(MOVR), 4); - assert_ok!(VtokenMinting::rebond(Some(CHARLIE).into(), MOVR, 19000000000000000000000)); - assert_ok!(VtokenMinting::rebond_by_unlock_id(Some(CHARLIE).into(), MOVR, 3)); - assert_eq!(UnlockingTotal::::get(MOVR), 0); - }); + + assert_eq!(SupportedEth::::get().to_vec(), vec![WETH]); + }) +} + +#[test] +fn eth() { + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + let (entrance_account, _) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_ok!(VtokenMinting::set_hook_iteration_limit( + RuntimeOrigin::signed(ALICE), + 10 + )); + assert_ok!(VtokenMinting::set_min_time_unit( + RuntimeOrigin::signed(ALICE), + WETH, + TimeUnit::Round(1) + )); + pub const FEE: Permill = Permill::from_percent(2); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + WETH, + TimeUnit::Round(1) + )); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + WETH, + TimeUnit::Round(1) + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + WETH, + 300000000000000000000, + BoundedVec::default(), + None + )); + assert_eq!( + Tokens::free_balance(WETH, &entrance_account), + 294000000000000000000 + ); + assert_eq!(Tokens::free_balance(V_WETH, &BOB), 294000000000000000000); + SupportedEth::::set(vec![WETH].try_into().unwrap()); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + Some(WETH), + V_WETH, + 200000000000000000000 + )); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + Some(WETH), + V_WETH, + 80000000000000000000 + )); + assert_ok!(VtokenMinting::redeem( + Some(BOB).into(), + Some(WETH), + V_WETH, + 10000000000000000000 + )); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + assert_eq!(MinTimeUnit::::get(WETH), TimeUnit::Round(2)); + assert_eq!( + OngoingTimeUnit::::get(WETH), + Some(TimeUnit::Round(1)) + ); + assert_eq!(Tokens::free_balance(WETH, &BOB), 984200000000000000000); + assert_eq!(TokenUnlockLedger::::get(WETH, 0), None); + assert_ok!(VtokenMinting::mint( + Some(CHARLIE).into(), + WETH, + 30000000000000000000000, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem( + Some(CHARLIE).into(), + Some(WETH), + V_WETH, + 20000000000000000000000 + )); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + WETH + )); + assert_eq!(TokenUnlockLedger::::get(WETH, 0), None); + assert_eq!(TokenUnlockLedger::::get(WETH, 1), None); + assert_eq!(TokenUnlockLedger::::get(WETH, 2), None); + assert_eq!(TokenUnlockNextId::::get(WETH), 4); + assert_ok!(VtokenMinting::rebond( + Some(CHARLIE).into(), + WETH, + 19000000000000000000000 + )); + assert_ok!(VtokenMinting::rebond_by_unlock_id( + Some(CHARLIE).into(), + WETH, + 3 + )); + assert_eq!(UnlockingTotal::::get(WETH), 0); + }); } #[test] fn hook() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(0)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(3))); - assert_eq!(OngoingTimeUnit::::get(KSM), Some(TimeUnit::Era(3))); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::set_hook_iteration_limit(RuntimeOrigin::signed(ALICE), 1)); - assert_eq!(UnlockDuration::::get(KSM), Some(TimeUnit::Era(1))); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(4)); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 200, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 100, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 200)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 100)); - assert_eq!(UnlockingTotal::::get(KSM), 300); // 200 + 100 - assert_noop!( - VtokenMinting::rebond(Some(BOB).into(), KSM, 100), - Error::::InvalidRebondToken - ); - assert_ok!(VtokenMinting::add_support_rebond_token(RuntimeOrigin::signed(ALICE), KSM)); - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_eq!(Tokens::free_balance(KSM, &entrance_account), 300); - VtokenMinting::on_initialize(100); - assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(4)); - VtokenMinting::on_initialize(100); - assert_eq!(TokenUnlockLedger::::get(KSM, 0), None); - assert_eq!(TokenUnlockLedger::::get(KSM, 1), None); - assert_eq!(TimeUnitUnlockLedger::::get(TimeUnit::Era(4), KSM), None); - assert_eq!(TimeUnitUnlockLedger::::get(TimeUnit::Era(5), KSM), None); - assert_eq!(UserUnlockLedger::::get(BOB, KSM), None); - assert_eq!(TokenPool::::get(KSM), 1000); - assert_eq!(Tokens::free_balance(KSM, &entrance_account), 0); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(5))); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(0); - VtokenMinting::on_initialize(1); - assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(6)); - assert_eq!(UnlockingTotal::::get(KSM), 0); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 100, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 200)); - VtokenMinting::on_initialize(0); - assert_eq!( - TokenUnlockLedger::::get(KSM, 2), - Some((BOB, 100, TimeUnit::Era(6), RedeemType::Native)) - ); - let mut ledger_list_origin = BoundedVec::default(); - assert_ok!(ledger_list_origin.try_push(2)); - let mut ledger_list_origin2 = BoundedVec::default(); - assert_ok!(ledger_list_origin2.try_push(2)); - assert_eq!( - TimeUnitUnlockLedger::::get(TimeUnit::Era(6), KSM), - Some((100, ledger_list_origin.clone(), KSM)) - ); - assert_eq!( - UserUnlockLedger::::get(BOB, KSM), - Some((100, ledger_list_origin2.clone())) - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(0)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(3) + )); + assert_eq!(OngoingTimeUnit::::get(KSM), Some(TimeUnit::Era(3))); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(1) + )); + assert_ok!(VtokenMinting::set_hook_iteration_limit( + RuntimeOrigin::signed(ALICE), + 1 + )); + assert_eq!(UnlockDuration::::get(KSM), Some(TimeUnit::Era(1))); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(4)); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 200, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 200)); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 100)); + assert_eq!(UnlockingTotal::::get(KSM), 300); // 200 + 100 + assert_noop!( + VtokenMinting::rebond(Some(BOB).into(), KSM, 100), + Error::::InvalidRebondToken + ); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + KSM + )); + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_eq!(Tokens::free_balance(KSM, &entrance_account), 300); + VtokenMinting::on_initialize(100); + assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(4)); + VtokenMinting::on_initialize(100); + assert_eq!(TokenUnlockLedger::::get(KSM, 0), None); + assert_eq!(TokenUnlockLedger::::get(KSM, 1), None); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Era(4), KSM), + None + ); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Era(5), KSM), + None + ); + assert_eq!(UserUnlockLedger::::get(BOB, KSM), None); + assert_eq!(TokenPool::::get(KSM), 1000); + assert_eq!(Tokens::free_balance(KSM, &entrance_account), 0); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(5) + )); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(0); + VtokenMinting::on_initialize(1); + assert_eq!(MinTimeUnit::::get(KSM), TimeUnit::Era(6)); + assert_eq!(UnlockingTotal::::get(KSM), 0); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 200)); + VtokenMinting::on_initialize(0); + assert_eq!( + TokenUnlockLedger::::get(KSM, 2), + Some((BOB, 100, TimeUnit::Era(6), RedeemType::Native)) + ); + let mut ledger_list_origin = BoundedVec::default(); + assert_ok!(ledger_list_origin.try_push(2)); + let mut ledger_list_origin2 = BoundedVec::default(); + assert_ok!(ledger_list_origin2.try_push(2)); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Era(6), KSM), + Some((100, ledger_list_origin.clone(), KSM)) + ); + assert_eq!( + UserUnlockLedger::::get(BOB, KSM), + Some((100, ledger_list_origin2.clone())) + ); + }); } #[test] fn rebond_by_unlock_id() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Era(0) - )); - assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - let mut ledger_list_origin = BoundedVec::default(); - assert_ok!(ledger_list_origin.try_push(1)); - let mut ledger_list_origin2 = BoundedVec::default(); - assert_ok!(ledger_list_origin2.try_push(1)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 200, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), KSM, 100, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 200)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VKSM, 100)); - assert_eq!(TokenPool::::get(KSM), 1000); - assert_noop!( - VtokenMinting::rebond_by_unlock_id(Some(BOB).into(), KSM, 0), - Error::::InvalidRebondToken - ); - assert_ok!(VtokenMinting::add_support_rebond_token(RuntimeOrigin::signed(ALICE), KSM)); - assert_noop!( - VtokenMinting::rebond_by_unlock_id(Some(ALICE).into(), KSM, 0), - Error::::CanNotRebond - ); - assert_ok!(VtokenMinting::rebond_by_unlock_id(Some(BOB).into(), KSM, 0)); - assert_eq!( - TimeUnitUnlockLedger::::get(TimeUnit::Era(1), KSM), - Some((100, ledger_list_origin.clone(), KSM)) - ); - assert_eq!( - UserUnlockLedger::::get(BOB, KSM), - Some((100, ledger_list_origin2.clone())) - ); - assert_eq!(TokenUnlockLedger::::get(KSM, 0), None); - assert_eq!( - TokenUnlockLedger::::get(KSM, 1), - Some((BOB, 100, TimeUnit::Era(1), RedeemType::Native)) - ); - assert_eq!(TokenPool::::get(KSM), 1200); - assert_eq!(UnlockingTotal::::get(KSM), 100); // 200 + 100 - 200 - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_eq!(Tokens::free_balance(KSM, &entrance_account), 300); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Era(0) + )); + assert_ok!(VtokenMinting::increase_token_pool(KSM, 1000)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + KSM, + TimeUnit::Era(1) + )); + let mut ledger_list_origin = BoundedVec::default(); + assert_ok!(ledger_list_origin.try_push(1)); + let mut ledger_list_origin2 = BoundedVec::default(); + assert_ok!(ledger_list_origin2.try_push(1)); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 200, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 200)); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VKSM, 100)); + assert_eq!(TokenPool::::get(KSM), 1000); + assert_noop!( + VtokenMinting::rebond_by_unlock_id(Some(BOB).into(), KSM, 0), + Error::::InvalidRebondToken + ); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + KSM + )); + assert_noop!( + VtokenMinting::rebond_by_unlock_id(Some(ALICE).into(), KSM, 0), + Error::::CanNotRebond + ); + assert_ok!(VtokenMinting::rebond_by_unlock_id(Some(BOB).into(), KSM, 0)); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Era(1), KSM), + Some((100, ledger_list_origin.clone(), KSM)) + ); + assert_eq!( + UserUnlockLedger::::get(BOB, KSM), + Some((100, ledger_list_origin2.clone())) + ); + assert_eq!(TokenUnlockLedger::::get(KSM, 0), None); + assert_eq!( + TokenUnlockLedger::::get(KSM, 1), + Some((BOB, 100, TimeUnit::Era(1), RedeemType::Native)) + ); + assert_eq!(TokenPool::::get(KSM), 1200); + assert_eq!(UnlockingTotal::::get(KSM), 100); // 200 + 100 - 200 + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_eq!(Tokens::free_balance(KSM, &entrance_account), 300); + }); } #[test] fn fast_redeem_for_fil() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); - assert_ok!(VtokenMinting::set_min_time_unit( - RuntimeOrigin::signed(ALICE), - FIL, - TimeUnit::Kblock(1) - )); - assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(1)); - assert_ok!(VtokenMinting::update_ongoing_time_unit(FIL, TimeUnit::Kblock(3))); - assert_eq!(OngoingTimeUnit::::get(FIL), Some(TimeUnit::Kblock(3))); - assert_ok!(VtokenMinting::set_unlock_duration( - RuntimeOrigin::signed(ALICE), - FIL, - TimeUnit::Kblock(1) - )); - assert_ok!(VtokenMinting::set_hook_iteration_limit(RuntimeOrigin::signed(ALICE), 1)); - assert_eq!(UnlockDuration::::get(FIL), Some(TimeUnit::Kblock(1))); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(100); - assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(4)); - assert_ok!(VtokenMinting::increase_token_pool(FIL, 1000)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), FIL, 200, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), FIL, 100, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VFIL, 200)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VFIL, 100)); - assert_eq!(UnlockingTotal::::get(FIL), 300); // 200 + 100 - assert_noop!( - VtokenMinting::rebond(Some(BOB).into(), FIL, 100), - Error::::InvalidRebondToken - ); - assert_ok!(VtokenMinting::add_support_rebond_token(RuntimeOrigin::signed(ALICE), FIL)); - let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); - assert_eq!(Tokens::free_balance(FIL, &entrance_account), 300); - VtokenMinting::on_initialize(100); - assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(4)); - VtokenMinting::on_initialize(100); - assert_eq!(TokenUnlockLedger::::get(FIL, 0), None); - assert_eq!(TokenUnlockLedger::::get(FIL, 1), None); - assert_eq!(TimeUnitUnlockLedger::::get(TimeUnit::Kblock(4), FIL), None); - assert_eq!(TimeUnitUnlockLedger::::get(TimeUnit::Kblock(5), FIL), None); - assert_eq!(UserUnlockLedger::::get(BOB, FIL), None); - assert_eq!(TokenPool::::get(FIL), 1000); - assert_eq!(Tokens::free_balance(FIL, &entrance_account), 0); - assert_ok!(VtokenMinting::update_ongoing_time_unit(FIL, TimeUnit::Kblock(5))); - VtokenMinting::on_initialize(100); - VtokenMinting::on_initialize(0); - VtokenMinting::on_initialize(1); - assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(6)); - assert_eq!(UnlockingTotal::::get(FIL), 0); - assert_ok!(VtokenMinting::mint(Some(BOB).into(), FIL, 100, BoundedVec::default(), None)); - assert_ok!(VtokenMinting::redeem(Some(BOB).into(), VFIL, 200)); - VtokenMinting::on_initialize(0); - assert_eq!( - TokenUnlockLedger::::get(FIL, 2), - Some((BOB, 100, TimeUnit::Kblock(6), RedeemType::Native)) - ); - let mut ledger_list_origin = BoundedVec::default(); - assert_ok!(ledger_list_origin.try_push(2)); - let mut ledger_list_origin2 = BoundedVec::default(); - assert_ok!(ledger_list_origin2.try_push(2)); - assert_eq!( - TimeUnitUnlockLedger::::get(TimeUnit::Kblock(6), FIL), - Some((100, ledger_list_origin.clone(), FIL)) - ); - assert_eq!( - UserUnlockLedger::::get(BOB, FIL), - Some((100, ledger_list_origin2.clone())) - ); - }); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); + assert_ok!(VtokenMinting::set_min_time_unit( + RuntimeOrigin::signed(ALICE), + FIL, + TimeUnit::Kblock(1) + )); + assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(1)); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + FIL, + TimeUnit::Kblock(3) + )); + assert_eq!( + OngoingTimeUnit::::get(FIL), + Some(TimeUnit::Kblock(3)) + ); + assert_ok!(VtokenMinting::set_unlock_duration( + RuntimeOrigin::signed(ALICE), + FIL, + TimeUnit::Kblock(1) + )); + assert_ok!(VtokenMinting::set_hook_iteration_limit( + RuntimeOrigin::signed(ALICE), + 1 + )); + assert_eq!( + UnlockDuration::::get(FIL), + Some(TimeUnit::Kblock(1)) + ); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(100); + assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(4)); + assert_ok!(VtokenMinting::increase_token_pool(FIL, 1000)); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + FIL, + 200, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + FIL, + 100, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VFIL, 200)); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VFIL, 100)); + assert_eq!(UnlockingTotal::::get(FIL), 300); // 200 + 100 + assert_noop!( + VtokenMinting::rebond(Some(BOB).into(), FIL, 100), + Error::::InvalidRebondToken + ); + assert_ok!(VtokenMinting::add_support_rebond_token( + RuntimeOrigin::signed(ALICE), + FIL + )); + let (entrance_account, _exit_account) = VtokenMinting::get_entrance_and_exit_accounts(); + assert_eq!(Tokens::free_balance(FIL, &entrance_account), 300); + VtokenMinting::on_initialize(100); + assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(4)); + VtokenMinting::on_initialize(100); + assert_eq!(TokenUnlockLedger::::get(FIL, 0), None); + assert_eq!(TokenUnlockLedger::::get(FIL, 1), None); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Kblock(4), FIL), + None + ); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Kblock(5), FIL), + None + ); + assert_eq!(UserUnlockLedger::::get(BOB, FIL), None); + assert_eq!(TokenPool::::get(FIL), 1000); + assert_eq!(Tokens::free_balance(FIL, &entrance_account), 0); + assert_ok!(VtokenMinting::update_ongoing_time_unit( + FIL, + TimeUnit::Kblock(5) + )); + VtokenMinting::on_initialize(100); + VtokenMinting::on_initialize(0); + VtokenMinting::on_initialize(1); + assert_eq!(MinTimeUnit::::get(FIL), TimeUnit::Kblock(6)); + assert_eq!(UnlockingTotal::::get(FIL), 0); + assert_ok!(VtokenMinting::mint( + Some(BOB).into(), + FIL, + 100, + BoundedVec::default(), + None + )); + assert_ok!(VtokenMinting::redeem(Some(BOB).into(), None, VFIL, 200)); + VtokenMinting::on_initialize(0); + assert_eq!( + TokenUnlockLedger::::get(FIL, 2), + Some((BOB, 100, TimeUnit::Kblock(6), RedeemType::Native)) + ); + let mut ledger_list_origin = BoundedVec::default(); + assert_ok!(ledger_list_origin.try_push(2)); + let mut ledger_list_origin2 = BoundedVec::default(); + assert_ok!(ledger_list_origin2.try_push(2)); + assert_eq!( + TimeUnitUnlockLedger::::get(TimeUnit::Kblock(6), FIL), + Some((100, ledger_list_origin.clone(), FIL)) + ); + assert_eq!( + UserUnlockLedger::::get(BOB, FIL), + Some((100, ledger_list_origin2.clone())) + ); + }); } #[test] fn set_ongoing_time_unit_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); - // set KSM ongoing time unit to be Era(1) - OngoingTimeUnit::::insert(KSM, TimeUnit::Era(1)); - assert_eq!(OngoingTimeUnit::::get(KSM), Some(TimeUnit::Era(1))); + // set KSM ongoing time unit to be Era(1) + OngoingTimeUnit::::insert(KSM, TimeUnit::Era(1)); + assert_eq!(OngoingTimeUnit::::get(KSM), Some(TimeUnit::Era(1))); - // set_ongoing_time_unit the ongoing time unit of KSM to be Round(2) - assert_ok!(VtokenMinting::set_ongoing_time_unit( - RuntimeOrigin::signed(ALICE), - KSM, - TimeUnit::Round(2) - )); - assert_eq!(OngoingTimeUnit::::get(KSM), Some(TimeUnit::Round(2))); - }) + // set_ongoing_time_unit the ongoing time unit of KSM to be Round(2) + assert_ok!(VtokenMinting::set_ongoing_time_unit( + RuntimeOrigin::signed(ALICE), + KSM, + TimeUnit::Round(2) + )); + assert_eq!( + OngoingTimeUnit::::get(KSM), + Some(TimeUnit::Round(2)) + ); + }) } #[test] fn mint_with_lock_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); + + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + // mint exceeds bob's KSM balance + assert_noop!( + VtokenMinting::mint_with_lock( + Some(BOB).into(), + KSM, + 10000000000000, + BoundedVec::default(), + None + ), + Error::::NotEnoughBalance + ); - // mint exceeds bob's KSM balance - assert_noop!( - VtokenMinting::mint_with_lock( + // Minimum Mint not set + assert_noop!( + VtokenMinting::mint_with_lock( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + ), + Error::::NotSupportTokenType + ); + + // Set minimum mint + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 100 + )); + + // vtoken coefficient not set + assert_noop!( + VtokenMinting::mint_with_lock( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + ), + Error::::IncentiveCoefNotFound + ); + + // set vtoken coefficient + assert_ok!(VtokenMinting::set_incentive_coef( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(1) + )); + + // pool not enough vKSM balance + assert_noop!( + VtokenMinting::mint_with_lock( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + ), + Error::::NotEnoughBalance + ); + + // set incentive pool balance + assert_ok!(Tokens::deposit( + VKSM, + &VtokenMinting::incentive_pool_account(), + 100000000000000000000 + )); + + // incentive lock blocks not set + assert_noop!( + VtokenMinting::mint_with_lock( + Some(BOB).into(), + KSM, + 100, + BoundedVec::default(), + None + ), + Error::::IncentiveLockBlocksNotSet + ); + + // set incentive lock blocks + assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(100) + )); + + let bob_old_balance = Tokens::free_balance(VKSM, &BOB); + // mint with lock + assert_ok!(VtokenMinting::mint_with_lock( Some(BOB).into(), KSM, - 10000000000000, + 100000000000, BoundedVec::default(), None - ), - Error::::NotEnoughBalance - ); - - // Minimum Mint not set - assert_noop!( - VtokenMinting::mint_with_lock(Some(BOB).into(), KSM, 100, BoundedVec::default(), None), - Error::::NotSupportTokenType - ); - - // Set minimum mint - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 100)); - - // vtoken coefficient not set - assert_noop!( - VtokenMinting::mint_with_lock(Some(BOB).into(), KSM, 100, BoundedVec::default(), None), - Error::::IncentiveCoefNotFound - ); - - // set vtoken coefficient - assert_ok!(VtokenMinting::set_incentive_coef(RuntimeOrigin::signed(ALICE), VKSM, Some(1))); - - // pool not enough vKSM balance - assert_noop!( - VtokenMinting::mint_with_lock(Some(BOB).into(), KSM, 100, BoundedVec::default(), None), - Error::::NotEnoughBalance - ); - - // set incentive pool balance - assert_ok!(Tokens::deposit( - VKSM, - &VtokenMinting::incentive_pool_account(), - 100000000000000000000 - )); + )); - // incentive lock blocks not set - assert_noop!( - VtokenMinting::mint_with_lock(Some(BOB).into(), KSM, 100, BoundedVec::default(), None), - Error::::IncentiveLockBlocksNotSet - ); + // check the vksm balance of bob. Should be minted_amount + incentive amount + original + // balance + assert_eq!( + Tokens::free_balance(VKSM, &BOB), + 95000000000 + 9499999990 + bob_old_balance + ); - // set incentive lock blocks - assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( - RuntimeOrigin::signed(ALICE), - VKSM, - Some(100) - )); - - let bob_old_balance = Tokens::free_balance(VKSM, &BOB); - // mint with lock - assert_ok!(VtokenMinting::mint_with_lock( - Some(BOB).into(), - KSM, - 100000000000, - BoundedVec::default(), - None - )); + // check the pool balance, should have been transferred 9499999990 to Bob account + assert_eq!( + Tokens::free_balance(VKSM, &VtokenMinting::incentive_pool_account()), + 100000000000000000000 - 9499999990 + ); - // check the vksm balance of bob. Should be minted_amount + incentive amount + original - // balance - assert_eq!(Tokens::free_balance(VKSM, &BOB), 95000000000 + 9499999990 + bob_old_balance); - - // check the pool balance, should have been transferred 9499999990 to Bob account - assert_eq!( - Tokens::free_balance(VKSM, &VtokenMinting::incentive_pool_account()), - 100000000000000000000 - 9499999990 - ); - - // check ledger - let lock_ledger = VtokenLockLedger::::get(BOB, VKSM).unwrap(); - let list = BoundedVec::try_from(vec![(95000000000u128, 100u64)]).unwrap(); - let should_be_ledger = (95000000000u128, list); - assert_eq!(lock_ledger, should_be_ledger); - }) + // check ledger + let lock_ledger = VtokenLockLedger::::get(BOB, VKSM).unwrap(); + let list = BoundedVec::try_from(vec![(95000000000u128, 100u64)]).unwrap(); + let should_be_ledger = (95000000000u128, list); + assert_eq!(lock_ledger, should_be_ledger); + }) } #[test] fn unlock_incentive_minted_vtoken_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); - - pub const FEE: Permill = Permill::from_percent(5); - assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); - // Set minimum mint - assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(ALICE), KSM, 100)); - // set vtoken coefficient - assert_ok!(VtokenMinting::set_incentive_coef(RuntimeOrigin::signed(ALICE), VKSM, Some(1))); - // set incentive pool balance - assert_ok!(Tokens::deposit( - VKSM, - &VtokenMinting::incentive_pool_account(), - 100000000000000000000 - )); - // set incentive lock blocks - assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( - RuntimeOrigin::signed(ALICE), - VKSM, - Some(100) - )); - // mint with lock - assert_ok!(VtokenMinting::mint_with_lock( - Some(BOB).into(), - KSM, - 100000000000, - BoundedVec::default(), - None - )); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); + + pub const FEE: Permill = Permill::from_percent(5); + assert_ok!(VtokenMinting::set_fees(RuntimeOrigin::root(), FEE, FEE)); + // Set minimum mint + assert_ok!(VtokenMinting::set_minimum_mint( + RuntimeOrigin::signed(ALICE), + KSM, + 100 + )); + // set vtoken coefficient + assert_ok!(VtokenMinting::set_incentive_coef( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(1) + )); + // set incentive pool balance + assert_ok!(Tokens::deposit( + VKSM, + &VtokenMinting::incentive_pool_account(), + 100000000000000000000 + )); + // set incentive lock blocks + assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(100) + )); + // mint with lock + assert_ok!(VtokenMinting::mint_with_lock( + Some(BOB).into(), + KSM, + 100000000000, + BoundedVec::default(), + None + )); - run_to_block(101); + run_to_block(101); - // check ledger - let lock_ledger = VtokenLockLedger::::get(BOB, VKSM).unwrap(); - let list = BoundedVec::try_from(vec![(95000000000u128, 100u64)]).unwrap(); - let should_be_ledger = (95000000000u128, list); - assert_eq!(lock_ledger, should_be_ledger); + // check ledger + let lock_ledger = VtokenLockLedger::::get(BOB, VKSM).unwrap(); + let list = BoundedVec::try_from(vec![(95000000000u128, 100u64)]).unwrap(); + let should_be_ledger = (95000000000u128, list); + assert_eq!(lock_ledger, should_be_ledger); - let bob_vksm_balance = Tokens::free_balance(VKSM, &BOB); - // Bob's account cannot withdraw the locked vksm - assert_eq!( - ::MultiCurrency::ensure_can_withdraw( - VKSM, - &BOB, - bob_vksm_balance - ), - Err(Module(ModuleError { - index: 1, - error: [2, 0, 0, 0,], - message: Some("LiquidityRestrictions",), - },),) - ); - - // unlock incentive minted vtoken - assert_ok!(VtokenMinting::unlock_incentive_minted_vtoken(RuntimeOrigin::signed(BOB), VKSM)); - - // Bob's amount can withdraw the locked vksm now - assert_ok!(::MultiCurrency::ensure_can_withdraw( - VKSM, - &BOB, - bob_vksm_balance - )); + let bob_vksm_balance = Tokens::free_balance(VKSM, &BOB); + // Bob's account cannot withdraw the locked vksm + assert_eq!( + ::MultiCurrency::ensure_can_withdraw( + VKSM, + &BOB, + bob_vksm_balance + ), + Err(Module(ModuleError { + index: 1, + error: [2, 0, 0, 0,], + message: Some("LiquidityRestrictions",), + },),) + ); - // total amount should be remain the same - let new_bob_vksm_balance = Tokens::free_balance(VKSM, &BOB); - assert_eq!(new_bob_vksm_balance, bob_vksm_balance); + // unlock incentive minted vtoken + assert_ok!(VtokenMinting::unlock_incentive_minted_vtoken( + RuntimeOrigin::signed(BOB), + VKSM + )); - // check ledger - let lock_ledger = VtokenLockLedger::::get(BOB, VKSM); - assert_eq!(lock_ledger, None); - }) + // Bob's amount can withdraw the locked vksm now + assert_ok!( + ::MultiCurrency::ensure_can_withdraw( + VKSM, + &BOB, + bob_vksm_balance + ) + ); + + // total amount should be remain the same + let new_bob_vksm_balance = Tokens::free_balance(VKSM, &BOB); + assert_eq!(new_bob_vksm_balance, bob_vksm_balance); + + // check ledger + let lock_ledger = VtokenLockLedger::::get(BOB, VKSM); + assert_eq!(lock_ledger, None); + }) } #[test] fn set_incentive_coef_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); - // get vksm coefficient should return None - assert_eq!(VtokenIncentiveCoef::::get(VKSM), None); + // get vksm coefficient should return None + assert_eq!(VtokenIncentiveCoef::::get(VKSM), None); - // set vksm coefficient - assert_ok!(VtokenMinting::set_incentive_coef(RuntimeOrigin::signed(ALICE), VKSM, Some(1))); + // set vksm coefficient + assert_ok!(VtokenMinting::set_incentive_coef( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(1) + )); - // get vksm coefficient should return Some(1) - assert_eq!(VtokenIncentiveCoef::::get(VKSM), Some(1)); + // get vksm coefficient should return Some(1) + assert_eq!(VtokenIncentiveCoef::::get(VKSM), Some(1)); - // set vksm coefficient to None - assert_ok!(VtokenMinting::set_incentive_coef(RuntimeOrigin::signed(ALICE), VKSM, None)); + // set vksm coefficient to None + assert_ok!(VtokenMinting::set_incentive_coef( + RuntimeOrigin::signed(ALICE), + VKSM, + None + )); - // get vksm coefficient should return None - assert_eq!(VtokenIncentiveCoef::::get(VKSM), None); - }) + // get vksm coefficient should return None + assert_eq!(VtokenIncentiveCoef::::get(VKSM), None); + }) } #[test] fn set_vtoken_incentive_lock_blocks_should_work() { - ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| { - env_logger::try_init().unwrap_or(()); + ExtBuilder::default() + .one_hundred_for_alice_n_bob() + .build() + .execute_with(|| { + env_logger::try_init().unwrap_or(()); - // get vksm lock blocks should return None - assert_eq!(MintWithLockBlocks::::get(VKSM), None); + // get vksm lock blocks should return None + assert_eq!(MintWithLockBlocks::::get(VKSM), None); - // set vksm lock blocks - assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( - RuntimeOrigin::signed(ALICE), - VKSM, - Some(100) - )); + // set vksm lock blocks + assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( + RuntimeOrigin::signed(ALICE), + VKSM, + Some(100) + )); - // get vksm lock blocks should return Some(100) - assert_eq!(MintWithLockBlocks::::get(VKSM), Some(100)); + // get vksm lock blocks should return Some(100) + assert_eq!(MintWithLockBlocks::::get(VKSM), Some(100)); - // set vksm lock blocks to None - assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( - RuntimeOrigin::signed(ALICE), - VKSM, - None - )); + // set vksm lock blocks to None + assert_ok!(VtokenMinting::set_vtoken_incentive_lock_blocks( + RuntimeOrigin::signed(ALICE), + VKSM, + None + )); - // get vksm lock blocks should return None - assert_eq!(MintWithLockBlocks::::get(VKSM), None); - }) + // get vksm lock blocks should return None + assert_eq!(MintWithLockBlocks::::get(VKSM), None); + }) } diff --git a/pallets/vtoken-voting/Cargo.toml b/pallets/vtoken-voting/Cargo.toml index cc7e02b77e..7fadc2cd97 100644 --- a/pallets/vtoken-voting/Cargo.toml +++ b/pallets/vtoken-voting/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-vtoken-voting" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" [package.metadata.docs.rs] diff --git a/pallets/vtoken-voting/src/agents/bifrost_agent/agent.rs b/pallets/vtoken-voting/src/agents/bifrost_agent/agent.rs index 53652e515c..f8bd9b3f57 100644 --- a/pallets/vtoken-voting/src/agents/bifrost_agent/agent.rs +++ b/pallets/vtoken-voting/src/agents/bifrost_agent/agent.rs @@ -144,8 +144,10 @@ impl VotingAgent for BifrostAgent { poll_index: PollIndex, _derivative_index: DerivativeIndex, ) -> Result, Error> { - Ok( as ConvictionVotingCall>::remove_vote(Some(class), poll_index) - .encode()) + Ok( + as ConvictionVotingCall>::remove_vote(Some(class), poll_index) + .encode(), + ) } fn block_number(&self) -> BlockNumberFor { diff --git a/pallets/vtoken-voting/src/benchmarking.rs b/pallets/vtoken-voting/src/benchmarking.rs index bb8f0f6ed7..e4d0cff3e0 100644 --- a/pallets/vtoken-voting/src/benchmarking.rs +++ b/pallets/vtoken-voting/src/benchmarking.rs @@ -38,9 +38,15 @@ fn funded_account(name: &'static str, index: u32) -> AccountIdOf { } fn account_vote(b: BalanceOf) -> AccountVote> { - let v = Vote { aye: true, conviction: Conviction::Locked1x }; - - AccountVote::Standard { vote: v, balance: b } + let v = Vote { + aye: true, + conviction: Conviction::Locked1x, + }; + + AccountVote::Standard { + vote: v, + balance: b, + } } fn init_vote(vtoken: CurrencyIdOf) -> Result<(), BenchmarkError> { @@ -78,9 +84,19 @@ mod benchmarks { init_vote::(vtoken)?; let r = T::MaxVotes::get() - 1; let response = Response::DispatchResult(MaybeErrorCode::Success); - for (i, index) in (0..T::MaxVotes::get()).collect::>().iter().skip(1).enumerate() { + for (i, index) in (0..T::MaxVotes::get()) + .collect::>() + .iter() + .skip(1) + .enumerate() + { Pallet::::on_idle(Zero::zero(), Weight::MAX); - Pallet::::vote(RawOrigin::Signed(caller.clone()).into(), vtoken, *index, vote)?; + Pallet::::vote( + RawOrigin::Signed(caller.clone()).into(), + vtoken, + *index, + vote, + )?; Pallet::::notify_vote( control_origin.clone() as ::RuntimeOrigin, i as QueryId, @@ -117,7 +133,12 @@ mod benchmarks { let r = 50; let response = Response::DispatchResult(MaybeErrorCode::Success); for index in (0..r).collect::>().iter() { - Pallet::::vote(RawOrigin::Signed(caller.clone()).into(), vtoken, *index, old_vote)?; + Pallet::::vote( + RawOrigin::Signed(caller.clone()).into(), + vtoken, + *index, + old_vote, + )?; Pallet::::notify_vote( control_origin.clone() as ::RuntimeOrigin, *index as QueryId, @@ -133,7 +154,12 @@ mod benchmarks { let poll_index = 1u32; let new_vote = account_vote::(200u32.into()); #[extrinsic_call] - Pallet::::vote(RawOrigin::Signed(caller.clone()), vtoken, poll_index, new_vote); + Pallet::::vote( + RawOrigin::Signed(caller.clone()), + vtoken, + poll_index, + new_vote, + ); assert_matches!( VotingForV2::::get(vtoken, &caller), @@ -235,7 +261,11 @@ mod benchmarks { )?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, vtoken, poll_index); + _( + origin as ::RuntimeOrigin, + vtoken, + poll_index, + ); Ok(()) } @@ -255,7 +285,11 @@ mod benchmarks { ); #[extrinsic_call] - _(origin as ::RuntimeOrigin, vtoken, derivative_index); + _( + origin as ::RuntimeOrigin, + vtoken, + derivative_index, + ); Ok(()) } @@ -276,7 +310,12 @@ mod benchmarks { Pallet::::vote(origin_caller.into(), vtoken, poll_index, vote)?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, vtoken, poll_index, info); + _( + origin as ::RuntimeOrigin, + vtoken, + poll_index, + info, + ); Ok(()) } @@ -289,7 +328,11 @@ mod benchmarks { let vote_locking_period = 100u32.into(); #[extrinsic_call] - _(origin as ::RuntimeOrigin, vtoken, vote_locking_period); + _( + origin as ::RuntimeOrigin, + vtoken, + vote_locking_period, + ); Ok(()) } @@ -302,7 +345,11 @@ mod benchmarks { let undeciding_timeout = 100u32.into(); #[extrinsic_call] - _(origin as ::RuntimeOrigin, vtoken, undeciding_timeout); + _( + origin as ::RuntimeOrigin, + vtoken, + undeciding_timeout, + ); Ok(()) } @@ -324,7 +371,11 @@ mod benchmarks { Pallet::::vote(origin_caller.into(), vtoken, poll_index, vote)?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, query_id, response); + _( + origin as ::RuntimeOrigin, + query_id, + response, + ); Ok(()) } @@ -346,7 +397,11 @@ mod benchmarks { Pallet::::vote(origin_caller.into(), vtoken, poll_index, vote)?; #[extrinsic_call] - _(origin as ::RuntimeOrigin, query_id, response); + _( + origin as ::RuntimeOrigin, + query_id, + response, + ); Ok(()) } @@ -359,7 +414,11 @@ mod benchmarks { let vote_cap_ratio = Perbill::from_percent(10); #[extrinsic_call] - _(origin as ::RuntimeOrigin, vtoken, vote_cap_ratio); + _( + origin as ::RuntimeOrigin, + vtoken, + vote_cap_ratio, + ); Ok(()) } diff --git a/pallets/vtoken-voting/src/lib.rs b/pallets/vtoken-voting/src/lib.rs index 40f610614a..e491fe3235 100644 --- a/pallets/vtoken-voting/src/lib.rs +++ b/pallets/vtoken-voting/src/lib.rs @@ -186,7 +186,11 @@ pub mod pallet { /// - `who`: The account whose tokens are unlocked. /// - `vtoken`: The token that was locked during voting. /// - `poll_index`: The index of the poll associated with the unlocking. - Unlocked { who: AccountIdOf, vtoken: CurrencyIdOf, poll_index: PollIndex }, + Unlocked { + who: AccountIdOf, + vtoken: CurrencyIdOf, + poll_index: PollIndex, + }, /// A delegator's vote has been removed. /// @@ -203,7 +207,10 @@ pub mod pallet { /// /// - `vtoken`: The token associated with the delegator. /// - `derivative_index`: The index of the derivative being added for the delegator. - DelegatorAdded { vtoken: CurrencyIdOf, derivative_index: DerivativeIndex }, + DelegatorAdded { + vtoken: CurrencyIdOf, + derivative_index: DerivativeIndex, + }, /// A new referendum information has been created. /// @@ -231,26 +238,39 @@ pub mod pallet { /// /// - `vtoken`: The token for which the locking period is being set. /// - `locking_period`: The period for which votes will be locked (in block numbers). - VoteLockingPeriodSet { vtoken: CurrencyIdOf, locking_period: BlockNumberFor }, + VoteLockingPeriodSet { + vtoken: CurrencyIdOf, + locking_period: BlockNumberFor, + }, /// The undeciding timeout period has been set. /// /// - `vtoken`: The token associated with the timeout. /// - `undeciding_timeout`: The period of time before a poll is considered undecided. - UndecidingTimeoutSet { vtoken: CurrencyIdOf, undeciding_timeout: BlockNumberFor }, + UndecidingTimeoutSet { + vtoken: CurrencyIdOf, + undeciding_timeout: BlockNumberFor, + }, /// A referendum has been killed (cancelled or ended). /// /// - `vtoken`: The token associated with the referendum. /// - `poll_index`: The index of the poll being killed. - ReferendumKilled { vtoken: CurrencyIdOf, poll_index: PollIndex }, + ReferendumKilled { + vtoken: CurrencyIdOf, + poll_index: PollIndex, + }, /// A notification about the result of a vote has been sent. /// /// - `vtoken`: The token associated with the poll. /// - `poll_index`: The index of the poll. /// - `success`: Whether the notification was successful or not. - VoteNotified { vtoken: CurrencyIdOf, poll_index: PollIndex, success: bool }, + VoteNotified { + vtoken: CurrencyIdOf, + poll_index: PollIndex, + success: bool, + }, /// A notification about the removal of a delegator's vote has been sent. /// @@ -268,13 +288,20 @@ pub mod pallet { /// - `responder`: The location that sent the response. /// - `query_id`: The ID of the query that was responded to. /// - `response`: The content of the response. - ResponseReceived { responder: Location, query_id: QueryId, response: Response }, + ResponseReceived { + responder: Location, + query_id: QueryId, + response: Response, + }, /// The vote cap ratio has been set. /// /// - `vtoken`: The token associated with the cap. /// - `vote_cap_ratio`: The maximum allowed ratio for the vote. - VoteCapRatioSet { vtoken: CurrencyIdOf, vote_cap_ratio: Perbill }, + VoteCapRatioSet { + vtoken: CurrencyIdOf, + vote_cap_ratio: Perbill, + }, } #[pallet::error] @@ -461,9 +488,11 @@ pub mod pallet { Delegators::::insert(vtoken, BoundedVec::truncate_from(delegators.clone())); }); - self.undeciding_timeouts.iter().for_each(|(vtoken, undeciding_timeout)| { - UndecidingTimeout::::insert(vtoken, undeciding_timeout); - }); + self.undeciding_timeouts + .iter() + .for_each(|(vtoken, undeciding_timeout)| { + UndecidingTimeout::::insert(vtoken, undeciding_timeout); + }); self.vote_cap_ratio.iter().for_each(|(vtoken, cap_ratio)| { VoteCapRatio::::insert(vtoken, cap_ratio); @@ -479,8 +508,8 @@ pub mod pallet { ) -> Weight { let db_weight = T::DbWeight::get(); let mut used_weight = db_weight.reads(3); - if remaining_weight.any_lt(used_weight) || - bifrost_current_block_number % T::ReferendumCheckInterval::get() != Zero::zero() + if remaining_weight.any_lt(used_weight) + || bifrost_current_block_number % T::ReferendumCheckInterval::get() != Zero::zero() { return Weight::zero(); } @@ -540,7 +569,10 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; Self::ensure_vtoken(&vtoken)?; - ensure!(UndecidingTimeout::::contains_key(vtoken), Error::::NoData); + ensure!( + UndecidingTimeout::::contains_key(vtoken), + Error::::NoData + ); Self::ensure_no_pending_vote(vtoken, poll_index)?; let token_vote = Self::compute_token_vote(vtoken, vtoken_vote)?; @@ -574,7 +606,8 @@ pub mod pallet { PendingDelegatorVotes::::try_mutate(vtoken, poll_index, |item| -> DispatchResult { for (derivative_index, vote) in new_delegator_votes.iter() { - item.try_push((*derivative_index, *vote)).map_err(|_| Error::::TooMany)?; + item.try_push((*derivative_index, *vote)) + .map_err(|_| Error::::TooMany)?; } Ok(()) })?; @@ -617,7 +650,11 @@ pub mod pallet { Self::try_remove_vote(&who, vtoken, poll_index, UnvoteScope::OnlyExpired)?; Self::update_lock(&who, vtoken)?; - Self::deposit_event(Event::::Unlocked { who, vtoken, poll_index }); + Self::deposit_event(Event::::Unlocked { + who, + vtoken, + poll_index, + }); Ok(()) } @@ -636,7 +673,10 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; Self::ensure_vtoken(&vtoken)?; - ensure!(DelegatorVotes::::get(vtoken, poll_index).len() > 0, Error::::NoData); + ensure!( + DelegatorVotes::::get(vtoken, poll_index).len() > 0, + Error::::NoData + ); Self::ensure_referendum_expired(vtoken, poll_index)?; let voting_agent = Self::get_voting_agent(&vtoken)?; @@ -647,7 +687,11 @@ pub mod pallet { derivative_index, )?; - Self::deposit_event(Event::::DelegatorVoteRemoved { who, vtoken, derivative_index }); + Self::deposit_event(Event::::DelegatorVoteRemoved { + who, + vtoken, + derivative_index, + }); Ok(()) } @@ -696,11 +740,15 @@ pub mod pallet { ); Delegators::::try_mutate(vtoken, |vec| -> DispatchResult { - vec.try_push(derivative_index).map_err(|_| Error::::TooMany)?; + vec.try_push(derivative_index) + .map_err(|_| Error::::TooMany)?; Ok(()) })?; - Self::deposit_event(Event::::DelegatorAdded { vtoken, derivative_index }); + Self::deposit_event(Event::::DelegatorAdded { + vtoken, + derivative_index, + }); Ok(()) } @@ -716,10 +764,17 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; Self::ensure_vtoken(&vtoken)?; - ensure!(ReferendumInfoFor::::contains_key(vtoken, poll_index), Error::::NoData); + ensure!( + ReferendumInfoFor::::contains_key(vtoken, poll_index), + Error::::NoData + ); ReferendumInfoFor::::insert(vtoken, poll_index, info.clone()); - Self::deposit_event(Event::::ReferendumInfoSet { vtoken, poll_index, info }); + Self::deposit_event(Event::::ReferendumInfoSet { + vtoken, + poll_index, + info, + }); Ok(()) } @@ -734,7 +789,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; Self::ensure_vtoken(&vtoken)?; VoteLockingPeriod::::insert(vtoken, locking_period); - Self::deposit_event(Event::::VoteLockingPeriodSet { vtoken, locking_period }); + Self::deposit_event(Event::::VoteLockingPeriodSet { + vtoken, + locking_period, + }); Ok(()) } @@ -749,7 +807,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; Self::ensure_vtoken(&vtoken)?; UndecidingTimeout::::insert(vtoken, undeciding_timeout); - Self::deposit_event(Event::::UndecidingTimeoutSet { vtoken, undeciding_timeout }); + Self::deposit_event(Event::::UndecidingTimeoutSet { + vtoken, + undeciding_timeout, + }); Ok(()) } @@ -777,14 +838,22 @@ pub mod pallet { )?; PendingVotingInfo::::remove(query_id); - Self::deposit_event(Event::::VoteNotified { vtoken, poll_index, success }); + Self::deposit_event(Event::::VoteNotified { + vtoken, + poll_index, + success, + }); } if let Some((_, _)) = PendingReferendumInfo::::get(query_id) { PendingReferendumInfo::::remove(query_id); } - Self::deposit_event(Event::::ResponseReceived { responder, query_id, response }); + Self::deposit_event(Event::::ResponseReceived { + responder, + query_id, + response, + }); Ok(()) } @@ -811,7 +880,11 @@ pub mod pallet { success, }); } - Self::deposit_event(Event::::ResponseReceived { responder, query_id, response }); + Self::deposit_event(Event::::ResponseReceived { + responder, + query_id, + response, + }); Ok(()) } @@ -826,7 +899,10 @@ pub mod pallet { T::ControlOrigin::ensure_origin(origin)?; Self::ensure_vtoken(&vtoken)?; VoteCapRatio::::insert(vtoken, vote_cap_ratio); - Self::deposit_event(Event::::VoteCapRatioSet { vtoken, vote_cap_ratio }); + Self::deposit_event(Event::::VoteCapRatioSet { + vtoken, + vote_cap_ratio, + }); Ok(()) } @@ -915,7 +991,10 @@ pub mod pallet { new_delegator_votes: Vec<(DerivativeIndex, AccountVote>)>, maybe_old_vote: Option<(AccountVote>, BalanceOf)>, ) -> DispatchResult { - let notify_call = Call::::notify_vote { query_id: 0, response: Default::default() }; + let notify_call = Call::::notify_vote { + query_id: 0, + response: Default::default(), + }; let (weight, extra_fee) = T::XcmDestWeightAndFee::get_operation_weight_and_fee( CurrencyId::to_token(&vtoken).map_err(|_| Error::::NoData)?, XcmOperationType::Vote, @@ -943,7 +1022,13 @@ pub mod pallet { } PendingVotingInfo::::insert( query_id, - (vtoken, poll_index, derivative_index, who.clone(), maybe_old_vote), + ( + vtoken, + poll_index, + derivative_index, + who.clone(), + maybe_old_vote, + ), ) }, )?; @@ -1035,11 +1120,16 @@ pub mod pallet { let para_id = T::ParachainId::get().into(); let asset = Asset { id: AssetId(Location::here()), - fun: Fungible(UniqueSaturatedInto::::unique_saturated_into(extra_fee)), + fun: Fungible(UniqueSaturatedInto::::unique_saturated_into( + extra_fee, + )), }; let xcm_message = sp_std::vec![ WithdrawAsset(asset.clone().into()), - BuyExecution { fees: asset, weight_limit: Unlimited }, + BuyExecution { + fees: asset, + weight_limit: Unlimited + }, Transact { origin_kind: OriginKind::SovereignAccount, require_weight_at_most: transact_weight, @@ -1067,7 +1157,10 @@ pub mod pallet { vote: AccountVote>, vtoken_balance: BalanceOf, ) -> Result< - (Option<(AccountVote>, BalanceOf)>, Option>>), + ( + Option<(AccountVote>, BalanceOf)>, + Option>>, + ), DispatchError, > { ensure!( @@ -1079,7 +1172,12 @@ pub mod pallet { Self::try_access_poll(vtoken, poll_index, |poll_status| { let tally = poll_status.ensure_ongoing().ok_or(Error::::NotOngoing)?; VotingForV2::::try_mutate(vtoken, who, |voting| { - if let Voting::Casting(Casting { ref mut votes, delegations, .. }) = voting { + if let Voting::Casting(Casting { + ref mut votes, + delegations, + .. + }) = voting + { match votes.binary_search_by_key(&poll_index, |i| i.0) { Ok(i) => { // Shouldn't be possible to fail, but we handle it gracefully. @@ -1091,7 +1189,7 @@ pub mod pallet { votes[i].1 = vote; votes[i].2 = 0; // Deprecated: derivative_index votes[i].3 = vtoken_balance; - }, + } Err(i) => { votes .try_insert( @@ -1100,7 +1198,7 @@ pub mod pallet { (poll_index, vote, 0, vtoken_balance), ) .map_err(|_| Error::::MaxVotesReached)?; - }, + } } // Shouldn't be possible to fail, but we handle it gracefully. tally.add(vote).ok_or(ArithmeticError::Overflow)?; @@ -1132,8 +1230,11 @@ pub mod pallet { scope: UnvoteScope, ) -> DispatchResult { VotingForV2::::try_mutate(vtoken, who, |voting| { - if let Voting::Casting(Casting { ref mut votes, delegations, ref mut prior }) = - voting + if let Voting::Casting(Casting { + ref mut votes, + delegations, + ref mut prior, + }) = voting { let i = votes .binary_search_by_key(&poll_index, |i| i.0) @@ -1149,7 +1250,7 @@ pub mod pallet { tally.reduce(approve, *delegations); } Ok(()) - }, + } PollStatus::Completed(end, approved) => { if let Some((lock_periods, _)) = v.1.locked_if(approved) { let unlock_at = end.saturating_add( @@ -1169,7 +1270,7 @@ pub mod pallet { } } Ok(()) - }, + } PollStatus::Killed(_) => Ok(()), // Poll was killed. PollStatus::None => Ok(()), // Poll was cancelled. }) @@ -1205,7 +1306,7 @@ pub mod pallet { all items in Vec associated with a unique class; \ qed" ); - }, + } } }); T::MultiCurrency::set_lock(CONVICTION_VOTING_ID, vtoken, who, lock_needed) @@ -1228,7 +1329,7 @@ pub mod pallet { all items in Vec associated with a unique class; \ qed" ); - }, + } } }); if amount.is_zero() { @@ -1239,7 +1340,10 @@ pub mod pallet { } fn ensure_vtoken(vtoken: &CurrencyIdOf) -> Result<(), DispatchError> { - ensure!(Self::supported_vtoken().contains(vtoken), Error::::VTokenNotSupport); + ensure!( + Self::supported_vtoken().contains(vtoken), + Error::::VTokenNotSupport + ); Ok(()) } @@ -1286,27 +1390,28 @@ pub mod pallet { let delegator_votes = DelegatorVotes::::get(vtoken, poll_index).into_inner(); let (_derivative_index, delegator_vote) = delegator_votes.first().ok_or(Error::::NoData)?; - match (ReferendumInfoFor::::get(vtoken, poll_index), delegator_vote.locked_if(true)) - { + match ( + ReferendumInfoFor::::get(vtoken, poll_index), + delegator_vote.locked_if(true), + ) { (Some(ReferendumInfo::Completed(moment)), Some((lock_periods, _balance))) => { let locking_period = VoteLockingPeriod::::get(vtoken).ok_or(Error::::NoData)?; let current_block = Self::get_agent_block_number(&vtoken)?; ensure!( - current_block >= - moment.saturating_add( - locking_period.saturating_mul(lock_periods.into()) - ), + current_block + >= moment + .saturating_add(locking_period.saturating_mul(lock_periods.into())), Error::::NotExpired ); Ok(()) - }, + } (Some(ReferendumInfo::Completed(moment)), None) => { let current_block = Self::get_agent_block_number(&vtoken)?; ensure!(current_block >= moment, Error::::NotExpired); Ok(()) - }, + } _ => Err(Error::::NotExpired.into()), } } @@ -1344,7 +1449,7 @@ pub mod pallet { ReferendumInfo::Ongoing(status), ); Ok(result) - }, + } Some(ReferendumInfo::Completed(end)) => f(PollStatus::Completed(end, false)), Some(ReferendumInfo::Killed(end)) => f(PollStatus::Killed(end)), _ => f(PollStatus::None), @@ -1379,9 +1484,12 @@ pub mod pallet { pub(crate) fn vote_to_capital(conviction: Conviction, vote: BalanceOf) -> BalanceOf { let capital = match conviction { - Conviction::None => - vote.checked_mul(&10u8.into()).unwrap_or_else(BalanceOf::::max_value), - x => vote.checked_div(&u8::from(x).into()).unwrap_or_else(Zero::zero), + Conviction::None => vote + .checked_mul(&10u8.into()) + .unwrap_or_else(BalanceOf::::max_value), + x => vote + .checked_div(&u8::from(x).into()) + .unwrap_or_else(Zero::zero), }; capital } @@ -1420,12 +1528,16 @@ pub mod pallet { let token = CurrencyId::to_token(&vtoken).map_err(|_| Error::::NoData)?; let mut delegator_votes = DelegatorVotes::::get(vtoken, poll_index).into_inner(); - let delegator_vote_keys = - delegator_votes.iter().map(|(index, _)| *index).collect::>(); + let delegator_vote_keys = delegator_votes + .iter() + .map(|(index, _)| *index) + .collect::>(); for derivative_index in Delegators::::get(vtoken) { if !delegator_vote_keys.contains(&derivative_index) { - delegator_votes - .push((derivative_index, AccountVote::>::from(vote_role))); + delegator_votes.push(( + derivative_index, + AccountVote::>::from(vote_role), + )); } } let data = delegator_votes @@ -1445,7 +1557,9 @@ pub mod pallet { return Ok(delegator_votes); } else { let account_vote = AccountVote::new_standard( - delegator_total_vote.as_standard_vote().ok_or(Error::::NoData)?, + delegator_total_vote + .as_standard_vote() + .ok_or(Error::::NoData)?, available_vote, ); delegator_votes.push((derivative_index, account_vote)); @@ -1497,11 +1611,12 @@ pub mod pallet { ) { for poll_index in referendum_timeout_list.iter() { ReferendumInfoFor::::mutate(vtoken, poll_index, |maybe_info| match maybe_info { - Some(info) => + Some(info) => { if let ReferendumInfo::Ongoing(_) = info { *info = ReferendumInfo::Completed(current_block_number); - }, - None => {}, + } + } + None => {} }); } ReferendumTimeoutV2::::remove(vtoken, time_out_block_number); diff --git a/pallets/vtoken-voting/src/migration.rs b/pallets/vtoken-voting/src/migration.rs index ce5a451fd2..6ee3955868 100644 --- a/pallets/vtoken-voting/src/migration.rs +++ b/pallets/vtoken-voting/src/migration.rs @@ -61,7 +61,10 @@ pub mod v2 { ValueQuery, >; - pub struct MigrateToV2(sp_std::marker::PhantomData, sp_std::marker::PhantomData); + pub struct MigrateToV2( + sp_std::marker::PhantomData, + sp_std::marker::PhantomData, + ); impl>> OnRuntimeUpgrade for MigrateToV2 { fn on_runtime_upgrade() -> Weight { if StorageVersion::get::>() < 2 { @@ -162,7 +165,10 @@ pub mod v3 { ValueQuery, >; - pub struct MigrateToV3(sp_std::marker::PhantomData, sp_std::marker::PhantomData); + pub struct MigrateToV3( + sp_std::marker::PhantomData, + sp_std::marker::PhantomData, + ); impl>> OnRuntimeUpgrade for MigrateToV3 { fn on_runtime_upgrade() -> Weight { if StorageVersion::get::>() == 2 { @@ -214,7 +220,10 @@ pub fn migrate_to_v3>>() -> Weight { ClassLocksFor::::translate::)>, _>( |_: T::AccountId, locks: Vec<(PollIndex, BalanceOf)>| { let max_locked_balance = locks.iter().fold(BalanceOf::::zero(), |a, i| a.max(i.1)); - log::info!("Migrated max_locked_balance for {:?}...", max_locked_balance); + log::info!( + "Migrated max_locked_balance for {:?}...", + max_locked_balance + ); weight += T::DbWeight::get().writes(1); Some(BoundedVec::try_from(vec![(vtoken, max_locked_balance)]).unwrap()) }, @@ -230,7 +239,10 @@ pub mod v4 { use frame_support::{pallet_prelude::StorageVersion, traits::OnRuntimeUpgrade}; use sp_runtime::traits::Get; - pub struct MigrateToV4(sp_std::marker::PhantomData, sp_std::marker::PhantomData); + pub struct MigrateToV4( + sp_std::marker::PhantomData, + sp_std::marker::PhantomData, + ); impl>> OnRuntimeUpgrade for MigrateToV4 { fn on_runtime_upgrade() -> Weight { if StorageVersion::get::>() == 3 { diff --git a/pallets/vtoken-voting/src/mocks/kusama_mock.rs b/pallets/vtoken-voting/src/mocks/kusama_mock.rs index 428788d4be..950ddec3ad 100644 --- a/pallets/vtoken-voting/src/mocks/kusama_mock.rs +++ b/pallets/vtoken-voting/src/mocks/kusama_mock.rs @@ -154,8 +154,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + } Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }; @@ -169,8 +170,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + } Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }?; @@ -191,7 +193,7 @@ impl Polling> for TestPolls { fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> { let mut polls = Polls::get(); match polls.get(&index) { - Some(Ongoing(..)) => {}, + Some(Ongoing(..)) => {} _ => return Err(()), } let now = frame_system::Pallet::::block_number(); @@ -451,7 +453,9 @@ impl vtoken_voting::Config for Runtime { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(ALICE, 10), (BOB, 20), (CHARLIE, 3000)], } diff --git a/pallets/vtoken-voting/src/mocks/polkadot_mock.rs b/pallets/vtoken-voting/src/mocks/polkadot_mock.rs index e5e4ace439..f1b62186bd 100644 --- a/pallets/vtoken-voting/src/mocks/polkadot_mock.rs +++ b/pallets/vtoken-voting/src/mocks/polkadot_mock.rs @@ -154,8 +154,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + } Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }; @@ -169,8 +170,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + } Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }?; @@ -191,7 +193,7 @@ impl Polling> for TestPolls { fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> { let mut polls = Polls::get(); match polls.get(&index) { - Some(Ongoing(..)) => {}, + Some(Ongoing(..)) => {} _ => return Err(()), } let now = frame_system::Pallet::::block_number(); @@ -451,7 +453,9 @@ impl vtoken_voting::Config for Runtime { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(ALICE, 10), (BOB, 20), (CHARLIE, 3000)], } diff --git a/pallets/vtoken-voting/src/tests/kusama_common_test.rs b/pallets/vtoken-voting/src/tests/kusama_common_test.rs index 2518ab06d6..f0b8bb7d4f 100644 --- a/pallets/vtoken-voting/src/tests/kusama_common_test.rs +++ b/pallets/vtoken-voting/src/tests/kusama_common_test.rs @@ -29,16 +29,32 @@ use frame_support::{ }; use pallet_xcm::Origin as XcmOrigin; -const TOKENS: &[CurrencyId] = if cfg!(feature = "kusama") { &[VKSM] } else { &[] }; +const TOKENS: &[CurrencyId] = if cfg!(feature = "kusama") { + &[VKSM] +} else { + &[] +}; fn aye(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: true, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } + let vote = Vote { + aye: true, + conviction: conviction.try_into().unwrap(), + }; + AccountVote::Standard { + vote, + balance: amount, + } } fn nay(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: false, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } + let vote = Vote { + aye: false, + conviction: conviction.try_into().unwrap(), + }; + AccountVote::Standard { + vote, + balance: amount, + } } fn tally(vtoken: CurrencyId, poll_index: u32) -> TallyOf { @@ -60,7 +76,9 @@ fn response_success() -> Response { } fn response_fail() -> Response { - Response::DispatchResult(MaybeErrorCode::Error(BoundedVec::try_from(vec![0u8, 1u8]).unwrap())) + Response::DispatchResult(MaybeErrorCode::Error( + BoundedVec::try_from(vec![0u8, 1u8]).unwrap(), + )) } #[test] @@ -83,9 +101,18 @@ fn basic_voting_works() { token_vote: aye(4, 5), delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 0, 0)); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); @@ -107,10 +134,19 @@ fn voting_balance_gets_locked() { nay(10, 0) )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 2, 0)); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 0, 0)); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); @@ -132,7 +168,11 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { aye(1, 1) )); assert_eq!(usable_balance(vtoken, &ALICE), 9); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, @@ -140,7 +180,11 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { aye(3, 1) )); assert_eq!(usable_balance(vtoken, &ALICE), 7); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(BOB), @@ -149,9 +193,17 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { nay(20, 0) )); assert_eq!(usable_balance(vtoken, &BOB), 0); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response_success() + )); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), vtoken, @@ -159,11 +211,19 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(BOB), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(BOB), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &BOB), 20); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); }); } @@ -187,14 +247,22 @@ fn unsuccessful_conviction_vote_balance_can_be_unlocked() { poll_index, aye(1, 1) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(BOB), vtoken, poll_index, nay(20, 0) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -203,7 +271,12 @@ fn unsuccessful_conviction_vote_balance_can_be_unlocked() { ReferendumInfoOf::::Completed(3), )); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); assert_eq!(usable_balance(vtoken, &ALICE), 10); }); @@ -229,14 +302,22 @@ fn ensure_balance_after_unlock() { poll_index, aye(10, 1) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, poll_index_2, aye(10, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -245,10 +326,17 @@ fn ensure_balance_after_unlock() { ReferendumInfoOf::::Completed(3), )); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 10); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); }); } } @@ -273,21 +361,33 @@ fn ensure_comprehensive_balance_after_unlock() { poll_index, aye(2, 1) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, poll_index_2, aye(1, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, poll_index_3, aye(2, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response_success() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -296,10 +396,17 @@ fn ensure_comprehensive_balance_after_unlock() { ReferendumInfoOf::::Completed(3), )); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 8); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 2); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 2); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 2 + ); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), @@ -307,11 +414,18 @@ fn ensure_comprehensive_balance_after_unlock() { poll_index_2, aye(10, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 3, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 3, + response_success() + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 10); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); }); } } @@ -334,7 +448,11 @@ fn successful_conviction_vote_balance_stays_locked_for_correct_time() { poll_index, aye(10, i as u8) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), i - 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + i - 1, + response_success() + )); } assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -344,7 +462,12 @@ fn successful_conviction_vote_balance_stays_locked_for_correct_time() { )); RelaychainDataProvider::set_block_number(163); for i in 1..=5 { - assert_ok!(VtokenVoting::try_remove_vote(&i, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &i, + vtoken, + poll_index, + UnvoteScope::Any + )); } for i in 1..=5 { assert_ok!(VtokenVoting::update_lock(&i, vtoken)); @@ -360,24 +483,51 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { new_test_ext().execute_with(|| { let response = response_success(); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 0, aye(5, 1))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 0, + aye(5, 1) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 5),]) .unwrap() ); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(10, 1))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(10, 1) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 10),]) .unwrap() ); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(5, 1))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(5, 1) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 5),]) @@ -385,8 +535,17 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); assert_eq!(usable_balance(vtoken, &ALICE), 5); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 2, aye(10, 2))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 3, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 2, + aye(10, 2) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 3, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 10),]) @@ -431,12 +590,22 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0), Error::::NoPermissionYet ); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); assert_eq!(usable_balance(vtoken, &ALICE), 0); RelaychainDataProvider::set_block_number(11); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0)); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 0 + )); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -445,7 +614,11 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); RelaychainDataProvider::set_block_number(11); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 1)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 1 + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -454,7 +627,11 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); RelaychainDataProvider::set_block_number(21); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 2)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 2 + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -470,14 +647,41 @@ fn removed_votes_when_referendum_killed() { new_test_ext().execute_with(|| { let response = response_success(); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 0, aye(5, 1))); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(10, 1))); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 2, aye(5, 2))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 0, + aye(5, 1) + )); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(10, 1) + )); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 2, + aye(5, 2) + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response.clone())); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response.clone())); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response.clone() + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response.clone() + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response.clone() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -498,9 +702,21 @@ fn removed_votes_when_referendum_killed() { ReferendumInfoOf::::Completed(1), )); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 0)); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 1)); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 2)); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 0 + )); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 1 + )); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 2 + )); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -508,7 +724,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 0 + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -516,7 +736,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 1)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 1 + )); assert_eq!(usable_balance(vtoken, &ALICE), 5); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -524,7 +748,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 2)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 2 + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -581,7 +809,11 @@ fn kill_referendum_works() { poll_index, ReferendumInfoOf::::Completed(1), )); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, poll_index)); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + poll_index + )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ReferendumKilled { vtoken, poll_index, @@ -820,7 +1052,11 @@ fn notify_vote_success_works() { delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); assert_eq!( ReferendumInfoFor::::get(vtoken, poll_index), Some(ReferendumInfo::Ongoing(ReferendumStatus { @@ -828,7 +1064,10 @@ fn notify_vote_success_works() { tally: TallyOf::::from_parts(20, 0, 4), })) ); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); assert_eq!( DelegatorVotes::::get(vtoken, poll_index), BoundedVec::<(DerivativeIndex, AccountVote), ConstU32<100>>::try_from( @@ -951,10 +1190,17 @@ fn notify_vote_fail_works() { delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); assert_eq!(ReferendumInfoFor::::get(vtoken, poll_index), None); assert_eq!(DelegatorVotes::::get(vtoken, poll_index).len(), 0); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ResponseReceived { responder: Parent.into(), query_id, @@ -970,7 +1216,11 @@ fn notify_vote_with_no_data_works() { let query_id = 0; let response = response_success(); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ResponseReceived { responder: Parent.into(), query_id, @@ -1011,7 +1261,11 @@ fn notify_remove_delegator_vote_success_works() { token_vote: aye(4, 5), delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); assert_eq!( DelegatorVotes::::get(vtoken, poll_index), BoundedVec::<(DerivativeIndex, AccountVote), ConstU32<100>>::try_from( @@ -1019,7 +1273,10 @@ fn notify_remove_delegator_vote_success_works() { ) .unwrap() ); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -1027,7 +1284,11 @@ fn notify_remove_delegator_vote_success_works() { poll_index, ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); RelaychainDataProvider::set_block_number(3); assert_ok!(VtokenVoting::remove_delegator_vote( @@ -1047,7 +1308,11 @@ fn notify_remove_delegator_vote_success_works() { )); assert_eq!(DelegatorVotes::::get(vtoken, poll_index).len(), 0); System::assert_has_event(RuntimeEvent::VtokenVoting( - Event::DelegatorVoteRemovedNotified { vtoken, poll_index, success: true }, + Event::DelegatorVoteRemovedNotified { + vtoken, + poll_index, + success: true, + }, )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ResponseReceived { responder: Parent.into(), @@ -1090,7 +1355,11 @@ fn notify_remove_delegator_vote_fail_works() { token_vote: aye(4, 5), delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response_success() + )); assert_eq!( DelegatorVotes::::get(vtoken, poll_index), BoundedVec::<(DerivativeIndex, AccountVote), ConstU32<100>>::try_from( @@ -1098,7 +1367,10 @@ fn notify_remove_delegator_vote_fail_works() { ) .unwrap() ); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -1106,7 +1378,11 @@ fn notify_remove_delegator_vote_fail_works() { poll_index, ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); RelaychainDataProvider::set_block_number(3); assert_ok!(VtokenVoting::remove_delegator_vote( @@ -1179,9 +1455,9 @@ fn on_idle_works() { count + UndecidingTimeout::::get(vtoken).unwrap(), ); let db_weight = RuntimeDbWeight { read: 1, write: 1 }; - let weight = db_weight.reads(3) + - db_weight.reads_writes(1, 2) * count + - db_weight.writes(2) * count; + let weight = db_weight.reads(3) + + db_weight.reads_writes(1, 2) * count + + db_weight.writes(2) * count; let used_weight = VtokenVoting::on_idle(Zero::zero(), weight); assert_eq!(used_weight, Weight::from_parts(0, 0)); @@ -1211,21 +1487,30 @@ fn set_vote_cap_ratio_works() { vtoken, Perbill::from_percent(0) )); - assert_eq!(VoteCapRatio::::get(vtoken), Perbill::from_percent(0)); + assert_eq!( + VoteCapRatio::::get(vtoken), + Perbill::from_percent(0) + ); assert_ok!(VtokenVoting::set_vote_cap_ratio( RuntimeOrigin::root(), vtoken, Perbill::from_percent(10) )); - assert_eq!(VoteCapRatio::::get(vtoken), Perbill::from_percent(10)); + assert_eq!( + VoteCapRatio::::get(vtoken), + Perbill::from_percent(10) + ); assert_ok!(VtokenVoting::set_vote_cap_ratio( RuntimeOrigin::root(), vtoken, Perbill::from_percent(100) )); - assert_eq!(VoteCapRatio::::get(vtoken), Perbill::from_percent(100)); + assert_eq!( + VoteCapRatio::::get(vtoken), + Perbill::from_percent(100) + ); }); } } @@ -1234,7 +1519,10 @@ fn set_vote_cap_ratio_works() { fn vote_cap_works() { for &vtoken in TOKENS { new_test_ext().execute_with(|| { - assert_eq!(VtokenVoting::vote_cap(vtoken), Ok((u64::MAX / 10) as Balance)); + assert_eq!( + VtokenVoting::vote_cap(vtoken), + Ok((u64::MAX / 10) as Balance) + ); }); } } @@ -1243,9 +1531,18 @@ fn vote_cap_works() { fn vote_to_capital_works() { new_test_ext().execute_with(|| { assert_eq!(VtokenVoting::vote_to_capital(Conviction::None, 300), 3000); - assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked1x, 300), 300); - assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked2x, 300), 150); - assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked3x, 300), 100); + assert_eq!( + VtokenVoting::vote_to_capital(Conviction::Locked1x, 300), + 300 + ); + assert_eq!( + VtokenVoting::vote_to_capital(Conviction::Locked2x, 300), + 150 + ); + assert_eq!( + VtokenVoting::vote_to_capital(Conviction::Locked3x, 300), + 100 + ); assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked4x, 300), 75); assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked5x, 300), 60); assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked6x, 300), 50); @@ -1469,7 +1766,10 @@ fn allocate_delegator_votes_works() { VtokenVoting::allocate_delegator_votes(vtoken, poll_index, vote); assert_eq!( delegator_votes, - Ok(vec![(0, aye(4294967295, conviction)), (1, aye(705032705, conviction))]) + Ok(vec![ + (0, aye(4294967295, conviction)), + (1, aye(705032705, conviction)) + ]) ); assert_eq!( delegator_votes diff --git a/pallets/vtoken-voting/src/tests/polkadot_common_test.rs b/pallets/vtoken-voting/src/tests/polkadot_common_test.rs index 4bde3a789d..fa124c6921 100644 --- a/pallets/vtoken-voting/src/tests/polkadot_common_test.rs +++ b/pallets/vtoken-voting/src/tests/polkadot_common_test.rs @@ -29,16 +29,32 @@ use frame_support::{ }; use pallet_xcm::Origin as XcmOrigin; -const TOKENS: &[CurrencyId] = if cfg!(feature = "polkadot") { &[VDOT] } else { &[] }; +const TOKENS: &[CurrencyId] = if cfg!(feature = "polkadot") { + &[VDOT] +} else { + &[] +}; fn aye(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: true, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } + let vote = Vote { + aye: true, + conviction: conviction.try_into().unwrap(), + }; + AccountVote::Standard { + vote, + balance: amount, + } } fn nay(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: false, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } + let vote = Vote { + aye: false, + conviction: conviction.try_into().unwrap(), + }; + AccountVote::Standard { + vote, + balance: amount, + } } fn tally(vtoken: CurrencyId, poll_index: u32) -> TallyOf { @@ -60,7 +76,9 @@ fn response_success() -> Response { } fn response_fail() -> Response { - Response::DispatchResult(MaybeErrorCode::Error(BoundedVec::try_from(vec![0u8, 1u8]).unwrap())) + Response::DispatchResult(MaybeErrorCode::Error( + BoundedVec::try_from(vec![0u8, 1u8]).unwrap(), + )) } #[test] @@ -83,9 +101,18 @@ fn basic_voting_works() { token_vote: aye(4, 5), delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 0, 0)); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); @@ -107,10 +134,19 @@ fn voting_balance_gets_locked() { nay(10, 0) )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 2, 0)); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 0, 0)); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); @@ -132,7 +168,11 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { aye(1, 1) )); assert_eq!(usable_balance(vtoken, &ALICE), 9); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, @@ -140,7 +180,11 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { aye(3, 1) )); assert_eq!(usable_balance(vtoken, &ALICE), 7); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(BOB), @@ -149,9 +193,17 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { nay(20, 0) )); assert_eq!(usable_balance(vtoken, &BOB), 0); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response_success() + )); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), vtoken, @@ -159,11 +211,19 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(BOB), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(BOB), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &BOB), 20); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); }); } @@ -187,14 +247,22 @@ fn unsuccessful_conviction_vote_balance_can_be_unlocked() { poll_index, aye(1, 1) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(BOB), vtoken, poll_index, nay(20, 0) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -203,7 +271,12 @@ fn unsuccessful_conviction_vote_balance_can_be_unlocked() { ReferendumInfoOf::::Completed(3), )); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); assert_eq!(usable_balance(vtoken, &ALICE), 10); }); @@ -229,14 +302,22 @@ fn ensure_balance_after_unlock() { poll_index, aye(10, 1) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, poll_index_2, aye(10, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -245,10 +326,17 @@ fn ensure_balance_after_unlock() { ReferendumInfoOf::::Completed(3), )); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 10); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); }); } } @@ -273,21 +361,33 @@ fn ensure_comprehensive_balance_after_unlock() { poll_index, aye(2, 1) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, poll_index_2, aye(1, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response_success() + )); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), vtoken, poll_index_3, aye(2, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response_success() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -296,10 +396,17 @@ fn ensure_comprehensive_balance_after_unlock() { ReferendumInfoOf::::Completed(3), )); RelaychainDataProvider::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 8); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 2); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 2); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 2 + ); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), @@ -307,11 +414,18 @@ fn ensure_comprehensive_balance_after_unlock() { poll_index_2, aye(10, 5) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 3, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 3, + response_success() + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 10); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); }); } } @@ -334,7 +448,11 @@ fn successful_conviction_vote_balance_stays_locked_for_correct_time() { poll_index, aye(10, i as u8) )); - assert_ok!(VtokenVoting::notify_vote(origin_response(), i - 1, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + i - 1, + response_success() + )); } assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -344,7 +462,12 @@ fn successful_conviction_vote_balance_stays_locked_for_correct_time() { )); RelaychainDataProvider::set_block_number(163); for i in 1..=5 { - assert_ok!(VtokenVoting::try_remove_vote(&i, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &i, + vtoken, + poll_index, + UnvoteScope::Any + )); } for i in 1..=5 { assert_ok!(VtokenVoting::update_lock(&i, vtoken)); @@ -360,24 +483,51 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { new_test_ext().execute_with(|| { let response = response_success(); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 0, aye(5, 1))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 0, + aye(5, 1) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 5),]) .unwrap() ); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(10, 1))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(10, 1) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 10),]) .unwrap() ); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(5, 1))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(5, 1) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 5),]) @@ -385,8 +535,17 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); assert_eq!(usable_balance(vtoken, &ALICE), 5); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 2, aye(10, 2))); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 3, response.clone())); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 2, + aye(10, 2) + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 3, + response.clone() + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 10),]) @@ -431,12 +590,22 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0), Error::::NoPermissionYet ); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); assert_eq!(usable_balance(vtoken, &ALICE), 0); RelaychainDataProvider::set_block_number(11); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0)); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 0 + )); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -445,7 +614,11 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); RelaychainDataProvider::set_block_number(11); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 1)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 1 + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -454,7 +627,11 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); RelaychainDataProvider::set_block_number(21); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 2)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 2 + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -470,14 +647,41 @@ fn removed_votes_when_referendum_killed() { new_test_ext().execute_with(|| { let response = response_success(); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 0, aye(5, 1))); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(10, 1))); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 2, aye(5, 2))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 0, + aye(5, 1) + )); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(10, 1) + )); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 2, + aye(5, 2) + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 0, response.clone())); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 1, response.clone())); - assert_ok!(VtokenVoting::notify_vote(origin_response(), 2, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 0, + response.clone() + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 1, + response.clone() + )); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + 2, + response.clone() + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -498,9 +702,21 @@ fn removed_votes_when_referendum_killed() { ReferendumInfoOf::::Completed(1), )); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 0)); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 1)); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 2)); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 0 + )); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 1 + )); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 2 + )); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -508,7 +724,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 0 + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -516,7 +736,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 1)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 1 + )); assert_eq!(usable_balance(vtoken, &ALICE), 5); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -524,7 +748,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 2)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 2 + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -581,7 +809,11 @@ fn kill_referendum_works() { poll_index, ReferendumInfoOf::::Completed(1), )); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, poll_index)); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + poll_index + )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ReferendumKilled { vtoken, poll_index, @@ -820,7 +1052,11 @@ fn notify_vote_success_works() { delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); assert_eq!( ReferendumInfoFor::::get(vtoken, poll_index), Some(ReferendumInfo::Ongoing(ReferendumStatus { @@ -828,7 +1064,10 @@ fn notify_vote_success_works() { tally: TallyOf::::from_parts(20, 0, 4), })) ); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); assert_eq!( DelegatorVotes::::get(vtoken, poll_index), BoundedVec::<(DerivativeIndex, AccountVote), ConstU32<100>>::try_from( @@ -951,10 +1190,17 @@ fn notify_vote_fail_works() { delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); assert_eq!(ReferendumInfoFor::::get(vtoken, poll_index), None); assert_eq!(DelegatorVotes::::get(vtoken, poll_index).len(), 0); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ResponseReceived { responder: Parent.into(), query_id, @@ -970,7 +1216,11 @@ fn notify_vote_with_no_data_works() { let query_id = 0; let response = response_success(); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ResponseReceived { responder: Parent.into(), query_id, @@ -1011,7 +1261,11 @@ fn notify_remove_delegator_vote_success_works() { token_vote: aye(4, 5), delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response.clone())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response.clone() + )); assert_eq!( DelegatorVotes::::get(vtoken, poll_index), BoundedVec::<(DerivativeIndex, AccountVote), ConstU32<100>>::try_from( @@ -1019,7 +1273,10 @@ fn notify_remove_delegator_vote_success_works() { ) .unwrap() ); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -1027,7 +1284,11 @@ fn notify_remove_delegator_vote_success_works() { poll_index, ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); RelaychainDataProvider::set_block_number(3); assert_ok!(VtokenVoting::remove_delegator_vote( @@ -1047,7 +1308,11 @@ fn notify_remove_delegator_vote_success_works() { )); assert_eq!(DelegatorVotes::::get(vtoken, poll_index).len(), 0); System::assert_has_event(RuntimeEvent::VtokenVoting( - Event::DelegatorVoteRemovedNotified { vtoken, poll_index, success: true }, + Event::DelegatorVoteRemovedNotified { + vtoken, + poll_index, + success: true, + }, )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ResponseReceived { responder: Parent.into(), @@ -1090,7 +1355,11 @@ fn notify_remove_delegator_vote_fail_works() { token_vote: aye(4, 5), delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::notify_vote(origin_response(), query_id, response_success())); + assert_ok!(VtokenVoting::notify_vote( + origin_response(), + query_id, + response_success() + )); assert_eq!( DelegatorVotes::::get(vtoken, poll_index), BoundedVec::<(DerivativeIndex, AccountVote), ConstU32<100>>::try_from( @@ -1098,7 +1367,10 @@ fn notify_remove_delegator_vote_fail_works() { ) .unwrap() ); - assert_eq!(PendingDelegatorVotes::::get(vtoken, poll_index).len(), 0); + assert_eq!( + PendingDelegatorVotes::::get(vtoken, poll_index).len(), + 0 + ); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), @@ -1106,7 +1378,11 @@ fn notify_remove_delegator_vote_fail_works() { poll_index, ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); RelaychainDataProvider::set_block_number(3); assert_ok!(VtokenVoting::remove_delegator_vote( @@ -1179,9 +1455,9 @@ fn on_idle_works() { count + UndecidingTimeout::::get(vtoken).unwrap(), ); let db_weight = RuntimeDbWeight { read: 1, write: 1 }; - let weight = db_weight.reads(3) + - db_weight.reads_writes(1, 2) * count + - db_weight.writes(2) * count; + let weight = db_weight.reads(3) + + db_weight.reads_writes(1, 2) * count + + db_weight.writes(2) * count; let used_weight = VtokenVoting::on_idle(Zero::zero(), weight); assert_eq!(used_weight, Weight::from_parts(0, 0)); @@ -1211,21 +1487,30 @@ fn set_vote_cap_ratio_works() { vtoken, Perbill::from_percent(0) )); - assert_eq!(VoteCapRatio::::get(vtoken), Perbill::from_percent(0)); + assert_eq!( + VoteCapRatio::::get(vtoken), + Perbill::from_percent(0) + ); assert_ok!(VtokenVoting::set_vote_cap_ratio( RuntimeOrigin::root(), vtoken, Perbill::from_percent(10) )); - assert_eq!(VoteCapRatio::::get(vtoken), Perbill::from_percent(10)); + assert_eq!( + VoteCapRatio::::get(vtoken), + Perbill::from_percent(10) + ); assert_ok!(VtokenVoting::set_vote_cap_ratio( RuntimeOrigin::root(), vtoken, Perbill::from_percent(100) )); - assert_eq!(VoteCapRatio::::get(vtoken), Perbill::from_percent(100)); + assert_eq!( + VoteCapRatio::::get(vtoken), + Perbill::from_percent(100) + ); }); } } @@ -1234,7 +1519,10 @@ fn set_vote_cap_ratio_works() { fn vote_cap_works() { for &vtoken in TOKENS { new_test_ext().execute_with(|| { - assert_eq!(VtokenVoting::vote_cap(vtoken), Ok((u64::MAX / 10) as Balance)); + assert_eq!( + VtokenVoting::vote_cap(vtoken), + Ok((u64::MAX / 10) as Balance) + ); }); } } @@ -1243,9 +1531,18 @@ fn vote_cap_works() { fn vote_to_capital_works() { new_test_ext().execute_with(|| { assert_eq!(VtokenVoting::vote_to_capital(Conviction::None, 300), 3000); - assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked1x, 300), 300); - assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked2x, 300), 150); - assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked3x, 300), 100); + assert_eq!( + VtokenVoting::vote_to_capital(Conviction::Locked1x, 300), + 300 + ); + assert_eq!( + VtokenVoting::vote_to_capital(Conviction::Locked2x, 300), + 150 + ); + assert_eq!( + VtokenVoting::vote_to_capital(Conviction::Locked3x, 300), + 100 + ); assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked4x, 300), 75); assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked5x, 300), 60); assert_eq!(VtokenVoting::vote_to_capital(Conviction::Locked6x, 300), 50); @@ -1469,7 +1766,10 @@ fn allocate_delegator_votes_works() { VtokenVoting::allocate_delegator_votes(vtoken, poll_index, vote); assert_eq!( delegator_votes, - Ok(vec![(0, aye(4294967295, conviction)), (1, aye(705032705, conviction))]) + Ok(vec![ + (0, aye(4294967295, conviction)), + (1, aye(705032705, conviction)) + ]) ); assert_eq!( delegator_votes diff --git a/pallets/vtoken-voting/src/tests/vbnc_test.rs b/pallets/vtoken-voting/src/tests/vbnc_test.rs index 94b8eaf307..7dbca4b6bc 100644 --- a/pallets/vtoken-voting/src/tests/vbnc_test.rs +++ b/pallets/vtoken-voting/src/tests/vbnc_test.rs @@ -27,16 +27,32 @@ use frame_support::{ }, }; -const TOKENS: &[CurrencyId] = if cfg!(feature = "polkadot") { &[VBNC] } else { &[] }; +const TOKENS: &[CurrencyId] = if cfg!(feature = "polkadot") { + &[VBNC] +} else { + &[] +}; fn aye(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: true, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } + let vote = Vote { + aye: true, + conviction: conviction.try_into().unwrap(), + }; + AccountVote::Standard { + vote, + balance: amount, + } } fn nay(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: false, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } + let vote = Vote { + aye: false, + conviction: conviction.try_into().unwrap(), + }; + AccountVote::Standard { + vote, + balance: amount, + } } fn tally(vtoken: CurrencyId, poll_index: u32) -> TallyOf { @@ -70,7 +86,12 @@ fn basic_voting_works() { delegator_vote: aye(200, 0), })); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 0, 0)); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); @@ -94,7 +115,12 @@ fn voting_balance_gets_locked() { assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 2, 0)); assert_eq!(usable_balance(vtoken, &ALICE), 0); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_eq!(tally(vtoken, poll_index), Tally::from_parts(0, 0, 0)); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); @@ -132,7 +158,11 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { )); assert_eq!(usable_balance(vtoken, &BOB), 0); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 10)); + assert_ok!(VtokenVoting::set_vote_locking_period( + RuntimeOrigin::root(), + vtoken, + 10 + )); assert_ok!(VtokenVoting::set_referendum_status( RuntimeOrigin::root(), vtoken, @@ -140,11 +170,19 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { ReferendumInfoOf::::Completed(3), )); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(BOB), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(BOB), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &BOB), 20); System::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); }); } @@ -182,7 +220,12 @@ fn unsuccessful_conviction_vote_balance_can_be_unlocked() { ReferendumInfoOf::::Completed(3), )); System::set_block_number(13); - assert_ok!(VtokenVoting::try_remove_vote(&ALICE, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &ALICE, + vtoken, + poll_index, + UnvoteScope::Any + )); assert_ok!(VtokenVoting::update_lock(&ALICE, vtoken)); assert_eq!(usable_balance(vtoken, &ALICE), 10); }); @@ -222,10 +265,17 @@ fn ensure_balance_after_unlock() { ReferendumInfoOf::::Completed(3), )); System::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 10); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); }); } } @@ -270,10 +320,17 @@ fn ensure_comprehensive_balance_after_unlock() { ReferendumInfoOf::::Completed(3), )); System::set_block_number(13); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, poll_index)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + poll_index + )); assert_eq!(usable_balance(vtoken, &ALICE), 8); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 2); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 2); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 2 + ); assert_ok!(VtokenVoting::vote( RuntimeOrigin::signed(ALICE), @@ -284,7 +341,10 @@ fn ensure_comprehensive_balance_after_unlock() { assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!(Tokens::accounts(&ALICE, vtoken).frozen, 10); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); }); } } @@ -316,7 +376,12 @@ fn successful_conviction_vote_balance_stays_locked_for_correct_time() { )); System::set_block_number(163); for i in 1..=5 { - assert_ok!(VtokenVoting::try_remove_vote(&i, vtoken, poll_index, UnvoteScope::Any)); + assert_ok!(VtokenVoting::try_remove_vote( + &i, + vtoken, + poll_index, + UnvoteScope::Any + )); } for i in 1..=5 { assert_ok!(VtokenVoting::update_lock(&i, vtoken)); @@ -330,21 +395,36 @@ fn successful_conviction_vote_balance_stays_locked_for_correct_time() { fn lock_amalgamation_valid_with_multiple_removed_votes() { for &vtoken in TOKENS { new_test_ext().execute_with(|| { - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 0, aye(5, 1))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 0, + aye(5, 1) + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 5),]) .unwrap() ); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(10, 1))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(10, 1) + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 10),]) .unwrap() ); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(5, 1))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(5, 1) + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 5),]) @@ -352,7 +432,12 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); assert_eq!(usable_balance(vtoken, &ALICE), 5); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 2, aye(10, 2))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 2, + aye(10, 2) + )); assert_eq!( ClassLocksFor::::get(&ALICE), BoundedVec::<(CurrencyId, u128), ConstU32<256>>::try_from(vec![(vtoken, 10),]) @@ -397,12 +482,22 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0), Error::::NoPermissionYet ); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); assert_eq!(usable_balance(vtoken, &ALICE), 0); System::set_block_number(11); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0)); - assert_eq!(VotingForV2::::get(vtoken, &ALICE).locked_balance(), 10); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 0 + )); + assert_eq!( + VotingForV2::::get(vtoken, &ALICE).locked_balance(), + 10 + ); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -411,7 +506,11 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); System::set_block_number(11); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 1)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 1 + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -420,7 +519,11 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { ); System::set_block_number(21); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 2)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 2 + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -434,9 +537,24 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { fn removed_votes_when_referendum_killed() { for &vtoken in TOKENS { new_test_ext().execute_with(|| { - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 0, aye(5, 1))); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 1, aye(10, 1))); - assert_ok!(VtokenVoting::vote(RuntimeOrigin::signed(ALICE), vtoken, 2, aye(5, 2))); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 0, + aye(5, 1) + )); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 1, + aye(10, 1) + )); + assert_ok!(VtokenVoting::vote( + RuntimeOrigin::signed(ALICE), + vtoken, + 2, + aye(5, 2) + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_ok!(VtokenVoting::set_referendum_status( @@ -458,9 +576,21 @@ fn removed_votes_when_referendum_killed() { ReferendumInfoOf::::Completed(1), )); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 0)); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 1)); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, 2)); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 0 + )); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 1 + )); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + 2 + )); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -468,7 +598,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 0)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 0 + )); assert_eq!(usable_balance(vtoken, &ALICE), 0); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -476,7 +610,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 1)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 1 + )); assert_eq!(usable_balance(vtoken, &ALICE), 5); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -484,7 +622,11 @@ fn removed_votes_when_referendum_killed() { .unwrap() ); - assert_ok!(VtokenVoting::unlock(RuntimeOrigin::signed(ALICE), vtoken, 2)); + assert_ok!(VtokenVoting::unlock( + RuntimeOrigin::signed(ALICE), + vtoken, + 2 + )); assert_eq!(usable_balance(vtoken, &ALICE), 10); assert_eq!( ClassLocksFor::::get(&ALICE), @@ -541,7 +683,11 @@ fn kill_referendum_works() { poll_index, ReferendumInfoOf::::Completed(1), )); - assert_ok!(VtokenVoting::kill_referendum(RuntimeOrigin::root(), vtoken, poll_index)); + assert_ok!(VtokenVoting::kill_referendum( + RuntimeOrigin::root(), + vtoken, + poll_index + )); System::assert_last_event(RuntimeEvent::VtokenVoting(Event::ReferendumKilled { vtoken, poll_index, @@ -793,7 +939,10 @@ fn allocate_delegator_votes_works() { VtokenVoting::allocate_delegator_votes(vtoken, poll_index, vote); assert_eq!( delegator_votes, - Ok(vec![(0, aye(4294967295, conviction)), (1, aye(705032705, conviction))]) + Ok(vec![ + (0, aye(4294967295, conviction)), + (1, aye(705032705, conviction)) + ]) ); assert_eq!( delegator_votes diff --git a/pallets/vtoken-voting/src/vote.rs b/pallets/vtoken-voting/src/vote.rs index f34984d7c8..a7968c8e95 100644 --- a/pallets/vtoken-voting/src/vote.rs +++ b/pallets/vtoken-voting/src/vote.rs @@ -73,8 +73,10 @@ pub enum VoteRole { impl From> for VoteRole { fn from(a: AccountVote) -> VoteRole { match a { - AccountVote::Standard { vote, balance: _ } => - VoteRole::Standard { aye: vote.aye, conviction: vote.conviction }, + AccountVote::Standard { vote, balance: _ } => VoteRole::Standard { + aye: vote.aye, + conviction: vote.conviction, + }, AccountVote::Split { .. } => VoteRole::Split, AccountVote::SplitAbstain { .. } => VoteRole::SplitAbstain, } @@ -84,9 +86,14 @@ impl From> for VoteRole { impl From for AccountVote { fn from(v: VoteRole) -> AccountVote { match v { - VoteRole::Standard { aye, conviction } => - AccountVote::Standard { vote: Vote { aye, conviction }, balance: Zero::zero() }, - VoteRole::Split => AccountVote::Split { aye: Zero::zero(), nay: Zero::zero() }, + VoteRole::Standard { aye, conviction } => AccountVote::Standard { + vote: Vote { aye, conviction }, + balance: Zero::zero(), + }, + VoteRole::Split => AccountVote::Split { + aye: Zero::zero(), + nay: Zero::zero(), + }, VoteRole::SplitAbstain => AccountVote::SplitAbstain { aye: Zero::zero(), nay: Zero::zero(), @@ -100,20 +107,62 @@ impl TryFrom for VoteRole { type Error = (); fn try_from(i: u8) -> Result { Ok(match i { - 0 => VoteRole::Standard { aye: true, conviction: Conviction::None }, - 1 => VoteRole::Standard { aye: true, conviction: Conviction::Locked1x }, - 2 => VoteRole::Standard { aye: true, conviction: Conviction::Locked2x }, - 3 => VoteRole::Standard { aye: true, conviction: Conviction::Locked3x }, - 4 => VoteRole::Standard { aye: true, conviction: Conviction::Locked4x }, - 5 => VoteRole::Standard { aye: true, conviction: Conviction::Locked5x }, - 6 => VoteRole::Standard { aye: true, conviction: Conviction::Locked6x }, - 10 => VoteRole::Standard { aye: false, conviction: Conviction::None }, - 11 => VoteRole::Standard { aye: false, conviction: Conviction::Locked1x }, - 12 => VoteRole::Standard { aye: false, conviction: Conviction::Locked2x }, - 13 => VoteRole::Standard { aye: false, conviction: Conviction::Locked3x }, - 14 => VoteRole::Standard { aye: false, conviction: Conviction::Locked4x }, - 15 => VoteRole::Standard { aye: false, conviction: Conviction::Locked5x }, - 16 => VoteRole::Standard { aye: false, conviction: Conviction::Locked6x }, + 0 => VoteRole::Standard { + aye: true, + conviction: Conviction::None, + }, + 1 => VoteRole::Standard { + aye: true, + conviction: Conviction::Locked1x, + }, + 2 => VoteRole::Standard { + aye: true, + conviction: Conviction::Locked2x, + }, + 3 => VoteRole::Standard { + aye: true, + conviction: Conviction::Locked3x, + }, + 4 => VoteRole::Standard { + aye: true, + conviction: Conviction::Locked4x, + }, + 5 => VoteRole::Standard { + aye: true, + conviction: Conviction::Locked5x, + }, + 6 => VoteRole::Standard { + aye: true, + conviction: Conviction::Locked6x, + }, + 10 => VoteRole::Standard { + aye: false, + conviction: Conviction::None, + }, + 11 => VoteRole::Standard { + aye: false, + conviction: Conviction::Locked1x, + }, + 12 => VoteRole::Standard { + aye: false, + conviction: Conviction::Locked2x, + }, + 13 => VoteRole::Standard { + aye: false, + conviction: Conviction::Locked3x, + }, + 14 => VoteRole::Standard { + aye: false, + conviction: Conviction::Locked4x, + }, + 15 => VoteRole::Standard { + aye: false, + conviction: Conviction::Locked5x, + }, + 16 => VoteRole::Standard { + aye: false, + conviction: Conviction::Locked6x, + }, 20 => VoteRole::Split, 21 => VoteRole::SplitAbstain, _ => return Err(()), @@ -148,7 +197,11 @@ pub enum AccountVote { /// A split vote with balances given for both ways as well as abstentions, and with no /// conviction, useful for parachains when voting, other off-chain aggregate accounts and /// individuals who wish to abstain. - SplitAbstain { aye: Balance, nay: Balance, abstain: Balance }, + SplitAbstain { + aye: Balance, + nay: Balance, + abstain: Balance, + }, } impl AccountVote { @@ -180,8 +233,9 @@ impl AccountVote { match self { AccountVote::Standard { balance, .. } => balance, AccountVote::Split { aye, nay } => aye.saturating_add(nay), - AccountVote::SplitAbstain { aye, nay, abstain } => - aye.saturating_add(nay).saturating_add(abstain), + AccountVote::SplitAbstain { aye, nay, abstain } => { + aye.saturating_add(nay).saturating_add(abstain) + } } } @@ -200,21 +254,35 @@ impl AccountVote { { match (self, vote) { ( - AccountVote::Standard { vote: v1, balance: b1 }, - AccountVote::Standard { vote: v2, balance: b2 }, + AccountVote::Standard { + vote: v1, + balance: b1, + }, + AccountVote::Standard { + vote: v2, + balance: b2, + }, ) if *v1 == v2 => b1.saturating_accrue(b2), (AccountVote::Split { aye: a1, nay: n1 }, AccountVote::Split { aye: a2, nay: n2 }) => { a1.saturating_accrue(a2); n1.saturating_accrue(n2); - }, + } ( - AccountVote::SplitAbstain { aye: a1, nay: n1, abstain: ab1 }, - AccountVote::SplitAbstain { aye: a2, nay: n2, abstain: ab2 }, + AccountVote::SplitAbstain { + aye: a1, + nay: n1, + abstain: ab1, + }, + AccountVote::SplitAbstain { + aye: a2, + nay: n2, + abstain: ab2, + }, ) => { a1.saturating_accrue(a2); n1.saturating_accrue(n2); ab1.saturating_accrue(ab2); - }, + } _ => return Err(()), } Ok(()) @@ -226,21 +294,35 @@ impl AccountVote { { match (self, vote) { ( - AccountVote::Standard { vote: v1, balance: b1 }, - AccountVote::Standard { vote: v2, balance: b2 }, + AccountVote::Standard { + vote: v1, + balance: b1, + }, + AccountVote::Standard { + vote: v2, + balance: b2, + }, ) if *v1 == v2 => b1.saturating_reduce(b2), (AccountVote::Split { aye: a1, nay: n1 }, AccountVote::Split { aye: a2, nay: n2 }) => { a1.saturating_reduce(a2); n1.saturating_reduce(n2); - }, + } ( - AccountVote::SplitAbstain { aye: a1, nay: n1, abstain: ab1 }, - AccountVote::SplitAbstain { aye: a2, nay: n2, abstain: ab2 }, + AccountVote::SplitAbstain { + aye: a1, + nay: n1, + abstain: ab1, + }, + AccountVote::SplitAbstain { + aye: a2, + nay: n2, + abstain: ab2, + }, ) => { a1.saturating_reduce(a2); n1.saturating_reduce(n2); ab1.saturating_reduce(ab2); - }, + } _ => return Err(()), } Ok(()) @@ -251,16 +333,23 @@ impl AccountVote { Balance: Copy + EnsureMulAssign, { match self { - AccountVote::Standard { vote: _, balance: b1 } => b1.ensure_mul_assign(balance)?, + AccountVote::Standard { + vote: _, + balance: b1, + } => b1.ensure_mul_assign(balance)?, AccountVote::Split { aye: a1, nay: n1 } => { a1.ensure_mul_assign(balance)?; n1.ensure_mul_assign(balance)?; - }, - AccountVote::SplitAbstain { aye: a1, nay: n1, abstain: ab1 } => { + } + AccountVote::SplitAbstain { + aye: a1, + nay: n1, + abstain: ab1, + } => { a1.ensure_mul_assign(balance)?; n1.ensure_mul_assign(balance)?; ab1.ensure_mul_assign(balance)?; - }, + } } Ok(()) } @@ -270,16 +359,23 @@ impl AccountVote { Balance: Copy + EnsureDivAssign, { match self { - AccountVote::Standard { vote: _, balance: b1 } => b1.ensure_div_assign(balance)?, + AccountVote::Standard { + vote: _, + balance: b1, + } => b1.ensure_div_assign(balance)?, AccountVote::Split { aye: a1, nay: n1 } => { a1.ensure_div_assign(balance)?; n1.ensure_div_assign(balance)?; - }, - AccountVote::SplitAbstain { aye: a1, nay: n1, abstain: ab1 } => { + } + AccountVote::SplitAbstain { + aye: a1, + nay: n1, + abstain: ab1, + } => { a1.ensure_div_assign(balance)?; n1.ensure_div_assign(balance)?; ab1.ensure_div_assign(balance)?; - }, + } } Ok(()) } @@ -414,16 +510,20 @@ where /// The amount of this account's balance that must currently be locked due to voting. pub fn locked_balance(&self) -> Balance { match self { - Voting::Casting(Casting { votes, prior, .. }) => - votes.iter().map(|i| i.3).fold(prior.locked(), |a, i| a.max(i)), + Voting::Casting(Casting { votes, prior, .. }) => votes + .iter() + .map(|i| i.3) + .fold(prior.locked(), |a, i| a.max(i)), Voting::Delegating(Delegating { balance, prior, .. }) => *balance.max(&prior.locked()), } } pub fn locked_vtoken_balance(&self) -> Balance { match self { - Voting::Casting(Casting { votes, .. }) => - votes.iter().map(|i| i.3).fold(Zero::zero(), |a, i| a.max(i)), + Voting::Casting(Casting { votes, .. }) => votes + .iter() + .map(|i| i.3) + .fold(Zero::zero(), |a, i| a.max(i)), Voting::Delegating(Delegating { .. }) => Zero::zero(), } } @@ -434,10 +534,16 @@ where prior: PriorLock, ) { let (d, p) = match self { - Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) => - (delegations, prior), - Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) => - (delegations, prior), + Voting::Casting(Casting { + ref mut delegations, + ref mut prior, + .. + }) => (delegations, prior), + Voting::Delegating(Delegating { + ref mut delegations, + ref mut prior, + .. + }) => (delegations, prior), }; *d = delegations; *p = prior; @@ -500,12 +606,18 @@ impl< pub fn account_vote(&self, conviction: Conviction) -> AccountVote { if self.ayes >= self.nays { AccountVote::Standard { - vote: Vote { aye: true, conviction }, + vote: Vote { + aye: true, + conviction, + }, balance: self.ayes - self.nays, } } else { AccountVote::Standard { - vote: Vote { aye: false, conviction }, + vote: Vote { + aye: false, + conviction, + }, balance: self.nays - self.ayes, } } @@ -520,26 +632,28 @@ impl< true => { self.support = self.support.checked_add(&capital)?; self.ayes = self.ayes.checked_add(&votes)? - }, + } false => self.nays = self.nays.checked_add(&votes)?, } - }, + } AccountVote::Split { aye, nay } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); self.support = self.support.checked_add(&aye.capital)?; self.ayes = self.ayes.checked_add(&aye.votes)?; self.nays = self.nays.checked_add(&nay.votes)?; - }, + } AccountVote::SplitAbstain { aye, nay, abstain } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); let abstain = Conviction::None.votes(abstain); - self.support = - self.support.checked_add(&aye.capital)?.checked_add(&abstain.capital)?; + self.support = self + .support + .checked_add(&aye.capital)? + .checked_add(&abstain.capital)?; self.ayes = self.ayes.checked_add(&aye.votes)?; self.nays = self.nays.checked_add(&nay.votes)?; - }, + } } Some(()) } @@ -553,26 +667,28 @@ impl< true => { self.support = self.support.checked_sub(&capital)?; self.ayes = self.ayes.checked_sub(&votes)? - }, + } false => self.nays = self.nays.checked_sub(&votes)?, } - }, + } AccountVote::Split { aye, nay } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); self.support = self.support.checked_sub(&aye.capital)?; self.ayes = self.ayes.checked_sub(&aye.votes)?; self.nays = self.nays.checked_sub(&nay.votes)?; - }, + } AccountVote::SplitAbstain { aye, nay, abstain } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); let abstain = Conviction::None.votes(abstain); - self.support = - self.support.checked_sub(&aye.capital)?.checked_sub(&abstain.capital)?; + self.support = self + .support + .checked_sub(&aye.capital)? + .checked_sub(&abstain.capital)?; self.ayes = self.ayes.checked_sub(&aye.votes)?; self.nays = self.nays.checked_sub(&nay.votes)?; - }, + } } Some(()) } @@ -583,7 +699,7 @@ impl< true => { self.support = self.support.saturating_add(delegations.capital); self.ayes = self.ayes.saturating_add(delegations.votes); - }, + } false => self.nays = self.nays.saturating_add(delegations.votes), } } @@ -594,7 +710,7 @@ impl< true => { self.support = self.support.saturating_sub(delegations.capital); self.ayes = self.ayes.saturating_sub(delegations.votes); - }, + } false => self.nays = self.nays.saturating_sub(delegations.votes), } } diff --git a/pallets/xcm-interface/Cargo.toml b/pallets/xcm-interface/Cargo.toml index 4ee81ed999..1df6d39651 100644 --- a/pallets/xcm-interface/Cargo.toml +++ b/pallets/xcm-interface/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-xcm-interface" version = "0.8.0" -authors = ["Ron yang"] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/pallets/xcm-interface/src/lib.rs b/pallets/xcm-interface/src/lib.rs index 1dbc6bba5f..8d949428bb 100644 --- a/pallets/xcm-interface/src/lib.rs +++ b/pallets/xcm-interface/src/lib.rs @@ -191,7 +191,10 @@ pub mod pallet { Box::new( Location::new( 0, - [AccountKey20 { network: None, key: to.to_fixed_bytes() }], + [AccountKey20 { + network: None, + key: to.to_fixed_bytes(), + }], ) .into(), ), @@ -204,7 +207,10 @@ pub mod pallet { let remote_xcm = Xcm(vec![ WithdrawAsset(fee.clone().into()), - BuyExecution { fees: fee.clone(), weight_limit: Unlimited }, + BuyExecution { + fees: fee.clone(), + weight_limit: Unlimited, + }, Transact { origin_kind: OriginKind::SovereignAccount, require_weight_at_most, diff --git a/pallets/xcm-interface/src/mock.rs b/pallets/xcm-interface/src/mock.rs index 34c94cfcfb..25c4aa126d 100644 --- a/pallets/xcm-interface/src/mock.rs +++ b/pallets/xcm-interface/src/mock.rs @@ -153,5 +153,8 @@ impl xcm_interface::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::::default().build_storage().unwrap().into() + system::GenesisConfig::::default() + .build_storage() + .unwrap() + .into() } diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 93e60be9f8..5642c2e8e0 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-primitives" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/primitives/src/currency.rs b/primitives/src/currency.rs index 6f8f76b421..5dcb8b20b7 100644 --- a/primitives/src/currency.rs +++ b/primitives/src/currency.rs @@ -80,6 +80,7 @@ pub const PEN_TOKEN_ID: u8 = 12u8; pub const PEN: CurrencyId = CurrencyId::Token2(PEN_TOKEN_ID); pub const WETH_TOKEN_ID: u8 = 13u8; pub const WETH: CurrencyId = CurrencyId::Token2(WETH_TOKEN_ID); +pub const V_WETH: CurrencyId = CurrencyId::VToken2(WETH_TOKEN_ID); pub const VSBOND_BNC_2001_0_8: CurrencyId = CurrencyId::VSBond(TokenSymbol::BNC, 2001, 0, 8); pub const CLOUD_TOKEN_ID: u8 = 12u8; pub const CLOUD: CurrencyId = CurrencyId::Token2(CLOUD_TOKEN_ID); @@ -92,12 +93,21 @@ pub const LUSDT: CurrencyId = CurrencyId::Lend(2); pub const LVDOT: CurrencyId = CurrencyId::Lend(3); pub const BLP_BNC_VBNC: CurrencyId = CurrencyId::BLP(2); pub const LP_BNC_VBNC: CurrencyId = CurrencyId::LPToken(TokenSymbol::ASG, 0, TokenSymbol::BNC, 1); -pub const KUSAMA_VBNC_ASSET_INDEX: AssetId = - AssetId { chain_id: 2001, asset_type: 2, asset_index: 257 }; -pub const KUSAMA_VBNC_LP_ASSET_INDEX: AssetId = - AssetId { chain_id: 2001, asset_type: 2, asset_index: 1103806596608 }; -pub const KUSAMA_BNC_ASSET_INDEX: AssetId = - AssetId { chain_id: 2001, asset_type: 0, asset_index: 0 }; +pub const KUSAMA_VBNC_ASSET_INDEX: AssetId = AssetId { + chain_id: 2001, + asset_type: 2, + asset_index: 257, +}; +pub const KUSAMA_VBNC_LP_ASSET_INDEX: AssetId = AssetId { + chain_id: 2001, + asset_type: 2, + asset_index: 1103806596608, +}; +pub const KUSAMA_BNC_ASSET_INDEX: AssetId = AssetId { + chain_id: 2001, + asset_type: 0, + asset_index: 0, +}; macro_rules! create_currency_id { ($(#[$meta:meta])* @@ -352,8 +362,9 @@ impl CurrencyId { let vsbond_origin = CurrencyId::VSBond(symbol, index, first_slot, last_slot); let vsbond_fixed = match vsbond_origin { - Self::VSBond(TokenSymbol::KSM, 2001, 13, 20) => - Self::VSBond(TokenSymbol::BNC, 2001, 13, 20), + Self::VSBond(TokenSymbol::KSM, 2001, 13, 20) => { + Self::VSBond(TokenSymbol::BNC, 2001, 13, 20) + } _ => vsbond_origin, }; @@ -455,28 +466,33 @@ impl TryFrom for CurrencyId { let token_symbol_1 = TokenSymbol::try_from(token_symbol_num_1).unwrap_or_default(); let token_symbol_2 = TokenSymbol::try_from(token_symbol_num_2).unwrap_or_default(); - Ok(Self::LPToken(token_symbol_1, token_type_1, token_symbol_2, token_type_2)) - }, + Ok(Self::LPToken( + token_symbol_1, + token_type_1, + token_symbol_2, + token_type_2, + )) + } 7 => { let foreign_asset_id = ((id & 0x0000_ffff_ffff_0000) >> 16) as ForeignAssetId; Ok(Self::ForeignAsset(foreign_asset_id)) - }, + } 8 => { let token_id = t_discr as TokenId; Ok(Self::Token2(token_id)) - }, + } 9 => { let token_id = t_discr as TokenId; Ok(Self::VToken2(token_id)) - }, + } 10 => { let token_id = t_discr as TokenId; Ok(Self::VSToken2(token_id)) - }, + } 11 => { let token_id = t_discr as TokenId; Ok(Self::VSBond2(token_id, pid, lp1, lp2)) - }, + } _ => Err(()), } } diff --git a/primitives/src/evm.rs b/primitives/src/evm.rs new file mode 100644 index 0000000000..0489bdf6a8 --- /dev/null +++ b/primitives/src/evm.rs @@ -0,0 +1,82 @@ +use frame_support::dispatch::{DispatchResult, DispatchResultWithPostInfo, PostDispatchInfo}; +use sp_core::{H160, H256, U256}; +use sp_std::vec::Vec; +use xcm::latest::Weight; + +pub trait EvmPermit { + fn validate_permit( + source: H160, + target: H160, + data: Vec, + value: U256, + gas_limit: u64, + deadline: U256, + v: u8, + r: H256, + s: H256, + ) -> DispatchResult; + + fn dispatch_permit( + source: H160, + target: H160, + data: Vec, + value: U256, + gas_limit: u64, + max_fee_per_gas: U256, + max_priority_fee_per_gas: Option, + nonce: Option, + access_list: Vec<(H160, Vec)>, + ) -> DispatchResultWithPostInfo; + + fn gas_price() -> (U256, Weight); + + fn dispatch_weight(gas_limit: u64) -> Weight; + + fn permit_nonce(account: H160) -> U256; + + fn on_dispatch_permit_error(); +} + +impl EvmPermit for () { + fn validate_permit( + _source: H160, + _target: H160, + _data: Vec, + _value: U256, + _gas_limit: u64, + _deadline: U256, + _v: u8, + _r: H256, + _s: H256, + ) -> DispatchResult { + Ok(()) + } + + fn dispatch_permit( + _source: H160, + _target: H160, + _data: Vec, + _value: U256, + _gas_limit: u64, + _max_fee_per_gas: U256, + _max_priority_fee_per_gas: Option, + _nonce: Option, + _access_list: Vec<(H160, Vec)>, + ) -> DispatchResultWithPostInfo { + Ok(PostDispatchInfo::default()) + } + + fn gas_price() -> (U256, Weight) { + Default::default() + } + + fn dispatch_weight(_gas_limit: u64) -> Weight { + Weight::zero() + } + + fn permit_nonce(_account: H160) -> U256 { + U256::default() + } + + fn on_dispatch_permit_error() {} +} diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index b114b3912c..fb04d8768e 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -46,6 +46,8 @@ pub mod traits; pub use crate::traits::*; pub mod time_unit; pub use crate::time_unit::*; +pub mod evm; +pub use crate::evm::*; #[cfg(test)] mod tests; diff --git a/primitives/src/mock_xcm.rs b/primitives/src/mock_xcm.rs index a52dda5438..35eac6edf9 100644 --- a/primitives/src/mock_xcm.rs +++ b/primitives/src/mock_xcm.rs @@ -50,7 +50,10 @@ impl XcmTransfer for MockXcmTransfer { Ok(Transferred { sender: who, assets: Default::default(), - fee: Asset { id: AssetId(Location::here()), fun: Fungible(amount) }, + fee: Asset { + id: AssetId(Location::here()), + fun: Fungible(amount), + }, dest, }) } @@ -127,7 +130,9 @@ impl ExecuteXcm for MockXcmExecutor { _hash: &mut XcmHash, _weight_credit: Weight, ) -> Outcome { - Outcome::Complete { used: Weight::default() } + Outcome::Complete { + used: Weight::default(), + } } fn charge_fees(_location: impl Into, _fees: Assets) -> XcmResult { diff --git a/primitives/src/tests.rs b/primitives/src/tests.rs index 49b9648693..72150960a3 100644 --- a/primitives/src/tests.rs +++ b/primitives/src/tests.rs @@ -214,14 +214,23 @@ fn to_vtoken_should_work() { let stable_lp_token = CurrencyId::StableLpToken(100); let lp_token = CurrencyId::LPToken(TokenSymbol::BNC, 0, TokenSymbol::KSM, 2); - assert_eq!(native_bnc.to_vtoken(), Ok(CurrencyId::VToken(TokenSymbol::BNC))); + assert_eq!( + native_bnc.to_vtoken(), + Ok(CurrencyId::VToken(TokenSymbol::BNC)) + ); assert_eq!(native_asg.to_vtoken(), Err(())); assert_eq!(vtoken_ksm.to_vtoken(), Err(())); - assert_eq!(token_ksm.to_vtoken(), Ok(CurrencyId::VToken(TokenSymbol::KSM))); + assert_eq!( + token_ksm.to_vtoken(), + Ok(CurrencyId::VToken(TokenSymbol::KSM)) + ); assert_eq!(stable_kusd.to_vtoken(), Err(())); assert_eq!(vstoken_eth.to_vtoken(), Err(())); assert_eq!(vsbond_ksm.to_vtoken(), Err(())); - assert_eq!(token2_dot.to_vtoken(), Ok(CurrencyId::VToken2(DOT_TOKEN_ID))); + assert_eq!( + token2_dot.to_vtoken(), + Ok(CurrencyId::VToken2(DOT_TOKEN_ID)) + ); assert_eq!(vtoken2_dot.to_vtoken(), Err(())); assert_eq!(vstoken2_dot.to_vtoken(), Err(())); assert_eq!(vsbond2_dot.to_vtoken(), Err(())); @@ -250,8 +259,14 @@ fn to_token_should_work() { let lp_token = CurrencyId::LPToken(TokenSymbol::BNC, 0, TokenSymbol::KSM, 2); assert_eq!(native_bnc.to_token(), Err(())); - assert_eq!(vtoken_bnc.to_token(), Ok(CurrencyId::Native(TokenSymbol::BNC))); - assert_eq!(vtoken_ksm.to_token(), Ok(CurrencyId::Token(TokenSymbol::KSM))); + assert_eq!( + vtoken_bnc.to_token(), + Ok(CurrencyId::Native(TokenSymbol::BNC)) + ); + assert_eq!( + vtoken_ksm.to_token(), + Ok(CurrencyId::Token(TokenSymbol::KSM)) + ); assert_eq!(token_ksm.to_token(), Err(())); assert_eq!(stable_kusd.to_token(), Err(())); assert_eq!(vstoken_eth.to_token(), Err(())); diff --git a/primitives/src/time_unit.rs b/primitives/src/time_unit.rs index bf2242bc1a..34cf1f5a7b 100644 --- a/primitives/src/time_unit.rs +++ b/primitives/src/time_unit.rs @@ -51,11 +51,13 @@ impl TimeUnit { pub fn add(self, other_time: Self) -> Option { match (self, other_time) { (TimeUnit::Era(a), TimeUnit::Era(b)) => Some(TimeUnit::Era(a.saturating_add(b))), - (TimeUnit::SlashingSpan(a), TimeUnit::SlashingSpan(b)) => - Some(TimeUnit::SlashingSpan(a.saturating_add(b))), + (TimeUnit::SlashingSpan(a), TimeUnit::SlashingSpan(b)) => { + Some(TimeUnit::SlashingSpan(a.saturating_add(b))) + } (TimeUnit::Round(a), TimeUnit::Round(b)) => Some(TimeUnit::Round(a.saturating_add(b))), - (TimeUnit::Kblock(a), TimeUnit::Kblock(b)) => - Some(TimeUnit::Kblock(a.saturating_add(b))), + (TimeUnit::Kblock(a), TimeUnit::Kblock(b)) => { + Some(TimeUnit::Kblock(a.saturating_add(b))) + } (TimeUnit::Hour(a), TimeUnit::Hour(b)) => Some(TimeUnit::Hour(a.saturating_add(b))), _ => None, } diff --git a/primitives/src/traits.rs b/primitives/src/traits.rs index b29a588bf4..5849e6e629 100644 --- a/primitives/src/traits.rs +++ b/primitives/src/traits.rs @@ -230,9 +230,11 @@ impl CurrencyIdRegister for () { } /// The interface to call farming pallet functions. -pub trait FarmingInfo { +pub trait FarmingInfo { /// Get the currency token shares. fn get_token_shares(pool_id: PoolId, currency_id: CurrencyId) -> Balance; + /// Update the token shares for the gauge pool. + fn refresh_gauge_pool(exchanger: &AccountId) -> DispatchResult; } pub trait VtokenMintingInterface { @@ -498,3 +500,14 @@ pub trait BalanceCmp { amount_precision: u32, ) -> Result; } + +impl FarmingInfo for () { + /// Get the currency token shares. + fn get_token_shares(_pool_id: PoolId, _currency_id: CurrencyId) -> Balance { + Zero::zero() + } + /// Update the token shares for the gauge pool. + fn refresh_gauge_pool(_exchanger: &AccountId) -> DispatchResult { + Ok(()) + } +} diff --git a/primitives/src/xcm.rs b/primitives/src/xcm.rs index 4bdfd87005..1e7fa85634 100644 --- a/primitives/src/xcm.rs +++ b/primitives/src/xcm.rs @@ -82,8 +82,8 @@ where { fn contains(asset: &Asset, origin: &Location) -> bool { let loc = Origin::get(); - &loc == origin && - matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } + &loc == origin + && matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } if asset_loc.starts_with(&Prefix::get())) } } @@ -93,8 +93,8 @@ pub struct NativeAssetFrom(PhantomData); impl> ContainsPair for NativeAssetFrom { fn contains(asset: &Asset, origin: &Location) -> bool { let loc = T::get(); - &loc == origin && - matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } + &loc == origin + && matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } if *asset_loc == Location::from(Parent)) } } @@ -103,7 +103,13 @@ impl> ContainsPair for NativeAssetFrom { pub struct AccountIdToLocation; impl Convert for AccountIdToLocation { fn convert(account: AccountId) -> Location { - Location::new(0, [AccountId32 { network: None, id: account.into() }]) + Location::new( + 0, + [AccountId32 { + network: None, + id: account.into(), + }], + ) } } @@ -122,7 +128,16 @@ mod test { fn bifrost_account_to_location() { let account: AccountId = AccountId::new([0u8; 32]); let location: Location = AccountIdToLocation::convert(account); - assert_eq!(location, Location::new(0, [AccountId32 { network: None, id: [0u8; 32] }])); + assert_eq!( + location, + Location::new( + 0, + [AccountId32 { + network: None, + id: [0u8; 32] + }] + ) + ); } #[test] diff --git a/runtime/bifrost-kusama/Cargo.toml b/runtime/bifrost-kusama/Cargo.toml index f5b09216eb..8b7c0c63ea 100644 --- a/runtime/bifrost-kusama/Cargo.toml +++ b/runtime/bifrost-kusama/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-kusama-runtime" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" build = "build.rs" @@ -61,6 +61,7 @@ sp-arithmetic = { workspace = true } sp-block-builder = { workspace = true } sp-consensus-aura = { workspace = true } sp-core = { workspace = true } +sp-debug-derive = { workspace = true } sp-inherents = { workspace = true } sp-io = { workspace = true } sp-offchain = { workspace = true } @@ -93,7 +94,7 @@ polkadot-runtime-common = { workspace = true } xcm = { workspace = true } xcm-builder = { workspace = true } xcm-executor = { workspace = true } -xcm-fee-payment-runtime-api = { workspace = true } +xcm-runtime-apis = { workspace = true } # orml orml-tokens = { workspace = true } @@ -132,7 +133,6 @@ bifrost-slp = { workspace = true } bifrost-slpx = { workspace = true } bifrost-stable-pool = { workspace = true } bifrost-stable-pool-rpc-runtime-api = { workspace = true } -bifrost-system-maker = { workspace = true } bifrost-system-staking = { workspace = true } bifrost-token-issuer = { workspace = true } bifrost-vesting = { workspace = true } @@ -200,6 +200,7 @@ std = [ "sp-block-builder/std", "sp-consensus-aura/std", "sp-core/std", + "sp-debug-derive/std", "sp-inherents/std", "sp-io/std", "sp-offchain/std", @@ -226,7 +227,7 @@ std = [ "xcm/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "orml-tokens/std", "orml-traits/std", @@ -259,7 +260,6 @@ std = [ "bifrost-slpx/std", "bifrost-stable-pool-rpc-runtime-api/std", "bifrost-stable-pool/std", - "bifrost-system-maker/std", "bifrost-system-staking/std", "bifrost-token-issuer/std", "bifrost-vesting/std", @@ -310,9 +310,7 @@ runtime-benchmarks = [ "bifrost-salp/runtime-benchmarks", "bifrost-token-issuer/runtime-benchmarks", "bifrost-vtoken-minting/runtime-benchmarks", - "bifrost-farming/runtime-benchmarks", "bifrost-system-staking/runtime-benchmarks", - "bifrost-system-maker/runtime-benchmarks", "bifrost-vstoken-conversion/runtime-benchmarks", "bifrost-slp/runtime-benchmarks", "bifrost-asset-registry/runtime-benchmarks", @@ -388,7 +386,6 @@ try-runtime = [ "bifrost-vstoken-conversion/try-runtime", "bifrost-farming/try-runtime", "bifrost-system-staking/try-runtime", - "bifrost-system-maker/try-runtime", "bifrost-fee-share/try-runtime", "bifrost-cross-in-out/try-runtime", "bifrost-slpx/try-runtime", @@ -418,3 +415,7 @@ on-chain-release-build = ["sp-api/disable-logging", "metadata-hash"] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] + +# By default RuntimeDebug implements Debug that outputs when std is disabled. +# This feature enables the detailed display of debug output. +force-debug = ["sp-debug-derive/force-debug"] \ No newline at end of file diff --git a/runtime/bifrost-kusama/src/constants.rs b/runtime/bifrost-kusama/src/constants.rs index 1c3ffc3bb6..2b63c6b47d 100644 --- a/runtime/bifrost-kusama/src/constants.rs +++ b/runtime/bifrost-kusama/src/constants.rs @@ -37,8 +37,8 @@ pub mod currency { pub const MICROBNC: Balance = 1_000_000; pub fn deposit(items: u32, bytes: u32) -> Balance { - items as Balance * 15 * cent::(CurrencyId::Native(TokenSymbol::BNC)) + - (bytes as Balance) * 6 * cent::(CurrencyId::Native(TokenSymbol::BNC)) + items as Balance * 15 * cent::(CurrencyId::Native(TokenSymbol::BNC)) + + (bytes as Balance) * 6 * cent::(CurrencyId::Native(TokenSymbol::BNC)) } pub struct WeightToFee; diff --git a/runtime/bifrost-kusama/src/governance/fellowship.rs b/runtime/bifrost-kusama/src/governance/fellowship.rs index b4453594d4..0f0dbe4872 100644 --- a/runtime/bifrost-kusama/src/governance/fellowship.rs +++ b/runtime/bifrost-kusama/src/governance/fellowship.rs @@ -362,4 +362,5 @@ impl pallet_ranked_collective::Config for Runtime #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (); type MemberSwappedHandler = (); + type MaxMemberCount = (); } diff --git a/runtime/bifrost-kusama/src/governance/tracks.rs b/runtime/bifrost-kusama/src/governance/tracks.rs index 613fc32fcb..7253b0b9b6 100644 --- a/runtime/bifrost-kusama/src/governance/tracks.rs +++ b/runtime/bifrost-kusama/src/governance/tracks.rs @@ -173,14 +173,15 @@ impl pallet_referenda::TracksInfo for TracksInfo { if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) { match system_origin { frame_system::RawOrigin::Root => { - if let Some((track_id, _)) = - Self::tracks().into_iter().find(|(_, track)| track.name == "root") + if let Some((track_id, _)) = Self::tracks() + .into_iter() + .find(|(_, track)| track.name == "root") { Ok(*track_id) } else { Err(()) } - }, + } _ => Err(()), } } else if let Ok(custom_origin) = custom_origins::Origin::try_from(id.clone()) { @@ -206,8 +207,8 @@ impl pallet_referenda::TracksInfo for TracksInfo { fn vote_locking_always_longer_than_enactment_period() { for (_, track) in TRACKS_DATA { assert!( - ::VoteLockingPeriod::get() >= - track.min_enactment_period, + ::VoteLockingPeriod::get() + >= track.min_enactment_period, "Track {} has enactment period {} < vote locking period {}", track.name, track.min_enactment_period, diff --git a/runtime/bifrost-kusama/src/lib.rs b/runtime/bifrost-kusama/src/lib.rs index 6146e4a9ca..efa7bcd179 100644 --- a/runtime/bifrost-kusama/src/lib.rs +++ b/runtime/bifrost-kusama/src/lib.rs @@ -27,7 +27,8 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use bifrost_primitives::{ - BLP_BNC_VBNC, KUSAMA_VBNC_ASSET_INDEX, KUSAMA_VBNC_LP_ASSET_INDEX, LP_BNC_VBNC, VBNC, VKSM, + BLP_BNC_VBNC, BNC, KSM, KUSAMA_VBNC_ASSET_INDEX, KUSAMA_VBNC_LP_ASSET_INDEX, KUSD, LP_BNC_VBNC, + VBNC, VKSM, }; use bifrost_slp::{DerivativeAccountProvider, QueryResponseManager}; use core::convert::TryInto; @@ -147,7 +148,7 @@ pub use xcm_config::{ SiblingParachainConvertsVia, XcmConfig, XcmRouter, }; use xcm_executor::{traits::QueryHandler, XcmExecutor}; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -164,7 +165,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bifrost"), impl_name: create_runtime_str!("bifrost"), authoring_version: 1, - spec_version: 15003, + spec_version: 16000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -174,7 +175,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } /// We assume that ~10% of the block weight is consumed by `on_initalize` handlers. @@ -212,14 +216,14 @@ parameter_types! { }) .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) .build_or_panic(); - pub const SS58Prefix: u8 = 6; + pub const SS58Prefix: u8 = 0; } parameter_types! { - pub const NativeCurrencyId: CurrencyId = CurrencyId::Native(TokenSymbol::BNC); - pub const RelayCurrencyId: CurrencyId = CurrencyId::Token(TokenSymbol::KSM); + pub const NativeCurrencyId: CurrencyId = BNC; + pub const RelayCurrencyId: CurrencyId = KSM; pub const RelayVCurrencyId: CurrencyId = VKSM; - pub const StableCurrencyId: CurrencyId = CurrencyId::Stable(TokenSymbol::KUSD); + pub const StableCurrencyId: CurrencyId = KUSD; pub SelfParaId: u32 = ParachainInfo::parachain_id().into(); pub const PolkadotCurrencyId: CurrencyId = CurrencyId::Token(TokenSymbol::DOT); } @@ -251,9 +255,9 @@ impl Contains for CallFilter { let is_disabled = match call { // Disable specific `transfer`, `transfer_all`, and `transfer_keep_alive` calls for // certain currencies - RuntimeCall::Tokens(orml_tokens::Call::transfer { currency_id, .. }) | - RuntimeCall::Tokens(orml_tokens::Call::transfer_all { currency_id, .. }) | - RuntimeCall::Tokens(orml_tokens::Call::transfer_keep_alive { + RuntimeCall::Tokens(orml_tokens::Call::transfer { currency_id, .. }) + | RuntimeCall::Tokens(orml_tokens::Call::transfer_all { currency_id, .. }) + | RuntimeCall::Tokens(orml_tokens::Call::transfer_keep_alive { currency_id, .. }) => [VBNC, BLP_BNC_VBNC, LP_BNC_VBNC].contains(currency_id), @@ -261,17 +265,17 @@ impl Contains for CallFilter { RuntimeCall::StablePool(bifrost_stable_pool::Call::add_liquidity { pool_id, .. - }) | - RuntimeCall::StablePool(bifrost_stable_pool::Call::swap { pool_id, .. }) | - RuntimeCall::StablePool(bifrost_stable_pool::Call::redeem_proportion { + }) + | RuntimeCall::StablePool(bifrost_stable_pool::Call::swap { pool_id, .. }) + | RuntimeCall::StablePool(bifrost_stable_pool::Call::redeem_proportion { pool_id, .. - }) | - RuntimeCall::StablePool(bifrost_stable_pool::Call::redeem_single { + }) + | RuntimeCall::StablePool(bifrost_stable_pool::Call::redeem_single { pool_id, .. - }) | - RuntimeCall::StablePool(bifrost_stable_pool::Call::redeem_multi { + }) + | RuntimeCall::StablePool(bifrost_stable_pool::Call::redeem_multi { pool_id, .. }) => *pool_id == 2, @@ -285,13 +289,13 @@ impl Contains for CallFilter { asset_0, asset_1, .. - }) | - RuntimeCall::ZenlinkProtocol(zenlink_protocol::Call::remove_liquidity { + }) + | RuntimeCall::ZenlinkProtocol(zenlink_protocol::Call::remove_liquidity { asset_0, asset_1, .. - }) | - RuntimeCall::ZenlinkProtocol(zenlink_protocol::Call::bootstrap_claim { + }) + | RuntimeCall::ZenlinkProtocol(zenlink_protocol::Call::bootstrap_claim { asset_0, asset_1, .. @@ -300,8 +304,8 @@ impl Contains for CallFilter { // Disable ZenlinkProtocol swap calls if the path contains VBNC assets RuntimeCall::ZenlinkProtocol( zenlink_protocol::Call::swap_exact_assets_for_assets { path, .. }, - ) | - RuntimeCall::ZenlinkProtocol( + ) + | RuntimeCall::ZenlinkProtocol( zenlink_protocol::Call::swap_assets_for_exact_assets { path, .. }, ) => path.contains(&KUSAMA_VBNC_ASSET_INDEX), @@ -459,8 +463,11 @@ impl InstanceFilter for ProxyType { RuntimeCall::ParachainStaking(..) ), ProxyType::Staking => { - matches!(c, RuntimeCall::ParachainStaking(..) | RuntimeCall::Utility(..)) - }, + matches!( + c, + RuntimeCall::ParachainStaking(..) | RuntimeCall::Utility(..) + ) + } ProxyType::Governance => matches!( c, RuntimeCall::Democracy(..) | @@ -476,12 +483,15 @@ impl InstanceFilter for ProxyType { RuntimeCall::Whitelist(..) ), ProxyType::CancelProxy => { - matches!(c, RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })) - }, + matches!( + c, + RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) + ) + } ProxyType::IdentityJudgement => matches!( c, - RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) | - RuntimeCall::Utility(..) + RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) + | RuntimeCall::Utility(..) ), } } @@ -831,13 +841,7 @@ parameter_types! { pub const MaxBalance: Balance = 800_000 * BNCS; } -type ApproveOrigin = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, ->; - impl pallet_treasury::Config for Runtime { - type ApproveOrigin = ApproveOrigin; type SpendOrigin = EitherOf, Spender>; type Burn = Burn; type BurnDestination = (); @@ -852,11 +856,7 @@ impl pallet_treasury::Config for Runtime { type PayoutPeriod = PayoutSpendPeriod; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); - type OnSlash = Treasury; type PalletId = TreasuryPalletId; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; type RejectOrigin = MoreThanHalfCouncil; type SpendFunds = (); type SpendPeriod = SpendPeriod; @@ -877,7 +877,10 @@ impl pallet_transaction_payment::Config for Runtime { pub struct TxPauseWhitelistedCalls; impl Contains> for TxPauseWhitelistedCalls { fn contains(full_name: &pallet_tx_pause::RuntimeCallNameOf) -> bool { - matches!(full_name.0.as_slice(), b"System" | b"Timestamp" | b"TxPause") + matches!( + full_name.0.as_slice(), + b"System" | b"Timestamp" | b"TxPause" + ) } } @@ -905,8 +908,10 @@ where ::SignaturePayload, )> { // take the biggest period possible. - let period = - BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64; + let period = BlockHashCount::get() + .checked_next_power_of_two() + .map(|c| c / 2) + .unwrap_or(2) as u64; let current_block = System::block_number() .saturated_into::() // The `System::block_number` is initialized with `n+1`, @@ -997,7 +1002,10 @@ parameter_types! { /// Rounds before the reward is paid pub const RewardPaymentDelay: u32 = 2; /// Minimum collators selected per round, default at genesis and minimum forever after - pub const MinSelectedCandidates: u32 = prod_or_fast!(16,6); + /// The collator incentives on Bifrost-Kusama will be discontinued. The number of active + /// collators will be set to 4, ensuring that all collators are nodes operated by Bifrost + /// itself. + pub const MinSelectedCandidates: u32 = prod_or_fast!(4,4); /// Maximum top delegations per candidate pub const MaxTopDelegationsPerCandidate: u32 = 300; /// Maximum bottom delegations per candidate @@ -1098,6 +1106,7 @@ impl bifrost_vesting::Config for Runtime { type WeightInfo = weights::bifrost_vesting::BifrostWeight; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; const MAX_VESTING_SCHEDULES: u32 = 28; + type BlockNumberProvider = System; } // Bifrost modules start @@ -1122,6 +1131,9 @@ impl bifrost_flexible_fee::Config for Runtime { type XcmRouter = XcmRouter; type PalletId = FlexibleFeePalletId; type OraclePriceProvider = Prices; + type InspectEvmAccounts = (); + type EvmPermit = bifrost_flexible_fee::impls::evm_permit::DisabledEvmPermitHandler; + type AssetIdMaps = AssetIdMaps; } parameter_types! { @@ -1149,7 +1161,7 @@ pub fn create_x2_multilocation(index: u16, currency_id: CurrencyId) -> xcm::v3:: ), ), // Only relay chain use the Bifrost para account with "para" - CurrencyId::Token(TokenSymbol::KSM) => xcm::v3::Location::new( + KSM => xcm::v3::Location::new( 1, xcm::v3::Junctions::X1(xcm::v3::Junction::AccountId32 { network: None, @@ -1161,7 +1173,7 @@ pub fn create_x2_multilocation(index: u16, currency_id: CurrencyId) -> xcm::v3:: }), ), // Bifrost Kusama Native token - CurrencyId::Native(TokenSymbol::BNC) => xcm::v3::Location::new( + BNC => xcm::v3::Location::new( 0, xcm::v3::Junctions::X1(xcm::v3::Junction::AccountId32 { network: None, @@ -1203,7 +1215,7 @@ pub fn create_x2_multilocation(index: u16, currency_id: CurrencyId) -> xcm::v3:: } else { xcm::v3::Location::default() } - }, + } } } @@ -1335,6 +1347,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = StablePool; type AssetIdMaps = AssetIdMaps; type TreasuryAccount = BifrostTreasuryAccount; + type BlockNumberProvider = System; } impl bifrost_vstoken_conversion::Config for Runtime { @@ -1366,6 +1379,7 @@ impl bifrost_farming::Config for Runtime { type BlockNumberToBalance = ConvertInto; type WhitelistMaximumLimit = WhitelistMaximumLimit; type GaugeRewardIssuer = FarmingGaugeRewardIssuerPalletId; + type BlockNumberProvider = System; } parameter_types! { @@ -1386,6 +1400,7 @@ impl bifrost_system_staking::Config for Runtime { type BlocksPerRound = BlocksPerRound; type MaxTokenLen = MaxTokenLen; type MaxFarmingPoolIdLen = MaxFarmingPoolIdLen; + type BlockNumberProvider = System; } impl bifrost_fee_share::Config for Runtime { @@ -1395,6 +1410,7 @@ impl bifrost_fee_share::Config for Runtime { type WeightInfo = weights::bifrost_fee_share::BifrostWeight; type FeeSharePalletId = FeeSharePalletId; type OraclePriceProvider = Prices; + type BlockNumberProvider = System; } impl bifrost_cross_in_out::Config for Runtime { @@ -1566,6 +1582,7 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = (); + type BlockNumberProvider = System; } impl bifrost_slpx::Config for Runtime { @@ -1581,6 +1598,7 @@ impl bifrost_slpx::Config for Runtime { type ParachainId = ParachainInfo; type WeightInfo = weights::bifrost_slpx::BifrostWeight; type MaxOrderSize = ConstU32<500>; + type BlockNumberProvider = System; } pub struct EnsurePoolAssetId; @@ -1605,6 +1623,7 @@ impl bifrost_stable_asset::Config for Runtime { type WeightInfo = (); type ListingOrigin = TechAdminOrCouncil; type EnsurePoolAssetId = EnsurePoolAssetId; + type BlockNumberProvider = System; } impl bifrost_stable_pool::Config for Runtime { @@ -1699,6 +1718,7 @@ impl lend_market::Config for Runtime { type RewardAssetId = NativeCurrencyId; type LiquidationFreeAssetId = RelayCurrencyId; type MaxLengthLimit = MaxLengthLimit; + type BlockNumberProvider = System; } parameter_types! { @@ -1743,6 +1763,7 @@ impl bifrost_channel_commission::Config for Runtime { type WeightInfo = weights::bifrost_channel_commission::BifrostWeight; type ClearingDuration = ClearingDuration; type NameLengthLimit = NameLengthLimit; + type BlockNumberProvider = System; } impl bifrost_vbnc_convert::Config for Runtime { @@ -2005,7 +2026,7 @@ pub mod migrations { pub type Unreleased = ( // permanent migration, do not remove pallet_xcm::migration::MigrateToLatestXcmVersion, - bifrost_vtoken_voting::migration::v4::MigrateToV4, + bifrost_channel_commission::migrations::v1::MigrateToV1, ); } @@ -2028,7 +2049,6 @@ mod benches { define_benchmarks!( [bifrost_asset_registry, AssetRegistry] [bifrost_cross_in_out, CrossInOut] - [bifrost_farming, Farming] [bifrost_fee_share, FeeShare] [bifrost_flexible_fee, FlexibleFee] [bifrost_slp, Slp] @@ -2177,7 +2197,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = AssetRegistry::asset_ids(); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -2210,7 +2230,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -2228,7 +2248,7 @@ impl_runtime_apis! { match rs { Ok(val) => val, - _ => (CurrencyId::Native(TokenSymbol::BNC), Zero::zero()), + _ => (BNC, Zero::zero()), } } } diff --git a/runtime/bifrost-kusama/src/migration.rs b/runtime/bifrost-kusama/src/migration.rs index 487a486171..c85da51546 100644 --- a/runtime/bifrost-kusama/src/migration.rs +++ b/runtime/bifrost-kusama/src/migration.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use super::*; use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade}; use log; @@ -60,13 +62,29 @@ pub mod v0 { >, ), /// Referendum finished with approval. Submission deposit is held. - Approved(Moment, Option>, Option>), + Approved( + Moment, + Option>, + Option>, + ), /// Referendum finished with rejection. Submission deposit is held. - Rejected(Moment, Option>, Option>), + Rejected( + Moment, + Option>, + Option>, + ), /// Referendum finished with cancellation. Submission deposit is held. - Cancelled(Moment, Option>, Option>), + Cancelled( + Moment, + Option>, + Option>, + ), /// Referendum finished and was never decided. Submission deposit is held. - TimedOut(Moment, Option>, Option>), + TimedOut( + Moment, + Option>, + Option>, + ), /// Referendum finished with a kill. Killed(Moment), } @@ -137,40 +155,64 @@ pub mod v1 { v0::ReferendumInfo::Ongoing(_) | v0::ReferendumInfo::Killed(_) => None, v0::ReferendumInfo::Approved(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::Approved(e, s, d)) - }, + } v0::ReferendumInfo::Rejected(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::Rejected(e, s, d)) - }, + } v0::ReferendumInfo::Cancelled(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::Cancelled(e, s, d)) - }, + } v0::ReferendumInfo::TimedOut(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::TimedOut(e, s, d)) - }, + } }; if let Some(new_value) = maybe_new_value { weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); @@ -190,7 +232,10 @@ pub mod v1 { let pre_referendum_count: u32 = Decode::decode(&mut &state[..]) .expect("failed to decode the state from pre-upgrade."); let post_referendum_count = ReferendumInfoFor::::iter().count() as u32; - ensure!(post_referendum_count == pre_referendum_count, "must migrate all referendums."); + ensure!( + post_referendum_count == pre_referendum_count, + "must migrate all referendums." + ); let result: Vec>> = serde_json::from_str(R::get()).expect("Failed to deserialize JSON"); @@ -200,15 +245,15 @@ pub mod v1 { match referendum_info { ReferendumInfo::Ongoing(_) | ReferendumInfo::Killed(_) => (), - ReferendumInfo::Approved(_e, s, d) | - ReferendumInfo::Rejected(_e, s, d) | - ReferendumInfo::Cancelled(_e, s, d) | - ReferendumInfo::TimedOut(_e, s, d) => { + ReferendumInfo::Approved(_e, s, d) + | ReferendumInfo::Rejected(_e, s, d) + | ReferendumInfo::Cancelled(_e, s, d) + | ReferendumInfo::TimedOut(_e, s, d) => { match (s, item.deposit1) { (Some(s), Some(a)) => { ensure!(s.amount == a.amount, "amount not equal"); ensure!(s.who == a.who, "who not equal"); - }, + } (None, None) => (), _ => return Err(TryRuntimeError::Other("Referenda Data mismatch")), } @@ -216,12 +261,12 @@ pub mod v1 { (Some(d), Some(a)) => { ensure!(d.amount == a.amount, "amount not equal"); ensure!(d.who == a.who, "who not equal"); - }, + } (None, None) => (), _ => return Err(TryRuntimeError::Other("Referenda Data mismatch")), } () - }, + } }; } @@ -239,11 +284,12 @@ pub mod slpx_migrates_whitelist { pub struct UpdateWhitelist; impl OnRuntimeUpgrade for UpdateWhitelist { fn on_runtime_upgrade() -> Weight { - let new_whitelist: BoundedVec> = - vec![AccountId::from_ss58check("gtXJWw9ME9w7cXfmR6n9MFkKCSu2MrtA3dcFV2BhHpEZFjZ") - .unwrap()] - .try_into() - .unwrap(); + let new_whitelist: BoundedVec> = vec![ + AccountId::from_ss58check("gtXJWw9ME9w7cXfmR6n9MFkKCSu2MrtA3dcFV2BhHpEZFjZ") + .unwrap(), + ] + .try_into() + .unwrap(); bifrost_slpx::WhitelistAccountId::::insert( SupportChain::Moonbeam, new_whitelist, @@ -256,11 +302,12 @@ pub mod slpx_migrates_whitelist { fn post_upgrade(_state: Vec) -> Result<(), TryRuntimeError> { let whitelist = bifrost_slpx::WhitelistAccountId::::get(SupportChain::Moonbeam); - let new_whitelist: BoundedVec> = - vec![AccountId::from_ss58check("gtXJWw9ME9w7cXfmR6n9MFkKCSu2MrtA3dcFV2BhHpEZFjZ") - .unwrap()] - .try_into() - .unwrap(); + let new_whitelist: BoundedVec> = vec![ + AccountId::from_ss58check("gtXJWw9ME9w7cXfmR6n9MFkKCSu2MrtA3dcFV2BhHpEZFjZ") + .unwrap(), + ] + .try_into() + .unwrap(); assert_eq!(whitelist, new_whitelist); Ok(()) @@ -462,10 +509,10 @@ pub mod vsbond_auction { Ok(_) => { count += 1; log::info!("Transfer successful: {:?} of BNC transferred", bnc_balance); - }, + } Err(e) => { log::error!("Failed to transfer {:?} of BNC: {:?}", bnc_balance, e); - }, + } } } else { log::info!("No transfer needed for BNC as the balance is 0"); @@ -482,10 +529,10 @@ pub mod vsbond_auction { Ok(_) => { count += 1; log::info!("Transfer successful: {:?} of KSM transferred", ksm_balance); - }, + } Err(e) => { log::error!("Failed to transfer {:?} of KSM: {:?}", ksm_balance, e); - }, + } } } else { log::info!("No transfer needed for KSM as the balance is 0"); @@ -506,14 +553,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::KSM, 2092, 15, 22); transferred", vs_bond_1_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::KSM, 2092, 15, 22);: {:?}", vs_bond_1_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::KSM, 2092, 15, 22) as the balance is 0"); @@ -534,14 +581,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::KSM, 2096, 17, 24) transferred", vs_bond_2_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::KSM, 2096, 17, 24): {:?}", vs_bond_2_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::KSM, 2096, 17, 24) as the balance is 0"); @@ -562,14 +609,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::KSM, 2100, 18, 25) transferred", vs_bond_3_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::KSM, 2100, 18, 25): {:?}", vs_bond_3_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::KSM, 2100, 18, 25) as the balance is 0"); @@ -590,14 +637,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::KSM, 2125, 23, 30) transferred", vs_bond_4_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::KSM, 2125, 23, 30): {:?}", vs_bond_4_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::KSM, 2125, 23, 30) as the balance is 0"); @@ -618,14 +665,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::KSM, 2114, 20, 27) transferred", vs_bond_5_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::KSM, 2114, 20, 27): {:?}", vs_bond_5_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::KSM, 2114, 20, 27) as the balance is 0"); @@ -646,14 +693,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::KSM, 2118, 22, 29) transferred", vs_bond_6_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::KSM, 2118, 22, 29): {:?}", vs_bond_6_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::KSM, 2118, 22, 29) as the balance is 0"); @@ -674,14 +721,14 @@ pub mod vsbond_auction { "Transfer successful: {:?} of VSBond(TokenSymbol::BNC, 2001, 13, 20) transferred", vs_bond_7_balance ); - }, + } Err(e) => { log::error!( "Failed to transfer {:?} of VSBond(TokenSymbol::BNC, 2001, 13, 20): {:?}", vs_bond_7_balance, e ); - }, + } } } else { log::info!("No transfer needed for VSBond(TokenSymbol::BNC, 2001, 13, 20) as the balance is 0"); diff --git a/runtime/bifrost-kusama/src/weights/bifrost_farming.rs b/runtime/bifrost-kusama/src/weights/bifrost_farming.rs index 71c9820855..ae26727bbc 100644 --- a/runtime/bifrost-kusama/src/weights/bifrost_farming.rs +++ b/runtime/bifrost-kusama/src/weights/bifrost_farming.rs @@ -132,23 +132,6 @@ impl bifrost_farming::WeightInfo for BifrostWeight { .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) } - // Storage: Farming GaugePoolInfos (r:1 w:1) - // Proof Skipped: Farming GaugePoolInfos (max_values: None, max_size: None, mode: Measured) - // Storage: Farming GaugeInfos (r:1 w:1) - // Proof Skipped: Farming GaugeInfos (max_values: None, max_size: None, mode: Measured) - // Storage: Farming PoolInfos (r:1 w:0) - // Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) - // Storage: Farming SharesAndWithdrawnRewards (r:1 w:0) - // Proof Skipped: Farming SharesAndWithdrawnRewards (max_values: None, max_size: None, mode: Measured) - fn gauge_withdraw() -> Weight { - // Proof Size summary in bytes: - // Measured: `832` - // Estimated: `4297` - // Minimum execution time: 82_224 nanoseconds. - Weight::from_parts(84_369_000, 4297) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(2)) - } // Storage: Farming PoolInfos (r:1 w:0) // Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) // Storage: Farming SharesAndWithdrawnRewards (r:1 w:1) @@ -356,4 +339,21 @@ impl bifrost_farming::WeightInfo for BifrostWeight { .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } + /// Storage: `Farming::UserFarmingPool` (r:1 w:0) + /// Proof: `Farming::UserFarmingPool` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::SharesAndWithdrawnRewards` (r:2 w:0) + /// Proof: `Farming::SharesAndWithdrawnRewards` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::PoolInfos` (r:1 w:0) + /// Proof: `Farming::PoolInfos` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserPositions` (r:1 w:0) + /// Proof: `BbBNC::UserPositions` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn refresh() -> Weight { + // Proof Size summary in bytes: + // Measured: `604` + // Estimated: `6544` + // Minimum execution time: 16_472_000 picoseconds. + Weight::from_parts(17_023_000, 0) + .saturating_add(Weight::from_parts(0, 6544)) + .saturating_add(T::DbWeight::get().reads(5)) + } } diff --git a/runtime/bifrost-kusama/src/weights/bifrost_system_maker.rs b/runtime/bifrost-kusama/src/weights/bifrost_system_maker.rs deleted file mode 100644 index e2109a2d24..0000000000 --- a/runtime/bifrost-kusama/src/weights/bifrost_system_maker.rs +++ /dev/null @@ -1,122 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Autogenerated weights for bifrost_system_maker -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` -//! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 - -// Executed Command: -// target/release/bifrost -// benchmark -// pallet -// --chain=bifrost-kusama-local -// --steps=50 -// --repeat=20 -// --pallet=bifrost_system_maker -// --extrinsic=* -// --execution=wasm -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./runtime/bifrost-kusama/src/weights/bifrost_system_maker.rs -// --template=./weight-template/runtime-weight-template.hbs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use sp_std::marker::PhantomData; - -/// Weight functions for bifrost_system_maker. -pub struct BifrostWeight(PhantomData); -impl bifrost_system_maker::WeightInfo for BifrostWeight { - // Storage: SystemMaker Infos (r:1 w:1) - // Proof Skipped: SystemMaker Infos (max_values: None, max_size: None, mode: Measured) - fn set_config() -> Weight { - // Proof Size summary in bytes: - // Measured: `109` - // Estimated: `3574` - // Minimum execution time: 32_211 nanoseconds. - Weight::from_parts(33_399_000, 3574) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - // Storage: Tokens Accounts (r:2 w:2) - // Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - // Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - // Storage: System Account (r:2 w:1) - // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn charge() -> Weight { - // Proof Size summary in bytes: - // Measured: `1402` - // Estimated: `6196` - // Minimum execution time: 122_457 nanoseconds. - Weight::from_parts(124_486_000, 6196) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) - } - // Storage: SystemMaker Infos (r:0 w:1) - // Proof Skipped: SystemMaker Infos (max_values: None, max_size: None, mode: Measured) - fn close() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 22_412 nanoseconds. - Weight::from_parts(22_806_000, 0) - .saturating_add(T::DbWeight::get().writes(1)) - } - // Storage: Tokens Accounts (r:2 w:2) - // Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - // Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - // Storage: System Account (r:2 w:1) - // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn payout() -> Weight { - // Proof Size summary in bytes: - // Measured: `1461` - // Estimated: `6196` - // Minimum execution time: 114_158 nanoseconds. - Weight::from_parts(116_409_000, 6196) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) - } - // Storage: SystemMaker Infos (r:2 w:0) - // Proof Skipped: SystemMaker Infos (max_values: None, max_size: None, mode: Measured) - // Storage: ParachainInfo ParachainId (r:1 w:0) - // Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - // Storage: Tokens Accounts (r:2 w:0) - // Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - fn on_idle() -> Weight { - // Proof Size summary in bytes: - // Measured: `894` - // Estimated: `6834` - // Minimum execution time: 54_792 nanoseconds. - Weight::from_parts(55_872_000, 6834) - .saturating_add(T::DbWeight::get().reads(5)) - } -} diff --git a/runtime/bifrost-kusama/src/weights/mod.rs b/runtime/bifrost-kusama/src/weights/mod.rs index c69a7e8be0..944900a817 100644 --- a/runtime/bifrost-kusama/src/weights/mod.rs +++ b/runtime/bifrost-kusama/src/weights/mod.rs @@ -31,7 +31,6 @@ pub mod bifrost_salp; pub mod bifrost_slp; pub mod bifrost_slpx; pub mod bifrost_stable_pool; -pub mod bifrost_system_maker; pub mod bifrost_system_staking; pub mod bifrost_token_issuer; pub mod bifrost_vbnc_convert; diff --git a/runtime/bifrost-kusama/src/xcm_config.rs b/runtime/bifrost-kusama/src/xcm_config.rs index e4100406bf..20dceca6eb 100644 --- a/runtime/bifrost-kusama/src/xcm_config.rs +++ b/runtime/bifrost-kusama/src/xcm_config.rs @@ -138,7 +138,11 @@ pub type BifrostAssetTransactor = MultiCurrencyAdapter< pub struct ToTreasury; impl TakeRevenue for ToTreasury { fn take_revenue(revenue: Asset) { - if let Asset { id: AssetId(location), fun: Fungible(amount) } = revenue { + if let Asset { + id: AssetId(location), + fun: Fungible(amount), + } = revenue + { if let Some(currency_id) = CurrencyIdConvert::::convert(location) { @@ -160,7 +164,10 @@ impl Contains for SafeCallFilter { fn contains(call: &RuntimeCall) -> bool { #[cfg(feature = "runtime-benchmarks")] { - if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + if matches!( + call, + RuntimeCall::System(frame_system::Call::remark_with_event { .. }) + ) { return true; } } @@ -424,10 +431,10 @@ impl Contains for DustRemovalWhitelist { SystemStakingPalletId::get().into_account_truncating(), VBNCConvertPalletId::get().into_account_truncating(), ]; - whitelist.contains(a) || - FarmingKeeperPalletId::get().check_sub_account::(a) || - FarmingRewardIssuerPalletId::get().check_sub_account::(a) || - FeeSharePalletId::get().check_sub_account::(a) + whitelist.contains(a) + || FarmingKeeperPalletId::get().check_sub_account::(a) + || FarmingRewardIssuerPalletId::get().check_sub_account::(a) + || FeeSharePalletId::get().check_sub_account::(a) } } diff --git a/runtime/bifrost-polkadot/Cargo.toml b/runtime/bifrost-polkadot/Cargo.toml index 80747c824a..dc4c4d9e4a 100644 --- a/runtime/bifrost-polkadot/Cargo.toml +++ b/runtime/bifrost-polkadot/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-polkadot-runtime" version = "0.8.0" -authors = ["Edwin Wang "] +authors = ["Liebi Technologies "] edition = "2021" build = "build.rs" @@ -61,6 +61,7 @@ sp-arithmetic = { workspace = true } sp-block-builder = { workspace = true } sp-consensus-aura = { workspace = true } sp-core = { workspace = true } +sp-debug-derive = { workspace = true } sp-inherents = { workspace = true } sp-io = { workspace = true } sp-offchain = { workspace = true } @@ -92,7 +93,7 @@ polkadot-runtime-common = { workspace = true } xcm = { workspace = true } xcm-builder = { workspace = true } xcm-executor = { workspace = true } -xcm-fee-payment-runtime-api = { workspace = true } +xcm-runtime-apis = { workspace = true } # orml orml-tokens = { workspace = true } @@ -130,6 +131,7 @@ pallet-evm-precompile-dispatch = { workspace = true } pallet-evm-precompile-modexp = { workspace = true } pallet-evm-precompile-sha3fips = { workspace = true } pallet-evm-precompile-simple = { workspace = true } +pallet-evm-precompile-call-permit = { workspace = true } pallet-evm-precompile-bn128 = { workspace = true } pallet-evm-precompile-blake2 = { workspace = true } pallet-evm-accounts = { workspace = true } @@ -155,7 +157,6 @@ bifrost-slp-v2 = { workspace = true, features = ["polkadot"] } bifrost-slpx = { workspace = true } bifrost-stable-pool = { workspace = true } bifrost-stable-pool-rpc-runtime-api = { workspace = true } -bifrost-system-maker = { workspace = true } bifrost-system-staking = { workspace = true } bb-bnc = { workspace = true } bb-bnc-rpc-runtime-api = { workspace = true } @@ -219,6 +220,7 @@ std = [ "sp-block-builder/std", "sp-consensus-aura/std", "sp-core/std", + "sp-debug-derive/std", "sp-inherents/std", "sp-io/std", "sp-offchain/std", @@ -243,7 +245,7 @@ std = [ "xcm-builder/std", "xcm-executor/std", "xcm/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "orml-tokens/std", "orml-traits/std", @@ -275,7 +277,6 @@ std = [ "bifrost-slpx/std", "bifrost-stable-pool-rpc-runtime-api/std", "bifrost-stable-pool/std", - "bifrost-system-maker/std", "bifrost-system-staking/std", "bb-bnc-rpc-runtime-api/std", "bb-bnc/std", @@ -303,6 +304,7 @@ std = [ "pallet-evm-precompile-modexp/std", "pallet-evm-precompile-sha3fips/std", "pallet-evm-precompile-simple/std", + "pallet-evm-precompile-call-permit/std", "pallet-evm-precompile-bn128/std", "pallet-evm-precompile-blake2/std", "pallet-evm-accounts/std", @@ -355,6 +357,8 @@ runtime-benchmarks = [ "bifrost-clouds-convert/runtime-benchmarks", "bifrost-buy-back/runtime-benchmarks", "bifrost-parachain-staking/runtime-benchmarks", + "bifrost-farming/runtime-benchmarks", + "pallet-evm-accounts/runtime-benchmarks", ] try-runtime = [ @@ -373,7 +377,6 @@ try-runtime = [ "bifrost-slpx/try-runtime", "bifrost-stable-asset/try-runtime", "bifrost-stable-pool/try-runtime", - "bifrost-system-maker/try-runtime", "bifrost-system-staking/try-runtime", "bb-bnc/try-runtime", "bifrost-vesting/try-runtime", @@ -451,3 +454,7 @@ on-chain-release-build = ["sp-api/disable-logging", "metadata-hash"] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] + +# By default RuntimeDebug implements Debug that outputs when std is disabled. +# This feature enables the detailed display of debug output. +force-debug = ["sp-debug-derive/force-debug"] diff --git a/runtime/bifrost-polkadot/src/evm/evm-utility/macro/src/lib.rs b/runtime/bifrost-polkadot/src/evm/evm-utility/macro/src/lib.rs index d913d31801..7d3ebec5d0 100644 --- a/runtime/bifrost-polkadot/src/evm/evm-utility/macro/src/lib.rs +++ b/runtime/bifrost-polkadot/src/evm/evm-utility/macro/src/lib.rs @@ -25,7 +25,14 @@ use syn::{parse_macro_input, Expr, ExprLit, Ident, ItemEnum, Lit, LitByteStr, Li pub fn generate_function_selector(_: TokenStream, input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as ItemEnum); - let ItemEnum { attrs, vis, enum_token, ident, variants, .. } = item; + let ItemEnum { + attrs, + vis, + enum_token, + ident, + variants, + .. + } = item; let mut ident_expressions: Vec = vec![]; let mut variant_expressions: Vec = vec![]; @@ -64,7 +71,10 @@ pub fn keccak256(input: TokenStream) -> TokenStream { let result = module_evm_utility::sha3_256(&lit_str.value()); - let eval = Lit::ByteStr(LitByteStr::new(result.as_ref(), proc_macro2::Span::call_site())); + let eval = Lit::ByteStr(LitByteStr::new( + result.as_ref(), + proc_macro2::Span::call_site(), + )); quote!(#eval).into() } diff --git a/runtime/bifrost-polkadot/src/evm/evm-utility/macro/tests/test.rs b/runtime/bifrost-polkadot/src/evm/evm-utility/macro/tests/test.rs index 9c4cc995ff..ec91ee7571 100644 --- a/runtime/bifrost-polkadot/src/evm/evm-utility/macro/tests/test.rs +++ b/runtime/bifrost-polkadot/src/evm/evm-utility/macro/tests/test.rs @@ -42,7 +42,10 @@ mod tests { #[test] fn keccak256_works() { - assert_eq!(module_evm_utility_macro::keccak256!(""), &module_evm_utility::sha3_256("")); + assert_eq!( + module_evm_utility_macro::keccak256!(""), + &module_evm_utility::sha3_256("") + ); assert_eq!( module_evm_utility_macro::keccak256!("keccak256"), &module_evm_utility::sha3_256("keccak256") diff --git a/runtime/bifrost-polkadot/src/evm/evm_fee.rs b/runtime/bifrost-polkadot/src/evm/evm_fee.rs index ce0de8c0de..9c4fdf2af6 100644 --- a/runtime/bifrost-polkadot/src/evm/evm_fee.rs +++ b/runtime/bifrost-polkadot/src/evm/evm_fee.rs @@ -106,7 +106,12 @@ where MC::withdraw(fee_currency, &account_id, fee_amount) .map_err(|_| Error::::WithdrawFailed)?; - Ok(Some(EvmPaymentInfo { fee_amount, fee_currency, fee_currency_price, weth_price })) + Ok(Some(EvmPaymentInfo { + fee_amount, + fee_currency, + fee_currency_price, + weth_price, + })) } fn correct_and_deposit_fee( @@ -126,7 +131,9 @@ where payment_info.fee_currency_price, ) { // Calculate how much refund we should return - let refund_amount = payment_info.fee_amount.saturating_sub(converted_corrected_fee); + let refund_amount = payment_info + .fee_amount + .saturating_sub(converted_corrected_fee); // refund to the account that paid the fees. If this fails, the // account might have dropped below the existential balance. In diff --git a/runtime/bifrost-polkadot/src/evm/mod.rs b/runtime/bifrost-polkadot/src/evm/mod.rs index 9b154e959c..a6e508c2ed 100644 --- a/runtime/bifrost-polkadot/src/evm/mod.rs +++ b/runtime/bifrost-polkadot/src/evm/mod.rs @@ -20,7 +20,6 @@ use frame_support::{pallet_prelude::Get, parameter_types, traits::FindAuthor, Co use orml_tokens::CurrencyAdapter; use pallet_ethereum::PostLogContent; use pallet_evm::EnsureAddressTruncated; -use pallet_transaction_payment::Multiplier; use primitive_types::U256; pub use crate::evm::accounts_conversion::{ExtendedAddressMapping, FindAuthorTruncated}; @@ -34,6 +33,7 @@ use bifrost_primitives::{currency::WETH, CurrencyId}; mod accounts_conversion; mod evm_fee; +pub mod permit; pub mod precompiles; mod runner; @@ -64,14 +64,6 @@ impl Get for WethAssetId { type WethCurrency = CurrencyAdapter; -pub struct TransactionPaymentMultiplier; - -impl Get for TransactionPaymentMultiplier { - fn get() -> Multiplier { - crate::TransactionPayment::next_fee_multiplier() - } -} - parameter_types! { /// The amount of gas per pov. A ratio of 4 if we convert ref_time to gas and we compare /// it with the pov_size for a block. E.g. diff --git a/runtime/bifrost-polkadot/src/evm/permit.rs b/runtime/bifrost-polkadot/src/evm/permit.rs new file mode 100644 index 0000000000..6a48213208 --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/permit.rs @@ -0,0 +1,213 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use crate::{evm::precompiles, ExtrinsicBaseWeight, Runtime}; +use bifrost_primitives::{AccountId, EvmPermit}; +use evm::ExitReason; +use fp_evm::FeeCalculator; +use frame_support::{ + dispatch::{DispatchErrorWithPostInfo, Pays, PostDispatchInfo, RawOrigin}, + ensure, + pallet_prelude::DispatchResultWithPostInfo, + traits::Time, +}; +use pallet_evm::{AddressMapping, GasWeightMapping, Runner}; +use pallet_evm_precompile_call_permit::NoncesStorage; +use primitive_types::{H160, H256, U256}; +use sp_core::crypto::AccountId32; +use sp_io::hashing::keccak_256; +use sp_runtime::{ + traits::{One, UniqueSaturatedInto}, + DispatchResult, +}; +use sp_std::vec::Vec; +use xcm::prelude::Weight; + +pub struct EvmPermitHandler(sp_std::marker::PhantomData); + +impl EvmPermit for EvmPermitHandler +where + R: frame_system::Config + + pallet_evm::Config + + bifrost_flexible_fee::Config + + pallet_tx_pause::Config + + pallet_evm_accounts::Config, + R::Nonce: Into, + AccountId: From, + R::AccountId: AsRef<[u8; 32]> + frame_support::traits::IsType, +{ + fn validate_permit( + source: H160, + target: H160, + data: Vec, + value: U256, + gas_limit: u64, + deadline: U256, + v: u8, + r: H256, + s: H256, + ) -> DispatchResult { + let account_nonce = NoncesStorage::get(source); + + let permit = pallet_evm_precompile_call_permit::CallPermitPrecompile::::generate_permit( + precompiles::CALLPERMIT, + source, + target, + value, + data, + gas_limit, + account_nonce, + deadline, + ); + + // Blockchain time is in ms while Ethereum use second timestamps. + let timestamp: u128 = ::Timestamp::now().unique_saturated_into(); + let timestamp: U256 = U256::from(timestamp / 1000); + + ensure!( + deadline >= timestamp, + bifrost_flexible_fee::Error::::EvmPermitExpired + ); + + let mut sig = [0u8; 65]; + sig[0..32].copy_from_slice(r.as_bytes()); + sig[32..64].copy_from_slice(s.as_bytes()); + sig[64] = v; + let signer = sp_io::crypto::secp256k1_ecdsa_recover(&sig, &permit) + .map_err(|_| bifrost_flexible_fee::Error::::EvmPermitInvalid)?; + let signer = H160::from(H256::from_slice(keccak_256(&signer).as_slice())); + ensure!( + signer != H160::zero() && signer == source, + bifrost_flexible_fee::Error::::EvmPermitInvalid + ); + + Ok(()) + } + + fn dispatch_permit( + source: H160, + target: H160, + data: Vec, + value: U256, + gas_limit: u64, + max_fee_per_gas: U256, + max_priority_fee_per_gas: Option, + _nonce: Option, + access_list: Vec<(H160, Vec)>, + ) -> DispatchResultWithPostInfo { + // Dispatching permit should not increase account nonce, as TX is not signed by the account. + // Therefore, we need to manually reset it back to current value after execution. + let account_id = ::AddressMapping::into_account_id(source); + let source_nonce = frame_system::Account::::get(&account_id).nonce; + + let is_transactional = true; + let validate = true; + let info = match ::Runner::call( + source, + target, + data, + value, + gas_limit, + Some(max_fee_per_gas), + max_priority_fee_per_gas, + None, + access_list, + is_transactional, + validate, + None, + None, + ::config(), + ) { + Ok(info) => info, + Err(e) => { + return Err(DispatchErrorWithPostInfo { + post_info: PostDispatchInfo { + actual_weight: Some(e.weight), + pays_fee: Pays::Yes, + }, + error: bifrost_flexible_fee::Error::::EvmPermitRunnerError.into(), + }) + } + }; + let account_source_nonce = frame_system::Account::::get(&account_id).nonce; + debug_assert_eq!( + account_source_nonce, + source_nonce + ::Nonce::one() + ); + frame_system::Account::::mutate(account_id, |a| { + a.nonce -= ::Nonce::one() + }); + + let permit_nonce = NoncesStorage::get(source); + NoncesStorage::insert(source, permit_nonce + U256::one()); + + let mut gas_to_weight = ::GasWeightMapping::gas_to_weight( + info.used_gas.standard.unique_saturated_into(), + true, + ); + if let Some(weight_info) = info.weight_info { + if let Some(proof_size_usage) = weight_info.proof_size_usage { + *gas_to_weight.proof_size_mut() = proof_size_usage; + } + } + let actual_weight = gas_to_weight; + let post_info = PostDispatchInfo { + actual_weight: Some(actual_weight), + pays_fee: Pays::No, + }; + + match info.exit_reason { + ExitReason::Succeed(_) => Ok(post_info), + _ => Err(DispatchErrorWithPostInfo { + post_info, + error: bifrost_flexible_fee::Error::::EvmPermitCallExecutionError.into(), + }), + } + } + + fn gas_price() -> (U256, Weight) { + ::FeeCalculator::min_gas_price() + } + + fn dispatch_weight(gas_limit: u64) -> Weight { + let without_base_extrinsic_weight = true; + let weight = ::GasWeightMapping::gas_to_weight( + gas_limit, + without_base_extrinsic_weight, + ); + + // As GasWeightMapping implementation does not include/exclude the weight-with-swap (only + // the frame_system::constants::ExtrinsicBaseWeight) therefore we need to add it manually + // here + weight.saturating_add(ExtrinsicBaseWeight::get()) + } + + fn permit_nonce(account: H160) -> U256 { + NoncesStorage::get(account) + } + + fn on_dispatch_permit_error() { + let _ = pallet_tx_pause::Pallet::::pause( + RawOrigin::Root.into(), + ( + b"FlexibleFee".to_vec().try_into().expect("FlexibleFee"), + b"dispatch_permit".to_vec().try_into().expect("FlexibleFee"), + ), + ); + } +} diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/CallPermit.sol b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/CallPermit.sol new file mode 100644 index 0000000000..1cc484356f --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/CallPermit.sol @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-3.0-only +pragma solidity >=0.8.3; + +/// @dev The CallPermit contract's address. +address constant CALL_PERMIT_ADDRESS = 0x000000000000000000000000000000000000080a; + +/// @dev The CallPermit contract's instance. +CallPermit constant CALL_PERMIT_CONTRACT = CallPermit(CALL_PERMIT_ADDRESS); + +/// @author The Moonbeam Team +/// @title Call Permit Interface +/// @dev The interface aims to be a general-purpose tool to perform gas-less transactions. It uses the EIP-712 standard, +/// and signed messages can be dispatched by another network participant with a transaction +/// @custom:address 0x000000000000000000000000000000000000080a +interface CallPermit { + /// @dev Dispatch a call on the behalf of an other user with a EIP712 permit. + /// Will revert if the permit is not valid or if the dispatched call reverts or errors (such as + /// out of gas). + /// If successful the EIP712 nonce is increased to prevent this permit to be replayed. + /// @param from Who made the permit and want its call to be dispatched on their behalf. + /// @param to Which address the call is made to. + /// @param value Value being transfered from the "from" account. + /// @param data Call data + /// @param gaslimit Gaslimit the dispatched call requires. + /// Providing it prevents the dispatcher to manipulate the gaslimit. + /// @param deadline Deadline in UNIX seconds after which the permit will no longer be valid. + /// @param v V part of the signature. + /// @param r R part of the signature. + /// @param s S part of the signature. + /// @return output Output of the call. + /// @custom:selector b5ea0966 + function dispatch( + address from, + address to, + uint256 value, + bytes memory data, + uint64 gaslimit, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) external returns (bytes memory output); + + /// @dev Returns the current nonce for given owner. + /// A permit must have this nonce to be consumed, which will + /// increase the nonce by one. + /// @custom:selector 7ecebe00 + function nonces(address owner) external view returns (uint256); + + /// @dev Returns the EIP712 domain separator. It is used to avoid replay + /// attacks accross assets or other similar EIP712 message structures. + /// @custom:selector 3644e515 + function DOMAIN_SEPARATOR() external view returns (bytes32); +} diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/Cargo.toml b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/Cargo.toml new file mode 100644 index 0000000000..4b2270cf5f --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/Cargo.toml @@ -0,0 +1,58 @@ +[package] +name = "pallet-evm-precompile-call-permit" +description = "A Precompile to dispatch a call with a ERC712 permit." +edition = "2021" +version = "0.1.3" +authors = ["PureStake"] +repository = "https://github.com/PureStake/moonbeam" + +[dependencies] +log = { workspace = true } +num_enum = { workspace = true } +paste = { workspace = true } +slices = { workspace = true } + +# Moonbeam +precompile-utils = { workspace = true } + +# Substrate +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-timestamp = { workspace = true } +parity-scale-codec = { workspace = true, features = [ "max-encoded-len" ] } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } + +# Frontier +evm = { workspace = true, features = [ "with-codec" ] } +fp-evm = { workspace = true } +pallet-evm = { workspace = true, features = [ "forbid-evm-reentrancy" ] } + +[dev-dependencies] +derive_more = { workspace = true } +hex-literal = { workspace = true } +libsecp256k1 = { workspace = true } +serde = { workspace = true } +sha3 = { workspace = true } + +pallet-balances = { workspace = true, features = [ "insecure_zero_ed", "std" ] } +pallet-timestamp = { workspace = true, features = [ "std" ] } +precompile-utils = { workspace = true, features = [ "std", "testing" ] } +scale-info = { workspace = true, features = [ "derive", "std" ] } +sp-runtime = { workspace = true, features = [ "std" ] } + +[features] +default = [ "std" ] +std = [ + "fp-evm/std", + "frame-support/std", + "frame-system/std", + "pallet-evm/std", +# "codec/std", + "precompile-utils/std", + "sp-core/std", + "sp-io/std", + "sp-std/std", +] diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/README.md b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/README.md new file mode 100644 index 0000000000..833327c13a --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/README.md @@ -0,0 +1,106 @@ +Shamelessly copied from [Moonbeam](https://github.com/moonbeam-foundation/moonbeam/tree/master/precompiles) + +Thanks. + + +# Call Permit Precompile + +This precompile aims to be a general-purpose tool to perform gas-less +transactions. + +It allows a user (we'll call her **Alice**) to sign a **call permit** with +MetaMask (using the EIP712 standard), which can then be dispatched by another +user (we'll call him **Bob**) with a transaction. + +**Bob** can make a transaction to the **Call Permit Precompile** with the call +data and **Alice**'s signature. If the permit and signature are valid, the +precompile will perform the call on the behalf of **Alice**, as if **Alice** +made a transaction herself. **Bob** is thus paying the transaction fees and +**Alice** can perform a call without having any native currency to pay for fees +(she'll still need to have some if the call includes a transfer). + +## How to sign the permit + +The following code is an exemple that is working in a Metamask-injected webpage. +**Bob** then need to make a transaction towards the precompile address with the same +data and **Alice**'s signature. + +```js +await window.ethereum.enable(); +const accounts = await window.ethereum.request({ + method: "eth_requestAccounts", +}); + +const from = accounts[0]; +const to = "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const value = 42; +const data = "0xdeadbeef"; +const gaslimit = 100000; +const nonce = 0; +const deadline = 1000; + +const createPermitMessageData = function () { + const message = { + from: from, + to: to, + value: value, + data: data, + gaslimit: gaslimit, + nonce: nonce, + deadline: deadline, + }; + + const typedData = JSON.stringify({ + types: { + EIP712Domain: [ + { name: "name", type: "string" }, + { name: "version", type: "string" }, + { name: "chainId", type: "uint256" }, + { name: "verifyingContract", type: "address" }, + ], + CallPermit: [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "value", type: "uint256" }, + { name: "data", type: "bytes" }, + { name: "gaslimit", type: "uint64" }, + { name: "nonce", type: "uint256" }, + { name: "deadline", type: "uint256" }, + ], + }, + primaryType: "CallPermit", + domain: { + name: "Call Permit Precompile", + version: "1", + chainId: 0, + verifyingContract: "0x000000000000000000000000000000000000080a", + }, + message: message, + }); + + return { + typedData, + message, + }; +}; + +const method = "eth_signTypedData_v4"; +const messageData = createPermitMessageData(); +const params = [from, messageData.typedData]; + +web3.currentProvider.sendAsync( + { + method, + params, + from, + }, + function (err, result) { + if (err) return console.dir(err); + if (result.error) { + alert(result.error.message); + return console.error("ERROR", result); + } + console.log("Signature:" + JSON.stringify(result.result)); + } +); +``` diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/lib.rs b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/lib.rs new file mode 100644 index 0000000000..8208fd7a71 --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/lib.rs @@ -0,0 +1,265 @@ +// Copyright 2019-2022 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Moonbeam is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Moonbeam. If not, see . + +#![allow(clippy::all)] +#![cfg_attr(not(feature = "std"), no_std)] + +use core::marker::PhantomData; +use fp_evm::{Context, ExitReason, ExitRevert, PrecompileFailure, PrecompileHandle, Transfer}; +use frame_support::{ + ensure, + storage::types::{StorageMap, ValueQuery}, + traits::{ConstU32, Get, StorageInstance, Time}, + Blake2_128Concat, +}; +use precompile_utils::{evm::costs::call_cost, prelude::*}; +use sp_core::{H160, H256, U256}; +use sp_io::hashing::keccak_256; +use sp_runtime::traits::UniqueSaturatedInto; +use sp_std::vec::Vec; + +#[cfg(test)] +mod mock; +#[cfg(test)] +mod tests; + +/// Storage prefix for nonces. +pub struct Nonces; + +impl StorageInstance for Nonces { + const STORAGE_PREFIX: &'static str = "Nonces"; + + fn pallet_prefix() -> &'static str { + "PrecompileCallPermit" + } +} + +/// Storage type used to store EIP2612 nonces. +pub type NoncesStorage = StorageMap< + Nonces, + // From + Blake2_128Concat, + H160, + // Nonce + U256, + ValueQuery, +>; + +/// EIP712 permit typehash. +pub const PERMIT_TYPEHASH: [u8; 32] = keccak256!( + "CallPermit(address from,address to,uint256 value,bytes data,uint64 gaslimit\ +,uint256 nonce,uint256 deadline)" +); + +/// EIP712 permit domain used to compute an individualized domain separator. +const PERMIT_DOMAIN: [u8; 32] = keccak256!( + "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" +); + +pub const CALL_DATA_LIMIT: u32 = 2u32.pow(16); + +/// Precompile allowing to issue and dispatch call permits for gasless transactions. +/// A user can sign a permit for a call that can be dispatched and paid by another user or +/// smart contract. +pub struct CallPermitPrecompile(PhantomData); + +#[precompile_utils::precompile] +impl CallPermitPrecompile +where + Runtime: pallet_evm::Config, +{ + fn compute_domain_separator(address: H160) -> [u8; 32] { + let name: H256 = keccak_256(b"Call Permit Precompile").into(); + let version: H256 = keccak256!("1").into(); + let chain_id: U256 = Runtime::ChainId::get().into(); + + let domain_separator_inner = solidity::encode_arguments(( + H256::from(PERMIT_DOMAIN), + name, + version, + chain_id, + Address(address), + )); + + keccak_256(&domain_separator_inner).into() + } + + pub fn generate_permit( + address: H160, + from: H160, + to: H160, + value: U256, + data: Vec, + gaslimit: u64, + nonce: U256, + deadline: U256, + ) -> [u8; 32] { + let domain_separator = Self::compute_domain_separator(address); + + let permit_content = solidity::encode_arguments(( + H256::from(PERMIT_TYPEHASH), + Address(from), + Address(to), + value, + // bytes are encoded as the keccak_256 of the content + H256::from(keccak_256(&data)), + gaslimit, + nonce, + deadline, + )); + let permit_content = keccak_256(&permit_content); + let mut pre_digest = Vec::with_capacity(2 + 32 + 32); + pre_digest.extend_from_slice(b"\x19\x01"); + pre_digest.extend_from_slice(&domain_separator); + pre_digest.extend_from_slice(&permit_content); + keccak_256(&pre_digest) + } + + pub fn dispatch_inherent_cost() -> u64 { + 3_000 // cost of ECRecover precompile for reference + + RuntimeHelper::::db_write_gas_cost() // we write nonce + } + + #[precompile::public( + "dispatch(address,address,uint256,bytes,uint64,uint256,uint8,bytes32,bytes32)" + )] + fn dispatch( + handle: &mut impl PrecompileHandle, + from: Address, + to: Address, + value: U256, + data: BoundedBytes>, + gas_limit: u64, + deadline: U256, + v: u8, + r: H256, + s: H256, + ) -> EvmResult { + // Now: 8 + handle.record_db_read::(8)?; + // NoncesStorage: Blake2_128(16) + contract(20) + Blake2_128(16) + owner(20) + nonce(32) + handle.record_db_read::(104)?; + + handle.record_cost(Self::dispatch_inherent_cost())?; + + let from: H160 = from.into(); + let to: H160 = to.into(); + let data: Vec = data.into(); + + // ENSURE GASLIMIT IS SUFFICIENT + let call_cost = call_cost(value, ::config()); + + let total_cost = gas_limit + .checked_add(call_cost) + .ok_or_else(|| revert("Call require too much gas (uint64 overflow)"))?; + + if total_cost > handle.remaining_gas() { + return Err(revert("Gaslimit is too low to dispatch provided call")); + } + + // VERIFY PERMIT + + // Blockchain time is in ms while Ethereum use second timestamps. + let timestamp: u128 = + ::Timestamp::now().unique_saturated_into(); + let timestamp: U256 = U256::from(timestamp / 1000); + + ensure!(deadline >= timestamp, revert("Permit expired")); + + let nonce = NoncesStorage::get(from); + + let permit = Self::generate_permit( + handle.context().address, + from, + to, + value, + data.clone(), + gas_limit, + nonce, + deadline, + ); + + let mut sig = [0u8; 65]; + sig[0..32].copy_from_slice(&r.as_bytes()); + sig[32..64].copy_from_slice(&s.as_bytes()); + sig[64] = v; + + let signer = sp_io::crypto::secp256k1_ecdsa_recover(&sig, &permit) + .map_err(|_| revert("Invalid permit"))?; + let signer = H160::from(H256::from_slice(keccak_256(&signer).as_slice())); + + ensure!( + signer != H160::zero() && signer == from, + revert("Invalid permit") + ); + + NoncesStorage::insert(from, nonce + U256::one()); + + // DISPATCH CALL + let sub_context = Context { + caller: from, + address: to.clone(), + apparent_value: value, + }; + + let transfer = if value.is_zero() { + None + } else { + Some(Transfer { + source: from, + target: to.clone(), + value, + }) + }; + + let (reason, output) = + handle.call(to, transfer, data, Some(gas_limit), false, &sub_context); + match reason { + ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }), + ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }), + ExitReason::Revert(_) => Err(PrecompileFailure::Revert { + exit_status: ExitRevert::Reverted, + output, + }), + ExitReason::Succeed(_) => Ok(output.into()), + } + } + + #[precompile::public("nonces(address)")] + #[precompile::view] + fn nonces(handle: &mut impl PrecompileHandle, owner: Address) -> EvmResult { + // NoncesStorage: Blake2_128(16) + contract(20) + Blake2_128(16) + owner(20) + nonce(32) + handle.record_db_read::(104)?; + + let owner: H160 = owner.into(); + + let nonce = NoncesStorage::get(owner); + + Ok(nonce) + } + + #[precompile::public("DOMAIN_SEPARATOR()")] + #[precompile::view] + fn domain_separator(handle: &mut impl PrecompileHandle) -> EvmResult { + // ChainId + handle.record_db_read::(8)?; + + let domain_separator: H256 = + Self::compute_domain_separator(handle.context().address).into(); + + Ok(domain_separator) + } +} diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/mock.rs b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/mock.rs new file mode 100644 index 0000000000..2d5f11533d --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/mock.rs @@ -0,0 +1,195 @@ +// Copyright 2019-2022 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Moonbeam is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Moonbeam. If not, see . + +//! Test utilities +use super::*; + +use frame_support::{construct_runtime, pallet_prelude::*, parameter_types, traits::Everything}; +use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; +use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount}; +use sp_core::H256; +use sp_runtime::{ + traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, Perbill, +}; + +pub type AccountId = MockAccount; +pub type Balance = u128; + +type Block = frame_system::mocking::MockBlockU32; + +construct_runtime!( + pub enum Runtime { + System: frame_system, + Balances: pallet_balances, + Evm: pallet_evm, + Timestamp: pallet_timestamp, + } +); + +parameter_types! { + pub const BlockHashCount: u32 = 250; + pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1); + pub const MaximumBlockLength: u32 = 2 * 1024; + pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub const SS58Prefix: u8 = 42; +} + +impl frame_system::Config for Runtime { + type BaseCallFilter = Everything; + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeTask = RuntimeTask; + type Nonce = u64; + type Block = Block; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + type SingleBlockMigrations = (); + type MultiBlockMigrator = (); + type PreInherents = (); + type PostInherents = (); + type PostTransactions = (); +} +parameter_types! { + pub const ExistentialDeposit: u128 = 0; +} +impl pallet_balances::Config for Runtime { + type MaxReserves = (); + type ReserveIdentifier = [u8; 4]; + type MaxLocks = (); + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type RuntimeFreezeReason = (); +} + +mock_account!(CallPermit, |_| MockAccount::from_u64(1)); +mock_account!(Revert, |_| MockAccount::from_u64(2)); + +pub type Precompiles = PrecompileSetBuilder< + R, + ( + PrecompileAt, CallPermitPrecompile, SubcallWithMaxNesting<0>>, + RevertPrecompile>, + ), +>; + +pub type PCall = CallPermitPrecompileCall; + +parameter_types! { + pub PrecompilesValue: Precompiles = Precompiles::new(); + pub const WeightPerGas: Weight = Weight::from_parts(1, 0); +} + +impl pallet_evm::Config for Runtime { + type FeeCalculator = (); + type GasWeightMapping = pallet_evm::FixedGasWeightMapping; + type WeightPerGas = WeightPerGas; + type CallOrigin = EnsureAddressRoot; + type WithdrawOrigin = EnsureAddressNever; + type AddressMapping = AccountId; + type Currency = Balances; + type RuntimeEvent = RuntimeEvent; + type Runner = pallet_evm::runner::stack::Runner; + type PrecompilesType = Precompiles; + type PrecompilesValue = PrecompilesValue; + type ChainId = (); + type OnChargeTransaction = (); + type BlockGasLimit = (); + type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping; + type FindAuthor = (); + type OnCreate = (); + type GasLimitPovSizeRatio = (); + type SuicideQuickClearLimit = ConstU32<0>; + type Timestamp = Timestamp; + type WeightInfo = pallet_evm::weights::SubstrateWeight; +} + +parameter_types! { + pub const MinimumPeriod: u64 = 5; +} +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + +pub(crate) struct ExtBuilder { + // endowed accounts with balances + balances: Vec<(AccountId, Balance)>, +} + +impl Default for ExtBuilder { + fn default() -> ExtBuilder { + ExtBuilder { balances: vec![] } + } +} + +impl ExtBuilder { + pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { + self.balances = balances; + self + } + + pub(crate) fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + + pallet_balances::GenesisConfig:: { + balances: self.balances, + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + System::set_block_number(1); + pallet_evm::Pallet::::create_account( + Revert.into(), + hex_literal::hex!("1460006000fd").to_vec(), + ); + }); + ext + } +} + +// pub fn balance(account: impl Into) -> Balance { +// pallet_balances::Pallet::::usable_balance(account.into()) +// } diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/tests.rs b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/tests.rs new file mode 100644 index 0000000000..bbf9702f6d --- /dev/null +++ b/runtime/bifrost-polkadot/src/evm/precompiles/call-permit/src/tests.rs @@ -0,0 +1,676 @@ +// Copyright 2019-2022 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Moonbeam is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Moonbeam. If not, see . + +use crate::{ + mock::{CallPermit, ExtBuilder, PCall, Precompiles, PrecompilesValue, Runtime}, + CallPermitPrecompile, +}; +use libsecp256k1::{sign, Message, SecretKey}; +use precompile_utils::{ + evm::costs::call_cost, prelude::*, solidity::revert::revert_as_bytes, testing::*, +}; +use sp_core::{H160, H256, U256}; + +fn precompiles() -> Precompiles { + PrecompilesValue::get() +} + +fn dispatch_cost() -> u64 { + CallPermitPrecompile::::dispatch_inherent_cost() +} + +#[test] +fn selectors() { + assert!(PCall::dispatch_selectors().contains(&0xb5ea0966)); + assert!(PCall::nonces_selectors().contains(&0x7ecebe00)); + assert!(PCall::domain_separator_selectors().contains(&0x3644e515)); +} + +#[test] +fn modifiers() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 1000)]) + .build() + .execute_with(|| { + let mut tester = PrecompilesModifierTester::new(precompiles(), CryptoAlith, CallPermit); + + tester.test_default_modifier(PCall::dispatch_selectors()); + tester.test_view_modifier(PCall::nonces_selectors()); + tester.test_view_modifier(PCall::domain_separator_selectors()); + }); +} + +#[test] +fn valid_permit_returns() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 1000)]) + .build() + .execute_with(|| { + let from: H160 = CryptoAlith.into(); + let to: H160 = Bob.into(); + let value: U256 = 42u8.into(); + let data: Vec = b"Test".to_vec(); + let gas_limit = 100_000u64; + let nonce: U256 = 0u8.into(); + let deadline: U256 = 1_000u32.into(); + let permit = CallPermitPrecompile::::generate_permit( + CallPermit.into(), + from, + to, + value, + data.clone(), + gas_limit, + nonce, + deadline, + ); + + let secret_key = SecretKey::parse(&alith_secret_key()).unwrap(); + let message = Message::parse(&permit); + let (rs, v) = sign(&message, &secret_key); + + precompiles() + .prepare_test( + CryptoAlith, + CallPermit, + PCall::nonces { + owner: Address(CryptoAlith.into()), + }, + ) + .expect_cost(0) // TODO: Test db read/write costs + .expect_no_logs() + .execute_returns(U256::from(0u8)); + + let call_cost = call_cost(value, ::config()); + + precompiles() + .prepare_test( + Charlie, // can be anyone + CallPermit, + PCall::dispatch { + from: Address(from), + to: Address(to), + value, + data: data.into(), + gas_limit, + deadline, + v: v.serialize(), + r: H256::from(rs.r.b32()), + s: H256::from(rs.s.b32()), + }, + ) + .with_subcall_handle(move |subcall| { + let Subcall { + address, + transfer, + input, + target_gas, + is_static, + context, + } = subcall; + + // Called on the behalf of the permit maker. + assert_eq!(context.caller, CryptoAlith.into()); + assert_eq!(address, Bob.into()); + assert_eq!(is_static, false); + assert_eq!(target_gas, Some(100_000), "forward requested gas"); + + let transfer = transfer.expect("there is a transfer"); + assert_eq!(transfer.source, CryptoAlith.into()); + assert_eq!(transfer.target, Bob.into()); + assert_eq!(transfer.value, 42u8.into()); + + assert_eq!(context.address, Bob.into()); + assert_eq!(context.apparent_value, 42u8.into()); + + assert_eq!(&input, b"Test"); + + SubcallOutput { + output: b"TEST".to_vec(), + cost: 13, + logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() + } + }) + .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) + .expect_cost(call_cost + 13 + dispatch_cost()) + .expect_log(log1(Bob, H256::repeat_byte(0x11), vec![])) + .execute_returns(UnboundedBytes::from(b"TEST")); + }) +} + +#[test] +fn valid_permit_reverts() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 1000)]) + .build() + .execute_with(|| { + let from: H160 = CryptoAlith.into(); + let to: H160 = Bob.into(); + let value: U256 = 42u8.into(); + let data: Vec = b"Test".to_vec(); + let gas_limit = 100_000u64; + let nonce: U256 = 0u8.into(); + let deadline: U256 = 1_000u32.into(); + + let permit = CallPermitPrecompile::::generate_permit( + CallPermit.into(), + from, + to, + value, + data.clone(), + gas_limit, + nonce, + deadline, + ); + + let secret_key = SecretKey::parse(&alith_secret_key()).unwrap(); + let message = Message::parse(&permit); + let (rs, v) = sign(&message, &secret_key); + + precompiles() + .prepare_test( + CryptoAlith, + CallPermit, + PCall::nonces { + owner: Address(CryptoAlith.into()), + }, + ) + .expect_cost(0) // TODO: Test db read/write costs + .expect_no_logs() + .execute_returns(U256::from(0u8)); + + let call_cost = call_cost(value, ::config()); + + precompiles() + .prepare_test( + Charlie, // can be anyone + CallPermit, + PCall::dispatch { + from: Address(from), + to: Address(to), + value, + data: data.into(), + gas_limit, + deadline, + v: v.serialize(), + r: H256::from(rs.r.b32()), + s: H256::from(rs.s.b32()), + }, + ) + .with_subcall_handle(move |subcall| { + let Subcall { + address, + transfer, + input, + target_gas, + is_static, + context, + } = subcall; + + // Called on the behalf of the permit maker. + assert_eq!(context.caller, CryptoAlith.into()); + assert_eq!(address, Bob.into()); + assert_eq!(is_static, false); + assert_eq!(target_gas, Some(100_000), "forward requested gas"); + + let transfer = transfer.expect("there is a transfer"); + assert_eq!(transfer.source, CryptoAlith.into()); + assert_eq!(transfer.target, Bob.into()); + assert_eq!(transfer.value, 42u8.into()); + + assert_eq!(context.address, Bob.into()); + assert_eq!(context.apparent_value, 42u8.into()); + + assert_eq!(&input, b"Test"); + + SubcallOutput { + output: revert_as_bytes("TEST"), + cost: 13, + ..SubcallOutput::revert() + } + }) + .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) + .expect_cost(call_cost + 13 + dispatch_cost()) + .expect_no_logs() + .execute_reverts(|x| x == b"TEST".to_vec()); + }) +} + +#[test] +fn invalid_permit_nonce() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 1000)]) + .build() + .execute_with(|| { + let from: H160 = CryptoAlith.into(); + let to: H160 = Bob.into(); + let value: U256 = 42u8.into(); + let data: Vec = b"Test".to_vec(); + let gas_limit = 100_000u64; + let nonce: U256 = 1u8.into(); // WRONG NONCE + let deadline: U256 = 1_000u32.into(); + + let permit = CallPermitPrecompile::::generate_permit( + CallPermit.into(), + from, + to, + value, + data.clone(), + gas_limit, + nonce, + deadline, + ); + + let secret_key = SecretKey::parse(&alith_secret_key()).unwrap(); + let message = Message::parse(&permit); + let (rs, v) = sign(&message, &secret_key); + + precompiles() + .prepare_test( + CryptoAlith, + CallPermit, + PCall::nonces { + owner: Address(CryptoAlith.into()), + }, + ) + .expect_cost(0) // TODO: Test db read/write costs + .expect_no_logs() + .execute_returns(U256::from(0u8)); + + let call_cost = call_cost(value, ::config()); + + precompiles() + .prepare_test( + Charlie, // can be anyone + CallPermit, + PCall::dispatch { + from: Address(from), + to: Address(to), + value, + data: data.into(), + gas_limit, + deadline, + v: v.serialize(), + r: H256::from(rs.r.b32()), + s: H256::from(rs.s.b32()), + }, + ) + .with_subcall_handle(move |_| panic!("should not perform subcall")) + .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) + .expect_cost(dispatch_cost()) + .execute_reverts(|x| x == b"Invalid permit"); + }) +} + +#[test] +fn invalid_permit_gas_limit_too_low() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 1000)]) + .build() + .execute_with(|| { + let from: H160 = CryptoAlith.into(); + let to: H160 = Bob.into(); + let value: U256 = 42u8.into(); + let data: Vec = b"Test".to_vec(); + let gas_limit = 100_000u64; + let nonce: U256 = 0u8.into(); + let deadline: U256 = 1_000u32.into(); + + let permit = CallPermitPrecompile::::generate_permit( + CallPermit.into(), + from, + to, + value, + data.clone(), + gas_limit, + nonce, + deadline, + ); + + let secret_key = SecretKey::parse(&alith_secret_key()).unwrap(); + let message = Message::parse(&permit); + let (rs, v) = sign(&message, &secret_key); + + precompiles() + .prepare_test( + CryptoAlith, + CallPermit, + PCall::nonces { + owner: Address(CryptoAlith.into()), + }, + ) + .expect_cost(0) // TODO: Test db read/write costs + .expect_no_logs() + .execute_returns(U256::from(0u8)); + + let call_cost = call_cost(value, ::config()); + + precompiles() + .prepare_test( + Charlie, // can be anyone + CallPermit, + PCall::dispatch { + from: Address(from), + to: Address(to), + value, + data: data.into(), + gas_limit, + deadline, + v: v.serialize(), + r: H256::from(rs.r.b32()), + s: H256::from(rs.s.b32()), + }, + ) + .with_subcall_handle(move |_| panic!("should not perform subcall")) + .with_target_gas(Some(call_cost + 99_999 + dispatch_cost())) + .expect_cost(dispatch_cost()) + .execute_reverts(|x| x == b"Gaslimit is too low to dispatch provided call"); + }) +} + +#[test] +fn invalid_permit_gas_limit_overflow() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 1000)]) + .build() + .execute_with(|| { + let from: H160 = CryptoAlith.into(); + let to: H160 = Bob.into(); + let value: U256 = 42u8.into(); + let data: Vec = b"Test".to_vec(); + let gas_limit = u64::MAX; + let nonce: U256 = 0u8.into(); + let deadline: U256 = 1_000u32.into(); + + let permit = CallPermitPrecompile::::generate_permit( + CallPermit.into(), + from, + to, + value, + data.clone(), + gas_limit, + nonce, + deadline, + ); + + dbg!(H256::from(permit)); + + let secret_key = SecretKey::parse(&alith_secret_key()).unwrap(); + let message = Message::parse(&permit); + let (rs, v) = sign(&message, &secret_key); + + precompiles() + .prepare_test( + CryptoAlith, + CallPermit, + PCall::nonces { + owner: Address(CryptoAlith.into()), + }, + ) + .expect_cost(0) // TODO: Test db read/write costs + .expect_no_logs() + .execute_returns(U256::from(0u8)); + + precompiles() + .prepare_test( + Charlie, // can be anyone + CallPermit, + PCall::dispatch { + from: Address(from), + to: Address(to), + value, + data: data.into(), + gas_limit, + deadline, + v: v.serialize(), + r: H256::from(rs.r.b32()), + s: H256::from(rs.s.b32()), + }, + ) + .with_subcall_handle(move |_| panic!("should not perform subcall")) + .with_target_gas(Some(100_000 + dispatch_cost())) + .expect_cost(dispatch_cost()) + .execute_reverts(|x| x == b"Call require too much gas (uint64 overflow)"); + }) +} + +// // This test checks the validity of a metamask signed message against the permit precompile +// // The code used to generate the signature is the following. +// // You will need to import CryptoAlith_PRIV_KEY in metamask. +// // If you put this code in the developer tools console, it will log the signature + +// await window.ethereum.enable(); +// const accounts = await window.ethereum.request({ method: "eth_requestAccounts" }); + +// const from = accounts[0]; +// const to = "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +// const value = 42; +// const data = "0xdeadbeef"; +// const gaslimit = 100000; +// const nonce = 0; +// const deadline = 1000; + +// const createPermitMessageData = function () { +// const message = { +// from: from, +// to: to, +// value: value, +// data: data, +// gaslimit: gaslimit, +// nonce: nonce, +// deadline: deadline, +// }; + +// const typedData = JSON.stringify({ +// types: { +// EIP712Domain: [ +// { +// name: "name", +// type: "string", +// }, +// { +// name: "version", +// type: "string", +// }, +// { +// name: "chainId", +// type: "uint256", +// }, +// { +// name: "verifyingContract", +// type: "address", +// }, +// ], +// CallPermit: [ +// { +// name: "from", +// type: "address", +// }, +// { +// name: "to", +// type: "address", +// }, +// { +// name: "value", +// type: "uint256", +// }, +// { +// name: "data", +// type: "bytes", +// }, +// { +// name: "gaslimit", +// type: "uint64", +// }, +// { +// name: "nonce", +// type: "uint256", +// }, +// { +// name: "deadline", +// type: "uint256", +// }, +// ], +// }, +// primaryType: "CallPermit", +// domain: { +// name: "Call Permit CallPermit", +// version: "1", +// chainId: 0, +// verifyingContract: "0x0000000000000000000000000000000000000001", +// }, +// message: message, +// }); + +// return { +// typedData, +// message, +// }; +// }; + +// const method = "eth_signTypedData_v4" +// const messageData = createPermitMessageData(); +// const params = [from, messageData.typedData]; + +// web3.currentProvider.sendAsync( +// { +// method, +// params, +// from, +// }, +// function (err, result) { +// if (err) return console.dir(err); +// if (result.error) { +// alert(result.error.message); +// } +// if (result.error) return console.error('ERROR', result); +// console.log('TYPED SIGNED:' + JSON.stringify(result.result)); + +// const recovered = sigUtil.recoverTypedSignature_v4({ +// data: JSON.parse(msgParams), +// sig: result.result, +// }); + +// if ( +// ethUtil.toChecksumAddress(recovered) === ethUtil.toChecksumAddress(from) +// ) { +// alert('Successfully recovered signer as ' + from); +// } else { +// alert( +// 'Failed to verify signer when comparing ' + result + ' to ' + from +// ); +// } +// } +// ); +#[test] +fn valid_permit_returns_with_metamask_signed_data() { + ExtBuilder::default() + .with_balances(vec![(CryptoAlith.into(), 2000)]) + .build() + .execute_with(|| { + let from: H160 = CryptoAlith.into(); + let to: H160 = Bob.into(); + let value: U256 = 42u8.into(); + let data: Vec = hex_literal::hex!("deadbeef").to_vec(); + let gas_limit = 100_000u64; + let deadline: U256 = 1_000u32.into(); + + // Made with MetaMask + let rsv = hex_literal::hex!( + "56b497d556cb1b57a16aac6e8d53f3cbf1108df467ffcb937a3744369a27478f608de05 + 34b8e0385e55ffd97cbafcfeac12ab52d0b74a2dea582bc8de46f257d1c" + ) + .as_slice(); + let (r, sv) = rsv.split_at(32); + let (s, v) = sv.split_at(32); + let v_real = v[0]; + let r_real: [u8; 32] = r.try_into().unwrap(); + let s_real: [u8; 32] = s.try_into().unwrap(); + + precompiles() + .prepare_test( + CryptoAlith, + CallPermit, + PCall::nonces { + owner: Address(CryptoAlith.into()), + }, + ) + .expect_cost(0) // TODO: Test db read/write costs + .expect_no_logs() + .execute_returns(U256::from(0u8)); + + let call_cost = call_cost(value, ::config()); + + precompiles() + .prepare_test( + Charlie, // can be anyone + CallPermit, + PCall::dispatch { + from: Address(from), + to: Address(to), + value, + data: data.clone().into(), + gas_limit, + deadline, + v: v_real, + r: r_real.into(), + s: s_real.into(), + }, + ) + .with_subcall_handle(move |subcall| { + let Subcall { + address, + transfer, + input, + target_gas, + is_static, + context, + } = subcall; + + // Called on the behalf of the permit maker. + assert_eq!(context.caller, CryptoAlith.into()); + assert_eq!(address, Bob.into()); + assert_eq!(is_static, false); + assert_eq!(target_gas, Some(100_000), "forward requested gas"); + + let transfer = transfer.expect("there is a transfer"); + assert_eq!(transfer.source, CryptoAlith.into()); + assert_eq!(transfer.target, Bob.into()); + assert_eq!(transfer.value, 42u8.into()); + + assert_eq!(context.address, Bob.into()); + assert_eq!(context.apparent_value, 42u8.into()); + + assert_eq!(&input, &data); + + SubcallOutput { + output: b"TEST".to_vec(), + cost: 13, + logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() + } + }) + .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) + .expect_cost(call_cost + 13 + dispatch_cost()) + .expect_log(log1(Bob, H256::repeat_byte(0x11), vec![])) + .execute_returns(UnboundedBytes::from(b"TEST")); + }) +} + +#[test] +fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { + check_precompile_implements_solidity_interfaces(&["CallPermit.sol"], PCall::supports_selector) +} diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/costs.rs b/runtime/bifrost-polkadot/src/evm/precompiles/costs.rs index adb0259f1b..980909b166 100644 --- a/runtime/bifrost-polkadot/src/evm/precompiles/costs.rs +++ b/runtime/bifrost-polkadot/src/evm/precompiles/costs.rs @@ -29,15 +29,23 @@ pub fn log_costs(topics: usize, data_len: usize) -> EvmResult { let topic_cost = G_LOGTOPIC .checked_mul(topics as u64) - .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas })?; + .ok_or(PrecompileFailure::Error { + exit_status: ExitError::OutOfGas, + })?; let data_cost = G_LOGDATA .checked_mul(data_len as u64) - .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas })?; + .ok_or(PrecompileFailure::Error { + exit_status: ExitError::OutOfGas, + })?; G_LOG .checked_add(topic_cost) - .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas })? + .ok_or(PrecompileFailure::Error { + exit_status: ExitError::OutOfGas, + })? .checked_add(data_cost) - .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) + .ok_or(PrecompileFailure::Error { + exit_status: ExitError::OutOfGas, + }) } diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/erc20_mapping.rs b/runtime/bifrost-polkadot/src/evm/precompiles/erc20_mapping.rs index 763b3275b3..dcce6f1980 100644 --- a/runtime/bifrost-polkadot/src/evm/precompiles/erc20_mapping.rs +++ b/runtime/bifrost-polkadot/src/evm/precompiles/erc20_mapping.rs @@ -16,6 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +#![allow(dead_code)] use crate::evm::precompiles::EvmAddress; use bifrost_primitives::CurrencyId; use parity_scale_codec::{Decode, Encode}; @@ -42,10 +43,12 @@ impl Erc20Mapping for BifrostErc20Mapping { evm_address_bytes[0..4].copy_from_slice(CURRENCY_PRECOMPILE_ADDRESS_PREFIX); match currency_id { - CurrencyId::VSBond(..) | CurrencyId::VSBond2(..) => - evm_address_bytes[6..].copy_from_slice(asset_id_bytes.as_slice()), - CurrencyId::LPToken(..) => - evm_address_bytes[15..].copy_from_slice(asset_id_bytes.as_slice()), + CurrencyId::VSBond(..) | CurrencyId::VSBond2(..) => { + evm_address_bytes[6..].copy_from_slice(asset_id_bytes.as_slice()) + } + CurrencyId::LPToken(..) => { + evm_address_bytes[15..].copy_from_slice(asset_id_bytes.as_slice()) + } _ => evm_address_bytes[18..].copy_from_slice(asset_id_bytes.as_slice()), }; diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/handle.rs b/runtime/bifrost-polkadot/src/evm/precompiles/handle.rs index 0eeb423432..aaab253d75 100644 --- a/runtime/bifrost-polkadot/src/evm/precompiles/handle.rs +++ b/runtime/bifrost-polkadot/src/evm/precompiles/handle.rs @@ -16,6 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +#![allow(dead_code)] use crate::evm::precompiles::{costs, revert, Address, Bytes, EvmResult}; use pallet_evm::{Context, Log, PrecompileHandle}; use primitive_types::{H160, H256, U256}; @@ -40,7 +41,11 @@ pub struct EvmDataWriter { impl EvmDataWriter { /// Creates a new empty output builder (without selector). pub fn new() -> Self { - Self { data: vec![], offset_data: vec![], selector: None } + Self { + data: vec![], + offset_data: vec![], + selector: None, + } } /// Return the built data. @@ -101,7 +106,11 @@ impl EvmDataWriter { let offset_position = self.data.len(); H256::write(self, H256::repeat_byte(0xff)); - self.offset_data.push(OffsetDatum { offset_position, data, offset_shift: 0 }); + self.offset_data.push(OffsetDatum { + offset_position, + data, + offset_shift: 0, + }); } } @@ -213,7 +222,10 @@ impl EvmData for Bytes { value.resize(padded_size, 0); writer.write_pointer( - EvmDataWriter::new().write(U256::from(length)).write_raw_bytes(&value).build(), + EvmDataWriter::new() + .write(U256::from(length)) + .write_raw_bytes(&value) + .build(), ); } @@ -357,7 +369,10 @@ impl<'a> EvmDataReader<'a> { return Err(revert("pointer points out of bounds")); } - Ok(Self { input: &self.input[offset..], cursor: 0 }) + Ok(Self { + input: &self.input[offset..], + cursor: 0, + }) } /// Move the reading cursor with provided length, and return a range from the previous cursor diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/mod.rs b/runtime/bifrost-polkadot/src/evm/precompiles/mod.rs index 56fe7ef921..4180c12965 100644 --- a/runtime/bifrost-polkadot/src/evm/precompiles/mod.rs +++ b/runtime/bifrost-polkadot/src/evm/precompiles/mod.rs @@ -91,6 +91,7 @@ pub const BN_ADD: H160 = H160(hex!("0000000000000000000000000000000000000006")); pub const BN_MUL: H160 = H160(hex!("0000000000000000000000000000000000000007")); pub const BN_PAIRING: H160 = H160(hex!("0000000000000000000000000000000000000008")); pub const BLAKE2F: H160 = H160(hex!("0000000000000000000000000000000000000009")); +pub const CALLPERMIT: H160 = H160(hex!("000000000000000000000000000000000000080a")); pub const ETH_PRECOMPILE_END: H160 = BLAKE2F; @@ -135,8 +136,12 @@ where Some(Bn128Pairing::execute(handle)) } else if address == BLAKE2F { Some(Blake2F::execute(handle)) + } else if address == CALLPERMIT { + Some(pallet_evm_precompile_call_permit::CallPermitPrecompile::::execute(handle)) } else if address == DISPATCH_ADDR { - Some(pallet_evm_precompile_dispatch::Dispatch::::execute(handle)) + Some(pallet_evm_precompile_dispatch::Dispatch::::execute( + handle, + )) } else if is_asset_address(address) { Some(MultiCurrencyPrecompile::::execute(handle)) } else { @@ -145,10 +150,13 @@ where } fn is_precompile(&self, address: H160, _remaining_gas: u64) -> IsPrecompileResult { - let is_precompile = address == DISPATCH_ADDR || - is_asset_address(address) || - is_standard_precompile(address); - IsPrecompileResult::Answer { is_precompile, extra_cost: 0 } + let is_precompile = address == DISPATCH_ADDR + || is_asset_address(address) + || is_standard_precompile(address); + IsPrecompileResult::Answer { + is_precompile, + extra_cost: 0, + } } } @@ -158,7 +166,9 @@ where // function. pub const fn addr(a: u64) -> H160 { let b = a.to_be_bytes(); - H160([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) + H160([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], + ]) } pub fn revert(output: impl AsRef<[u8]>) -> PrecompileFailure { @@ -169,7 +179,10 @@ pub fn revert(output: impl AsRef<[u8]>) -> PrecompileFailure { } pub fn succeed(output: impl AsRef<[u8]>) -> PrecompileOutput { - PrecompileOutput { exit_status: ExitSucceed::Returned, output: output.as_ref().to_owned() } + PrecompileOutput { + exit_status: ExitSucceed::Returned, + output: output.as_ref().to_owned(), + } } pub struct Output; diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/multicurrency.rs b/runtime/bifrost-polkadot/src/evm/precompiles/multicurrency.rs index 85c571694e..5c2c99e44a 100644 --- a/runtime/bifrost-polkadot/src/evm/precompiles/multicurrency.rs +++ b/runtime/bifrost-polkadot/src/evm/precompiles/multicurrency.rs @@ -126,7 +126,7 @@ where Some(metadata) => { let encoded = Output::encode_bytes(metadata.name.as_slice()); Ok(succeed(encoded)) - }, + } None => Err(PrecompileFailure::Error { exit_status: pallet_evm::ExitError::Other("Non-existing asset.".into()), }), @@ -144,7 +144,7 @@ where Some(metadata) => { let encoded = Output::encode_bytes(metadata.symbol.as_slice()); Ok(succeed(encoded)) - }, + } None => Err(PrecompileFailure::Error { exit_status: pallet_evm::ExitError::Other("Non-existing asset.".into()), }), @@ -162,7 +162,7 @@ where Some(metadata) => { let encoded = Output::encode_uint::(metadata.decimals); Ok(succeed(encoded)) - }, + } None => Err(PrecompileFailure::Error { exit_status: pallet_evm::ExitError::Other("Non-existing asset.".into()), }), diff --git a/runtime/bifrost-polkadot/src/evm/precompiles/tests/erc20_mapping.rs b/runtime/bifrost-polkadot/src/evm/precompiles/tests/erc20_mapping.rs index 266a062f2b..0ec72e0606 100644 --- a/runtime/bifrost-polkadot/src/evm/precompiles/tests/erc20_mapping.rs +++ b/runtime/bifrost-polkadot/src/evm/precompiles/tests/erc20_mapping.rs @@ -44,14 +44,38 @@ macro_rules! decode_optional { #[test] fn decode_asset_id_from_evm_address_should_work() { - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000001")), CurrencyId::Native(BNC)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000800")), CurrencyId::Token2(0)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000900")), CurrencyId::VToken2(0)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000204")), CurrencyId::Token(KSM)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000104")), CurrencyId::VToken(KSM)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000404")), CurrencyId::VSToken(KSM)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000a00")), CurrencyId::VSToken2(0)); - assert_eq!(decode!(hex!("ffffffff00000000000000000000000000000a00")), CurrencyId::VSToken2(0)); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000001")), + CurrencyId::Native(BNC) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000800")), + CurrencyId::Token2(0) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000900")), + CurrencyId::VToken2(0) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000204")), + CurrencyId::Token(KSM) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000104")), + CurrencyId::VToken(KSM) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000404")), + CurrencyId::VSToken(KSM) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000a00")), + CurrencyId::VSToken2(0) + ); + assert_eq!( + decode!(hex!("ffffffff00000000000000000000000000000a00")), + CurrencyId::VSToken2(0) + ); assert_eq!( decode!(hex!("ffffffff00000b00000000000000000000000000")), CurrencyId::VSBond2(0, 0, 0, 0) @@ -68,12 +92,30 @@ fn decode_asset_id_from_evm_address_should_work() { #[test] fn decode_asset_id_from_evm_address_should_not_work_with_invalid_asset_addresses() { - assert_eq!(decode_optional!(hex!("0000000000000000000000000000000200000000")), None); - assert_eq!(decode_optional!(hex!("0000000000000000000000000000000000000001")), None); - assert_eq!(decode_optional!(hex!("90000000000000000000000000000001ffffffff")), None); - assert_eq!(decode_optional!(hex!("0000000000000000000000000000001100000003")), None); - assert_eq!(decode_optional!(hex!("0000000000000000900000000000000100000003")), None); - assert_eq!(decode_optional!(hex!("7777777777777777777777777777777777777777")), None); + assert_eq!( + decode_optional!(hex!("0000000000000000000000000000000200000000")), + None + ); + assert_eq!( + decode_optional!(hex!("0000000000000000000000000000000000000001")), + None + ); + assert_eq!( + decode_optional!(hex!("90000000000000000000000000000001ffffffff")), + None + ); + assert_eq!( + decode_optional!(hex!("0000000000000000000000000000001100000003")), + None + ); + assert_eq!( + decode_optional!(hex!("0000000000000000900000000000000100000003")), + None + ); + assert_eq!( + decode_optional!(hex!("7777777777777777777777777777777777777777")), + None + ); } #[test] @@ -103,7 +145,12 @@ fn encode_asset_id_to_evm_address_should_work() { H160::from(hex!("ffffffff00000b00000000000000000000000000")) ); assert_eq!( - encode!(CurrencyId::LPToken(TokenSymbol::BNC, 0, TokenSymbol::DOT, 0)), + encode!(CurrencyId::LPToken( + TokenSymbol::BNC, + 0, + TokenSymbol::DOT, + 0 + )), H160::from(hex!("ffffffff00000000000000000000000601000300")) ); assert_eq!( diff --git a/runtime/bifrost-polkadot/src/evm/runner.rs b/runtime/bifrost-polkadot/src/evm/runner.rs index 1bce826537..4c84772410 100644 --- a/runtime/bifrost-polkadot/src/evm/runner.rs +++ b/runtime/bifrost-polkadot/src/evm/runner.rs @@ -66,8 +66,12 @@ where ) -> Result { let from_currency = AC::get_fee_currency(account, fee) .map_err(|_| DispatchError::Other("Get Currency Error."))?; - let account_balance = - I::reducible_balance(from_currency, account, Preservation::Preserve, Fortitude::Polite); + let account_balance = I::reducible_balance( + from_currency, + account, + Preservation::Preserve, + Fortitude::Polite, + ); let price_weight = T::DbWeight::get().reads(2); // 1 read to get currency and 1 read to get balance if from_currency == to_currency { @@ -117,11 +121,11 @@ where let account_id = T::AddressMapping::into_account_id(source); let account_nonce = frame_system::Pallet::::account_nonce(&account_id); - let (balance, b_weight) = B::get_balance_in_currency(evm_currency, &account_id, base_fee) - .map_err(|_| RunnerError { - error: R::Error::from(TransactionValidationError::BalanceTooLow), - weight, - })?; + let (balance, b_weight) = + match B::get_balance_in_currency(evm_currency, &account_id, base_fee) { + Ok((balance, b_weight)) => (balance, b_weight), + Err(_) => (0, T::DbWeight::get().reads(2)), + }; let (source_account, inner_weight) = ( Account { diff --git a/runtime/bifrost-polkadot/src/governance/fellowship.rs b/runtime/bifrost-polkadot/src/governance/fellowship.rs index bbcec0fdca..9ce9a26510 100644 --- a/runtime/bifrost-polkadot/src/governance/fellowship.rs +++ b/runtime/bifrost-polkadot/src/governance/fellowship.rs @@ -361,4 +361,5 @@ impl pallet_ranked_collective::Config for Runtime type RemoveOrigin = Self::DemoteOrigin; #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (); + type MaxMemberCount = (); } diff --git a/runtime/bifrost-polkadot/src/governance/tracks.rs b/runtime/bifrost-polkadot/src/governance/tracks.rs index 613fc32fcb..7253b0b9b6 100644 --- a/runtime/bifrost-polkadot/src/governance/tracks.rs +++ b/runtime/bifrost-polkadot/src/governance/tracks.rs @@ -173,14 +173,15 @@ impl pallet_referenda::TracksInfo for TracksInfo { if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) { match system_origin { frame_system::RawOrigin::Root => { - if let Some((track_id, _)) = - Self::tracks().into_iter().find(|(_, track)| track.name == "root") + if let Some((track_id, _)) = Self::tracks() + .into_iter() + .find(|(_, track)| track.name == "root") { Ok(*track_id) } else { Err(()) } - }, + } _ => Err(()), } } else if let Ok(custom_origin) = custom_origins::Origin::try_from(id.clone()) { @@ -206,8 +207,8 @@ impl pallet_referenda::TracksInfo for TracksInfo { fn vote_locking_always_longer_than_enactment_period() { for (_, track) in TRACKS_DATA { assert!( - ::VoteLockingPeriod::get() >= - track.min_enactment_period, + ::VoteLockingPeriod::get() + >= track.min_enactment_period, "Track {} has enactment period {} < vote locking period {}", track.name, track.min_enactment_period, diff --git a/runtime/bifrost-polkadot/src/lib.rs b/runtime/bifrost-polkadot/src/lib.rs index a7948bcec3..10ae22c4f7 100644 --- a/runtime/bifrost-polkadot/src/lib.rs +++ b/runtime/bifrost-polkadot/src/lib.rs @@ -38,7 +38,7 @@ use bifrost_primitives::{ IncentivePalletId, IncentivePoolAccount, LendMarketPalletId, LiquidityAccount, LocalBncLocation, MerkleDirtributorPalletId, OraclePalletId, ParachainStakingPalletId, SlpEntrancePalletId, SlpExitPalletId, SystemMakerPalletId, SystemStakingPalletId, - TreasuryPalletId, BNC, VDOT, + TreasuryPalletId, BNC, DOT, VDOT, }; use cumulus_pallet_parachain_system::{RelayNumberMonotonicallyIncreases, RelaychainDataProvider}; pub use frame_support::{ @@ -146,7 +146,7 @@ use governance::{ TechAdminOrCouncil, }; use xcm::IntoVersion; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -188,7 +188,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bifrost_polkadot"), impl_name: create_runtime_str!("bifrost_polkadot"), authoring_version: 0, - spec_version: 15003, + spec_version: 16000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -198,7 +198,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } /// We assume that ~10% of the block weight is consumed by `on_initalize` handlers. @@ -236,12 +239,12 @@ parameter_types! { }) .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) .build_or_panic(); - pub const SS58Prefix: u8 = 6; + pub const SS58Prefix: u8 = 0; } parameter_types! { - pub const NativeCurrencyId: CurrencyId = CurrencyId::Native(TokenSymbol::BNC); - pub const RelayCurrencyId: CurrencyId = CurrencyId::Token2(DOT_TOKEN_ID); + pub const NativeCurrencyId: CurrencyId = BNC; + pub const RelayCurrencyId: CurrencyId = DOT; pub const RelayVCurrencyId: CurrencyId = VDOT; pub SelfParaId: u32 = ParachainInfo::parachain_id().into(); } @@ -386,24 +389,30 @@ impl InstanceFilter for ProxyType { RuntimeCall::ParachainStaking(..) ), ProxyType::Staking => { - matches!(c, RuntimeCall::ParachainStaking(..) | RuntimeCall::Utility(..)) - }, + matches!( + c, + RuntimeCall::ParachainStaking(..) | RuntimeCall::Utility(..) + ) + } ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) | - RuntimeCall::Council(..) | - RuntimeCall::TechnicalCommittee(..) | - RuntimeCall::PhragmenElection(..) | - RuntimeCall::Treasury(..) | - RuntimeCall::Utility(..) + RuntimeCall::Democracy(..) + | RuntimeCall::Council(..) + | RuntimeCall::TechnicalCommittee(..) + | RuntimeCall::PhragmenElection(..) + | RuntimeCall::Treasury(..) + | RuntimeCall::Utility(..) ), ProxyType::CancelProxy => { - matches!(c, RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })) - }, + matches!( + c, + RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) + ) + } ProxyType::IdentityJudgement => matches!( c, - RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) | - RuntimeCall::Utility(..) + RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) + | RuntimeCall::Utility(..) ), } } @@ -750,13 +759,7 @@ parameter_types! { pub const MaxBalance: Balance = 800_000 * BNCS; } -type ApproveOrigin = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, ->; - impl pallet_treasury::Config for Runtime { - type ApproveOrigin = ApproveOrigin; type SpendOrigin = EitherOf, Spender>; type Burn = Burn; type BurnDestination = (); @@ -771,11 +774,7 @@ impl pallet_treasury::Config for Runtime { type PayoutPeriod = PayoutSpendPeriod; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); - type OnSlash = Treasury; type PalletId = TreasuryPalletId; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; type RejectOrigin = MoreThanHalfCouncil; type SpendFunds = (); type SpendPeriod = SpendPeriod; @@ -796,7 +795,10 @@ impl pallet_transaction_payment::Config for Runtime { pub struct TxPauseWhitelistedCalls; impl Contains> for TxPauseWhitelistedCalls { fn contains(full_name: &pallet_tx_pause::RuntimeCallNameOf) -> bool { - matches!(full_name.0.as_slice(), b"System" | b"Timestamp" | b"TxPause") + matches!( + full_name.0.as_slice(), + b"System" | b"Timestamp" | b"TxPause" + ) } } @@ -959,6 +961,7 @@ impl bifrost_vesting::Config for Runtime { type WeightInfo = weights::bifrost_vesting::BifrostWeight; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; const MAX_VESTING_SCHEDULES: u32 = 28; + type BlockNumberProvider = System; } // Bifrost modules start @@ -983,6 +986,9 @@ impl bifrost_flexible_fee::Config for Runtime { type XcmRouter = XcmRouter; type PalletId = FlexibleFeePalletId; type OraclePriceProvider = Prices; + type InspectEvmAccounts = EVMAccounts; + type EvmPermit = evm::permit::EvmPermitHandler; + type AssetIdMaps = AssetIdMaps; } parameter_types! { @@ -1009,7 +1015,7 @@ pub fn create_x2_multilocation(index: u16, currency_id: CurrencyId) -> MultiLoca ), ), // Only relay chain use the Bifrost para account with "para" - CurrencyId::Token2(DOT_TOKEN_ID) => xcm::v3::Location::new( + DOT => xcm::v3::Location::new( 1, xcm::v3::Junctions::X1(xcm::v3::Junction::AccountId32 { network: None, @@ -1021,7 +1027,7 @@ pub fn create_x2_multilocation(index: u16, currency_id: CurrencyId) -> MultiLoca }), ), // Bifrost Polkadot Native token - CurrencyId::Native(TokenSymbol::BNC) => xcm::v3::Location::new( + BNC => xcm::v3::Location::new( 0, xcm::v3::Junctions::X1(xcm::v3::Junction::AccountId32 { network: None, @@ -1063,7 +1069,7 @@ pub fn create_x2_multilocation(index: u16, currency_id: CurrencyId) -> MultiLoca } else { xcm::v3::Location::default() } - }, + } } } @@ -1180,6 +1186,7 @@ impl bifrost_slp::Config for Runtime { type StablePoolHandler = StablePool; type AssetIdMaps = AssetIdMaps; type TreasuryAccount = BifrostTreasuryAccount; + type BlockNumberProvider = System; } parameter_types! { @@ -1215,6 +1222,7 @@ impl bifrost_farming::Config for Runtime { type BlockNumberToBalance = ConvertInto; type WhitelistMaximumLimit = WhitelistMaximumLimit; type GaugeRewardIssuer = FarmingGaugeRewardIssuerPalletId; + type BlockNumberProvider = System; } parameter_types! { @@ -1236,6 +1244,7 @@ impl bifrost_system_staking::Config for Runtime { type BlocksPerRound = BlocksPerRound; type MaxTokenLen = MaxTokenLen; type MaxFarmingPoolIdLen = MaxFarmingPoolIdLen; + type BlockNumberProvider = System; } impl bifrost_fee_share::Config for Runtime { @@ -1245,6 +1254,7 @@ impl bifrost_fee_share::Config for Runtime { type WeightInfo = weights::bifrost_fee_share::BifrostWeight; type FeeSharePalletId = FeeSharePalletId; type OraclePriceProvider = Prices; + type BlockNumberProvider = System; } impl bifrost_cross_in_out::Config for Runtime { @@ -1269,6 +1279,7 @@ impl bifrost_slpx::Config for Runtime { type ParachainId = ParachainInfo; type WeightInfo = weights::bifrost_slpx::BifrostWeight; type MaxOrderSize = ConstU32<500>; + type BlockNumberProvider = System; } pub struct EnsurePoolAssetId; @@ -1293,6 +1304,7 @@ impl bifrost_stable_asset::Config for Runtime { type WeightInfo = (); type ListingOrigin = TechAdminOrCouncil; type EnsurePoolAssetId = EnsurePoolAssetId; + type BlockNumberProvider = System; } impl bifrost_stable_pool::Config for Runtime { @@ -1419,11 +1431,13 @@ impl bifrost_vtoken_minting::Config for Runtime { type MaxLockRecords = ConstU32<100>; type IncentivePoolAccount = IncentivePoolAccount; type BbBNC = BbBNC; + type BlockNumberProvider = System; } parameter_types! { pub const BbBNCTokenType: CurrencyId = CurrencyId::VToken(TokenSymbol::BNC); pub const Week: BlockNumber = prod_or_fast!(WEEKS, 10); + pub const OneYear: BlockNumber = 365 * DAYS; pub const MaxBlock: BlockNumber = 4 * 365 * DAYS; pub const Multiplier: Balance = 10_u128.pow(12); pub const VoteWeightMultiplier: Balance = 1; @@ -1446,6 +1460,11 @@ impl bb_bnc::Config for Runtime { type VoteWeightMultiplier = VoteWeightMultiplier; type MaxPositions = MaxPositions; type MarkupRefreshLimit = MarkupRefreshLimit; + type VtokenMinting = VtokenMinting; + type FarmingInfo = Farming; + type FourYears = MaxBlock; + type OneYear = OneYear; + type BlockNumberProvider = System; } parameter_types! { @@ -1529,6 +1548,7 @@ impl lend_market::Config for Runtime { type RewardAssetId = NativeCurrencyId; type LiquidationFreeAssetId = RelayCurrencyId; type MaxLengthLimit = MaxLengthLimit; + type BlockNumberProvider = System; } parameter_types! { @@ -1573,6 +1593,7 @@ impl bifrost_channel_commission::Config for Runtime { type WeightInfo = weights::bifrost_channel_commission::BifrostWeight; type ClearingDuration = ClearingDuration; type NameLengthLimit = NameLengthLimit; + type BlockNumberProvider = System; } impl bifrost_clouds_convert::Config for Runtime { @@ -1596,6 +1617,7 @@ impl bifrost_buy_back::Config for Runtime { type ParachainId = ParachainInfo; type CurrencyIdRegister = AssetIdMaps; type BbBNC = BbBNC; + type BlockNumberProvider = System; } impl bifrost_slp_v2::Config for Runtime { @@ -1905,7 +1927,7 @@ pub mod migrations { pub type Unreleased = ( // permanent migration, do not remove pallet_xcm::migration::MigrateToLatestXcmVersion, - bifrost_vtoken_voting::migration::v4::MigrateToV4, + bifrost_channel_commission::migrations::v1::MigrateToV1, ); } @@ -1955,8 +1977,9 @@ 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, } } @@ -1966,10 +1989,11 @@ 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, } } @@ -1986,6 +2010,9 @@ mod benches { [bifrost_buy_back, BuyBack] [bifrost_slp_v2, SlpV2] [bifrost_xcm_interface, XcmInterface] + [bifrost_farming, Farming] + [bifrost_clouds_convert, CloudsConvert] + [pallet_evm_accounts, EVMAccounts] ); } @@ -2123,7 +2150,7 @@ impl fp_rpc::EthereumRuntimeRPCApi for Runtime { }; // don't allow calling EVM RPC or Runtime API from a bound address - if EVMAccounts::bound_account_id(from).is_some() { + if !estimate && EVMAccounts::bound_account_id(from).is_some() { return Err(pallet_evm_accounts::Error::::BoundAddressCannotBeUsed.into()) }; @@ -2204,9 +2231,9 @@ impl fp_rpc::EthereumRuntimeRPCApi for Runtime { }; // don't allow calling EVM RPC or Runtime API from a bound address - if EVMAccounts::bound_account_id(from).is_some() { + if !estimate && EVMAccounts::bound_account_id(from).is_some() { return Err(pallet_evm_accounts::Error::::BoundAddressCannotBeUsed.into()) - }; + }; // the address needs to have a permission to deploy smart contract if !EVMAccounts::can_deploy_contracts(from) { @@ -2287,6 +2314,10 @@ impl fp_rpc::EthereumRuntimeRPCApi for Runtime { pallet_ethereum::CurrentTransactionStatuses::::get() ) } + + fn initialize_pending_block(header: &::Header) { + Executive::initialize_block(header); + } } impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { @@ -2388,7 +2419,7 @@ impl fp_rpc::EthereumRuntimeRPCApi for Runtime { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = AssetRegistry::asset_ids(); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -2421,7 +2452,7 @@ impl fp_rpc::EthereumRuntimeRPCApi for Runtime { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -2439,7 +2470,7 @@ impl fp_rpc::EthereumRuntimeRPCApi for Runtime { match rs { Ok(val) => val, - _ => (CurrencyId::Native(TokenSymbol::BNC), Zero::zero()), + _ => (BNC, Zero::zero()), } } } diff --git a/runtime/bifrost-polkadot/src/migration.rs b/runtime/bifrost-polkadot/src/migration.rs index f6b3651df3..a3aa396a28 100644 --- a/runtime/bifrost-polkadot/src/migration.rs +++ b/runtime/bifrost-polkadot/src/migration.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use super::*; use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade}; use log; @@ -60,13 +62,29 @@ pub mod v0 { >, ), /// Referendum finished with approval. Submission deposit is held. - Approved(Moment, Option>, Option>), + Approved( + Moment, + Option>, + Option>, + ), /// Referendum finished with rejection. Submission deposit is held. - Rejected(Moment, Option>, Option>), + Rejected( + Moment, + Option>, + Option>, + ), /// Referendum finished with cancellation. Submission deposit is held. - Cancelled(Moment, Option>, Option>), + Cancelled( + Moment, + Option>, + Option>, + ), /// Referendum finished and was never decided. Submission deposit is held. - TimedOut(Moment, Option>, Option>), + TimedOut( + Moment, + Option>, + Option>, + ), /// Referendum finished with a kill. Killed(Moment), } @@ -137,40 +155,64 @@ pub mod v1 { v0::ReferendumInfo::Ongoing(_) | v0::ReferendumInfo::Killed(_) => None, v0::ReferendumInfo::Approved(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::Approved(e, s, d)) - }, + } v0::ReferendumInfo::Rejected(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::Rejected(e, s, d)) - }, + } v0::ReferendumInfo::Cancelled(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::Cancelled(e, s, d)) - }, + } v0::ReferendumInfo::TimedOut(e, mut s, mut d) => { if let Some(a) = &item[0].deposit1 { - s = Some(Deposit { amount: a.amount, who: a.who.clone() }) + s = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } if let Some(a) = &item[0].deposit2 { - d = Some(Deposit { amount: a.amount, who: a.who.clone() }) + d = Some(Deposit { + amount: a.amount, + who: a.who.clone(), + }) } Some(ReferendumInfo::TimedOut(e, s, d)) - }, + } }; if let Some(new_value) = maybe_new_value { weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); @@ -190,7 +232,10 @@ pub mod v1 { let pre_referendum_count: u32 = Decode::decode(&mut &state[..]) .expect("failed to decode the state from pre-upgrade."); let post_referendum_count = ReferendumInfoFor::::iter().count() as u32; - ensure!(post_referendum_count == pre_referendum_count, "must migrate all referendums."); + ensure!( + post_referendum_count == pre_referendum_count, + "must migrate all referendums." + ); let result: Vec>> = serde_json::from_str(R::get()).expect("Failed to deserialize JSON"); @@ -200,15 +245,15 @@ pub mod v1 { match referendum_info { ReferendumInfo::Ongoing(_) | ReferendumInfo::Killed(_) => (), - ReferendumInfo::Approved(_e, s, d) | - ReferendumInfo::Rejected(_e, s, d) | - ReferendumInfo::Cancelled(_e, s, d) | - ReferendumInfo::TimedOut(_e, s, d) => { + ReferendumInfo::Approved(_e, s, d) + | ReferendumInfo::Rejected(_e, s, d) + | ReferendumInfo::Cancelled(_e, s, d) + | ReferendumInfo::TimedOut(_e, s, d) => { match (s, item.deposit1) { (Some(s), Some(a)) => { ensure!(s.amount == a.amount, "amount not equal"); ensure!(s.who == a.who, "who not equal"); - }, + } (None, None) => (), _ => return Err(TryRuntimeError::Other("Referenda Data mismatch")), } @@ -216,12 +261,12 @@ pub mod v1 { (Some(d), Some(a)) => { ensure!(d.amount == a.amount, "amount not equal"); ensure!(d.who == a.who, "who not equal"); - }, + } (None, None) => (), _ => return Err(TryRuntimeError::Other("Referenda Data mismatch")), } () - }, + } }; } diff --git a/runtime/bifrost-polkadot/src/weights/bb_bnc.rs b/runtime/bifrost-polkadot/src/weights/bb_bnc.rs index a10ad217d3..4dd0155da7 100644 --- a/runtime/bifrost-polkadot/src/weights/bb_bnc.rs +++ b/runtime/bifrost-polkadot/src/weights/bb_bnc.rs @@ -54,6 +54,32 @@ use sp_std::marker::PhantomData; /// Weight functions for bb_bnc. pub struct BifrostWeight(PhantomData); impl bb_bnc::WeightInfo for BifrostWeight { + /// Storage: `BbBNC::IncentiveConfigs` (r:1 w:1) + /// Proof: `BbBNC::IncentiveConfigs` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Number` (r:1 w:0) + /// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `BbBNC::Epoch` (r:1 w:0) + /// Proof: `BbBNC::Epoch` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::PointHistory` (r:1 w:0) + /// Proof: `BbBNC::PointHistory` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::ExecutionPhase` (r:1 w:0) + /// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `System::EventCount` (r:1 w:1) + /// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `System::Events` (r:1 w:1) + /// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn on_initialize() -> Weight { + // Proof Size summary in bytes: + // Measured: `462` + // Estimated: `6196` + // Minimum execution time: 22_033_000 picoseconds. + Weight::from_parts(22_373_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(3)) + } // Storage: BbBNC VeConfigs (r:1 w:1) // Proof Skipped: BbBNC VeConfigs (max_values: Some(1), max_size: None, mode: Measured) // Storage: System Number (r:1 w:0) diff --git a/runtime/bifrost-polkadot/src/weights/bifrost_buy_back.rs b/runtime/bifrost-polkadot/src/weights/bifrost_buy_back.rs index 2efdc3a796..f8b8a00355 100644 --- a/runtime/bifrost-polkadot/src/weights/bifrost_buy_back.rs +++ b/runtime/bifrost-polkadot/src/weights/bifrost_buy_back.rs @@ -117,7 +117,7 @@ impl bifrost_buy_back::WeightInfo for BifrostWeight /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:2 w:0) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(118), added: 2593, mode: `MaxEncodedLen`) - fn on_idle() -> Weight { + fn on_initialize() -> Weight { // Proof Size summary in bytes: // Measured: `502` // Estimated: `6442` diff --git a/runtime/bifrost-polkadot/src/weights/bifrost_farming.rs b/runtime/bifrost-polkadot/src/weights/bifrost_farming.rs index 71c9820855..ae26727bbc 100644 --- a/runtime/bifrost-polkadot/src/weights/bifrost_farming.rs +++ b/runtime/bifrost-polkadot/src/weights/bifrost_farming.rs @@ -132,23 +132,6 @@ impl bifrost_farming::WeightInfo for BifrostWeight { .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) } - // Storage: Farming GaugePoolInfos (r:1 w:1) - // Proof Skipped: Farming GaugePoolInfos (max_values: None, max_size: None, mode: Measured) - // Storage: Farming GaugeInfos (r:1 w:1) - // Proof Skipped: Farming GaugeInfos (max_values: None, max_size: None, mode: Measured) - // Storage: Farming PoolInfos (r:1 w:0) - // Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) - // Storage: Farming SharesAndWithdrawnRewards (r:1 w:0) - // Proof Skipped: Farming SharesAndWithdrawnRewards (max_values: None, max_size: None, mode: Measured) - fn gauge_withdraw() -> Weight { - // Proof Size summary in bytes: - // Measured: `832` - // Estimated: `4297` - // Minimum execution time: 82_224 nanoseconds. - Weight::from_parts(84_369_000, 4297) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(2)) - } // Storage: Farming PoolInfos (r:1 w:0) // Proof Skipped: Farming PoolInfos (max_values: None, max_size: None, mode: Measured) // Storage: Farming SharesAndWithdrawnRewards (r:1 w:1) @@ -356,4 +339,21 @@ impl bifrost_farming::WeightInfo for BifrostWeight { .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } + /// Storage: `Farming::UserFarmingPool` (r:1 w:0) + /// Proof: `Farming::UserFarmingPool` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::SharesAndWithdrawnRewards` (r:2 w:0) + /// Proof: `Farming::SharesAndWithdrawnRewards` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Farming::PoolInfos` (r:1 w:0) + /// Proof: `Farming::PoolInfos` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BbBNC::UserPositions` (r:1 w:0) + /// Proof: `BbBNC::UserPositions` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn refresh() -> Weight { + // Proof Size summary in bytes: + // Measured: `604` + // Estimated: `6544` + // Minimum execution time: 16_472_000 picoseconds. + Weight::from_parts(17_023_000, 0) + .saturating_add(Weight::from_parts(0, 6544)) + .saturating_add(T::DbWeight::get().reads(5)) + } } diff --git a/runtime/bifrost-polkadot/src/weights/bifrost_system_maker.rs b/runtime/bifrost-polkadot/src/weights/bifrost_system_maker.rs deleted file mode 100644 index e2109a2d24..0000000000 --- a/runtime/bifrost-polkadot/src/weights/bifrost_system_maker.rs +++ /dev/null @@ -1,122 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Autogenerated weights for bifrost_system_maker -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` -//! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 - -// Executed Command: -// target/release/bifrost -// benchmark -// pallet -// --chain=bifrost-kusama-local -// --steps=50 -// --repeat=20 -// --pallet=bifrost_system_maker -// --extrinsic=* -// --execution=wasm -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./runtime/bifrost-kusama/src/weights/bifrost_system_maker.rs -// --template=./weight-template/runtime-weight-template.hbs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use sp_std::marker::PhantomData; - -/// Weight functions for bifrost_system_maker. -pub struct BifrostWeight(PhantomData); -impl bifrost_system_maker::WeightInfo for BifrostWeight { - // Storage: SystemMaker Infos (r:1 w:1) - // Proof Skipped: SystemMaker Infos (max_values: None, max_size: None, mode: Measured) - fn set_config() -> Weight { - // Proof Size summary in bytes: - // Measured: `109` - // Estimated: `3574` - // Minimum execution time: 32_211 nanoseconds. - Weight::from_parts(33_399_000, 3574) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - // Storage: Tokens Accounts (r:2 w:2) - // Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - // Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - // Storage: System Account (r:2 w:1) - // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn charge() -> Weight { - // Proof Size summary in bytes: - // Measured: `1402` - // Estimated: `6196` - // Minimum execution time: 122_457 nanoseconds. - Weight::from_parts(124_486_000, 6196) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) - } - // Storage: SystemMaker Infos (r:0 w:1) - // Proof Skipped: SystemMaker Infos (max_values: None, max_size: None, mode: Measured) - fn close() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 22_412 nanoseconds. - Weight::from_parts(22_806_000, 0) - .saturating_add(T::DbWeight::get().writes(1)) - } - // Storage: Tokens Accounts (r:2 w:2) - // Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - // Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - // Storage: System Account (r:2 w:1) - // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn payout() -> Weight { - // Proof Size summary in bytes: - // Measured: `1461` - // Estimated: `6196` - // Minimum execution time: 114_158 nanoseconds. - Weight::from_parts(116_409_000, 6196) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) - } - // Storage: SystemMaker Infos (r:2 w:0) - // Proof Skipped: SystemMaker Infos (max_values: None, max_size: None, mode: Measured) - // Storage: ParachainInfo ParachainId (r:1 w:0) - // Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - // Storage: Tokens Accounts (r:2 w:0) - // Proof: Tokens Accounts (max_values: None, max_size: Some(118), added: 2593, mode: MaxEncodedLen) - fn on_idle() -> Weight { - // Proof Size summary in bytes: - // Measured: `894` - // Estimated: `6834` - // Minimum execution time: 54_792 nanoseconds. - Weight::from_parts(55_872_000, 6834) - .saturating_add(T::DbWeight::get().reads(5)) - } -} diff --git a/runtime/bifrost-polkadot/src/weights/mod.rs b/runtime/bifrost-polkadot/src/weights/mod.rs index c2ecca9ad6..812a4fb6c3 100644 --- a/runtime/bifrost-polkadot/src/weights/mod.rs +++ b/runtime/bifrost-polkadot/src/weights/mod.rs @@ -35,7 +35,6 @@ pub mod bifrost_slp; pub mod bifrost_slp_v2; pub mod bifrost_slpx; pub mod bifrost_stable_pool; -pub mod bifrost_system_maker; pub mod bifrost_system_staking; pub mod bifrost_vesting; pub mod bifrost_vstoken_conversion; diff --git a/runtime/bifrost-polkadot/src/xcm_config.rs b/runtime/bifrost-polkadot/src/xcm_config.rs index 7bb1b2760f..a21cd93cd1 100644 --- a/runtime/bifrost-polkadot/src/xcm_config.rs +++ b/runtime/bifrost-polkadot/src/xcm_config.rs @@ -140,7 +140,11 @@ pub type BifrostAssetTransactor = MultiCurrencyAdapter< pub struct ToTreasury; impl TakeRevenue for ToTreasury { fn take_revenue(revenue: Asset) { - if let Asset { id: AssetId(location), fun: Fungible(amount) } = revenue { + if let Asset { + id: AssetId(location), + fun: Fungible(amount), + } = revenue + { if let Some(currency_id) = CurrencyIdConvert::::convert(location) { @@ -162,7 +166,10 @@ impl Contains for SafeCallFilter { fn contains(call: &RuntimeCall) -> bool { #[cfg(feature = "runtime-benchmarks")] { - if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + if matches!( + call, + RuntimeCall::System(frame_system::Call::remark_with_event { .. }) + ) { return true; } } @@ -405,10 +412,10 @@ impl Contains for DustRemovalWhitelist { BuyBackAccount::get().into_account_truncating(), LiquidityAccount::get().into_account_truncating(), ]; - whitelist.contains(a) || - FarmingKeeperPalletId::get().check_sub_account::(a) || - FarmingRewardIssuerPalletId::get().check_sub_account::(a) || - FeeSharePalletId::get().check_sub_account::(a) + whitelist.contains(a) + || FarmingKeeperPalletId::get().check_sub_account::(a) + || FarmingRewardIssuerPalletId::get().check_sub_account::(a) + || FeeSharePalletId::get().check_sub_account::(a) } } diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index c4907fdf9d..c35e2a39b8 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bifrost-runtime-common" version = "0.8.0" -authors = ["Ron yang"] +authors = ["Liebi Technologies "] edition = "2021" [dependencies] diff --git a/runtime/common/src/currency_adapter.rs b/runtime/common/src/currency_adapter.rs index 82f5d48af8..f39d5e736b 100644 --- a/runtime/common/src/currency_adapter.rs +++ b/runtime/common/src/currency_adapter.rs @@ -53,12 +53,15 @@ enum Error { impl From for XcmError { fn from(e: Error) -> Self { match e { - Error::FailedToMatchFungible => - XcmError::FailedToTransactAsset("FailedToMatchFungible"), - Error::AccountIdConversionFailed => - XcmError::FailedToTransactAsset("AccountIdConversionFailed"), - Error::CurrencyIdConversionFailed => - XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), + Error::FailedToMatchFungible => { + XcmError::FailedToTransactAsset("FailedToMatchFungible") + } + Error::AccountIdConversionFailed => { + XcmError::FailedToTransactAsset("AccountIdConversionFailed") + } + Error::CurrencyIdConversionFailed => { + XcmError::FailedToTransactAsset("CurrencyIdConversionFailed") + } } } } @@ -180,13 +183,15 @@ impl< Match::matches_fungible(asset), ) { // known asset - (Some(who), Some(currency_id), Some(amount)) => + (Some(who), Some(currency_id), Some(amount)) => { MultiCurrency::deposit(currency_id, &who, amount).or_else(|err| { DepositFailureHandler::on_deposit_currency_fail(err, currency_id, &who, amount) - }), + }) + } // bad beneficiary - (None, Some(currency_id), Some(amount)) => - DepositFailureHandler::on_account_id_convert_fail(currency_id, amount), + (None, Some(currency_id), Some(amount)) => { + DepositFailureHandler::on_account_id_convert_fail(currency_id, amount) + } // unknown asset _ => UnknownAsset::deposit(asset, location).or_else(|err| { DepositFailureHandler::on_deposit_unknown_asset_fail(err, asset, location) diff --git a/runtime/common/src/currency_converter.rs b/runtime/common/src/currency_converter.rs index eb7190d41a..5622be0716 100644 --- a/runtime/common/src/currency_converter.rs +++ b/runtime/common/src/currency_converter.rs @@ -50,7 +50,11 @@ impl, R: bifrost_asset_registry::Config> Convert { fn convert(asset: Asset) -> Option { - if let Asset { id: AssetId(id), fun: Fungible(_) } = asset { + if let Asset { + id: AssetId(id), + fun: Fungible(_), + } = asset + { Self::convert(id) } else { None diff --git a/runtime/common/src/xcm_weight_trader.rs b/runtime/common/src/xcm_weight_trader.rs index 42bc9ba6ee..c3c65a2ec2 100644 --- a/runtime/common/src/xcm_weight_trader.rs +++ b/runtime/common/src/xcm_weight_trader.rs @@ -31,7 +31,11 @@ pub struct XcmWeightTrader< Price: OraclePriceProvider, CM: CurrencyIdMapping>, R: TakeRevenue, ->(Weight, Option, PhantomData<(WeightToFee, Price, CM, R)>); +>( + Weight, + Option, + PhantomData<(WeightToFee, Price, CM, R)>, +); impl< WeightToFee: frame_support::weights::WeightToFee, @@ -82,8 +86,11 @@ impl< log::trace!(target: "xcm-weight-trader", "buy_weight weight: {:?}, payment: {:?}", weight, payment); // only support first fungible assets now. - let first_asset = - payment.clone().fungible_assets_iter().next().ok_or(XcmError::AssetNotFound)?; + let first_asset = payment + .clone() + .fungible_assets_iter() + .next() + .ok_or(XcmError::AssetNotFound)?; match (first_asset.id, first_asset.fun) { (AssetId(location), Fungible(_)) => { @@ -97,15 +104,19 @@ impl< return Ok(payment); } - let required = Asset { fun: Fungible(amount), id: AssetId(location) }; - let unused = - payment.checked_sub(required.clone()).map_err(|_| XcmError::TooExpensive)?; + let required = Asset { + fun: Fungible(amount), + id: AssetId(location), + }; + let unused = payment + .checked_sub(required.clone()) + .map_err(|_| XcmError::TooExpensive)?; self.0 = weight; self.1 = Some(required); Ok(unused) - }, + } _ => Err(XcmError::AssetNotFound), } } @@ -120,10 +131,16 @@ impl< self.1 ); - if let Some(Asset { fun: Fungible(initial_amount), id: AssetId(location) }) = self.1.take() + if let Some(Asset { + fun: Fungible(initial_amount), + id: AssetId(location), + }) = self.1.take() { if actual_weight == self.0 { - self.1 = Some(Asset { fun: Fungible(initial_amount), id: AssetId(location) }); + self.1 = Some(Asset { + fun: Fungible(initial_amount), + id: AssetId(location), + }); None } else { let weight = actual_weight.min(self.0); @@ -132,13 +149,19 @@ impl< let final_amount = amount.min(initial_amount); let amount_to_refund = initial_amount.saturating_sub(final_amount); self.0 -= weight; - self.1 = Some(Asset { fun: Fungible(final_amount), id: AssetId(location.clone()) }); + self.1 = Some(Asset { + fun: Fungible(final_amount), + id: AssetId(location.clone()), + }); log::trace!( target: "xcm-weight-trader", "refund_weight amount to refund: {:?}", amount_to_refund ); - Some(Asset { fun: Fungible(amount_to_refund), id: AssetId(location) }) + Some(Asset { + fun: Fungible(amount_to_refund), + id: AssetId(location), + }) } } else { None diff --git a/rust-toolchain.toml b/rust-toolchain.toml index b365e13a84..6d985f163a 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.77.0" +channel = "1.81.0" components = ["rust-src", "rustfmt", "clippy"] targets = ["wasm32-unknown-unknown"] diff --git a/rustfmt.toml b/rustfmt.toml index 5a51b31bfd..b8cd6861aa 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,23 +1,4 @@ -# Basic -edition = "2021" hard_tabs = true -max_width = 100 -use_small_heuristics = "Max" -# Imports -imports_granularity = "Crate" reorder_imports = true -# Consistency -newline_style = "Unix" -# Format comments -comment_width = 100 -wrap_comments = true -# Misc -binop_separator = "Back" -chain_width = 80 -match_arm_blocks = false -match_arm_leading_pipes = "Preserve" -match_block_trailing_comma = true -reorder_impl_items = false -spaces_around_ranges = false -trailing_comma = "Vertical" -use_field_init_shorthand = true +max_width = 100 +tab_spaces = 4 \ No newline at end of file diff --git a/scripts/init.sh b/scripts/init.sh index 3f6ed0ed14..95df75d837 100755 --- a/scripts/init.sh +++ b/scripts/init.sh @@ -4,6 +4,6 @@ set -e echo "*** Initializing WASM build environment" -rustup default 1.77.0 +rustup default 1.81.0 -rustup target add wasm32-unknown-unknown --toolchain 1.77.0 +rustup target add wasm32-unknown-unknown --toolchain 1.81.0