diff --git a/Cargo.lock b/Cargo.lock index 85ea12834..16d449e52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -702,7 +702,7 @@ dependencies = [ "cfg-if", "libc", "miniz_oxide", - "object 0.36.0", + "object 0.36.1", "rustc-demangle", ] @@ -1175,9 +1175,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.100" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c891175c3fb232128f48de6590095e59198bbeb8620c310be349bfc3afd12c7b" +checksum = "74b6a57f98764a267ff415d50a25e6e166f3831a5071af4995296ea97d210490" dependencies = [ "jobserver", "libc", @@ -1320,9 +1320,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.7" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db83dced34638ad474f39f250d7fea9598bdd239eaced1bdf45d597da0f433f" +checksum = "84b3edb18336f4df585bc9aa31dd99c036dfa5dc5e9a2939a722a188f3a8970d" dependencies = [ "clap_builder", "clap_derive", @@ -1330,9 +1330,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.7" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7e204572485eb3fbf28f871612191521df159bc3e15a9f5064c66dba3a8c05f" +checksum = "c1c09dd5ada6c6c78075d6fd0da3f90d8080651e2d6cc8eb2f1aaa4034ced708" dependencies = [ "anstream", "anstyle", @@ -1342,9 +1342,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.5" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c780290ccf4fb26629baa7a1081e68ced113f1d3ec302fa5948f1c381ebf06c6" +checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -1420,7 +1420,7 @@ dependencies = [ [[package]] name = "common" version = "0.1.0" -source = "git+https://github.com/w3f/ring-proof#b273d33f9981e2bb3375ab45faeb537f7ee35224" +source = "git+https://github.com/w3f/ring-proof#96137b150288a66bc9e4df495efc64769b5d1321" dependencies = [ "ark-ec", "ark-ff", @@ -1703,7 +1703,7 @@ checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" name = "crowdloan-verifier" version = "0.1.0" dependencies = [ - "clap 4.5.7", + "clap 4.5.8", "csv", "pallet-rewards", "polkadex-primitives", @@ -1795,7 +1795,7 @@ name = "cumulus-client-cli" version = "0.1.0" source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" dependencies = [ - "clap 4.5.7", + "clap 4.5.8", "parity-scale-codec", "sc-chain-spec", "sc-cli", @@ -2841,9 +2841,9 @@ dependencies = [ [[package]] name = "either" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "elliptic-curve" @@ -3285,7 +3285,7 @@ dependencies = [ "Inflector", "array-bytes", "chrono", - "clap 4.5.7", + "clap 4.5.8", "comfy-table", "frame-benchmarking", "frame-support", @@ -5270,9 +5270,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "lru" @@ -5801,9 +5801,11 @@ checksum = "43794a0ace135be66a25d3ae77d41b91615fb68ae937f904090203e81f755b65" name = "node-polkadex-runtime" version = "6.0.0" dependencies = [ + "docify", "frame-benchmarking", "frame-election-provider-support", "frame-executive", + "frame-metadata-hash-extension", "frame-support", "frame-system", "frame-system-benchmarking", @@ -5913,9 +5915,9 @@ checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" [[package]] name = "num-bigint" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c165a9ab64cf766f73521c0dd2cfdff64f488b8f0b3e621face3462d3db536d7" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" dependencies = [ "num-integer", "num-traits", @@ -6005,9 +6007,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.0" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "576dfe1fc8f9df304abb159d767a29d0476f7750fbf8aa7ad07816004a207434" +checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" dependencies = [ "memchr", ] @@ -6115,7 +6117,7 @@ dependencies = [ [[package]] name = "orml-traits" version = "0.4.1-dev" -source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#7efeb66494d8564d802e7e5e2272f933a0600f60" +source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#3218cb843957fd9cf4c3beb24b9cd15e9493b8c3" dependencies = [ "frame-support", "impl-trait-for-tuples", @@ -6134,7 +6136,7 @@ dependencies = [ [[package]] name = "orml-utilities" version = "0.4.1-dev" -source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#7efeb66494d8564d802e7e5e2272f933a0600f60" +source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#3218cb843957fd9cf4c3beb24b9cd15e9493b8c3" dependencies = [ "frame-support", "parity-scale-codec", @@ -6148,7 +6150,7 @@ dependencies = [ [[package]] name = "orml-vesting" version = "0.4.1-dev" -source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#7efeb66494d8564d802e7e5e2272f933a0600f60" +source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#3218cb843957fd9cf4c3beb24b9cd15e9493b8c3" dependencies = [ "frame-support", "frame-system", @@ -6163,7 +6165,7 @@ dependencies = [ [[package]] name = "orml-xcm-support" version = "0.4.1-dev" -source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#7efeb66494d8564d802e7e5e2272f933a0600f60" +source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#3218cb843957fd9cf4c3beb24b9cd15e9493b8c3" dependencies = [ "frame-support", "orml-traits", @@ -6177,7 +6179,7 @@ dependencies = [ [[package]] name = "orml-xtokens" version = "0.4.1-dev" -source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#7efeb66494d8564d802e7e5e2272f933a0600f60" +source = "git+https://github.com/Polkadex-Substrate/orml-1.1.0.git?branch=master#3218cb843957fd9cf4c3beb24b9cd15e9493b8c3" dependencies = [ "cumulus-primitives-core", "frame-support", @@ -7476,7 +7478,7 @@ dependencies = [ name = "parachain-polkadex-node" version = "1.1.0" dependencies = [ - "clap 4.5.7", + "clap 4.5.8", "color-print", "cumulus-client-cli", "cumulus-client-collator", @@ -7534,7 +7536,7 @@ dependencies = [ "sp-timestamp", "sp-transaction-pool", "staging-xcm", - "substrate-build-script-utils 3.0.0", + "substrate-build-script-utils", "substrate-frame-rpc-system", "substrate-prometheus-endpoint", "try-runtime-cli", @@ -7800,9 +7802,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.10" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560131c633294438da9f7c4b08189194b20946c8274c6b9e38881a7874dc8ee8" +checksum = "cd53dff83f26735fdc1ca837098ccf133605d794cdae66acfc2bfac3ec809d95" dependencies = [ "memchr", "thiserror", @@ -7811,9 +7813,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.10" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26293c9193fbca7b1a3bf9b79dc1e388e927e6cacaa78b4a3ab705a1d3d41459" +checksum = "2a548d2beca6773b1c244554d36fcf8548a8a58e74156968211567250e48e49a" dependencies = [ "pest", "pest_generator", @@ -7821,9 +7823,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.10" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ec22af7d3fb470a85dd2ca96b7c577a1eb4ef6f1683a9fe9a8c16e136c04687" +checksum = "3c93a82e8d145725dcbaf44e5ea887c8a869efdcc28706df2d08c69e17077183" dependencies = [ "pest", "pest_meta", @@ -7834,9 +7836,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.7.10" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a240022f37c361ec1878d646fc5b7d7c4d28d5946e1a80ad5a7a4f4ca0bdcd" +checksum = "a941429fea7e08bedec25e4f6785b6ffaacc6b755da98df5ef3e7dcf4a124c4f" dependencies = [ "once_cell", "pest", @@ -7918,12 +7920,6 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" -[[package]] -name = "platforms" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8d0eef3571242013a0d5dc84861c3ae4a652e56e12adf8bdc26ff5f8cb34c94" - [[package]] name = "polkadex-client" version = "5.4.2" @@ -7939,8 +7935,9 @@ dependencies = [ name = "polkadex-node" version = "6.0.0" dependencies = [ - "clap 4.5.7", + "clap 4.5.8", "frame-benchmarking-cli", + "frame-metadata-hash-extension", "frame-support", "frame-system", "frame-try-runtime", @@ -7968,12 +7965,10 @@ dependencies = [ "sc-consensus", "sc-consensus-babe", "sc-consensus-babe-rpc", - "sc-consensus-epochs", "sc-consensus-grandpa", "sc-consensus-grandpa-rpc", "sc-consensus-slots", "sc-executor", - "sc-keystore", "sc-network", "sc-network-statement", "sc-network-sync", @@ -7981,7 +7976,6 @@ dependencies = [ "sc-rpc", "sc-rpc-api", "sc-service", - "sc-service-test", "sc-statement-store", "sc-storage-monitor", "sc-sync-state-rpc", @@ -8004,13 +7998,11 @@ dependencies = [ "sp-runtime", "sp-statement-store", "sp-timestamp", - "sp-tracing", "sp-transaction-storage-proof", "structopt", - "substrate-build-script-utils 5.0.0", + "substrate-build-script-utils", "substrate-frame-rpc-system", "swap-rpc", - "tempfile", "thea", "try-runtime-cli", ] @@ -8044,16 +8036,23 @@ version = "1.0.0" dependencies = [ "frame-support", "frame-system", + "hex", "log", + "orml-traits", + "orml-xcm-support", + "orml-xtokens", + "pallet-assets", "pallet-balances", "pallet-message-queue", "pallet-uniques", "pallet-xcm", "parity-scale-codec", + "polkadex-primitives", "polkadot-core-primitives", "polkadot-parachain-primitives", "polkadot-runtime-parachains", "scale-info", + "smallvec", "sp-core", "sp-io", "sp-runtime", @@ -8062,6 +8061,10 @@ dependencies = [ "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", + "thea", + "thea-message-handler", + "thea-primitives", + "xcm-helper", "xcm-simulator", ] @@ -8148,7 +8151,7 @@ name = "polkadot-cli" version = "1.1.0" source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" dependencies = [ - "clap 4.5.7", + "clap 4.5.8", "frame-benchmarking-cli", "futures 0.3.30", "log", @@ -8165,7 +8168,7 @@ dependencies = [ "sp-io", "sp-keyring", "sp-maybe-compressed-blob", - "substrate-build-script-utils 3.0.0", + "substrate-build-script-utils", "thiserror", "try-runtime-cli", ] @@ -8535,7 +8538,7 @@ dependencies = [ "sp-core", "sp-maybe-compressed-blob", "sp-wasm-interface", - "substrate-build-script-utils 3.0.0", + "substrate-build-script-utils", "tempfile", "tokio", "tracing-gum", @@ -9946,7 +9949,7 @@ dependencies = [ [[package]] name = "ring" version = "0.1.0" -source = "git+https://github.com/w3f/ring-proof#b273d33f9981e2bb3375ab45faeb537f7ee35224" +source = "git+https://github.com/w3f/ring-proof#96137b150288a66bc9e4df495efc64769b5d1321" dependencies = [ "ark-ec", "ark-ff", @@ -10510,7 +10513,7 @@ source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot dependencies = [ "array-bytes", "chrono", - "clap 4.5.7", + "clap 4.5.8", "fdlimit", "futures 0.3.30", "libp2p-identity", @@ -11324,43 +11327,6 @@ dependencies = [ "tracing-futures", ] -[[package]] -name = "sc-service-test" -version = "2.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" -dependencies = [ - "array-bytes", - "async-channel 1.9.0", - "fdlimit", - "futures 0.3.30", - "log", - "parity-scale-codec", - "parking_lot 0.12.3", - "sc-block-builder", - "sc-client-api", - "sc-client-db", - "sc-consensus", - "sc-executor", - "sc-network", - "sc-network-sync", - "sc-service", - "sc-transaction-pool-api", - "sp-api", - "sp-blockchain", - "sp-consensus", - "sp-core", - "sp-io", - "sp-runtime", - "sp-state-machine", - "sp-storage", - "sp-tracing", - "sp-trie", - "substrate-test-runtime", - "substrate-test-runtime-client", - "tempfile", - "tokio", -] - [[package]] name = "sc-state-db" version = "0.10.0-dev" @@ -11396,7 +11362,7 @@ name = "sc-storage-monitor" version = "0.1.0" source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" dependencies = [ - "clap 4.5.7", + "clap 4.5.8", "fs4", "log", "sc-client-db", @@ -11838,9 +11804,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.118" +version = "1.0.120" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d947f6b3163d8857ea16c4fa0dd4840d52f3041039a85decd46867eb1abef2e4" +checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" dependencies = [ "itoa", "ryu", @@ -11858,9 +11824,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.8.1" +version = "3.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20" +checksum = "079f3a42cd87588d924ed95b533f8d30a483388c4e400ab736a7058e34f16169" dependencies = [ "base64 0.22.1", "chrono", @@ -11876,9 +11842,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.8.1" +version = "3.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2" +checksum = "bc03aad67c1d26b7de277d51c86892e7d9a0110a2fe44bf6b26cc569fba302d6" dependencies = [ "darling", "proc-macro2", @@ -13291,15 +13257,6 @@ name = "substrate-build-script-utils" version = "3.0.0" source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" -[[package]] -name = "substrate-build-script-utils" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbc6b6e856dfd283e5116c3cc40c9f2efec2f0be49d9aaa27231a2b24bd454d" -dependencies = [ - "platforms", -] - [[package]] name = "substrate-frame-rpc-system" version = "4.0.0-dev" @@ -13361,94 +13318,6 @@ dependencies = [ "trie-db", ] -[[package]] -name = "substrate-test-client" -version = "2.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" -dependencies = [ - "array-bytes", - "async-trait", - "futures 0.3.30", - "parity-scale-codec", - "sc-client-api", - "sc-client-db", - "sc-consensus", - "sc-executor", - "sc-offchain", - "sc-service", - "serde", - "serde_json", - "sp-blockchain", - "sp-consensus", - "sp-core", - "sp-keyring", - "sp-keystore", - "sp-runtime", - "sp-state-machine", -] - -[[package]] -name = "substrate-test-runtime" -version = "2.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" -dependencies = [ - "array-bytes", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-rpc-runtime-api", - "log", - "pallet-babe", - "pallet-balances", - "pallet-timestamp", - "parity-scale-codec", - "sc-service", - "scale-info", - "serde", - "serde_json", - "sp-api", - "sp-application-crypto", - "sp-block-builder", - "sp-consensus-aura", - "sp-consensus-babe", - "sp-consensus-grandpa", - "sp-core", - "sp-externalities", - "sp-genesis-builder", - "sp-inherents", - "sp-io", - "sp-keyring", - "sp-offchain", - "sp-runtime", - "sp-session", - "sp-state-machine", - "sp-std", - "sp-transaction-pool", - "sp-trie", - "sp-version", - "substrate-wasm-builder", - "trie-db", -] - -[[package]] -name = "substrate-test-runtime-client" -version = "2.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" -dependencies = [ - "futures 0.3.30", - "sc-block-builder", - "sc-client-api", - "sc-consensus", - "sp-api", - "sp-blockchain", - "sp-consensus", - "sp-core", - "sp-runtime", - "substrate-test-client", - "substrate-test-runtime", -] - [[package]] name = "substrate-wasm-builder" version = "5.0.0-dev" @@ -14326,7 +14195,7 @@ version = "0.10.0-dev" source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#39482e78cc1580c9f16a8f8d8261baf914ab5559" dependencies = [ "async-trait", - "clap 4.5.7", + "clap 4.5.8", "frame-remote-externalities", "frame-try-runtime", "hex", @@ -15108,9 +14977,9 @@ dependencies = [ [[package]] name = "wide" -version = "0.7.24" +version = "0.7.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a040b111774ab63a19ef46bbc149398ab372b4ccdcfd719e9814dbd7dfd76c8" +checksum = "2caba658a80831539b30698ae9862a72db6697dfdd7151e46920f5f2755c3ce2" dependencies = [ "bytemuck", "safe_arch", @@ -15554,18 +15423,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.34" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae87e3fcd617500e5d106f0380cf7b77f3c6092aae37191433159dda23cfb087" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.34" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 731db1851..ff45bf732 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -118,12 +118,12 @@ pallet-statement = { git = "https://github.com/paritytech/polkadot-sdk", branch sp-statement-store = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } pallet-asset-conversion = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } pallet-asset-conversion-tx-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } - +frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } orml-vesting = { git = "https://github.com/Polkadex-Substrate/orml-1.1.0.git", branch = "master", default-features = false } sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } -sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } +sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false} sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } @@ -187,7 +187,6 @@ serde = { version = "1.0.171", default-features = false, features = ["derive"] } serde_json = { version = "1.0.102", default-features = false, features = ["alloc"] } hash-db = { version = "0.16.0", default-features = false } trie-db = { version = "0.27.1", default-features = false } - #Parachain Dependencies cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } orml-xtokens = { git = "https://github.com/Polkadex-Substrate/orml-1.1.0.git", branch = "master", default-features = false } #FIXME: Remove rev @@ -204,7 +203,7 @@ cumulus-pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branc cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } cumulus-primitives-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } cumulus-primitives-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } -#Here Oeml +#Here Orml orml-xcm-support = { git = "https://github.com/Polkadex-Substrate/orml-1.1.0.git", branch = "master", default-features = false } #FIXME: Remove rev pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.1.0" } pallet-collator-selection = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } diff --git a/check-all-ci-tests.sh b/check-all-ci-tests.sh index 9b7827e3c..807b12b43 100755 --- a/check-all-ci-tests.sh +++ b/check-all-ci-tests.sh @@ -18,7 +18,7 @@ cargo fmt --check || exit RUSTFLAGS="-D warnings" cargo build || exit -cargo build --features try-runtime || exit +RUSTFLAGS="-D warnings" cargo build --features try-runtime || exit cargo build --features runtime-benchmarks || exit ./target/debug/polkadex-node benchmark pallet --pallet "*" --extrinsic "*" --steps 2 --repeat 1 || exit cargo clippy -- -D warnings || exit diff --git a/nodes/mainnet/Cargo.toml b/nodes/mainnet/Cargo.toml index 359317476..30142cc7a 100644 --- a/nodes/mainnet/Cargo.toml +++ b/nodes/mainnet/Cargo.toml @@ -13,7 +13,7 @@ repository = "https://github.com/Polkadex-Substrate/Polkadex/" targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -substrate-build-script-utils = { version = "5.0.0" } +substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } structopt = { version = "0.3.8", optional = true } [dependencies] @@ -26,16 +26,18 @@ clap = { version = "4.0.9", features = ["derive"] } itertools = "0.10.1" jsonrpsee = { version = "0.16.2", features = ["server"] } # local dependencies -node-polkadex-runtime = { path = "../../runtimes/mainnet" } +node-polkadex-runtime = { path = "../../runtimes/mainnet"} rpc-assets = { path = "../../rpc/assets" } pallet-rewards-rpc = { path = "../../pallets/rewards/rpc" } pallet-ocex-rpc = { path = "../../pallets/ocex/rpc" } polkadex-client = { path = "../../client" } - thea = { path = "../../pallets/thea" } pallet-ocex-lmp = { path = "../../pallets/ocex" } swap-rpc = { path = "../../rpc/swap" } + + # Substrate dependencies +frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } pallet-im-online = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } @@ -73,7 +75,6 @@ sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "rel sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -#sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } sp-authority-discovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } @@ -82,7 +83,7 @@ sp-statement-store = { git = "https://github.com/paritytech/polkadot-sdk", branc sc-network-statement = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } pallet-asset-conversion-tx-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } pallet-asset-conversion = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -#Primitives +##Primitives polkadex-primitives = { path = "../../primitives/polkadex" } sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } @@ -93,13 +94,12 @@ try-runtime-cli = { git = "https://github.com/paritytech/polkadot-sdk.git", bran [dev-dependencies] futures = "0.3.9" -tempfile = "3.1.0" -sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-consensus-epochs = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-service-test = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +#tempfile = "3.1.0" +#sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +#sc-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +#sc-consensus-epochs = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +#sp-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +#sc-service-test = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0"} [features] default = [] diff --git a/nodes/mainnet/src/chain_spec.rs b/nodes/mainnet/src/chain_spec.rs index 576c90297..1ff160fc0 100644 --- a/nodes/mainnet/src/chain_spec.rs +++ b/nodes/mainnet/src/chain_spec.rs @@ -1224,6 +1224,7 @@ pub fn get_stakeholder_tokens() -> Vec<(AccountId, Balance)> { } #[cfg(test)] +#[allow(dead_code)] pub(crate) mod tests { use sp_runtime::BuildStorage; diff --git a/nodes/mainnet/src/service.rs b/nodes/mainnet/src/service.rs index 8d3ac83a6..611ced713 100644 --- a/nodes/mainnet/src/service.rs +++ b/nodes/mainnet/src/service.rs @@ -107,6 +107,7 @@ pub fn create_extrinsic( pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::< node_polkadex_runtime::Runtime, >::from(tip, None), + frame_metadata_hash_extension::CheckMetadataHash::new(false), ); let raw_payload = node_polkadex_runtime::SignedPayload::from_raw( @@ -121,6 +122,7 @@ pub fn create_extrinsic( (), (), (), + None, ), ); let signature = raw_payload.using_encoded(|e| sender.sign(e)); @@ -312,6 +314,7 @@ pub fn new_partial( } /// Result of [`new_full_base`]. +#[allow(dead_code)] pub struct NewFullBase { /// The task manager of the node. pub task_manager: TaskManager, @@ -632,265 +635,265 @@ pub fn new_full(config: Configuration, cli: Cli) -> Result::Signer; - - #[test] - // It is "ignored", but the node-cli ignored tests are running on the CI. - // This can be run locally with `cargo test --release -p node-cli test_sync -- --ignored`. - #[ignore] - fn test_sync() { - sp_tracing::try_init_simple(); - - let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore: KeystorePtr = LocalKeystore::open(keystore_path.path(), None) - .expect("Creates keystore") - .into(); - let alice: sp_consensus_babe::AuthorityId = keystore - .sr25519_generate_new(BABE, Some("//Alice")) - .expect("Creates authority pair") - .into(); - - let chain_spec = crate::chain_spec::tests::integration_test_config_with_single_authority(); - - // For the block factory - let mut slot = 1u64; - - // For the extrinsics factory - let bob = Arc::new(AccountKeyring::Bob.pair()); - let charlie = Arc::new(AccountKeyring::Charlie.pair()); - let mut index = 0; - - sc_service_test::sync( - chain_spec, - |config| { - let mut setup_handles = None; - let NewFullBase { task_manager, client, network, sync, transaction_pool, .. } = - new_full_base( - config, - false, - |block_import: &sc_consensus_babe::BabeBlockImport, - babe_link: &sc_consensus_babe::BabeLink| { - setup_handles = Some((block_import.clone(), babe_link.clone())); - }, - )?; - - let node = sc_service_test::TestNetComponents::new( - task_manager, - client, - network, - sync, - transaction_pool, - ); - Ok((node, setup_handles.unwrap())) - }, - |service, &mut (ref mut block_import, ref babe_link): &mut (_, _)| { - let parent_hash = service.client().chain_info().best_hash; - let parent_header = service.client().header(parent_hash).unwrap().unwrap(); - let parent_number = parent_header.number; - - futures::executor::block_on(service.transaction_pool().maintain( - ChainEvent::NewBestBlock { hash: parent_header.hash(), tree_route: None }, - )); - - let mut proposer_factory = sc_basic_authorship::ProposerFactory::new( - service.spawn_handle(), - service.client(), - service.transaction_pool(), - None, - None, - ); - - let mut digest = Digest::default(); - - // even though there's only one authority some slots might be empty, - // so we must keep trying the next slots until we can claim one. - let (babe_pre_digest, epoch_descriptor) = loop { - let epoch_descriptor = babe_link - .epoch_changes() - .shared_data() - .epoch_descriptor_for_child_of( - descendent_query(&*service.client()), - &parent_hash, - parent_number, - slot.into(), - ) - .unwrap() - .unwrap(); - - let epoch = babe_link - .epoch_changes() - .shared_data() - .epoch_data(&epoch_descriptor, |slot| { - sc_consensus_babe::Epoch::genesis(babe_link.config(), slot) - }) - .unwrap(); - - if let Some(babe_pre_digest) = - sc_consensus_babe::authorship::claim_slot(slot.into(), &epoch, &keystore) - .map(|(digest, _)| digest) - { - break (babe_pre_digest, epoch_descriptor); - } - - slot += 1; - }; - - let inherent_data = futures::executor::block_on( - ( - sp_timestamp::InherentDataProvider::new( - std::time::Duration::from_millis(SLOT_DURATION * slot).into(), - ), - sp_consensus_babe::inherents::InherentDataProvider::new(slot.into()), - ) - .create_inherent_data(), - ) - .expect("Creates inherent data"); - - digest.push(::babe_pre_digest(babe_pre_digest)); - - let new_block = futures::executor::block_on(async move { - let proposer = proposer_factory.init(&parent_header).await; - proposer - .unwrap() - .propose(inherent_data, digest, std::time::Duration::from_secs(1), None) - .await - }) - .expect("Error making test block") - .block; - - let (new_header, new_body) = new_block.deconstruct(); - let pre_hash = new_header.hash(); - // sign the pre-sealed hash of the block and then - // add it to a digest item. - let to_sign = pre_hash.encode(); - let signature = keystore - .sr25519_sign(sp_consensus_babe::AuthorityId::ID, alice.as_ref(), &to_sign) - .unwrap() - .unwrap(); - let item = ::babe_seal(signature.into()); - slot += 1; - - let mut params = BlockImportParams::new(BlockOrigin::File, new_header); - params.post_digests.push(item); - params.body = Some(new_body); - params.insert_intermediate( - INTERMEDIATE_KEY, - BabeIntermediate:: { epoch_descriptor }, - ); - params.fork_choice = Some(ForkChoiceStrategy::LongestChain); - - futures::executor::block_on(block_import.import_block(params)) - .expect("error importing test block"); - }, - |service, _| { - let amount = 5 * CENTS; - let to: Address = AccountPublic::from(bob.public()).into_account().into(); - let from: Address = AccountPublic::from(charlie.public()).into_account().into(); - let genesis_hash = service.client().block_hash(0).unwrap().unwrap(); - let best_hash = service.client().chain_info().best_hash; - let (_, _) = { - let version = service.client().runtime_version_at(best_hash).unwrap(); - (version.spec_version, version.transaction_version) - }; - let signer = charlie.clone(); - - let function = RuntimeCall::Balances(BalancesCall::transfer_allow_death { - dest: to.into(), - value: amount, - }); - - let check_spec_version = frame_system::CheckSpecVersion::new(); - let check_tx_version = frame_system::CheckTxVersion::new(); - let check_genesis = frame_system::CheckGenesis::new(); - let check_era = frame_system::CheckEra::from(Era::Immortal); - let check_nonce = frame_system::CheckNonce::from(index); - let check_weight = frame_system::CheckWeight::new(); - let tx_payment = - pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::from(0, None); - let check_non_zero_sender = frame_system::CheckNonZeroSender::new(); - let extra = ( - check_non_zero_sender, - check_spec_version, - check_tx_version, - check_genesis, - check_era, - check_nonce, - check_weight, - tx_payment, - ); - let raw_payload = node_polkadex_runtime::SignedPayload::from_raw( - function.clone(), - extra.clone(), - ( - (), - node_polkadex_runtime::VERSION.spec_version, - node_polkadex_runtime::VERSION.transaction_version, - genesis_hash, - best_hash, - (), - (), - (), - ), - ); - let signature = raw_payload.using_encoded(|payload| signer.sign(payload)); - let (function, extra, _) = raw_payload.deconstruct(); - index += 1; - UncheckedExtrinsic::new_signed(function, from.into(), signature.into(), extra) - .into() - }, - ); - } - - #[test] - #[ignore] - fn test_consensus() { - sp_tracing::try_init_simple(); - - sc_service_test::consensus( - crate::chain_spec::tests::integration_test_config_with_two_authorities(), - |config| { - let NewFullBase { task_manager, client, network, sync, transaction_pool, .. } = - new_full_base(config, false, |_, _| ())?; - Ok(sc_service_test::TestNetComponents::new( - task_manager, - client, - network, - sync, - transaction_pool, - )) - }, - vec!["//Alice".into(), "//Bob".into()], - ) - } -} +// #[cfg(test)] +// mod tests { +// use crate::service::{new_full_base, NewFullBase}; +// use codec::Encode; +// use node_polkadex_runtime::{ +// constants::{currency::CENTS, time::SLOT_DURATION}, +// Address, BalancesCall, RuntimeCall, UncheckedExtrinsic, +// }; +// use polkadex_primitives::{Block, DigestItem, Signature}; +// use sc_client_api::BlockBackend; +// use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy}; +// use sc_consensus_babe::{BabeIntermediate, CompatibleDigestItem, INTERMEDIATE_KEY}; +// use sc_consensus_epochs::descendent_query; +// use sc_keystore::LocalKeystore; +// use sc_transaction_pool_api::{ChainEvent, MaintainedTransactionPool}; +// use sp_api::BlockT; +// use sp_consensus::{BlockOrigin, Environment, Proposer}; +// use sp_core::crypto::Pair; +// use sp_inherents::InherentDataProvider; +// use sp_keyring::AccountKeyring; +// use sp_keystore::KeystorePtr; +// use sp_runtime::{ +// generic::{Digest, Era}, +// key_types::BABE, +// traits::{IdentifyAccount, Verify}, +// RuntimeAppPublic, +// }; +// use sp_timestamp; +// use std::sync::Arc; +// +// type AccountPublic = ::Signer; +// +// #[test] +// // It is "ignored", but the node-cli ignored tests are running on the CI. +// // This can be run locally with `cargo test --release -p node-cli test_sync -- --ignored`. +// #[ignore] +// fn test_sync() { +// sp_tracing::try_init_simple(); +// +// let keystore_path = tempfile::tempdir().expect("Creates keystore path"); +// let keystore: KeystorePtr = LocalKeystore::open(keystore_path.path(), None) +// .expect("Creates keystore") +// .into(); +// let alice: sp_consensus_babe::AuthorityId = keystore +// .sr25519_generate_new(BABE, Some("//Alice")) +// .expect("Creates authority pair") +// .into(); +// +// let chain_spec = crate::chain_spec::tests::integration_test_config_with_single_authority(); +// +// // For the block factory +// let mut slot = 1u64; +// +// // For the extrinsics factory +// let bob = Arc::new(AccountKeyring::Bob.pair()); +// let charlie = Arc::new(AccountKeyring::Charlie.pair()); +// let mut index = 0; +// +// sc_service_test::sync( +// chain_spec, +// |config| { +// let mut setup_handles = None; +// let NewFullBase { task_manager, client, network, sync, transaction_pool, .. } = +// new_full_base( +// config, +// false, +// |block_import: &sc_consensus_babe::BabeBlockImport, +// babe_link: &sc_consensus_babe::BabeLink| { +// setup_handles = Some((block_import.clone(), babe_link.clone())); +// }, +// )?; +// +// let node = sc_service_test::TestNetComponents::new( +// task_manager, +// client, +// network, +// sync, +// transaction_pool, +// ); +// Ok((node, setup_handles.unwrap())) +// }, +// |service, &mut (ref mut block_import, ref babe_link): &mut (_, _)| { +// let parent_hash = service.client().chain_info().best_hash; +// let parent_header = service.client().header(parent_hash).unwrap().unwrap(); +// let parent_number = parent_header.number; +// +// futures::executor::block_on(service.transaction_pool().maintain( +// ChainEvent::NewBestBlock { hash: parent_header.hash(), tree_route: None }, +// )); +// +// let mut proposer_factory = sc_basic_authorship::ProposerFactory::new( +// service.spawn_handle(), +// service.client(), +// service.transaction_pool(), +// None, +// None, +// ); +// +// let mut digest = Digest::default(); +// +// // even though there's only one authority some slots might be empty, +// // so we must keep trying the next slots until we can claim one. +// let (babe_pre_digest, epoch_descriptor) = loop { +// let epoch_descriptor = babe_link +// .epoch_changes() +// .shared_data() +// .epoch_descriptor_for_child_of( +// descendent_query(&*service.client()), +// &parent_hash, +// parent_number, +// slot.into(), +// ) +// .unwrap() +// .unwrap(); +// +// let epoch = babe_link +// .epoch_changes() +// .shared_data() +// .epoch_data(&epoch_descriptor, |slot| { +// sc_consensus_babe::Epoch::genesis(babe_link.config(), slot) +// }) +// .unwrap(); +// +// if let Some(babe_pre_digest) = +// sc_consensus_babe::authorship::claim_slot(slot.into(), &epoch, &keystore) +// .map(|(digest, _)| digest) +// { +// break (babe_pre_digest, epoch_descriptor); +// } +// +// slot += 1; +// }; +// +// let inherent_data = futures::executor::block_on( +// ( +// sp_timestamp::InherentDataProvider::new( +// std::time::Duration::from_millis(SLOT_DURATION * slot).into(), +// ), +// sp_consensus_babe::inherents::InherentDataProvider::new(slot.into()), +// ) +// .create_inherent_data(), +// ) +// .expect("Creates inherent data"); +// +// digest.push(::babe_pre_digest(babe_pre_digest)); +// +// let new_block = futures::executor::block_on(async move { +// let proposer = proposer_factory.init(&parent_header).await; +// proposer +// .unwrap() +// .propose(inherent_data, digest, std::time::Duration::from_secs(1), None) +// .await +// }) +// .expect("Error making test block") +// .block; +// +// let (new_header, new_body) = new_block.deconstruct(); +// let pre_hash = new_header.hash(); +// // sign the pre-sealed hash of the block and then +// // add it to a digest item. +// let to_sign = pre_hash.encode(); +// let signature = keystore +// .sr25519_sign(sp_consensus_babe::AuthorityId::ID, alice.as_ref(), &to_sign) +// .unwrap() +// .unwrap(); +// let item = ::babe_seal(signature.into()); +// slot += 1; +// +// let mut params = BlockImportParams::new(BlockOrigin::File, new_header); +// params.post_digests.push(item); +// params.body = Some(new_body); +// params.insert_intermediate( +// INTERMEDIATE_KEY, +// BabeIntermediate:: { epoch_descriptor }, +// ); +// params.fork_choice = Some(ForkChoiceStrategy::LongestChain); +// +// futures::executor::block_on(block_import.import_block(params)) +// .expect("error importing test block"); +// }, +// |service, _| { +// let amount = 5 * CENTS; +// let to: Address = AccountPublic::from(bob.public()).into_account().into(); +// let from: Address = AccountPublic::from(charlie.public()).into_account().into(); +// let genesis_hash = service.client().block_hash(0).unwrap().unwrap(); +// let best_hash = service.client().chain_info().best_hash; +// let (_, _) = { +// let version = service.client().runtime_version_at(best_hash).unwrap(); +// (version.spec_version, version.transaction_version) +// }; +// let signer = charlie.clone(); +// +// let function = RuntimeCall::Balances(BalancesCall::transfer_allow_death { +// dest: to.into(), +// value: amount, +// }); +// +// let check_spec_version = frame_system::CheckSpecVersion::new(); +// let check_tx_version = frame_system::CheckTxVersion::new(); +// let check_genesis = frame_system::CheckGenesis::new(); +// let check_era = frame_system::CheckEra::from(Era::Immortal); +// let check_nonce = frame_system::CheckNonce::from(index); +// let check_weight = frame_system::CheckWeight::new(); +// let tx_payment = +// pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::from(0, None); +// let check_non_zero_sender = frame_system::CheckNonZeroSender::new(); +// let extra = ( +// check_non_zero_sender, +// check_spec_version, +// check_tx_version, +// check_genesis, +// check_era, +// check_nonce, +// check_weight, +// tx_payment, +// ); +// let raw_payload = node_polkadex_runtime::SignedPayload::from_raw( +// function.clone(), +// extra.clone(), +// ( +// (), +// node_polkadex_runtime::VERSION.spec_version, +// node_polkadex_runtime::VERSION.transaction_version, +// genesis_hash, +// best_hash, +// (), +// (), +// (), +// None +// ), +// ); +// let signature = raw_payload.using_encoded(|payload| signer.sign(payload)); +// let (function, extra, _) = raw_payload.deconstruct(); +// index += 1; +// UncheckedExtrinsic::new_signed(function, from.into(), signature.into(), extra) +// .into() +// }, +// ); +// } +// +// #[test] +// #[ignore] +// fn test_consensus() { +// sp_tracing::try_init_simple(); +// +// sc_service_test::consensus( +// crate::chain_spec::tests::integration_test_config_with_two_authorities(), +// |config| { +// let NewFullBase { task_manager, client, network, sync, transaction_pool, .. } = +// new_full_base(config, false, |_, _| ())?; +// Ok(sc_service_test::TestNetComponents::new( +// task_manager, +// client, +// network, +// sync, +// transaction_pool, +// )) +// }, +// vec!["//Alice".into(), "//Bob".into()], +// ) +// } +// } diff --git a/pallets/ocex/src/aggregator.rs b/pallets/ocex/src/aggregator.rs index fab4c6480..481ce76f8 100644 --- a/pallets/ocex/src/aggregator.rs +++ b/pallets/ocex/src/aggregator.rs @@ -46,7 +46,12 @@ impl AggregatorClient { /// Load signed summary and send it to the aggregator /// # Parameters /// * `snapshot_id`: Snapshot id for which signed summary should be loaded and sent - pub fn load_signed_summary_and_send(snapshot_id: u64) { + pub fn load_signed_summary_and_send( + current_set_id: u64, + snapshot_id: u64, + signer: &T::AuthorityId, + auth_index: u16, + ) -> Result<(), &'static str> { let mut key = LAST_PROCESSED_SNAPSHOT.to_vec(); key.append(&mut snapshot_id.encode()); @@ -56,7 +61,14 @@ impl AggregatorClient { <::AuthorityId as RuntimeAppPublic>::Signature, u16, )>() { - Ok(Some((summary, signature, index))) => { + Ok(Some((mut summary, mut signature, mut index))) => { + // Check if the validator set id is same as the current active, if not, update it and sign again + if summary.validator_set_id != current_set_id { + log::info!(target:"ocex","Signing with new validator set id's keys"); + summary.validator_set_id = current_set_id; + signature = signer.sign(&summary.encode()).ok_or("Private key not found")?; + index = auth_index; + } match serde_json::to_string(&ApprovedSnapshot { summary: summary.encode(), index: index.saturated_into(), @@ -83,6 +95,7 @@ impl AggregatorClient { log::error!(target:"ocex","Error loading signed summary for: nonce {:?}, {:?}",snapshot_id,err); }, } + Ok(()) } /// Load user action batch from aggregator diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index b6206d4e2..793b72b76 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -970,11 +970,7 @@ pub mod pallet { claim_safety_period: Option, ) -> DispatchResult { T::GovernanceOrigin::ensure_origin(origin)?; - let mut config = if let Some(config) = >::get() { - config - } else { - LMPEpochConfig::default() - }; + let mut config = >::get().unwrap_or_default(); let unit: Decimal = Decimal::from(UNIT_BALANCE); if let Some(total_liquidity_mining_rewards) = total_liquidity_mining_rewards { config.total_liquidity_mining_rewards = @@ -2250,8 +2246,8 @@ impl>> Pallet signatures.len() { diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 1c516d9c7..5e3f031d8 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -82,8 +82,7 @@ impl Pallet { let authorities = Self::validator_set().validators; let mut available_keys = authorities .iter() - .enumerate() - .filter_map(move |(_index, authority)| { + .filter_map(move |authority| { local_keys .binary_search(authority) .ok() @@ -120,9 +119,8 @@ impl Pallet { return Err("Last processed snapshot root is not same as on-chain root"); } info - } else if info.snapshot_id != 0 { + } else if info.snapshot_id != 0 && info.snapshot_id != next_nonce { log::error!(target:"ocex","Unable to load last processed snapshot summary from on-chain: {:?}",info.snapshot_id); - store_trie_root(H256::zero()); return Err("Unable to load last processed snapshot summary from on-chain"); } else { info @@ -139,8 +137,22 @@ impl Pallet { // Check if we already processed this snapshot and updated our offchain state. if last_processed_nonce == next_nonce { log::debug!(target:"ocex","Submitting last processed snapshot: {:?}",next_nonce); + if !sp_io::offchain::is_validator() { + log::error!(target: "ocex","We have stale signed summary for {:?} but not a validator anymore", last_processed_nonce); + return Ok(true); + } + let current_set_id = Self::validator_set().set_id; + let key = available_keys.first().ok_or("No active keys found")?; + let auth_index = Self::calculate_signer_index(&authorities, key) + .ok_or("Unable to calculate signer index")?; + // resubmit the summary to aggregator - AggregatorClient::::load_signed_summary_and_send(next_nonce); + AggregatorClient::::load_signed_summary_and_send( + current_set_id, + next_nonce, + key, + auth_index as u16, + )?; return Ok(true); } log::info!(target:"ocex","last_processed_nonce: {:?}, next_nonce: {:?}",last_processed_nonce, next_nonce); @@ -657,7 +669,8 @@ impl Pallet { /// Reset the offchain state's LMP index and set the epoch fn start_new_lmp_epoch(state: &mut OffchainState, epoch: u16) -> Result<(), &'static str> { let mut config = if epoch > 1 { - get_lmp_config(state, epoch)? + get_lmp_config(state, epoch) + .unwrap_or(orderbook_primitives::lmp::LMPConfig { epoch, index: 0 }) } else { // To Handle the corner case of zero orderbook_primitives::lmp::LMPConfig { epoch, index: 0 } diff --git a/pallets/thea-council/src/mock.rs b/pallets/thea-council/src/mock.rs index 5eceef617..7adb46d39 100644 --- a/pallets/thea-council/src/mock.rs +++ b/pallets/thea-council/src/mock.rs @@ -144,6 +144,7 @@ impl xcm_helper::Config for Test { type SubstrateNetworkId = frame_support::traits::ConstU8<0>; type NativeAssetId = NativeAssetId; type WeightInfo = xcm_helper::weights::WeightInfo; + type SiblingAddressConverter = (); } parameter_types! { diff --git a/pallets/xcm-helper/src/lib.rs b/pallets/xcm-helper/src/lib.rs index f999f690f..889fadbf0 100644 --- a/pallets/xcm-helper/src/lib.rs +++ b/pallets/xcm-helper/src/lib.rs @@ -222,6 +222,8 @@ pub mod pallet { type NativeAssetId: Get; /// Weight Info type WeightInfo: XcmHelperWeightInfo; + /// Sibling Address Converter + type SiblingAddressConverter: xcm_executor::traits::ConvertLocation; } /// Pending Withdrawals @@ -271,8 +273,11 @@ pub mod pallet { Box, Box, polkadex_primitives::AssetId, + u128, // Amount ExtraData, ), + /// Sibling Deposit + SiblingDeposit(Box, Box), /// Asset Withdraw using XCM /// parameters. [id, asset_id] AssetWithdrawn(H160, polkadex_primitives::AssetId), @@ -286,6 +291,20 @@ pub mod pallet { NativeAssetIdMappingRegistered(polkadex_primitives::AssetId, Box), /// Whitelisted Token removed WhitelistedTokenRemoved(polkadex_primitives::AssetId), + /// Not able too decode Destination + NotAbleToDecodeDestination, + /// Not able to mint token + NotAbleToMintToken, + /// Not able to Make Xcm Call + NotAbleToMakeXcmCall, + /// Not able to handle Destination + NotAbleToHandleDestination, + /// Xcm sibling deposit failed + XcmSiblingDepositFailed(Box, Box), + /// Parachain asset mapped + ParachainAssetMapped(polkadex_primitives::AssetId, Box), + /// Parachain asset not mapped + ParachainAssetNotMapped, } // Errors inform users that something went wrong. @@ -387,6 +406,22 @@ pub mod pallet { Self::deposit_event(Event::::XcmFeeTransferred(to, amount.saturated_into())); Ok(()) } + + #[pallet::call_index(4)] + #[pallet::weight(T::WeightInfo::transfer_fee(1))] + pub fn insert_asset( + origin: OriginFor, + asset_id: polkadex_primitives::AssetId, + asset_multilocation: AssetId, + ) -> DispatchResult { + T::AssetCreateUpdateOrigin::ensure_origin(origin)?; + >::insert(asset_id, asset_multilocation); + Self::deposit_event(Event::::ParachainAssetMapped( + asset_id, + Box::new(asset_multilocation), + )); + Ok(()) + } } impl Convert> for Pallet { @@ -407,31 +442,59 @@ pub mod pallet { ) -> xcm::latest::Result { // Create approved deposit let MultiAsset { id, fun } = what; - - let (recipient, extra) = - extract_data_from_multilocation(*who).ok_or(XcmError::FailedToDecode)?; - - let amount: u128 = Self::get_amount(fun).ok_or(XcmError::Trap(101))?; let asset_id = Self::generate_asset_id_for_parachain(*id); - let deposit: Deposit = Deposit { - id: Self::new_random_id(None), - recipient: recipient.into(), - asset_id, - amount, - extra: extra.clone(), - }; - - let parachain_network_id = T::SubstrateNetworkId::get(); - let unique_id = deposit.id; - T::Executor::execute_withdrawals(parachain_network_id, sp_std::vec![deposit].encode()) + if let Some(account) = T::SiblingAddressConverter::convert_location(who) { + let pallet_account: T::AccountId = + T::AssetHandlerPalletId::get().into_account_truncating(); + let amount: u128 = Self::get_amount(fun).ok_or(XcmError::Trap(101))?; + if Self::resolve_deposit_parachain( + asset_id.into(), + amount, + &account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + log::error!(target:"xcm-helper","Deposit Failed"); + Self::deposit_event(Event::::XcmSiblingDepositFailed( + Box::new(*who), + Box::new(what.clone()), + )); + }; + Self::deposit_event(Event::::SiblingDeposit( + Box::new(*who), + Box::new(what.clone()), + )); + } else { + let (recipient, extra) = + extract_data_from_multilocation(*who).ok_or(XcmError::Trap(99))?; + let amount: u128 = Self::get_amount(fun).ok_or(XcmError::Trap(101))?; + let asset_id = Self::generate_asset_id_for_parachain(*id); + let deposit: Deposit = Deposit { + id: Self::new_random_id(None), + recipient: recipient.into(), + asset_id, + amount, + extra: extra.clone(), + }; + let parachain_network_id = T::SubstrateNetworkId::get(); + let unique_id = deposit.id; + T::Executor::execute_withdrawals( + parachain_network_id, + sp_std::vec![deposit].encode(), + ) .map_err(|_| XcmError::Trap(102))?; - Self::deposit_event(Event::::AssetDeposited( - unique_id, - Box::new(*who), - Box::new(what.clone()), - asset_id, - extra, - )); + Self::deposit_event(Event::::AssetDeposited( + unique_id, + Box::new(*who), + Box::new(what.clone()), + asset_id, + amount, + extra, + )); + } Ok(()) } @@ -443,13 +506,19 @@ pub mod pallet { _context: Option<&XcmContext>, ) -> sp_std::result::Result { let MultiAsset { id: _, fun } = what; - let who = T::AccountIdConvert::convert_location(who).ok_or(XcmError::FailedToDecode)?; + let who_account = + T::AccountIdConvert::convert_location(who).ok_or(XcmError::FailedToDecode)?; let amount: u128 = Self::get_amount(fun).ok_or(XcmError::Trap(101))?; let asset_id = Self::generate_asset_id_for_parachain(what.id); let pallet_account: T::AccountId = T::AssetHandlerPalletId::get().into_account_truncating(); - Self::resolver_withdraw(asset_id.into(), amount.saturated_into(), &who, pallet_account) - .map_err(|_| XcmError::Trap(25))?; + Self::resolver_withdraw_parachain( + asset_id.into(), + amount.saturated_into(), + &who_account, + pallet_account, + ) + .map_err(|_| XcmError::Trap(110))?; Ok(what.clone().into()) } @@ -504,7 +573,7 @@ pub mod pallet { .ok_or(Error::::UnableToConvertToAccount)?; let pallet_account: T::AccountId = T::AssetHandlerPalletId::get().into_account_truncating(); - Self::resolver_deposit( + Self::resolve_deposit_parachain( withdrawal.asset_id.into(), withdrawal.amount, &destination_account, @@ -565,7 +634,9 @@ pub mod pallet { == AssetId::Concrete(MultiLocation { parents: 1, interior: Junctions::X1(Parachain(T::ParachainId::get())), - }) { + }) || asset + == AssetId::Concrete(MultiLocation { parents: 0, interior: Junctions::Here }) + { return polkadex_primitives::AssetId::Polkadex; } // If it's not native, then hash and generate the asset id @@ -618,6 +689,10 @@ pub mod pallet { >::insert(block_no, vec![withdrawal]); } + pub fn insert_parachain_asset(asset: AssetId, asset_id: polkadex_primitives::AssetId) { + >::insert(asset_id, asset); + } + pub fn handle_new_pending_withdrawals(n: BlockNumberFor) { let mut failed_withdrawal: Vec = Vec::default(); >::mutate(n, |withdrawals| { @@ -630,6 +705,8 @@ pub mod pallet { Err(_) => { failed_withdrawal.push(withdrawal); log::error!(target:"xcm-helper","Withdrawal failed: Not able to decode destination"); + // Emit Event + Self::deposit_event(Event::::NotAbleToDecodeDestination); continue; }, }; @@ -651,7 +728,7 @@ pub mod pallet { }; let pallet_account: T::AccountId = T::AssetHandlerPalletId::get().into_account_truncating(); - if Self::resolver_deposit( + if Self::resolve_deposit_parachain( withdrawal.asset_id.into(), withdrawal.amount, &pallet_account, @@ -663,9 +740,10 @@ pub mod pallet { { failed_withdrawal.push(withdrawal.clone()); log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + Self::deposit_event(Event::::NotAbleToMintToken); }; // Deposit Fee - if Self::resolver_deposit( + if Self::resolve_deposit_parachain( fee_asset_id.into(), fee_amount, &pallet_account, @@ -677,22 +755,23 @@ pub mod pallet { { failed_withdrawal.push(withdrawal.clone()); log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + Self::deposit_event(Event::::NotAbleToMintToken); }; - if orml_xtokens::module::Pallet::::transfer_multiassets( - RawOrigin::Signed( - T::AssetHandlerPalletId::get() - .into_account_truncating(), - ) - .into(), - Box::new(vec![multi_asset, fee_multi_asset].into()), - 1, - Box::new(destination.clone()), - cumulus_primitives_core::WeightLimit::Unlimited, - ) - .is_err() - { + if let Err(err) = + orml_xtokens::module::Pallet::::transfer_multiassets( + RawOrigin::Signed( + T::AssetHandlerPalletId::get() + .into_account_truncating(), + ) + .into(), + Box::new(vec![multi_asset, fee_multi_asset].into()), + 1, + Box::new(destination.clone()), + cumulus_primitives_core::WeightLimit::Unlimited, + ) { failed_withdrawal.push(withdrawal.clone()); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); + Self::deposit_event(Event::::NotAbleToMakeXcmCall); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls: {:?}", err); } else { // Deposit event Self::deposit_event(Event::::AssetWithdrawn( @@ -708,8 +787,42 @@ pub mod pallet { }; let pallet_account: T::AccountId = T::AssetHandlerPalletId::get().into_account_truncating(); + let destination_location = match destination { + VersionedMultiLocation::V3(location) => location, + _ => { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to decode destination"); + Self::deposit_event(Event::::NotAbleToDecodeDestination); + continue; + }, + }; + if let ( + Some(soverign_account), + polkadex_primitives::AssetId::Polkadex, + ) = ( + T::SiblingAddressConverter::convert_location( + &destination_location, + ), + withdrawal.asset_id, + ) { + // Deposit to Sovereign Account + if Self::resolve_deposit_parachain( + withdrawal.asset_id.into(), + withdrawal.amount, + &soverign_account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + Self::deposit_event(Event::::NotAbleToMintToken); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + }; + } // Mint - if Self::resolver_deposit( + if Self::resolve_deposit_parachain( withdrawal.asset_id.into(), withdrawal.amount, &pallet_account, @@ -720,22 +833,24 @@ pub mod pallet { .is_err() { failed_withdrawal.push(withdrawal.clone()); + Self::deposit_event(Event::::NotAbleToMintToken); log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); }; - if orml_xtokens::module::Pallet::::transfer_multiassets( - RawOrigin::Signed( - T::AssetHandlerPalletId::get().into_account_truncating(), - ) - .into(), - Box::new(multi_asset.into()), - 0, - Box::new(destination.clone()), - cumulus_primitives_core::WeightLimit::Unlimited, - ) - .is_err() - { + if let Err(err) = + orml_xtokens::module::Pallet::::transfer_multiassets( + RawOrigin::Signed( + T::AssetHandlerPalletId::get() + .into_account_truncating(), + ) + .into(), + Box::new(multi_asset.into()), + 0, + Box::new(destination.clone()), + cumulus_primitives_core::WeightLimit::Unlimited, + ) { failed_withdrawal.push(withdrawal.clone()); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls {:?}", err); + Self::deposit_event(Event::::NotAbleToMakeXcmCall); } else { // Deposit event Self::deposit_event(Event::::AssetWithdrawn( @@ -744,10 +859,13 @@ pub mod pallet { )) } } else { - failed_withdrawal.push(withdrawal) + log::error!(target:"xcm-helper","Withdrawal failed: Not able to handle dest"); + Self::deposit_event(Event::::ParachainAssetNotMapped); + failed_withdrawal.push(withdrawal); } } else if Self::handle_deposit(withdrawal.clone(), destination).is_err() { failed_withdrawal.push(withdrawal); + Self::deposit_event(Event::::NotAbleToHandleDestination); log::error!(target:"xcm-helper","Withdrawal failed: Not able to handle dest"); } } else { @@ -761,6 +879,10 @@ pub mod pallet { >::insert(n, failed_withdrawal); } } + + pub fn sibling_account_converter(para_id: MultiLocation) -> Option { + T::SiblingAddressConverter::convert_location(¶_id) + } } impl AssetIdConverter for Pallet { diff --git a/pallets/xcm-helper/src/mock.rs b/pallets/xcm-helper/src/mock.rs index ef34875e3..1b24bca63 100644 --- a/pallets/xcm-helper/src/mock.rs +++ b/pallets/xcm-helper/src/mock.rs @@ -127,6 +127,7 @@ impl xcm_helper::Config for Test { type SubstrateNetworkId = (); type NativeAssetId = NativeAssetId; type WeightInfo = crate::weights::WeightInfo; + type SiblingAddressConverter = (); } parameter_types! { diff --git a/polkadex-xcm-simulator/Cargo.toml b/polkadex-xcm-simulator/Cargo.toml index 37ae52ba2..a6b630800 100644 --- a/polkadex-xcm-simulator/Cargo.toml +++ b/polkadex-xcm-simulator/Cargo.toml @@ -11,6 +11,7 @@ log = { version = "0.4.14", default-features = false } frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +pallet-assets = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } pallet-uniques = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } @@ -28,6 +29,23 @@ polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot-sdk", polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } polkadot-parachain-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +#ORML Pallets +orml-xtokens = { git = "https://github.com/Polkadex-Substrate/orml-1.1.0.git", branch = "master" } +orml-xcm-support = { git = "https://github.com/Polkadex-Substrate/orml-1.1.0.git", branch = "master" } +orml-traits = { git = "https://github.com/Polkadex-Substrate/orml-1.1.0.git", branch = "master" } + +#Polkadex Pallets +thea-primitives = { workspace = true } +polkadex-primitives = { workspace = true } +xcm-helper = { path = "../pallets/xcm-helper" } +thea-message-handler = { path = "../pallets/thea-message-handler" } +thea = { path = "../pallets/thea" } +smallvec = "1.13.1" +hex = "0.4.3" + + + + [features] default = [] runtime-benchmarks = [ diff --git a/polkadex-xcm-simulator/src/lib.rs b/polkadex-xcm-simulator/src/lib.rs index 4b7958bf0..fa7102c24 100644 --- a/polkadex-xcm-simulator/src/lib.rs +++ b/polkadex-xcm-simulator/src/lib.rs @@ -43,6 +43,15 @@ decl_test_parachain! { } } +decl_test_parachain! { + pub struct ParaC { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::MsgQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(3), + } +} + decl_test_relay_chain! { pub struct Relay { Runtime = relay_chain::Runtime, @@ -61,6 +70,7 @@ decl_test_network! { parachains = vec![ (1, ParaA), (2, ParaB), + (3, ParaC), ], } } @@ -120,6 +130,7 @@ pub fn relay_ext() -> sp_io::TestExternalities { (ALICE, INITIAL_BALANCE), (child_account_id(1), INITIAL_BALANCE), (child_account_id(2), INITIAL_BALANCE), + (child_account_id(3), INITIAL_BALANCE), ], } .assimilate_storage(&mut t) @@ -141,8 +152,11 @@ pub type ParachainPalletXcm = pallet_xcm::Pallet; mod tests { use super::*; - use codec::Encode; + use crate::parachain::{Balances, XcmHelper}; + use codec::{Decode, Encode}; + use frame_support::traits::fungible::Mutate; use frame_support::{assert_ok, weights::Weight}; + use thea_primitives::extras::ExtraData; use xcm::latest::QueryResponseInfo; use xcm_simulator::TestExt; @@ -264,69 +278,15 @@ mod tests { ParaA::execute_with(|| { // free execution, full amount received + use parachain::{RuntimeEvent, System}; assert_eq!( pallet_balances::Pallet::::free_balance(&ALICE), - INITIAL_BALANCE + withdraw_amount - ); - }); - } - - #[test] - fn remote_locking_and_unlocking() { - MockNet::reset(); - - let locked_amount = 100; - - ParaB::execute_with(|| { - let message = Xcm(vec![LockAsset { - asset: (Here, locked_amount).into(), - unlocker: Parachain(1).into(), - }]); - assert_ok!(ParachainPalletXcm::send_xcm(Here, Parent, message.clone())); - }); - - Relay::execute_with(|| { - use pallet_balances::{BalanceLock, Reasons}; - assert_eq!( - relay_chain::Balances::locks(&child_account_id(2)), - vec![BalanceLock { - id: *b"py/xcmlk", - amount: locked_amount, - reasons: Reasons::All - }] - ); - }); - - ParaA::execute_with(|| { - assert_eq!( - parachain::MsgQueue::received_dmp(), - vec![Xcm(vec![NoteUnlockable { - owner: (Parent, Parachain(2)).into(), - asset: (Parent, locked_amount).into() - }])] - ); - }); - - ParaB::execute_with(|| { - // Request unlocking part of the funds on the relay chain - let message = Xcm(vec![RequestUnlock { - asset: (Parent, locked_amount - 50).into(), - locker: Parent.into(), - }]); - assert_ok!(ParachainPalletXcm::send_xcm(Here, (Parent, Parachain(1)), message)); - }); - - Relay::execute_with(|| { - use pallet_balances::{BalanceLock, Reasons}; - // Lock is reduced - assert_eq!( - relay_chain::Balances::locks(&child_account_id(2)), - vec![BalanceLock { - id: *b"py/xcmlk", - amount: locked_amount - 50, - reasons: Reasons::All - }] + INITIAL_BALANCE ); + assert!(System::events().iter().any(|r| matches!( + r.event, + RuntimeEvent::XcmHelper(xcm_helper::Event::AssetDeposited(..)) + ))); }); } @@ -356,141 +316,6 @@ mod tests { }); } - /// Scenario: - /// The relay-chain teleports an NFT to a parachain. - /// - /// Asserts that the parachain accounts are updated as expected. - #[test] - fn teleport_nft() { - MockNet::reset(); - - Relay::execute_with(|| { - // Mint the NFT (1, 69) and give it to our "parachain#1 alias". - assert_ok!(relay_chain::Uniques::mint( - relay_chain::RuntimeOrigin::signed(ALICE), - 1, - 69, - child_account_account_id(1, ALICE), - )); - // The parachain#1 alias of Alice is what must hold it on the Relay-chain for it to be - // withdrawable by Alice on the parachain. - assert_eq!( - relay_chain::Uniques::owner(1, 69), - Some(child_account_account_id(1, ALICE)) - ); - }); - ParaA::execute_with(|| { - assert_ok!(parachain::ForeignUniques::force_create( - parachain::RuntimeOrigin::root(), - (Parent, GeneralIndex(1)).into(), - ALICE, - false, - )); - assert_eq!( - parachain::ForeignUniques::owner((Parent, GeneralIndex(1)).into(), 69u32.into()), - None, - ); - assert_eq!(parachain::Balances::reserved_balance(&ALICE), 0); - - // IRL Alice would probably just execute this locally on the Relay-chain, but we can't - // easily do that here since we only send between chains. - let message = Xcm(vec![ - WithdrawAsset((GeneralIndex(1), 69u32).into()), - InitiateTeleport { - assets: AllCounted(1).into(), - dest: Parachain(1).into(), - xcm: Xcm(vec![DepositAsset { - assets: AllCounted(1).into(), - beneficiary: (AccountId32 { id: ALICE.into(), network: None },).into(), - }]), - }, - ]); - // Send teleport - let alice = AccountId32 { id: ALICE.into(), network: None }; - assert_ok!(ParachainPalletXcm::send_xcm(alice, Parent, message)); - }); - ParaA::execute_with(|| { - assert_eq!( - parachain::ForeignUniques::owner((Parent, GeneralIndex(1)).into(), 69u32.into()), - Some(ALICE), - ); - assert_eq!(parachain::Balances::reserved_balance(&ALICE), 1000); - }); - Relay::execute_with(|| { - assert_eq!(relay_chain::Uniques::owner(1, 69), None); - }); - } - - /// Scenario: - /// The relay-chain transfers an NFT into a parachain's sovereign account, who then mints a - /// trustless-backed-derivated locally. - /// - /// Asserts that the parachain accounts are updated as expected. - #[test] - fn reserve_asset_transfer_nft() { - sp_tracing::init_for_tests(); - MockNet::reset(); - - Relay::execute_with(|| { - assert_ok!(relay_chain::Uniques::force_create( - relay_chain::RuntimeOrigin::root(), - 2, - ALICE, - false - )); - assert_ok!(relay_chain::Uniques::mint( - relay_chain::RuntimeOrigin::signed(ALICE), - 2, - 69, - child_account_account_id(1, ALICE) - )); - assert_eq!( - relay_chain::Uniques::owner(2, 69), - Some(child_account_account_id(1, ALICE)) - ); - }); - ParaA::execute_with(|| { - assert_ok!(parachain::ForeignUniques::force_create( - parachain::RuntimeOrigin::root(), - (Parent, GeneralIndex(2)).into(), - ALICE, - false, - )); - assert_eq!( - parachain::ForeignUniques::owner((Parent, GeneralIndex(2)).into(), 69u32.into()), - None, - ); - assert_eq!(parachain::Balances::reserved_balance(&ALICE), 0); - - let message = Xcm(vec![ - WithdrawAsset((GeneralIndex(2), 69u32).into()), - DepositReserveAsset { - assets: AllCounted(1).into(), - dest: Parachain(1).into(), - xcm: Xcm(vec![DepositAsset { - assets: AllCounted(1).into(), - beneficiary: (AccountId32 { id: ALICE.into(), network: None },).into(), - }]), - }, - ]); - // Send transfer - let alice = AccountId32 { id: ALICE.into(), network: None }; - assert_ok!(ParachainPalletXcm::send_xcm(alice, Parent, message)); - }); - ParaA::execute_with(|| { - log::debug!(target: "xcm-exceutor", "Hello"); - assert_eq!( - parachain::ForeignUniques::owner((Parent, GeneralIndex(2)).into(), 69u32.into()), - Some(ALICE), - ); - assert_eq!(parachain::Balances::reserved_balance(&ALICE), 1000); - }); - - Relay::execute_with(|| { - assert_eq!(relay_chain::Uniques::owner(2, 69), Some(child_account_id(1))); - }); - } - /// Scenario: /// The relay-chain creates an asset class on a parachain and then Alice transfers her NFT into /// that parachain's sovereign account, who then mints a trustless-backed-derivative locally. @@ -648,4 +473,184 @@ mod tests { ); }); } + + #[test] + fn trasnfer_pdex_token_to_non_native_chain() { + MockNet::reset(); + ParaA::execute_with(|| { + let destination = MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(2), + Junction::AccountId32 { network: None, id: [1; 32] }, + ), + }; + let destination = VersionedMultiLocation::V3(destination); + let deposit = thea_primitives::types::Withdraw { + id: Default::default(), + asset_id: polkadex_primitives::AssetId::Polkadex, + amount: 2000000000000, + destination: destination.encode(), + fee_asset_id: None, + fee_amount: None, + is_blocked: false, + extra: ExtraData::None, + }; + let block_no = 1; + let multlocation = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(1)) }; + let pdex_asset_id = AssetId::Concrete(multlocation); + assert_ok!(Balances::mint_into(&XcmHelper::get_pallet_account(), 100000000000000000)); + XcmHelper::insert_parachain_asset( + pdex_asset_id, + polkadex_primitives::AssetId::Polkadex, + ); + XcmHelper::insert_pending_withdrawal(block_no, deposit.clone()); + XcmHelper::handle_new_pending_withdrawals(block_no); + }); + + ParaB::execute_with(|| { + use parachain::{RuntimeEvent, System}; + assert!(System::events().iter().any(|r| matches!( + r.event, + RuntimeEvent::XcmHelper(xcm_helper::Event::AssetDeposited(..)) + ))); + }) + } + + #[test] + fn test_on_initialize_with_native_asset_deposit_to_polkadex_parachain() { + MockNet::reset(); + ParaA::execute_with(|| { + let location = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(1)) }; + let asset_id_ml = AssetId::Concrete(location); + let destination = MultiLocation { + parents: 0, + interior: Junctions::X1(Junction::AccountId32 { network: None, id: [1; 32] }), + }; + let destination: VersionedMultiLocation = destination.into(); + let deposit = thea_primitives::types::Withdraw { + id: Default::default(), + asset_id: polkadex_primitives::AssetId::Polkadex, + amount: 2000000000000, + destination: destination.encode(), + fee_asset_id: None, + fee_amount: None, + is_blocked: false, + extra: ExtraData::None, + }; + assert_ok!(Balances::mint_into(&XcmHelper::get_pallet_account(), 100000000000000000)); + XcmHelper::insert_parachain_asset(asset_id_ml, polkadex_primitives::AssetId::Polkadex); + let block_no = 1; + XcmHelper::insert_pending_withdrawal(block_no, deposit.clone()); + XcmHelper::handle_new_pending_withdrawals(block_no); + }); + } + + #[test] + fn send_sibling_asset_to_non_reserve_sibling() { + MockNet::reset(); + + ParaC::execute_with(|| { + let multlocation = MultiLocation { parents: 0, interior: Junctions::Here }; + let pdex_asset_id = AssetId::Concrete(multlocation); + assert_ok!(Balances::mint_into( + &XcmHelper::get_pallet_account(), + 100_000_000_000_000_000 + )); + let para_a = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(1)) }; + let para_b = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(2)) }; + let para_c = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(3)) }; + assert_ok!(Balances::mint_into( + &XcmHelper::sibling_account_converter(para_a).unwrap(), + 100_000_000_000_000_000 + )); + assert_ok!(Balances::mint_into( + &XcmHelper::sibling_account_converter(para_b).unwrap(), + 100_000_000_000_000_000 + )); + assert_ok!(Balances::mint_into( + &XcmHelper::sibling_account_converter(para_c).unwrap(), + 100_000_000_000_000_000 + )); + XcmHelper::insert_parachain_asset( + pdex_asset_id, + polkadex_primitives::AssetId::Polkadex, + ); + }); + ParaA::execute_with(|| { + let destination = MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(2), + Junction::AccountId32 { network: None, id: [1; 32] }, + ), + }; + let destination = VersionedMultiLocation::V3(destination); + let multlocation = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(3)) }; + let non_reserve_asset_id = AssetId::Concrete(multlocation); + let asset_id = XcmHelper::generate_asset_id_for_parachain(non_reserve_asset_id); + let deposit = thea_primitives::types::Withdraw { + id: Default::default(), + asset_id, + amount: 2000000000000, + destination: destination.encode(), + fee_asset_id: None, + fee_amount: None, + is_blocked: false, + extra: ExtraData::None, + }; + let block_no = 1; + assert_ok!(Balances::mint_into(&XcmHelper::get_pallet_account(), 100000000000000000)); + XcmHelper::insert_parachain_asset(non_reserve_asset_id, asset_id); + XcmHelper::insert_pending_withdrawal(block_no, deposit.clone()); + XcmHelper::handle_new_pending_withdrawals(block_no); + }); + ParaC::execute_with(|| { + let multlocation = MultiLocation { parents: 0, interior: Junctions::Here }; + let pdex_asset_id = AssetId::Concrete(multlocation); + assert_ok!(Balances::mint_into(&XcmHelper::get_pallet_account(), 100000000000000000)); + XcmHelper::insert_parachain_asset( + pdex_asset_id, + polkadex_primitives::AssetId::Polkadex, + ); + use parachain::{RuntimeEvent, System}; + assert!(System::events().iter().any(|r| matches!( + r.event, + RuntimeEvent::XcmHelper(xcm_helper::Event::SiblingDeposit(..)) + ))); + }); + ParaB::execute_with(|| { + use parachain::{RuntimeEvent, System}; + assert!(System::events().iter().any(|r| matches!( + r.event, + RuntimeEvent::XcmHelper(xcm_helper::Event::AssetDeposited(..)) + ))); + }) + } + + #[test] + fn test_with_thea_payload() { + MockNet::reset(); + ParaA::execute_with(|| { + let hex = hex::decode("0400000000c9104ef90d846adb8cd6727f57c8e46d010010a5d4e800000000000000000000007003010200511f03007b9a3a0bd813c61006d94c7206137052f1cd6ce100000000").unwrap(); + let payload: Vec = + Decode::decode(&mut &hex[..]).unwrap(); + let block_no = 1; + let multlocation = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(1)) }; + let pdex_asset_id = AssetId::Concrete(multlocation); + XcmHelper::insert_parachain_asset( + pdex_asset_id, + polkadex_primitives::AssetId::Polkadex, + ); + XcmHelper::insert_pending_withdrawal(block_no, payload.first().unwrap().clone()); + XcmHelper::handle_new_pending_withdrawals(block_no); + }) + } } diff --git a/polkadex-xcm-simulator/src/parachain.rs b/polkadex-xcm-simulator/src/parachain.rs index 6ec8c22ec..7e93377b2 100644 --- a/polkadex-xcm-simulator/src/parachain.rs +++ b/polkadex-xcm-simulator/src/parachain.rs @@ -18,37 +18,40 @@ use codec::{Decode, Encode}; use core::marker::PhantomData; +use frame_support::traits::AsEnsureOriginWithArg; use frame_support::{ construct_runtime, parameter_types, - traits::{ContainsPair, EnsureOrigin, EnsureOriginWithArg, Everything, EverythingBut, Nothing}, + traits::{EnsureOrigin, EnsureOriginWithArg, Everything, EverythingBut, Nothing}, weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, + PalletId, }; - -use frame_system::EnsureRoot; -use sp_core::{ConstU32, H256}; -use sp_runtime::{ - traits::{Get, Hash, IdentityLookup}, - AccountId32, -}; -use sp_std::prelude::*; - +use frame_system::{EnsureRoot, EnsureSigned}; +use orml_traits::location::AbsoluteReserveProvider; +use orml_traits::parameter_type_with_key; use pallet_xcm::XcmPassthrough; use polkadot_core_primitives::BlockNumber as RelayBlockNumber; use polkadot_parachain_primitives::primitives::{ DmpMessageHandler, Id as ParaId, Sibling, XcmpMessageFormat, XcmpMessageHandler, }; +use sp_core::{ConstU32, H256}; +use sp_runtime::traits::Convert; +use sp_runtime::{ + traits::{Get, Hash, IdentityLookup}, + AccountId32, Perbill, SaturatedConversion, +}; +use sp_std::prelude::*; +use thea::ecdsa::AuthorityId; +use thea::ecdsa::AuthoritySignature; use xcm::{latest::prelude::*, VersionedXcm}; use xcm_builder::{ - Account32Hash, AccountId32Aliases, AllowUnpaidExecutionFrom, ConvertedConcreteId, - CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, - IsConcrete, NativeAsset, NoChecking, NonFungiblesAdapter, ParentIsPreset, + Account32Hash, AccountId32Aliases, AllowUnpaidExecutionFrom, EnsureXcmOrigin, + FixedRateOfFungible, FixedWeightBounds, NativeAsset, ParentIsPreset, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, -}; -use xcm_executor::{ - traits::{ConvertLocation, JustTry}, - Config, XcmExecutor, + SovereignSignedViaLocation, TakeRevenue, }; +use xcm_executor::traits::WeightTrader; +use xcm_executor::{traits::ConvertLocation, Config, XcmExecutor}; +use xcm_helper::{AssetIdConverter, WhitelistedTokenHandler}; pub type SovereignAccountOf = ( SiblingParachainConvertsVia, @@ -63,6 +66,13 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } +pub mod currency { + pub type Balance = u128; + pub const PDEX: Balance = 1_000_000_000_000; + pub const DOLLARS: Balance = PDEX; // 1_000_000_000_000 + pub const CENTS: Balance = DOLLARS / 100; // 10_000_000_000 +} + impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -197,19 +207,23 @@ parameter_types! { pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; pub ForeignPrefix: MultiLocation = (Parent,).into(); + pub const RelayLocation: MultiLocation = MultiLocation::parent(); + pub PdexLocation: MultiLocation = Here.into(); } -pub type LocalAssetTransactor = ( - XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>, - NonFungiblesAdapter< - ForeignUniques, - ConvertedConcreteId, - SovereignAccountOf, - AccountId, - NoChecking, - (), - >, -); +// Can be used later +// pub type LocalAssetTransactor = CurrencyAdapter< +// // Use this currency: +// Balances, +// // Use this currency when it is a fungible asset matching the given location or name: +// IsConcrete, +// // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: +// LocationToAccountId, +// // Our chain's account ID type (we can't get away without mentioning it explicitly): +// AccountId, +// // We don't track any teleports. +// (), +// >; pub type XcmRouter = super::ParachainXcmRouter; pub type Barrier = AllowUnpaidExecutionFrom; @@ -223,18 +237,48 @@ parameter_types! { pub type TrustedTeleporters = xcm_builder::Case; pub type TrustedReserves = EverythingBut>; +use smallvec::smallvec; + +pub struct WeightToFee; +impl WeightToFeePolynomial for WeightToFee { + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // Extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: + let p = CENTS; + let q = 10 * Balance::from(ExtrinsicBaseWeight::get().ref_time()); + smallvec![WeightToFeeCoefficient { + degree: 1, + negative: false, + coeff_frac: Perbill::from_rational(p % q, q), + coeff_integer: p / q, + }] + } +} + pub struct XcmConfig; impl Config for XcmConfig { type RuntimeCall = RuntimeCall; type XcmSender = XcmRouter; - type AssetTransactor = LocalAssetTransactor; + type AssetTransactor = XcmHelper; type OriginConverter = XcmOriginToCallOrigin; type IsReserve = (NativeAsset, TrustedReserves); type IsTeleporter = TrustedTeleporters; type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = FixedWeightBounds; - type Trader = FixedRateOfFungible; + type Trader = ( + // If the XCM message is paying the fees in PDEX ( the native ) then + // it will go to the author of the block as rewards + //UsingComponents>, + FixedRateOfFungible, + ForeignAssetFeeHandler< + //TODO: Should we go for FixedRateOfForeignAsset + WeightToFee, + RevenueCollector, + XcmHelper, + XcmHelper, + >, + ); type ResponseHandler = (); type AssetTrap = (); type AssetLocker = PolkadotXcm; @@ -404,22 +448,10 @@ parameter_types! { pub ReachableDest: Option = Some(Parent.into()); } -pub struct TrustedLockerCase(PhantomData); -impl> ContainsPair - for TrustedLockerCase -{ - fn contains(origin: &MultiLocation, asset: &MultiAsset) -> bool { - let (o, a) = T::get(); - a.matches(asset) && &o == origin - } -} - parameter_types! { pub RelayTokenForRelay: (MultiLocation, MultiAssetFilter) = (Parent.into(), Wild(AllOf { id: Concrete(Parent.into()), fun: WildFungible })); } -pub type TrustedLockers = TrustedLockerCase; - impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SendXcmOrigin = EnsureXcmOrigin; @@ -437,8 +469,8 @@ impl pallet_xcm::Config for Runtime { type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; type Currency = Balances; type CurrencyMatcher = (); - type TrustedLockers = TrustedLockers; - type SovereignAccountOf = LocationToAccountId; + type TrustedLockers = (); + type SovereignAccountOf = (); type MaxLockers = ConstU32<8>; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); @@ -450,6 +482,124 @@ impl pallet_xcm::Config for Runtime { type Block = frame_system::mocking::MockBlock; +parameter_types! { + pub const AssetDeposit: Balance = 100 * currency::DOLLARS; + pub const ApprovalDeposit: Balance = currency::DOLLARS; + pub const StringLimit: u32 = 50; + pub const MetadataDepositBase: Balance = 10 * currency::DOLLARS; + pub const MetadataDepositPerByte: Balance = currency::DOLLARS; +} +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type RemoveItemsLimit = ConstU32<1000>; + type AssetId = u128; + type AssetIdParameter = codec::Compact; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = StringLimit; + type Freezer = (); + type Extra = (); + type CallbackHandle = (); + type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = AssetU128; +} + +#[cfg(feature = "runtime-benchmarks")] +pub struct AssetU128; +#[cfg(feature = "runtime-benchmarks")] +use pallet_assets::BenchmarkHelper; + +#[cfg(feature = "runtime-benchmarks")] +impl BenchmarkHelper> for AssetU128 { + fn create_asset_id_parameter(id: u32) -> codec::Compact { + codec::Compact::from(id as u128) + } +} + +pub const POLKADEX_NATIVE_ASSET_ID: u128 = 0; + +parameter_types! { + pub const AssetHandlerPalletId: PalletId = PalletId(*b"XcmHandl"); + pub const WithdrawalExecutionBlockDiff: u32 = 1; + pub ParachainId: u32 = MsgQueue::parachain_id().into(); + pub const ParachainNetworkId: u8 = 1; // Our parachain's thea id is one. + pub const PolkadexAssetid: u128 = POLKADEX_NATIVE_ASSET_ID; +} + +impl xcm_helper::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type AccountIdConvert = LocationToAccountId; + type Assets = Assets; + type AssetId = u128; + type Currency = Balances; + type AssetCreateUpdateOrigin = EnsureRoot; + type Executor = TheaMessageHandler; + type AssetHandlerPalletId = AssetHandlerPalletId; + type WithdrawalExecutionBlockDiff = WithdrawalExecutionBlockDiff; + type ParachainId = ParachainId; + type SubstrateNetworkId = ParachainNetworkId; + type NativeAssetId = PolkadexAssetid; + type WeightInfo = xcm_helper::weights::WeightInfo; + type SiblingAddressConverter = SiblingParachainConvertsVia; +} + +parameter_types! { + pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(MsgQueue::parachain_id().into()))); + pub BaseXcmWeight: Weight = Weight::from_parts(100_000_000, 0); + pub const MaxAssetsForTransfer: usize = 2; +} + +parameter_type_with_key! { + pub ParachainMinFee: |_location: MultiLocation| -> Option { + Some(1u128) + }; +} + +pub struct AccountIdToMultiLocation; +impl Convert for AccountIdToMultiLocation { + fn convert(account: AccountId) -> MultiLocation { + X1(xcm::prelude::AccountId32 { network: None, id: account.into() }).into() + } +} + +impl orml_xtokens::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type CurrencyId = polkadex_primitives::AssetId; + type CurrencyIdConvert = XcmHelper; + type AccountIdToMultiLocation = AccountIdToMultiLocation; + type SelfLocation = SelfLocation; + type MinXcmFee = ParachainMinFee; + type XcmExecutor = XcmExecutor; + type MultiLocationsFilter = Everything; + type Weigher = FixedWeightBounds; + type BaseXcmWeight = BaseXcmWeight; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type ReserveProvider = AbsoluteReserveProvider; + type UniversalLocation = UniversalLocation; +} + +parameter_types! { + pub const TheaMaxAuthorities: u32 = 200; +} + +impl thea_message_handler::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type TheaId = AuthorityId; + type Signature = AuthoritySignature; + type MaxAuthorities = TheaMaxAuthorities; + type Executor = XcmHelper; + type WeightInfo = thea_message_handler::weights::WeightInfo; +} + construct_runtime!( pub enum Runtime { @@ -458,5 +608,113 @@ construct_runtime!( MsgQueue: mock_msg_queue::{Pallet, Storage, Event}, PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, ForeignUniques: pallet_uniques::{Pallet, Call, Storage, Event}, + Assets: pallet_assets::{Pallet, Call, Storage, Event}, + XTokens: orml_xtokens::{Pallet, Call, Storage, Event}, + XcmHelper: xcm_helper::{Pallet, Call, Storage, Event}, + TheaMessageHandler: thea_message_handler::{Pallet, Call, Storage, Event} } ); + +pub struct ForeignAssetFeeHandler +where + T: WeightToFeeT, + R: TakeRevenue, + AC: AssetIdConverter, + WH: WhitelistedTokenHandler, +{ + /// Total used weight + weight: Weight, + /// Total consumed assets + consumed: u128, + /// Asset Id (as MultiLocation) and units per second for payment + asset_location_and_units_per_second: Option<(MultiLocation, u128)>, + _pd: PhantomData<(T, R, AC, WH)>, +} + +impl WeightTrader for ForeignAssetFeeHandler +where + T: WeightToFeeT, + R: TakeRevenue, + AC: AssetIdConverter, + WH: WhitelistedTokenHandler, +{ + fn new() -> Self { + Self { + weight: Weight::zero(), + consumed: 0, + asset_location_and_units_per_second: None, + _pd: PhantomData, + } + } + + /// NOTE: If the token is allowlisted by AMM pallet ( probably using governance ) + /// then it will be allowed to execute for free even if the pool is not there. + /// If pool is not there and token is not present in allowlisted then it will be rejected. + fn buy_weight( + &mut self, + weight: Weight, + payment: xcm_executor::Assets, + _context: &XcmContext, + ) -> sp_std::result::Result { + let _fee_in_native_token = T::weight_to_fee(&weight); + let payment_asset = payment.fungible_assets_iter().next().ok_or(XcmError::Trap(1000))?; + if let AssetId::Concrete(location) = payment_asset.id { + // let foreign_currency_asset_id = + // AC::convert_location_to_asset_id(location).ok_or(XcmError::Trap(1001))?; + // let _path = [PolkadexAssetid::get(), foreign_currency_asset_id.into()]; + //WILL BE RESTORED LATER + // let (unused, expected_fee_in_foreign_currency) = + // if WH::check_whitelisted_token(foreign_currency_asset_id) { + // (payment, 0u128) + // } else { + // return Err(XcmError::Trap(1004)); + // }; + let (unused, expected_fee_in_foreign_currency) = (payment, 0u128); + self.weight = self.weight.saturating_add(weight); + if let Some((old_asset_location, _)) = self.asset_location_and_units_per_second { + if old_asset_location == location { + self.consumed = self + .consumed + .saturating_add((expected_fee_in_foreign_currency).saturated_into()); + } + } else { + self.consumed = self + .consumed + .saturating_add((expected_fee_in_foreign_currency).saturated_into()); + self.asset_location_and_units_per_second = Some((location, 0)); + } + Ok(unused) + } else { + Err(XcmError::Trap(1005)) + } + } +} + +use crate::parachain::currency::CENTS; +use frame_support::weights::constants::ExtrinsicBaseWeight; +use frame_support::weights::WeightToFee as WeightToFeeT; +use frame_support::weights::{ + WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, +}; + +impl Drop for ForeignAssetFeeHandler +where + T: WeightToFeeT, + R: TakeRevenue, + AC: AssetIdConverter, + WH: WhitelistedTokenHandler, +{ + fn drop(&mut self) { + if let Some((asset_location, _)) = self.asset_location_and_units_per_second { + if self.consumed > 0 { + R::take_revenue((asset_location, self.consumed).into()); + } + } + } +} + +pub struct RevenueCollector; + +impl TakeRevenue for RevenueCollector { + fn take_revenue(_revenue: MultiAsset) {} +} diff --git a/primitives/polkadex/src/assets.rs b/primitives/polkadex/src/assets.rs index c4be5e631..29ed9537c 100644 --- a/primitives/polkadex/src/assets.rs +++ b/primitives/polkadex/src/assets.rs @@ -79,6 +79,45 @@ pub trait Resolver< Ok(()) } + fn resolve_deposit_parachain( + asset: AssetId, + amount: Balance, + who: &AccountId, + admin: AccountId, + min_balance: Balance, + _locking_account: AccountId, + ) -> Result<(), DispatchError> { + if asset == NativeAssetId::get() { + Native::mint_into(who, amount.saturated_into())?; + } else { + if !Others::asset_exists(asset.into()) { + Others::create(asset.into(), admin, true, min_balance.saturated_into())?; + } + Others::mint_into(asset.into(), who, amount.saturated_into())?; + } + Ok(()) + } + + fn resolver_withdraw_parachain( + asset: AssetId, + amount: Balance, + who: &AccountId, + _locking_account: AccountId, + ) -> Result<(), DispatchError> { + if asset == NativeAssetId::get() { + Native::burn_from(who, amount.saturated_into(), Precision::Exact, Fortitude::Force)?; + } else { + Others::burn_from( + asset.into(), + who, + amount.saturated_into(), + Precision::Exact, + Fortitude::Polite, + )?; + } + Ok(()) + } + /// Deposit will burn tokens if asset is non native and in case of native, will transfer /// native tokens from `who` to `NativeLockingAccount` fn resolver_withdraw( diff --git a/runtimes/mainnet/Cargo.toml b/runtimes/mainnet/Cargo.toml index 4453dc82c..5e9231161 100644 --- a/runtimes/mainnet/Cargo.toml +++ b/runtimes/mainnet/Cargo.toml @@ -118,14 +118,29 @@ frame-try-runtime = { workspace = true, optional = true, default-features = fals rpc-assets-runtime-api = { path = "../../rpc/assets/runtime-api", default-features = false } pallet-rewards-runtime-api = { path = "../../pallets/rewards/rpc/runtime-api", default-features = false } pallet-ocex-runtime-api = { path = "../../pallets/ocex/rpc/runtime-api", default-features = false } - +frame-metadata-hash-extension = { workspace = true, default-features = false } [build-dependencies] -substrate-wasm-builder = { workspace = true } +substrate-wasm-builder = { workspace = true , features = ["frame-metadata"]} +docify = "0.2.8" [features] default = ["std"] +# Enable the metadata hash generation. +# +# This is hidden behind a feature because it increases the compile time. +# The wasm binary needs to be compiled twice, once to fetch the metadata, +# generate the metadata hash and then a second time with the +# `RUNTIME_METADATA_HASH` environment variable set for the `CheckMetadataHash` +# extension. +metadata-hash = ["substrate-wasm-builder/metadata-hash"] + +# A convenience feature for enabling things when doing a build +# for an on-chain release. +on-chain-release-build = ["metadata-hash"] + std = [ "rust_decimal/std", + "frame-metadata-hash-extension/std", "parity-scale-codec/std", "scale-info/std", "log/std", diff --git a/runtimes/mainnet/build.rs b/runtimes/mainnet/build.rs index 453eebcc8..dd047a83d 100644 --- a/runtimes/mainnet/build.rs +++ b/runtimes/mainnet/build.rs @@ -16,12 +16,20 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use substrate_wasm_builder::WasmBuilder; +#[cfg(all(feature = "std", feature = "metadata-hash"))] +#[docify::export(template_enable_metadata_hash)] +fn main() { + substrate_wasm_builder::WasmBuilder::init_with_defaults() + .enable_metadata_hash("PDEX", 12) + .build(); +} +#[cfg(all(feature = "std", not(feature = "metadata-hash")))] fn main() { - WasmBuilder::new() - .with_current_project() - .import_memory() - .export_heap_base() - .build() + substrate_wasm_builder::WasmBuilder::build_using_defaults(); } + +/// The wasm builder is deactivated when compiling +/// this crate for wasm to speed up the compilation. +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 0b21ea717..1f1fa930c 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 358, + spec_version: 369, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, @@ -1019,9 +1019,9 @@ impl pallet_sudo::Config for Runtime { } parameter_types! { - pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); + pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::MAX; /// We prioritize im-online heartbeats over election solution submission. - pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; + pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::MAX / 2; pub const MaxKeys: u32 = 10_000; pub const MaxPeerInHeartbeats: u32 = 10_000; pub const MaxPeerDataEncodingSize: u32 = 1_000; @@ -1055,6 +1055,7 @@ where frame_system::CheckNonce::::from(nonce), frame_system::CheckWeight::::new(), pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::::from(tip, None), + frame_metadata_hash_extension::CheckMetadataHash::new(false), ); let raw_payload = SignedPayload::new(call, extra) .map_err(|e| { @@ -1589,6 +1590,7 @@ pub type SignedExtra = ( frame_system::CheckNonce, frame_system::CheckWeight, pallet_asset_conversion_tx_payment::ChargeAssetTxPayment, + frame_metadata_hash_extension::CheckMetadataHash, ); /// Unchecked extrinsic type as expected by this runtime. diff --git a/runtimes/parachain/src/lib.rs b/runtimes/parachain/src/lib.rs index c53ba6b00..1fb5ee714 100644 --- a/runtimes/parachain/src/lib.rs +++ b/runtimes/parachain/src/lib.rs @@ -179,7 +179,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("polkadex-parachain"), impl_name: create_runtime_str!("polkadex-parachain"), authoring_version: 1, - spec_version: 14, + spec_version: 16, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -490,6 +490,7 @@ impl xcm_helper::Config for Runtime { type SubstrateNetworkId = ParachainNetworkId; type NativeAssetId = PolkadexAssetid; type WeightInfo = xcm_helper::weights::WeightInfo; + type SiblingAddressConverter = SiblingParachainConvertsVia; } parameter_types! { @@ -538,6 +539,8 @@ impl pallet_assets::Config for Runtime { pub struct AssetU128; #[cfg(feature = "runtime-benchmarks")] use pallet_assets::BenchmarkHelper; +use polkadot_parachain::primitives::Sibling; +use xcm_builder::SiblingParachainConvertsVia; #[cfg(feature = "runtime-benchmarks")] impl BenchmarkHelper> for AssetU128 { diff --git a/runtimes/parachain/src/xcm_config.rs b/runtimes/parachain/src/xcm_config.rs index 54ff3ed25..520a88d43 100644 --- a/runtimes/parachain/src/xcm_config.rs +++ b/runtimes/parachain/src/xcm_config.rs @@ -26,6 +26,7 @@ use frame_support::{ }; use frame_system::EnsureRoot; +use orml_traits::location::RelativeReserveProvider; use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::MultiNativeAsset; use pallet_xcm::XcmPassthrough; @@ -167,7 +168,7 @@ impl xcm_executor::Config for XcmConfig { // How to withdraw and deposit an asset. type AssetTransactor = XcmHelper; type OriginConverter = XcmOriginToTransactDispatchOrigin; - type IsReserve = MultiNativeAsset; + type IsReserve = MultiNativeAsset; // Teleporting is disabled. type IsTeleporter = (); type Aliasers = Nothing;