From 58f6a78b142b00f0c8e9579ecb5c07b7f78ed069 Mon Sep 17 00:00:00 2001 From: Malte Kliemann Date: Mon, 24 Jun 2024 17:37:19 +0200 Subject: [PATCH] Revert "New Asset System (#1295)" (#1338) * Revert "New Asset System (#1295)" This reverts commit a956877d596ac41d8bda5c341b35472ef915fa18. * Fix formatting * Update copyright * Remove pallet-assets dependency * Fix fuzz tests --- CODEOWNERS | 1 - Cargo.lock | 53 -- Cargo.toml | 8 - README.md | 2 - docs/changelog_for_devs.md | 24 +- macros/src/lib.rs | 8 +- primitives/Cargo.toml | 1 - primitives/src/{assets.rs => asset.rs} | 58 +- primitives/src/assets/all_assets.rs | 170 ------ primitives/src/assets/campaign_assets.rs | 51 -- primitives/src/assets/currencies.rs | 77 --- primitives/src/assets/custom_assets.rs | 49 -- primitives/src/assets/market_assets.rs | 63 --- primitives/src/assets/subsets/base_assets.rs | 48 -- primitives/src/assets/subsets/mod.rs | 26 - primitives/src/assets/subsets/parimutuel.rs | 38 -- primitives/src/assets/subsets/xcm_assets.rs | 43 -- primitives/src/assets/tests.rs | 24 - primitives/src/assets/tests/conversion.rs | 358 ------------ primitives/src/assets/tests/scale_codec.rs | 146 ----- primitives/src/constants.rs | 2 +- primitives/src/constants/base_multiples.rs | 2 - primitives/src/constants/mock.rs | 36 +- primitives/src/lib.rs | 3 +- primitives/src/market.rs | 192 +++---- primitives/src/serde_wrapper.rs | 66 +++ primitives/src/traits.rs | 4 - primitives/src/traits/dispute_api.rs | 10 +- primitives/src/traits/market_builder.rs | 26 +- .../src/traits/market_commons_pallet_api.rs | 9 +- primitives/src/traits/market_id.rs | 14 +- .../src/traits/market_transition_api.rs | 322 ----------- primitives/src/traits/swaps.rs | 8 +- primitives/src/traits/weights.rs | 60 -- primitives/src/types.rs | 41 +- runtime/battery-station/Cargo.toml | 6 - .../src/integration_tests/xcm/setup.rs | 22 +- .../src/integration_tests/xcm/test_net.rs | 10 +- .../xcm/tests/currency_id_convert.rs | 154 ++---- .../integration_tests/xcm/tests/transfers.rs | 58 +- runtime/battery-station/src/lib.rs | 33 +- runtime/battery-station/src/parameters.rs | 65 +-- .../src/xcm_config/asset_registry.rs | 10 +- .../battery-station/src/xcm_config/config.rs | 130 ++--- .../battery-station/src/xcm_config/fees.rs | 4 +- runtime/common/Cargo.toml | 2 - runtime/common/src/fees.rs | 431 +++++---------- runtime/common/src/lib.rs | 203 ++----- runtime/common/src/weights/mod.rs | 1 - runtime/common/src/weights/pallet_assets.rs | 421 -------------- runtime/zeitgeist/Cargo.toml | 6 - .../src/integration_tests/xcm/setup.rs | 24 +- .../src/integration_tests/xcm/test_net.rs | 10 +- .../xcm/tests/currency_id_convert.rs | 154 ++---- .../integration_tests/xcm/tests/transfers.rs | 77 ++- runtime/zeitgeist/src/lib.rs | 31 +- runtime/zeitgeist/src/parameters.rs | 63 +-- .../src/xcm_config/asset_registry.rs | 10 +- runtime/zeitgeist/src/xcm_config/config.rs | 130 ++--- runtime/zeitgeist/src/xcm_config/fees.rs | 4 +- scripts/benchmarks/configuration.sh | 6 +- zrml/asset-router/Cargo.toml | 39 -- zrml/asset-router/README.md | 61 -- zrml/asset-router/src/lib.rs | 520 ------------------ zrml/asset-router/src/macros.rs | 151 ----- zrml/asset-router/src/mock.rs | 302 ---------- zrml/asset-router/src/pallet_impl/create.rs | 37 -- zrml/asset-router/src/pallet_impl/destroy.rs | 42 -- zrml/asset-router/src/pallet_impl/inspect.rs | 124 ----- .../src/pallet_impl/managed_destroy.rs | 73 --- zrml/asset-router/src/pallet_impl/mod.rs | 28 - .../src/pallet_impl/multi_currency.rs | 217 -------- .../pallet_impl/multi_currency_extended.rs | 80 --- .../pallet_impl/multi_lockable_currency.rs | 81 --- .../pallet_impl/multi_reserveable_currency.rs | 82 --- .../named_multi_reserveable_currency.rs | 130 ----- .../src/pallet_impl/transfer_all.rs | 26 - .../src/pallet_impl/unbalanced.rs | 67 --- zrml/asset-router/src/tests/create.rs | 61 -- zrml/asset-router/src/tests/custom_types.rs | 86 --- zrml/asset-router/src/tests/destroy.rs | 101 ---- zrml/asset-router/src/tests/inspect.rs | 113 ---- .../asset-router/src/tests/managed_destroy.rs | 337 ------------ zrml/asset-router/src/tests/mod.rs | 48 -- zrml/asset-router/src/tests/multi_currency.rs | 152 ----- .../src/tests/multi_lockable_currency.rs | 99 ---- .../src/tests/multi_reservable_currency.rs | 100 ---- .../tests/named_multi_reservable_currency.rs | 118 ---- zrml/asset-router/src/tests/unbalanced.rs | 125 ----- zrml/asset-router/src/types.rs | 120 ---- zrml/authorized/src/lib.rs | 9 +- zrml/authorized/src/weights.rs | 12 +- zrml/court/src/benchmarks.rs | 4 +- zrml/court/src/lib.rs | 4 +- zrml/court/src/tests.rs | 8 +- zrml/court/src/weights.rs | 18 +- zrml/global-disputes/src/utils.rs | 3 +- zrml/global-disputes/src/weights.rs | 8 +- zrml/hybrid-router/Cargo.toml | 5 - zrml/hybrid-router/src/benchmarking.rs | 35 +- zrml/hybrid-router/src/lib.rs | 14 +- zrml/hybrid-router/src/mock.rs | 178 +----- zrml/hybrid-router/src/tests/buy.rs | 97 ++-- zrml/hybrid-router/src/tests/mod.rs | 14 +- zrml/hybrid-router/src/tests/sell.rs | 94 ++-- zrml/hybrid-router/src/utils.rs | 10 +- zrml/liquidity-mining/src/tests.rs | 6 +- zrml/market-commons/src/lib.rs | 19 +- zrml/market-commons/src/migrations.rs | 373 ------------- zrml/market-commons/src/tests.rs | 4 +- .../src/types/market_builder.rs | 22 +- zrml/neo-swaps/Cargo.toml | 8 +- zrml/neo-swaps/src/benchmarking.rs | 2 +- zrml/neo-swaps/src/lib.rs | 10 +- zrml/neo-swaps/src/macros.rs | 6 +- zrml/neo-swaps/src/mock.rs | 182 +----- zrml/neo-swaps/src/tests/deploy_pool.rs | 52 +- zrml/neo-swaps/src/tests/join.rs | 3 +- zrml/neo-swaps/src/tests/mod.rs | 16 +- zrml/neo-swaps/src/tests/sell.rs | 2 +- zrml/neo-swaps/src/types/max_assets.rs | 2 +- zrml/neo-swaps/src/weights.rs | 20 - zrml/orderbook/Cargo.toml | 14 +- .../fuzz/orderbook_v1_full_workflow.rs | 4 +- zrml/orderbook/src/benchmarks.rs | 4 +- zrml/orderbook/src/lib.rs | 206 ++++--- zrml/orderbook/src/mock.rs | 160 +----- zrml/orderbook/src/tests.rs | 281 +++------- zrml/orderbook/src/utils.rs | 9 +- zrml/orderbook/src/weights.rs | 6 - zrml/parimutuel/Cargo.toml | 5 - zrml/parimutuel/src/benchmarking.rs | 81 +-- zrml/parimutuel/src/lib.rs | 259 ++------- zrml/parimutuel/src/mock.rs | 184 +------ zrml/parimutuel/src/tests/buy.rs | 67 ++- zrml/parimutuel/src/tests/claim.rs | 103 ++-- zrml/parimutuel/src/tests/mod.rs | 1 - zrml/parimutuel/src/tests/refund.rs | 51 +- zrml/parimutuel/src/utils.rs | 4 +- zrml/parimutuel/src/weights.rs | 102 +--- zrml/prediction-markets/Cargo.toml | 12 +- .../fuzz/pm_full_workflow.rs | 4 +- .../prediction-markets/runtime-api/src/lib.rs | 6 +- zrml/prediction-markets/src/benchmarks.rs | 18 +- zrml/prediction-markets/src/lib.rs | 204 +++---- zrml/prediction-markets/src/mock.rs | 253 ++------- .../src/tests/admin_move_market_to_closed.rs | 10 +- .../tests/admin_move_market_to_resolved.rs | 17 +- .../src/tests/approve_market.rs | 33 +- .../src/tests/buy_complete_set.rs | 30 +- ...lose_market.rs => close_trusted_market.rs} | 23 +- .../src/tests/create_market.rs | 80 +-- .../tests/create_market_and_deploy_pool.rs | 2 +- zrml/prediction-markets/src/tests/dispute.rs | 45 +- .../src/tests/dispute_early_close.rs | 16 +- .../src/tests/edit_market.rs | 18 +- .../src/tests/integration.rs | 81 ++- .../src/tests/manually_close_market.rs | 8 +- zrml/prediction-markets/src/tests/mod.rs | 47 +- .../src/tests/on_initialize.rs | 2 +- .../src/tests/on_market_close.rs | 30 +- .../src/tests/on_resolution.rs | 140 ++--- .../src/tests/redeem_shares.rs | 56 +- .../src/tests/reject_early_close.rs | 10 +- .../src/tests/reject_market.rs | 25 +- zrml/prediction-markets/src/tests/report.rs | 66 ++- .../src/tests/request_edit.rs | 6 +- .../src/tests/schedule_early_close.rs | 12 +- .../src/tests/sell_complete_set.rs | 33 +- .../src/tests/start_global_dispute.rs | 2 +- zrml/prediction-markets/src/weights.rs | 133 +++-- zrml/simple-disputes/src/lib.rs | 7 +- zrml/simple-disputes/src/mock.rs | 10 +- zrml/simple-disputes/src/tests.rs | 4 +- zrml/swaps/Cargo.toml | 4 +- zrml/swaps/fuzz/create_pool.rs | 7 +- zrml/swaps/fuzz/pool_exit.rs | 20 +- .../fuzz/pool_exit_with_exact_asset_amount.rs | 21 +- .../fuzz/pool_exit_with_exact_pool_amount.rs | 20 +- zrml/swaps/fuzz/pool_join.rs | 13 +- .../fuzz/pool_join_with_exact_asset_amount.rs | 13 +- .../fuzz/pool_join_with_exact_pool_amount.rs | 13 +- zrml/swaps/fuzz/swap_exact_amount_in.rs | 19 +- zrml/swaps/fuzz/swap_exact_amount_out.rs | 11 +- zrml/swaps/fuzz/utils.rs | 4 +- zrml/swaps/rpc/src/lib.rs | 30 +- zrml/swaps/runtime-api/src/lib.rs | 14 +- zrml/swaps/src/benchmarks.rs | 6 +- zrml/swaps/src/lib.rs | 60 +- zrml/swaps/src/mock.rs | 20 +- zrml/swaps/src/utils.rs | 20 +- zrml/swaps/src/weights.rs | 18 - 192 files changed, 2052 insertions(+), 10113 deletions(-) rename primitives/src/{assets.rs => asset.rs} (55%) delete mode 100644 primitives/src/assets/all_assets.rs delete mode 100644 primitives/src/assets/campaign_assets.rs delete mode 100644 primitives/src/assets/currencies.rs delete mode 100644 primitives/src/assets/custom_assets.rs delete mode 100644 primitives/src/assets/market_assets.rs delete mode 100644 primitives/src/assets/subsets/base_assets.rs delete mode 100644 primitives/src/assets/subsets/mod.rs delete mode 100644 primitives/src/assets/subsets/parimutuel.rs delete mode 100644 primitives/src/assets/subsets/xcm_assets.rs delete mode 100644 primitives/src/assets/tests.rs delete mode 100644 primitives/src/assets/tests/conversion.rs delete mode 100644 primitives/src/assets/tests/scale_codec.rs create mode 100644 primitives/src/serde_wrapper.rs delete mode 100644 primitives/src/traits/market_transition_api.rs delete mode 100644 primitives/src/traits/weights.rs delete mode 100644 runtime/common/src/weights/pallet_assets.rs delete mode 100644 zrml/asset-router/Cargo.toml delete mode 100644 zrml/asset-router/README.md delete mode 100644 zrml/asset-router/src/lib.rs delete mode 100644 zrml/asset-router/src/macros.rs delete mode 100644 zrml/asset-router/src/mock.rs delete mode 100644 zrml/asset-router/src/pallet_impl/create.rs delete mode 100644 zrml/asset-router/src/pallet_impl/destroy.rs delete mode 100644 zrml/asset-router/src/pallet_impl/inspect.rs delete mode 100644 zrml/asset-router/src/pallet_impl/managed_destroy.rs delete mode 100644 zrml/asset-router/src/pallet_impl/mod.rs delete mode 100644 zrml/asset-router/src/pallet_impl/multi_currency.rs delete mode 100644 zrml/asset-router/src/pallet_impl/multi_currency_extended.rs delete mode 100644 zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs delete mode 100644 zrml/asset-router/src/pallet_impl/multi_reserveable_currency.rs delete mode 100644 zrml/asset-router/src/pallet_impl/named_multi_reserveable_currency.rs delete mode 100644 zrml/asset-router/src/pallet_impl/transfer_all.rs delete mode 100644 zrml/asset-router/src/pallet_impl/unbalanced.rs delete mode 100644 zrml/asset-router/src/tests/create.rs delete mode 100644 zrml/asset-router/src/tests/custom_types.rs delete mode 100644 zrml/asset-router/src/tests/destroy.rs delete mode 100644 zrml/asset-router/src/tests/inspect.rs delete mode 100644 zrml/asset-router/src/tests/managed_destroy.rs delete mode 100644 zrml/asset-router/src/tests/mod.rs delete mode 100644 zrml/asset-router/src/tests/multi_currency.rs delete mode 100644 zrml/asset-router/src/tests/multi_lockable_currency.rs delete mode 100644 zrml/asset-router/src/tests/multi_reservable_currency.rs delete mode 100644 zrml/asset-router/src/tests/named_multi_reservable_currency.rs delete mode 100644 zrml/asset-router/src/tests/unbalanced.rs delete mode 100644 zrml/asset-router/src/types.rs rename zrml/prediction-markets/src/tests/{close_market.rs => close_trusted_market.rs} (91%) diff --git a/CODEOWNERS b/CODEOWNERS index 03f736322..059ede2ac 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -8,7 +8,6 @@ # Ignore everything but mod.rs in /runtime/common/src/weights/ /runtime/common/src/weights/* /runtime/common/src/weights/mod.rs @sea212 -/zrml/asset-router/ @sea212 /zrml/authorized/ @Chralt98 /zrml/court/ @Chralt98 /zrml/global-disputes/ @Chralt98 diff --git a/Cargo.lock b/Cargo.lock index 1057c1dcf..50d882012 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -562,7 +562,6 @@ dependencies = [ "orml-xcm-support", "orml-xtokens", "pallet-asset-tx-payment", - "pallet-assets", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -620,7 +619,6 @@ dependencies = [ "xcm-emulator", "xcm-executor", "zeitgeist-primitives", - "zrml-asset-router", "zrml-authorized", "zrml-court", "zrml-global-disputes", @@ -1218,7 +1216,6 @@ dependencies = [ "orml-currencies", "orml-tokens", "pallet-asset-tx-payment", - "pallet-assets", "pallet-author-inherent", "pallet-author-mapping", "pallet-author-slot-filter", @@ -5862,21 +5859,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-assets" -version = "4.0.0-dev" -source = "git+https://github.com/zeitgeistpm/substrate.git?branch=polkadot-v0.9.38-zeitgeist-adjustments#bd498817bb4479836a47231b4fc36831a19806ae" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-runtime", - "sp-std", -] - [[package]] name = "pallet-aura" version = "4.0.0-dev" @@ -14391,7 +14373,6 @@ dependencies = [ "fixed", "frame-support", "frame-system", - "impl-trait-for-tuples", "more-asserts", "num-traits", "orml-currencies", @@ -14439,7 +14420,6 @@ dependencies = [ "orml-xcm-support", "orml-xtokens", "pallet-asset-tx-payment", - "pallet-assets", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -14496,7 +14476,6 @@ dependencies = [ "xcm-emulator", "xcm-executor", "zeitgeist-primitives", - "zrml-asset-router", "zrml-authorized", "zrml-court", "zrml-global-disputes", @@ -14534,26 +14513,6 @@ dependencies = [ "syn 2.0.28", ] -[[package]] -name = "zrml-asset-router" -version = "0.4.1" -dependencies = [ - "frame-support", - "frame-system", - "log", - "orml-tokens", - "orml-traits", - "pallet-assets", - "pallet-balances", - "parity-scale-codec", - "scale-info", - "sp-io", - "sp-runtime", - "test-case", - "zeitgeist-macros", - "zeitgeist-primitives", -] - [[package]] name = "zrml-authorized" version = "0.5.2" @@ -14631,7 +14590,6 @@ dependencies = [ "orml-currencies", "orml-tokens", "orml-traits", - "pallet-assets", "pallet-balances", "pallet-randomness-collective-flip", "pallet-timestamp", @@ -14646,7 +14604,6 @@ dependencies = [ "xcm", "xcm-builder", "zeitgeist-primitives", - "zrml-asset-router", "zrml-authorized", "zrml-court", "zrml-global-disputes", @@ -14712,7 +14669,6 @@ dependencies = [ "orml-currencies", "orml-tokens", "orml-traits", - "pallet-assets", "pallet-balances", "pallet-randomness-collective-flip", "pallet-timestamp", @@ -14729,7 +14685,6 @@ dependencies = [ "xcm", "xcm-builder", "zeitgeist-primitives", - "zrml-asset-router", "zrml-authorized", "zrml-court", "zrml-global-disputes", @@ -14753,7 +14708,6 @@ dependencies = [ "orml-currencies", "orml-tokens", "orml-traits", - "pallet-assets", "pallet-balances", "pallet-timestamp", "parity-scale-codec", @@ -14761,9 +14715,7 @@ dependencies = [ "sp-io", "sp-runtime", "test-case", - "zeitgeist-macros", "zeitgeist-primitives", - "zrml-asset-router", "zrml-market-commons", "zrml-orderbook", ] @@ -14790,7 +14742,6 @@ dependencies = [ "orml-currencies", "orml-tokens", "orml-traits", - "pallet-assets", "pallet-balances", "pallet-timestamp", "parity-scale-codec", @@ -14798,9 +14749,7 @@ dependencies = [ "sp-io", "sp-runtime", "test-case", - "zeitgeist-macros", "zeitgeist-primitives", - "zrml-asset-router", "zrml-market-commons", ] @@ -14817,7 +14766,6 @@ dependencies = [ "orml-currencies", "orml-tokens", "orml-traits", - "pallet-assets", "pallet-balances", "pallet-randomness-collective-flip", "pallet-timestamp", @@ -14832,7 +14780,6 @@ dependencies = [ "test-case", "xcm", "zeitgeist-primitives", - "zrml-asset-router", "zrml-authorized", "zrml-court", "zrml-global-disputes", diff --git a/Cargo.toml b/Cargo.toml index 3f94c60a9..4485139ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,6 @@ default-members = [ "runtime/battery-station", "runtime/zeitgeist", "zrml/authorized", - "zrml/asset-router", "zrml/court", "zrml/hybrid-router", "zrml/global-disputes", @@ -33,7 +32,6 @@ members = [ "runtime/battery-station", "runtime/zeitgeist", "zrml/authorized", - "zrml/asset-router", "zrml/court", "zrml/hybrid-router", "zrml/global-disputes", @@ -167,7 +165,6 @@ frame-system-benchmarking = { git = "https://github.com/paritytech/substrate", b frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } frame-try-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } pallet-asset-tx-payment = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } -pallet-assets = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } pallet-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } pallet-bounties = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38", default-features = false } @@ -237,7 +234,6 @@ zrml-swaps-rpc = { path = "zrml/swaps/rpc" } common-runtime = { path = "runtime/common", default-features = false } zeitgeist-macros = { path = "macros", default-features = false } zeitgeist-primitives = { path = "primitives", default-features = false } -zrml-asset-router = { path = "zrml/asset-router", default-features = false } zrml-authorized = { path = "zrml/authorized", default-features = false } zrml-court = { path = "zrml/court", default-features = false } zrml-global-disputes = { path = "zrml/global-disputes", default-features = false } @@ -269,7 +265,6 @@ arbitrary = { version = "1.3.0", default-features = false } arrayvec = { version = "0.7.4", default-features = false } cfg-if = { version = "1.0.0" } fixed = { version = "=1.15.0", default-features = false, features = ["num-traits"] } -impl-trait-for-tuples = { version = "0.2.2" } # Using math code directly from the HydraDX node repository as https://github.com/galacticcouncil/hydradx-math is outdated and has been archived in May 2023. hydra-dx-math = { git = "https://github.com/galacticcouncil/HydraDX-node", package = "hydra-dx-math", tag = "v21.1.1", default-features = false } # Hashbrown works in no_std by default and default features are used in Rikiddo @@ -339,9 +334,6 @@ opt-level = 3 panic = "unwind" [patch."https://github.com/paritytech/substrate"] -# pallet-asset adjustments (managed asset destruction) -pallet-assets = { git = "https://github.com/zeitgeistpm/substrate.git", branch = "polkadot-v0.9.38-zeitgeist-adjustments" } - # fix that allow to build with recent rustc substrate-wasm-builder = { git = "https://github.com/zeitgeistpm/substrate.git", branch = "polkadot-v0.9.38-zeitgeist-adjustments" } diff --git a/README.md b/README.md index 1fa93686c..7350560e5 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,6 @@ decentralized court. ## Modules -- [asset-router](./zrml/asset-router) - Routes all asset classes to the - respective pallets and provides a garbage collection for destructible assets. - [authorized](./zrml/authorized) - Offers authorized resolution of disputes. - [court](./zrml/court) - An implementation of a court mechanism used to resolve disputes in a decentralized fashion. diff --git a/docs/changelog_for_devs.md b/docs/changelog_for_devs.md index e12a38733..69c4109a4 100644 --- a/docs/changelog_for_devs.md +++ b/docs/changelog_for_devs.md @@ -128,28 +128,22 @@ if ztg_supply / campaign_asset_supply >= 100 { [#1197]: https://github.com/zeitgeistpm/zeitgeist/pull/1197 [#1178]: https://github.com/zeitgeistpm/zeitgeist/pull/1178 -### Changed +### Changes -- ⚠️ Move the `zeitgeist_primitives::Pool` struct to `zrml_swaps::types::Pool` - and change the following fields ([#1197]): - - Remove `market_id` - - Make `swap_fee` non-optional - - Remove `total_subsidy` - - Make `total_weight` non-optional - - Make `weights` non-optional -- ⚠️ Change the type of `liquidity_shares_manager` in - `zrml_neo_swaps::types::Pool` from `zrml_neo_swaps::types::SoloLp` to - `zrml_neo_swaps::types::LiquidityTree`. Details on the liquidity tree can be - found in the `README.md` of zrml-neo-swaps and the documentation of the - `LiquidityTree` object ([#1179]). +- ⚠️ Move the `zeitgeist_primitives::Pool` struct to `zrml_swaps::types::Pool` and change the following fields ([#1197]): + - Remove `market_id` + - Make `swap_fee` non-optional + - Remove `total_subsidy` + - Make `total_weight` non-optional + - Make `weights` non-optional +- ⚠️ Change the type of `liquidity_shares_manager` in `zrml_neo_swaps::types::Pool` from `zrml_neo_swaps::types::SoloLp` to `zrml_neo_swaps::types::LiquidityTree`. Details on the liquidity tree can be found in the `README.md` of zrml-neo-swaps and the documentation of the `LiquidityTree` object ([#1179]). ### Migrations - Closed all CPMM pools. Withdrawals are still allowed. Creating new pools will be impossible until further updates are deployed. ([#1197]) - Remove all Rikiddo storage elements. ([#1197]) -- Migrate neo-swaps `Pools` storage. The market creator's liquidity position is - translated into a position in the liquidity tree of the same value ([#1178]). +- Migrate neo-swaps `Pools` storage. The market creator's liquidity position is translated into a position in the liquidity tree of the same value ([#1178]). ### Removed diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 6b4609b19..b6ee80362 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -50,7 +50,7 @@ macro_rules! create_b_tree_map { #[macro_export] macro_rules! unreachable_non_terminating { ($condition: expr, $message: literal, $($message_args: tt)*) => { - let message = alloc::format!($message, $($message_args)*); + let message = format!($message, $($message_args)*); #[cfg(test)] assert!($condition, "{}", message); @@ -60,7 +60,7 @@ macro_rules! unreachable_non_terminating { } }; ($condition: expr, $log_target: ident, $message: literal, $($message_args: tt)*) => { - let message = alloc::format!($message, $($message_args)*); + let message = format!($message, $($message_args)*); #[cfg(test)] assert!($condition, "{}", message); @@ -70,7 +70,7 @@ macro_rules! unreachable_non_terminating { } }; ($condition: expr, $extra_code: expr, $message: literal, $($message_args: tt)*) => { - let message = alloc::format!($message, $($message_args)*); + let message = format!($message, $($message_args)*); #[cfg(test)] assert!($condition, "{}", message); @@ -81,7 +81,7 @@ macro_rules! unreachable_non_terminating { } }; ($condition: expr, $log_target: ident, $extra_code: expr, $message: literal, $($message_args: tt)*) => { - let message = alloc::format!($message, $($message_args)*); + let message = format!($message, $($message_args)*); #[cfg(test)] assert!($condition, "{}", message); diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 689562b82..e8007e1ce 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -3,7 +3,6 @@ arbitrary = { workspace = true, optional = true } fixed = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } -impl-trait-for-tuples = { workspace = true } num-traits = { workspace = true } orml-currencies = { workspace = true } orml-tokens = { workspace = true } diff --git a/primitives/src/assets.rs b/primitives/src/asset.rs similarity index 55% rename from primitives/src/assets.rs rename to primitives/src/asset.rs index 7de237bb8..513ba1203 100644 --- a/primitives/src/assets.rs +++ b/primitives/src/asset.rs @@ -20,26 +20,52 @@ use crate::traits::ZeitgeistAssetEnumerator; use crate::{ traits::PoolSharesId, - types::{CampaignAssetId, CategoryIndex, CustomAssetId, PoolId}, + types::{CategoryIndex, PoolId, SerdeWrapper}, }; -use parity_scale_codec::{Compact, CompactAs, Decode, Encode, HasCompact, MaxEncodedLen}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -pub use all_assets::Asset; -pub use campaign_assets::CampaignAssetClass; -pub use currencies::CurrencyClass; -pub use custom_assets::CustomAssetClass; -pub use market_assets::MarketAssetClass; -pub use subsets::{BaseAssetClass, ParimutuelAssetClass, XcmAssetClass}; +/// The `Asset` enum represents all types of assets available in the Zeitgeist +/// system. +#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] +#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] +#[derive( + Clone, + Copy, + Debug, + Decode, + Default, + Eq, + Encode, + MaxEncodedLen, + Ord, + PartialEq, + PartialOrd, + TypeInfo, +)] +pub enum Asset { + CategoricalOutcome(MarketId, CategoryIndex), + ScalarOutcome(MarketId, ScalarPosition), + CombinatorialOutcome, + PoolShare(SerdeWrapper), + #[default] + Ztg, + ForeignAsset(u32), + ParimutuelShare(MarketId, CategoryIndex), +} -mod all_assets; -mod campaign_assets; -mod currencies; -mod custom_assets; -mod market_assets; -mod subsets; -#[cfg(test)] -mod tests; +impl PoolSharesId> for Asset { + fn pool_shares_id(pool_id: SerdeWrapper) -> Self { + Self::PoolShare(pool_id) + } +} + +#[cfg(feature = "runtime-benchmarks")] +impl ZeitgeistAssetEnumerator for Asset { + fn create_asset_id(t: MarketId) -> Self { + Asset::CategoricalOutcome(t, 0) + } +} /// In a scalar market, users can either choose a `Long` position, /// meaning that they think the outcome will be closer to the upper bound diff --git a/primitives/src/assets/all_assets.rs b/primitives/src/assets/all_assets.rs deleted file mode 100644 index 012486af9..000000000 --- a/primitives/src/assets/all_assets.rs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `Asset` enum represents all types of assets available in the Zeitgeist -/// system. -/// -/// This complete enumeration is intended to abstract the common interaction -/// with tokens away. For example, the developer is not forced to be aware -/// about which exact implementation will handle the desired asset class to -/// instruct operations such as `transfer` or `freeze`, instead it is -/// sufficient to call a crate that manages the routing. -/// While it is not recommended to use this enum in storage, it should not pose -/// a problem as long as all other asset types use the same scale encoding for -/// a matching asset variant in this enum. -/// -/// **Deprecated:** Market and Pool assets are "lazy" migrated to -/// pallet-assets. -/// Do not create any new market or pool assets using the deprecated variants -/// in this enum. -/// -/// # Types -/// -/// * `MI`: Market Id -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive( - Clone, - Copy, - Debug, - Decode, - Default, - Eq, - Encode, - MaxEncodedLen, - Ord, - PartialEq, - PartialOrd, - TypeInfo, -)] -pub enum Asset { - #[codec(index = 0)] - CategoricalOutcome(MI, CategoryIndex), - - #[codec(index = 1)] - ScalarOutcome(MI, ScalarPosition), - - #[codec(index = 3)] - PoolShare(PoolId), - - #[codec(index = 4)] - #[default] - Ztg, - - #[codec(index = 5)] - ForeignAsset(u32), - - #[codec(index = 6)] - ParimutuelShare(MI, CategoryIndex), - - #[codec(index = 7)] - CampaignAsset(#[codec(compact)] CampaignAssetId), - - #[codec(index = 8)] - CustomAsset(#[codec(compact)] CustomAssetId), -} - -impl PoolSharesId for Asset { - fn pool_shares_id(pool_id: PoolId) -> Self { - Self::PoolShare(pool_id) - } -} - -#[cfg(feature = "runtime-benchmarks")] -impl ZeitgeistAssetEnumerator for Asset { - fn create_asset_id(t: MI) -> Self { - Asset::CategoricalOutcome(t, 0) - } -} - -impl From> for Asset { - fn from(value: MarketAssetClass) -> Self { - match value { - MarketAssetClass::::CategoricalOutcome(market_id, cat_id) => { - Self::CategoricalOutcome(market_id, cat_id) - } - MarketAssetClass::::ScalarOutcome(market_id, scalar_pos) => { - Self::ScalarOutcome(market_id, scalar_pos) - } - MarketAssetClass::::ParimutuelShare(market_id, cat_id) => { - Self::ParimutuelShare(market_id, cat_id) - } - MarketAssetClass::::PoolShare(pool_id) => Self::PoolShare(pool_id), - } - } -} - -impl From for Asset { - fn from(value: CampaignAssetClass) -> Self { - Self::CampaignAsset(value.0) - } -} - -impl From for Asset { - fn from(value: CustomAssetClass) -> Self { - Self::CustomAsset(value.0) - } -} - -impl From> for Asset { - fn from(value: CurrencyClass) -> Self { - match value { - CurrencyClass::::CategoricalOutcome(market_id, cat_id) => { - Self::CategoricalOutcome(market_id, cat_id) - } - CurrencyClass::::ScalarOutcome(market_id, scalar_pos) => { - Self::ScalarOutcome(market_id, scalar_pos) - } - CurrencyClass::::ParimutuelShare(market_id, cat_id) => { - Self::ParimutuelShare(market_id, cat_id) - } - CurrencyClass::::PoolShare(pool_id) => Self::PoolShare(pool_id), - CurrencyClass::::ForeignAsset(asset_id) => Self::ForeignAsset(asset_id), - } - } -} - -impl From for Asset { - fn from(value: BaseAssetClass) -> Self { - match value { - BaseAssetClass::Ztg => Self::Ztg, - BaseAssetClass::ForeignAsset(id) => Self::ForeignAsset(id), - BaseAssetClass::CampaignAsset(id) => Self::CampaignAsset(id), - } - } -} - -impl From> for Asset { - fn from(value: ParimutuelAssetClass) -> Self { - match value { - ParimutuelAssetClass::::Share(market_id, cat_id) => { - Self::ParimutuelShare(market_id, cat_id) - } - } - } -} - -impl From for Asset { - fn from(value: XcmAssetClass) -> Self { - match value { - XcmAssetClass::Ztg => Self::Ztg, - XcmAssetClass::ForeignAsset(id) => Self::ForeignAsset(id), - } - } -} diff --git a/primitives/src/assets/campaign_assets.rs b/primitives/src/assets/campaign_assets.rs deleted file mode 100644 index dcf912a77..000000000 --- a/primitives/src/assets/campaign_assets.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `CampaignAsset` tuple struct represents all campaign assets. -/// Campaign assets can have special properties, such as the capability -/// to pay fees. -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive( - Clone, CompactAs, Copy, Debug, Decode, Default, Eq, Encode, MaxEncodedLen, PartialEq, TypeInfo, -)] -pub struct CampaignAssetClass(#[codec(compact)] pub CampaignAssetId); - -impl From> for CampaignAssetClass { - fn from(value: Compact) -> CampaignAssetClass { - CampaignAssetClass(value.into()) - } -} - -impl From for Compact { - fn from(value: CampaignAssetClass) -> Compact { - value.0.into() - } -} - -impl TryFrom> for CampaignAssetClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::CampaignAsset(id) => Ok(Self(id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/currencies.rs b/primitives/src/assets/currencies.rs deleted file mode 100644 index d29359d43..000000000 --- a/primitives/src/assets/currencies.rs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `CurrencyClass` enum represents all non-ztg currencies -// used in orml-tokens -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive( - Clone, Copy, Debug, Decode, Eq, Encode, MaxEncodedLen, Ord, PartialEq, PartialOrd, TypeInfo, -)] -pub enum CurrencyClass { - // All Outcome and Share variants will be removed once the lazy migration from - // orml-tokens to pallet-assets is complete - #[codec(index = 0)] - CategoricalOutcome(MI, CategoryIndex), - - #[codec(index = 1)] - ScalarOutcome(MI, ScalarPosition), - - #[codec(index = 3)] - PoolShare(PoolId), - - #[codec(index = 5)] - ForeignAsset(u32), - - #[codec(index = 6)] - ParimutuelShare(MI, CategoryIndex), -} - -impl CurrencyClass { - pub fn is_foreign_asset(&self) -> bool { - matches!(self, Self::ForeignAsset(_)) - } -} - -impl Default for CurrencyClass { - fn default() -> Self { - Self::ForeignAsset(u32::default()) - } -} - -impl TryFrom> for CurrencyClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::CategoricalOutcome(market_id, cat_id) => { - Ok(Self::CategoricalOutcome(market_id, cat_id)) - } - Asset::::ScalarOutcome(market_id, scalar_pos) => { - Ok(Self::ScalarOutcome(market_id, scalar_pos)) - } - Asset::::ParimutuelShare(market_id, cat_id) => { - Ok(Self::ParimutuelShare(market_id, cat_id)) - } - Asset::::PoolShare(pool_id) => Ok(Self::PoolShare(pool_id)), - Asset::::ForeignAsset(id) => Ok(Self::ForeignAsset(id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/custom_assets.rs b/primitives/src/assets/custom_assets.rs deleted file mode 100644 index b5f8339ec..000000000 --- a/primitives/src/assets/custom_assets.rs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `CustomAsset` tuple struct represents all custom assets. -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive( - Clone, CompactAs, Copy, Debug, Decode, Default, Eq, Encode, MaxEncodedLen, PartialEq, TypeInfo, -)] -pub struct CustomAssetClass(#[codec(compact)] pub CustomAssetId); - -impl From> for CustomAssetClass { - fn from(value: Compact) -> CustomAssetClass { - CustomAssetClass(value.into()) - } -} - -impl From for Compact { - fn from(value: CustomAssetClass) -> Compact { - value.0.into() - } -} - -impl TryFrom> for CustomAssetClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::CustomAsset(id) => Ok(Self(id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/market_assets.rs b/primitives/src/assets/market_assets.rs deleted file mode 100644 index 7573cf74a..000000000 --- a/primitives/src/assets/market_assets.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `MarketAsset` enum represents all types of assets available in the -/// Prediction Market protocol -/// -/// # Types -/// -/// * `MI`: Market Id -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive( - Clone, Copy, Debug, Decode, Eq, Encode, MaxEncodedLen, PartialEq, PartialOrd, Ord, TypeInfo, -)] -pub enum MarketAssetClass { - #[codec(index = 0)] - CategoricalOutcome(MI, CategoryIndex), - - #[codec(index = 1)] - ScalarOutcome(MI, ScalarPosition), - - #[codec(index = 3)] - PoolShare(PoolId), - - #[codec(index = 6)] - ParimutuelShare(MI, CategoryIndex), -} - -impl TryFrom> for MarketAssetClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::CategoricalOutcome(market_id, cat_id) => { - Ok(Self::CategoricalOutcome(market_id, cat_id)) - } - Asset::::ScalarOutcome(market_id, scalar_pos) => { - Ok(Self::ScalarOutcome(market_id, scalar_pos)) - } - Asset::::ParimutuelShare(market_id, cat_id) => { - Ok(Self::ParimutuelShare(market_id, cat_id)) - } - Asset::::PoolShare(pool_id) => Ok(Self::PoolShare(pool_id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/subsets/base_assets.rs b/primitives/src/assets/subsets/base_assets.rs deleted file mode 100644 index 041d0b10c..000000000 --- a/primitives/src/assets/subsets/base_assets.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `BaseAssetClass` enum represents all assets that can be used as collateral in -/// prediction markets. -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive(Clone, Copy, Debug, Decode, Default, Eq, Encode, MaxEncodedLen, PartialEq, TypeInfo)] -pub enum BaseAssetClass { - #[codec(index = 4)] - #[default] - Ztg, - - #[codec(index = 5)] - ForeignAsset(u32), - - #[codec(index = 7)] - CampaignAsset(#[codec(compact)] CampaignAssetId), -} - -impl TryFrom> for BaseAssetClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::Ztg => Ok(Self::Ztg), - Asset::::ForeignAsset(id) => Ok(Self::ForeignAsset(id)), - Asset::::CampaignAsset(id) => Ok(Self::CampaignAsset(id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/subsets/mod.rs b/primitives/src/assets/subsets/mod.rs deleted file mode 100644 index eafe22f04..000000000 --- a/primitives/src/assets/subsets/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -pub use base_assets::BaseAssetClass; -pub use parimutuel::ParimutuelAssetClass; -pub use xcm_assets::XcmAssetClass; - -mod base_assets; -mod parimutuel; -mod xcm_assets; diff --git a/primitives/src/assets/subsets/parimutuel.rs b/primitives/src/assets/subsets/parimutuel.rs deleted file mode 100644 index 26d412a4e..000000000 --- a/primitives/src/assets/subsets/parimutuel.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `ParimutuelAssetClass` enum represents all assets that are specific to parimutuel markets. -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive(Clone, Copy, Debug, Decode, Eq, Encode, MaxEncodedLen, PartialEq, TypeInfo)] -pub enum ParimutuelAssetClass { - #[codec(index = 6)] - Share(MI, CategoryIndex), -} - -impl TryFrom> for ParimutuelAssetClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::ParimutuelShare(market_id, cat_id) => Ok(Self::Share(market_id, cat_id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/subsets/xcm_assets.rs b/primitives/src/assets/subsets/xcm_assets.rs deleted file mode 100644 index bbad9de08..000000000 --- a/primitives/src/assets/subsets/xcm_assets.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::*; - -/// The `XcmAssetClass` enum represents all assets that can be transferred via XCM. -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -#[derive(Clone, Copy, Debug, Decode, Default, Eq, Encode, MaxEncodedLen, PartialEq, TypeInfo)] -pub enum XcmAssetClass { - #[codec(index = 4)] - #[default] - Ztg, - - #[codec(index = 5)] - ForeignAsset(u32), -} - -impl TryFrom> for XcmAssetClass { - type Error = (); - - fn try_from(value: Asset) -> Result { - match value { - Asset::::Ztg => Ok(Self::Ztg), - Asset::::ForeignAsset(id) => Ok(Self::ForeignAsset(id)), - _ => Err(()), - } - } -} diff --git a/primitives/src/assets/tests.rs b/primitives/src/assets/tests.rs deleted file mode 100644 index 9aa7bec90..000000000 --- a/primitives/src/assets/tests.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use crate::types::MarketId; - -mod conversion; -mod scale_codec; diff --git a/primitives/src/assets/tests/conversion.rs b/primitives/src/assets/tests/conversion.rs deleted file mode 100644 index 49829978c..000000000 --- a/primitives/src/assets/tests/conversion.rs +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use test_case::test_case; - -// Assets <> MarketAssetClass -#[test_case( - Asset::::CategoricalOutcome(7, 8), - MarketAssetClass::::CategoricalOutcome(7, 8); - "categorical_outcome" -)] -#[test_case( - Asset::::ScalarOutcome(7, ScalarPosition::Long), - MarketAssetClass::::ScalarOutcome(7, ScalarPosition::Long); - "scalar_outcome" -)] -#[test_case( - Asset::::PoolShare(7), - MarketAssetClass::::PoolShare(7); - "pool_share" -)] -#[test_case( - Asset::::ParimutuelShare(7, 8), - MarketAssetClass::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -fn from_all_assets_to_market_assets( - old_asset: Asset, - new_asset: MarketAssetClass, -) { - let new_asset_converted: MarketAssetClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::Ztg; "ztg")] -#[test_case(Asset::::ForeignAsset(7); "foreign_asset")] -#[test_case(Asset::::CampaignAsset(7); "campaign_asset")] -#[test_case(Asset::::CustomAsset(7); "custom_asset")] -fn from_all_assets_to_market_assets_fails(asset: Asset) { - assert!(MarketAssetClass::::try_from(asset).is_err()); -} - -#[test_case( - MarketAssetClass::::CategoricalOutcome(7, 8), - Asset::::CategoricalOutcome(7, 8); - "categorical_outcome" -)] -#[test_case( - MarketAssetClass::::ScalarOutcome(7, ScalarPosition::Long), - Asset::::ScalarOutcome(7, ScalarPosition::Long); - "scalar_outcome" -)] -#[test_case( - MarketAssetClass::::PoolShare(7), - Asset::::PoolShare(7); - "pool_share" -)] -#[test_case( - MarketAssetClass::::ParimutuelShare(7, 8), - Asset::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -fn from_market_assets_to_all_assets( - old_asset: MarketAssetClass, - new_asset: Asset, -) { - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// Assets <> CurrencyClass -#[test_case( - Asset::::CategoricalOutcome(7, 8), - CurrencyClass::::CategoricalOutcome(7, 8); - "categorical_outcome" -)] -#[test_case( - Asset::::ScalarOutcome(7, ScalarPosition::Long), - CurrencyClass::::ScalarOutcome(7, ScalarPosition::Long); - "scalar_outcome" -)] -#[test_case( - Asset::::PoolShare(7), - CurrencyClass::::PoolShare(7); - "pool_share" -)] -#[test_case( - Asset::::ParimutuelShare(7, 8), - CurrencyClass::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -#[test_case( - Asset::::ForeignAsset(7), - CurrencyClass::::ForeignAsset(7); - "foreign_asset" -)] -fn from_all_assets_to_currencies(old_asset: Asset, new_asset: CurrencyClass) { - let new_asset_converted: CurrencyClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::Ztg; "ztg")] -#[test_case(Asset::::CampaignAsset(7); "campaign_asset")] -#[test_case(Asset::::CustomAsset(7); "custom_asset")] -fn from_all_assets_to_currencies_fails(asset: Asset) { - assert!(CurrencyClass::::try_from(asset).is_err()); -} - -#[test_case( - CurrencyClass::::CategoricalOutcome(7, 8), - Asset::::CategoricalOutcome(7, 8); - "categorical_outcome" -)] -#[test_case( - CurrencyClass::::ScalarOutcome(7, ScalarPosition::Long), - Asset::::ScalarOutcome(7, ScalarPosition::Long); - "scalar_outcome" -)] -#[test_case( - CurrencyClass::::PoolShare(7), - Asset::::PoolShare(7); - "pool_share" -)] -#[test_case( - CurrencyClass::::ParimutuelShare(7, 8), - Asset::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -#[test_case( - CurrencyClass::::ForeignAsset(7), - Asset::::ForeignAsset(7); - "foreign_asset" -)] -fn from_currencies_to_all_assets(old_asset: CurrencyClass, new_asset: Asset) { - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// Assets <> CampaignAssetClass -#[test] -fn from_all_assets_to_campaign_assets() { - let old_asset = Asset::::CampaignAsset(7); - let new_asset = CampaignAssetClass(7); - - let new_asset_converted: CampaignAssetClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::CategoricalOutcome(7, 8); "categorical_outcome")] -#[test_case(Asset::::ScalarOutcome(7, ScalarPosition::Long); "scalar_outcome")] -#[test_case(Asset::::PoolShare(7); "pool_share")] -#[test_case(Asset::::Ztg; "ztg")] -#[test_case(Asset::::ForeignAsset(7); "foreign_asset")] -#[test_case(Asset::::ParimutuelShare(7, 8); "parimutuel_share")] -#[test_case(Asset::::CustomAsset(7); "custom_asset")] -fn from_all_assets_to_campaign_assets_fails(asset: Asset) { - assert!(CampaignAssetClass::try_from(asset).is_err()); -} - -#[test] -fn from_campaign_assets_to_all_assets() { - let old_asset = CampaignAssetClass(7); - let new_asset = Asset::::CampaignAsset(7); - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// Assets <> CustomAssetClass -#[test] -fn from_all_assets_to_custom_assets() { - let old_asset = Asset::::CustomAsset(7); - let new_asset = CustomAssetClass(7); - - let new_asset_converted: CustomAssetClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::CategoricalOutcome(7, 8); "categorical_outcome")] -#[test_case(Asset::::ScalarOutcome(7, ScalarPosition::Long); "scalar_outcome")] -#[test_case(Asset::::PoolShare(7); "pool_share")] -#[test_case(Asset::::Ztg; "ztg")] -#[test_case(Asset::::ForeignAsset(7); "foreign_asset")] -#[test_case(Asset::::ParimutuelShare(7, 8); "parimutuel_share")] -#[test_case(Asset::::CampaignAsset(7); "campaign_asset")] -fn from_all_assets_to_custom_assets_fails(asset: Asset) { - assert!(CustomAssetClass::try_from(asset).is_err()); -} - -#[test] -fn from_custom_assets_to_all_assets() { - let old_asset = CampaignAssetClass(7); - let new_asset = Asset::::CampaignAsset(7); - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// Assets <> BaseAssetClass -#[test_case( - Asset::::CampaignAsset(7), - BaseAssetClass::CampaignAsset(7); - "campaign_asset" -)] -#[test_case( - Asset::::ForeignAsset(7), - BaseAssetClass::ForeignAsset(7); - "foreign_asset" -)] -#[test_case( - Asset::::Ztg, - BaseAssetClass::Ztg; - "ztg" -)] -fn from_all_assets_to_base_assets(old_asset: Asset, new_asset: BaseAssetClass) { - let new_asset_converted: BaseAssetClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::CategoricalOutcome(7, 8); "categorical_outcome")] -#[test_case(Asset::::ScalarOutcome(7, ScalarPosition::Long); "scalar_outcome")] -#[test_case(Asset::::PoolShare(7); "pool_share")] -#[test_case(Asset::::ParimutuelShare(7, 8); "parimutuel_share")] -#[test_case(Asset::::CustomAsset(7); "custom_asset")] -fn from_all_assets_to_base_assets_fails(asset: Asset) { - assert!(BaseAssetClass::try_from(asset).is_err()); -} - -#[test_case( - BaseAssetClass::CampaignAsset(7), - Asset::::CampaignAsset(7); - "campaign_asset" -)] -#[test_case( - BaseAssetClass::ForeignAsset(7), - Asset::::ForeignAsset(7); - "foreign_asset" -)] -#[test_case( - BaseAssetClass::Ztg, - Asset::::Ztg; - "ztg" -)] -fn from_base_assets_to_all_assets(old_asset: BaseAssetClass, new_asset: Asset) { - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// Assets <> ParimutuelAssetClass -#[test_case( - Asset::::ParimutuelShare(7, 8), - ParimutuelAssetClass::::Share(7, 8); - "parimutuel_share" -)] -fn from_all_assets_to_parimutuel_assets( - old_asset: Asset, - new_asset: ParimutuelAssetClass, -) { - let new_asset_converted: ParimutuelAssetClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::CategoricalOutcome(7, 8); "categorical_outcome")] -#[test_case(Asset::::ScalarOutcome(7, ScalarPosition::Long); "scalar_outcome")] -#[test_case(Asset::::PoolShare(7); "pool_share")] -#[test_case(Asset::::Ztg; "ztg")] -#[test_case(Asset::::ForeignAsset(7); "foreign_asset")] -#[test_case(Asset::::CampaignAsset(7); "campaign_asset")] -#[test_case(Asset::::CustomAsset(7); "custom_asset")] -fn from_all_assets_to_parimutuel_assets_fails(asset: Asset) { - assert!(ParimutuelAssetClass::::try_from(asset).is_err()); -} - -#[test_case( - ParimutuelAssetClass::::Share(7, 8), - Asset::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -fn from_parimutuel_assets_to_all_assets( - old_asset: ParimutuelAssetClass, - new_asset: Asset, -) { - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// Assets <> XcmAssetClass -#[test_case( - Asset::::ForeignAsset(7), - XcmAssetClass::ForeignAsset(7); - "foreign_asset" -)] -#[test_case( - Asset::::Ztg, - XcmAssetClass::Ztg; - "ztg" -)] -fn from_all_assets_to_xcm_assets(old_asset: Asset, new_asset: XcmAssetClass) { - let new_asset_converted: XcmAssetClass = old_asset.try_into().unwrap(); - assert_eq!(new_asset, new_asset_converted); -} - -#[test_case(Asset::::CategoricalOutcome(7, 8); "categorical_outcome")] -#[test_case(Asset::::ScalarOutcome(7, ScalarPosition::Long); "scalar_outcome")] -#[test_case(Asset::::PoolShare(7); "pool_share")] -#[test_case(Asset::::CampaignAsset(7); "campaign_asset")] -#[test_case(Asset::::CustomAsset(7); "custom_asset")] -fn from_all_assets_to_xcm_assets_fails(asset: Asset) { - assert!(XcmAssetClass::try_from(asset).is_err()); -} - -#[test_case( - XcmAssetClass::ForeignAsset(7), - Asset::::ForeignAsset(7); - "foreign_asset" -)] -#[test_case( - XcmAssetClass::Ztg, - Asset::::Ztg; - "ztg" -)] -fn from_xcm_assets_to_all_assets(old_asset: XcmAssetClass, new_asset: Asset) { - let new_asset_converted: Asset = old_asset.into(); - assert_eq!(new_asset, new_asset_converted); -} - -// CampaignAssetId <> CampaignAssetClass -#[test] -fn from_campaign_asset_id_to_campaign_asset() { - let campaign_asset_id = Compact(7); - let campaign_asset = CampaignAssetClass::from(campaign_asset_id); - let campaign_asset_id_converted = campaign_asset.into(); - assert_eq!(campaign_asset_id, campaign_asset_id_converted); -} - -// CustomAssetId <> CustomAssetClass -#[test] -fn from_custom_asset_id_to_custom_asset() { - let custom_asset_id = Compact(7); - let custom_asset = CustomAssetClass::from(custom_asset_id); - let custom_asset_id_converted = custom_asset.into(); - assert_eq!(custom_asset_id, custom_asset_id_converted); -} diff --git a/primitives/src/assets/tests/scale_codec.rs b/primitives/src/assets/tests/scale_codec.rs deleted file mode 100644 index 050da1db5..000000000 --- a/primitives/src/assets/tests/scale_codec.rs +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use test_case::test_case; - -// Assets <> BaseAssetClass -#[test_case( - Asset::::CampaignAsset(7), - BaseAssetClass::CampaignAsset(7); - "campaign_asset" -)] -#[test_case( - Asset::::ForeignAsset(7), - BaseAssetClass::ForeignAsset(7); - "foreign_asset" -)] -#[test_case( - Asset::::Ztg, - BaseAssetClass::Ztg; - "ztg" -)] -fn index_matching_works_for_base_assets(old_asset: Asset, new_asset: BaseAssetClass) { - let old_asset_encoded: Vec = old_asset.encode(); - let new_asset_decoded = - ::decode(&mut old_asset_encoded.as_slice()).unwrap(); - assert_eq!(new_asset_decoded, new_asset); -} - -// Assets <> CurrencyClass -#[test_case( - Asset::::CategoricalOutcome(7, 8), - CurrencyClass::::CategoricalOutcome(7, 8); - "categorical_outcome" -)] -#[test_case( - Asset::::ScalarOutcome(7, ScalarPosition::Long), - CurrencyClass::::ScalarOutcome(7, ScalarPosition::Long); - "scalar_outcome" -)] -#[test_case( - Asset::::PoolShare(7), - CurrencyClass::::PoolShare(7); - "pool_share" -)] -#[test_case( - Asset::::ParimutuelShare(7, 8), - CurrencyClass::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -#[test_case( - Asset::::ForeignAsset(7), - CurrencyClass::::ForeignAsset(7); - "foreign_asset" -)] -fn index_matching_works_for_currencies( - old_asset: Asset, - new_asset: CurrencyClass, -) { - let old_asset_encoded: Vec = old_asset.encode(); - let new_asset_decoded = - as Decode>::decode(&mut old_asset_encoded.as_slice()).unwrap(); - assert_eq!(new_asset_decoded, new_asset); -} - -// Assets <> MarketAssetClass -#[test_case( - Asset::::CategoricalOutcome(7, 8), - MarketAssetClass::::CategoricalOutcome(7, 8); - "categorical_outcome" -)] -#[test_case( - Asset::::ScalarOutcome(7, ScalarPosition::Long), - MarketAssetClass::::ScalarOutcome(7, ScalarPosition::Long); - "scalar_outcome" -)] -#[test_case( - Asset::::PoolShare(7), - MarketAssetClass::::PoolShare(7); - "pool_share" -)] -#[test_case( - Asset::::ParimutuelShare(7, 8), - MarketAssetClass::::ParimutuelShare(7, 8); - "parimutuel_share" -)] -fn index_matching_works_for_market_assets( - old_asset: Asset, - new_asset: MarketAssetClass, -) { - let old_asset_encoded: Vec = old_asset.encode(); - let new_asset_decoded = - as Decode>::decode(&mut old_asset_encoded.as_slice()).unwrap(); - assert_eq!(new_asset_decoded, new_asset); -} - -// Assets <> ParimutuelAssetClass -#[test_case( - Asset::::ParimutuelShare(7, 8), - ParimutuelAssetClass::Share(7, 8); - "parimutuel_share" -)] -fn index_matching_works_for_parimutuel_assets( - old_asset: Asset, - new_asset: ParimutuelAssetClass, -) { - let old_asset_encoded: Vec = old_asset.encode(); - let new_asset_decoded = - as Decode>::decode(&mut old_asset_encoded.as_slice()) - .unwrap(); - assert_eq!(new_asset_decoded, new_asset); -} - -// Assets <> XcmAssetClass -#[test_case( - Asset::::ForeignAsset(7), - XcmAssetClass::ForeignAsset(7); - "foreign_asset" -)] -#[test_case( - Asset::::Ztg, - XcmAssetClass::Ztg; - "ztg" -)] -fn index_matching_works_for_xcm_assets(old_asset: Asset, new_asset: XcmAssetClass) { - let old_asset_encoded: Vec = old_asset.encode(); - let new_asset_decoded = - ::decode(&mut old_asset_encoded.as_slice()).unwrap(); - assert_eq!(new_asset_decoded, new_asset); -} diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index d5f42caf9..b48768d01 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -22,7 +22,7 @@ clippy::arithmetic_side_effects )] -#[cfg(feature = "mock")] +// #[cfg(any(feature = "mock", feature = "runtime-benchmarks"))] pub mod base_multiples; #[cfg(feature = "mock")] pub mod mock; diff --git a/primitives/src/constants/base_multiples.rs b/primitives/src/constants/base_multiples.rs index e714d61d5..2f8c41d8e 100644 --- a/primitives/src/constants/base_multiples.rs +++ b/primitives/src/constants/base_multiples.rs @@ -15,8 +15,6 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -#![cfg(feature = "mock")] - use crate::constants::BASE; pub const _1: u128 = BASE; diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 47530ebea..0e25aa429 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -20,30 +20,13 @@ pub use super::*; use crate::{ - assets::Asset, - types::{Assets, Balance, Currencies, Moment}, + asset::Asset, + types::{Balance, CurrencyId, Moment}, }; -use frame_support::{pallet_prelude::Weight, parameter_types, traits::LockIdentifier, PalletId}; +use frame_support::{parameter_types, traits::LockIdentifier, PalletId}; use orml_traits::parameter_type_with_key; use sp_arithmetic::Perbill; -// Asset-Router -parameter_types! { - pub const DestroyAccountWeight: Weight = Weight::from_all(1000); - pub const DestroyApprovalWeight: Weight = Weight::from_all(1000); - pub const DestroyFinishWeight: Weight = Weight::from_all(1000); -} - -// Assets -parameter_types! { - pub const AssetsAccountDeposit: Balance = 0; - pub const AssetsApprovalDeposit: Balance = 0; - pub const AssetsDeposit: Balance = 0; - pub const AssetsStringLimit: u32 = 256; - pub const AssetsMetadataDepositBase: Balance = 0; - pub const AssetsMetadataDepositPerByte: Balance = 0; -} - // Authorized parameter_types! { pub const AuthorizedPalletId: PalletId = PalletId(*b"zge/atzd"); @@ -178,15 +161,16 @@ parameter_types! { // ORML parameter_types! { // ORML - pub const GetNativeCurrencyId: Assets = Asset::Ztg; -} - -parameter_type_with_key! { - pub ExistentialDeposits: |_currency_id: Currencies| -> Balance {2}; + pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; } parameter_type_with_key! { - pub ExistentialDepositsAssets: |_asset_id: Assets| -> Balance {2}; + pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { + match currency_id { + Asset::Ztg => ExistentialDeposit::get(), + _ => 10 + } + }; } // System diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 2002bcd97..de0033306 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -20,7 +20,7 @@ extern crate alloc; -mod assets; +mod asset; pub mod constants; pub mod hybrid_router_api_types; mod market; @@ -29,5 +29,6 @@ mod max_runtime_usize; pub mod orderbook; mod outcome_report; mod proxy_type; +mod serde_wrapper; pub mod traits; pub mod types; diff --git a/primitives/src/market.rs b/primitives/src/market.rs index 46b1deef8..3b727f4e6 100644 --- a/primitives/src/market.rs +++ b/primitives/src/market.rs @@ -16,68 +16,58 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::types::{MarketAssetClass, OutcomeReport, ScalarPosition}; +use crate::types::{Asset, OutcomeReport, ScalarPosition}; use alloc::{vec, vec::Vec}; use core::ops::{Range, RangeInclusive}; -use parity_scale_codec::{Decode, Encode, HasCompact, MaxEncodedLen}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_arithmetic::per_things::Perbill; use sp_runtime::RuntimeDebug; -/// Types -/// -/// * `AI`: Account id -/// * `BA`: Balance type -/// * `BN`: Block number -/// * `M`: Moment (time moment) -/// * `A`: Asset -/// * `MI`: Market ID #[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] -pub struct Market { - pub market_id: MI, +pub struct Market { + pub market_id: MarketId, /// Base asset of the market. - pub base_asset: A, + pub base_asset: Asset, /// Creator of this market. - pub creator: AI, + pub creator: AccountId, /// Creation type. pub creation: MarketCreation, /// A fee that is charged each trade and given to the market creator. pub creator_fee: Perbill, /// Oracle that reports the outcome of this market. - pub oracle: AI, + pub oracle: AccountId, /// Metadata for the market, usually a content address of IPFS /// hosted JSON. Currently limited to 66 bytes (see `MaxEncodedLen` implementation) pub metadata: Vec, /// The type of the market. pub market_type: MarketType, /// Market start and end - pub period: MarketPeriod, + pub period: MarketPeriod, /// Market deadlines. - pub deadlines: Deadlines, + pub deadlines: Deadlines, /// The scoring rule used for the market. pub scoring_rule: ScoringRule, /// The current status of the market. pub status: MarketStatus, /// The report of the market. Only `Some` if it has been reported. - pub report: Option>, + pub report: Option>, /// The resolved outcome. pub resolved_outcome: Option, /// See [`MarketDisputeMechanism`]. pub dispute_mechanism: Option, /// The bonds reserved for this market. - pub bonds: MarketBonds, + pub bonds: MarketBonds, /// The time at which the market was closed early. - pub early_close: Option>, + pub early_close: Option>, } -impl Market +impl + Market where - MI: Copy + HasCompact + MaxEncodedLen, + MarketId: Copy + MaxEncodedLen, { - /// Returns the `ResolutionMechanism` of market, currently either: - /// - `RedeemTokens`, which implies that the module that handles the state transitions of - /// a market is also responsible to provide means for redeeming rewards - /// - `Noop`, which implies that another module provides the means for redeeming rewards + /// Returns the `ResolutionMechanism` of this market. pub fn resolution_mechanism(&self) -> ResolutionMechanism { match self.scoring_rule { ScoringRule::AmmCdaHybrid => ResolutionMechanism::RedeemTokens, @@ -85,13 +75,11 @@ where } } - /// Returns whether the market is redeemable, i.e. reward payout is managed within - /// the same module that controls the state transitions of the underlying market. pub fn is_redeemable(&self) -> bool { matches!(self.resolution_mechanism(), ResolutionMechanism::RedeemTokens) } - /// Returns the number of outcomes for a market. + /// Returns the number of outcomes of this market. pub fn outcomes(&self) -> u16 { match self.market_type { MarketType::Categorical(categories) => categories, @@ -116,17 +104,18 @@ where } /// Returns a `Vec` of all outcomes for `market_id`. - pub fn outcome_assets(&self) -> Vec> { + pub fn outcome_assets(&self) -> Vec> { match self.market_type { MarketType::Categorical(categories) => { let mut assets = Vec::new(); for i in 0..categories { match self.scoring_rule { - ScoringRule::AmmCdaHybrid => assets - .push(MarketAssetClass::::CategoricalOutcome(self.market_id, i)), + ScoringRule::AmmCdaHybrid => { + assets.push(Asset::::CategoricalOutcome(self.market_id, i)) + } ScoringRule::Parimutuel => { - assets.push(MarketAssetClass::::ParimutuelShare(self.market_id, i)) + assets.push(Asset::::ParimutuelShare(self.market_id, i)) } }; } @@ -135,8 +124,8 @@ where } MarketType::Scalar(_) => { vec![ - MarketAssetClass::::ScalarOutcome(self.market_id, ScalarPosition::Long), - MarketAssetClass::::ScalarOutcome(self.market_id, ScalarPosition::Short), + Asset::::ScalarOutcome(self.market_id, ScalarPosition::Long), + Asset::::ScalarOutcome(self.market_id, ScalarPosition::Short), ] } } @@ -146,7 +135,7 @@ where /// returns `None` if not possible. Cases where `None` is returned are: /// - The reported outcome does not exist /// - The reported outcome does not have a corresponding asset type - pub fn report_into_asset(&self) -> Option> { + pub fn report_into_asset(&self) -> Option> { let outcome = if let Some(ref report) = self.report { &report.outcome } else { @@ -160,24 +149,21 @@ where /// returns `None` if not possible. Cases where `None` is returned are: /// - The resolved outcome does not exist /// - The resolved outcome does not have a corresponding asset type - pub fn resolved_outcome_into_asset(&self) -> Option> { + pub fn resolved_outcome_into_asset(&self) -> Option> { let outcome = self.resolved_outcome.as_ref()?; self.outcome_report_into_asset(outcome) } /// Tries to convert a `outcome_report` for `market_id` into an asset, /// returns `None` if not possible. - fn outcome_report_into_asset( - &self, - outcome_report: &OutcomeReport, - ) -> Option> { + fn outcome_report_into_asset(&self, outcome_report: &OutcomeReport) -> Option> { match outcome_report { OutcomeReport::Categorical(idx) => match self.scoring_rule { ScoringRule::AmmCdaHybrid => { - Some(MarketAssetClass::::CategoricalOutcome(self.market_id, *idx)) + Some(Asset::::CategoricalOutcome(self.market_id, *idx)) } ScoringRule::Parimutuel => { - Some(MarketAssetClass::::ParimutuelShare(self.market_id, *idx)) + Some(Asset::::ParimutuelShare(self.market_id, *idx)) } }, OutcomeReport::Scalar(_) => None, @@ -187,38 +173,40 @@ where /// Tracks the status of a bond. #[derive(Clone, Decode, Encode, MaxEncodedLen, PartialEq, Eq, RuntimeDebug, TypeInfo)] -pub struct Bond { +pub struct Bond { /// The account that reserved the bond. - pub who: AI, + pub who: AccountId, /// The amount reserved. - pub value: BA, + pub value: Balance, /// `true` if and only if the bond is unreserved and/or (partially) slashed. pub is_settled: bool, } -impl Bond { - pub fn new(who: AI, value: BA) -> Bond { +impl Bond { + pub fn new(who: AccountId, value: Balance) -> Bond { Bond { who, value, is_settled: false } } } /// Tracks bonds associated with a prediction market. #[derive(Clone, Decode, Encode, MaxEncodedLen, PartialEq, Eq, RuntimeDebug, TypeInfo)] -pub struct MarketBonds { - pub creation: Option>, - pub oracle: Option>, - pub outsider: Option>, - pub dispute: Option>, - pub close_request: Option>, - pub close_dispute: Option>, +pub struct MarketBonds { + pub creation: Option>, + pub oracle: Option>, + pub outsider: Option>, + pub dispute: Option>, + pub close_request: Option>, + pub close_dispute: Option>, } -impl MarketBonds { +impl + MarketBonds +{ /// Return the combined value of the open bonds for `who`. - pub fn total_amount_bonded(&self, who: &AI) -> BA { - let value_or_default = |bond: &Option>| match bond { + pub fn total_amount_bonded(&self, who: &AccountId) -> Balance { + let value_or_default = |bond: &Option>| match bond { Some(bond) if bond.who == *who => bond.value, - _ => BA::zero(), + _ => Balance::zero(), }; value_or_default(&self.creation) .saturating_add(value_or_default(&self.oracle)) @@ -230,7 +218,7 @@ impl MarketBonds { } // Used primarily for testing purposes. -impl Default for MarketBonds { +impl Default for MarketBonds { fn default() -> Self { MarketBonds { creation: None, @@ -243,34 +231,34 @@ impl Default for MarketBonds { } } -impl MaxEncodedLen for Market +impl MaxEncodedLen + for Market where - AI: MaxEncodedLen, - BA: MaxEncodedLen, - BN: MaxEncodedLen, - M: MaxEncodedLen, - A: MaxEncodedLen, - MI: MaxEncodedLen, + AccountId: MaxEncodedLen, + Balance: MaxEncodedLen, + BlockNumber: MaxEncodedLen, + Moment: MaxEncodedLen, + MarketId: MaxEncodedLen, { fn max_encoded_len() -> usize { - AI::max_encoded_len() - .saturating_add(MI::max_encoded_len()) - .saturating_add(A::max_encoded_len()) + AccountId::max_encoded_len() + .saturating_add(MarketId::max_encoded_len()) + .saturating_add(Asset::::max_encoded_len()) .saturating_add(MarketCreation::max_encoded_len()) .saturating_add(Perbill::max_encoded_len()) - .saturating_add(AI::max_encoded_len()) + .saturating_add(AccountId::max_encoded_len()) // We assume that at max. a 512 bit hash function is used .saturating_add(u8::max_encoded_len().saturating_mul(68)) .saturating_add(MarketType::max_encoded_len()) - .saturating_add(>::max_encoded_len()) - .saturating_add(Deadlines::::max_encoded_len()) + .saturating_add(>::max_encoded_len()) + .saturating_add(Deadlines::::max_encoded_len()) .saturating_add(ScoringRule::max_encoded_len()) .saturating_add(MarketStatus::max_encoded_len()) - .saturating_add(>>::max_encoded_len()) + .saturating_add(>>::max_encoded_len()) .saturating_add(>::max_encoded_len()) .saturating_add(>::max_encoded_len()) - .saturating_add(>::max_encoded_len()) - .saturating_add(>>::max_encoded_len()) + .saturating_add(>::max_encoded_len()) + .saturating_add(>>::max_encoded_len()) } } @@ -326,22 +314,27 @@ pub enum MarketDisputeMechanism { /// 3. With inclusive ranges it is not possible to express empty ranges and this feature /// mostly conflicts with existent tests and corner cases. #[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] -pub enum MarketPeriod { - Block(Range), - Timestamp(Range), +pub enum MarketPeriod { + Block(Range), + Timestamp(Range), } -impl MaxEncodedLen for MarketPeriod { +impl MaxEncodedLen + for MarketPeriod +{ fn max_encoded_len() -> usize { // Since it is an enum, the biggest element is the only one of interest here. - BN::max_encoded_len().max(M::max_encoded_len()).saturating_mul(2).saturating_add(1) + BlockNumber::max_encoded_len() + .max(Moment::max_encoded_len()) + .saturating_mul(2) + .saturating_add(1) } } #[derive(Clone, Decode, Encode, Eq, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)] -pub struct EarlyClose { - pub old: MarketPeriod, - pub new: MarketPeriod, +pub struct EarlyClose { + pub old: MarketPeriod, + pub new: MarketPeriod, pub state: EarlyCloseState, } @@ -357,10 +350,10 @@ pub enum EarlyCloseState { #[derive( Clone, Copy, Decode, Default, Encode, Eq, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo, )] -pub struct Deadlines { - pub grace_period: BN, - pub oracle_duration: BN, - pub dispute_duration: BN, +pub struct Deadlines { + pub grace_period: BlockNumber, + pub oracle_duration: BlockNumber, + pub dispute_duration: BlockNumber, } #[derive(TypeInfo, Clone, Copy, Encode, Eq, Decode, MaxEncodedLen, PartialEq, RuntimeDebug)] @@ -424,13 +417,10 @@ pub enum ResolutionMechanism { #[cfg(test)] mod tests { - use crate::{ - market::*, - types::{Asset, MarketAsset}, - }; + use crate::{market::*, types::Asset}; use test_case::test_case; type MarketId = u128; - type Market = crate::market::Market, MarketId>; + type Market = crate::market::Market; #[test_case( MarketType::Categorical(6), @@ -514,28 +504,28 @@ mod tests { #[test_case( MarketType::Categorical(2), ScoringRule::AmmCdaHybrid, - vec![MarketAsset::CategoricalOutcome(0, 0), MarketAsset::CategoricalOutcome(0, 1)]; + vec![Asset::CategoricalOutcome(0, 0), Asset::CategoricalOutcome(0, 1)]; "categorical_market_amm_cda_hybrid" )] #[test_case( MarketType::Categorical(2), ScoringRule::Parimutuel, - vec![MarketAsset::ParimutuelShare(0, 0), MarketAsset::ParimutuelShare(0, 1)]; + vec![Asset::ParimutuelShare(0, 0), Asset::ParimutuelShare(0, 1)]; "categorical_market_parimutuel" )] #[test_case( MarketType::Scalar(12..=34), ScoringRule::AmmCdaHybrid, vec![ - MarketAsset::ScalarOutcome(0, ScalarPosition::Long), - MarketAsset::ScalarOutcome(0, ScalarPosition::Short), + Asset::ScalarOutcome(0, ScalarPosition::Long), + Asset::ScalarOutcome(0, ScalarPosition::Short), ]; "scalar_market" )] fn provides_correct_list_of_assets( market_type: MarketType, scoring_rule: ScoringRule, - expected: Vec, + expected: Vec>, ) { let market = Market { market_id: 0, @@ -567,14 +557,14 @@ mod tests { MarketType::Categorical(2), ScoringRule::AmmCdaHybrid, OutcomeReport::Categorical(2), - Some(MarketAsset::CategoricalOutcome(0, 2)); + Some(Asset::CategoricalOutcome(0, 2)); "categorical_market_amm_cda_hybrid" )] #[test_case( MarketType::Categorical(2), ScoringRule::Parimutuel, OutcomeReport::Categorical(2), - Some(MarketAsset::ParimutuelShare(0, 2)); + Some(Asset::ParimutuelShare(0, 2)); "categorical_market_parimutuel" )] #[test_case( @@ -588,7 +578,7 @@ mod tests { market_type: MarketType, scoring_rule: ScoringRule, outcome: OutcomeReport, - expected: Option, + expected: Option>, ) { let report = Some(Report { at: Default::default(), diff --git a/primitives/src/serde_wrapper.rs b/primitives/src/serde_wrapper.rs new file mode 100644 index 000000000..cf1a9861b --- /dev/null +++ b/primitives/src/serde_wrapper.rs @@ -0,0 +1,66 @@ +// Copyright 2024 Forecasting Technologies LTD. +// Copyright 2021-2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; +#[cfg(feature = "std")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// Used to workaround serde serialization/deserialization problems involving `u128`. +/// +/// # Types +/// +/// * `B`: Balance +#[derive( + scale_info::TypeInfo, + Clone, + Copy, + Debug, + Decode, + Default, + Encode, + Eq, + MaxEncodedLen, + Ord, + PartialEq, + PartialOrd, +)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] +pub struct SerdeWrapper( + #[cfg_attr(feature = "std", serde(bound(serialize = "B: std::fmt::Display")))] + #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] + #[cfg_attr(feature = "std", serde(bound(deserialize = "B: std::str::FromStr")))] + #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] + pub B, +); + +#[cfg(feature = "std")] +fn serialize_as_string( + t: &T, + serializer: S, +) -> Result { + serializer.serialize_str(&t.to_string()) +} + +#[cfg(feature = "std")] +fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>( + deserializer: D, +) -> Result { + let s = String::deserialize(deserializer)?; + s.parse::().map_err(|_| serde::de::Error::custom("Parse from string failed")) +} diff --git a/primitives/src/traits.rs b/primitives/src/traits.rs index 7d7bde094..1298baa68 100644 --- a/primitives/src/traits.rs +++ b/primitives/src/traits.rs @@ -25,9 +25,7 @@ mod hybrid_router_orderbook_api; mod market_builder; mod market_commons_pallet_api; mod market_id; -mod market_transition_api; mod swaps; -mod weights; mod zeitgeist_asset; pub use complete_set_operations_api::*; @@ -39,7 +37,5 @@ pub use hybrid_router_orderbook_api::*; pub use market_builder::*; pub use market_commons_pallet_api::*; pub use market_id::*; -pub use market_transition_api::*; pub use swaps::*; -pub use weights::*; pub use zeitgeist_asset::*; diff --git a/primitives/src/traits/dispute_api.rs b/primitives/src/traits/dispute_api.rs index 8ef6b952b..c8e2c279f 100644 --- a/primitives/src/traits/dispute_api.rs +++ b/primitives/src/traits/dispute_api.rs @@ -20,11 +20,11 @@ extern crate alloc; use crate::{ outcome_report::OutcomeReport, - types::{BaseAsset, GlobalDisputeItem, Market, ResultWithWeightInfo}, + types::{GlobalDisputeItem, Market, ResultWithWeightInfo}, }; use alloc::vec::Vec; use frame_support::pallet_prelude::Weight; -use parity_scale_codec::{HasCompact, MaxEncodedLen}; +use parity_scale_codec::MaxEncodedLen; use sp_runtime::DispatchError; // Abstraction of the market type, which is not a part of `DisputeApi` because Rust doesn't support @@ -34,7 +34,6 @@ pub type MarketOfDisputeApi = Market< ::Balance, ::BlockNumber, ::Moment, - BaseAsset, ::MarketId, >; @@ -46,7 +45,7 @@ pub trait DisputeApi { type Balance; type NegativeImbalance; type BlockNumber; - type MarketId: MaxEncodedLen + HasCompact; + type MarketId: MaxEncodedLen; type Moment; type Origin; @@ -151,7 +150,6 @@ pub type MarketOfDisputeResolutionApi = Market< ::Balance, ::BlockNumber, ::Moment, - BaseAsset, ::MarketId, >; @@ -159,7 +157,7 @@ pub trait DisputeResolutionApi { type AccountId; type Balance; type BlockNumber; - type MarketId: MaxEncodedLen + HasCompact; + type MarketId: MaxEncodedLen; type Moment; /// Resolve a market. diff --git a/primitives/src/traits/market_builder.rs b/primitives/src/traits/market_builder.rs index 7f682c8d7..0bf0d2cf3 100644 --- a/primitives/src/traits/market_builder.rs +++ b/primitives/src/traits/market_builder.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use crate::types::{ - Deadlines, EarlyClose, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, + Asset, Deadlines, EarlyClose, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, OutcomeReport, Report, ScoringRule, }; use alloc::vec::Vec; @@ -36,26 +36,28 @@ macro_rules! builder_methods { /// builder.field1(value1).field2(value2); /// builder.clone().build() /// ``` -pub trait MarketBuilderTrait { - fn build(self) -> Result, DispatchError>; +pub trait MarketBuilderTrait { + fn build( + self, + ) -> Result, DispatchError>; builder_methods! { - market_id: MI, - base_asset: A, - creator: AI, + market_id: MarketId, + base_asset: Asset, + creator: AccountId, creation: MarketCreation, creator_fee: Perbill, - oracle: AI, + oracle: AccountId, metadata: Vec, market_type: MarketType, - period: MarketPeriod, - deadlines: Deadlines, + period: MarketPeriod, + deadlines: Deadlines, scoring_rule: ScoringRule, status: MarketStatus, - report: Option>, + report: Option>, resolved_outcome: Option, dispute_mechanism: Option, - bonds: MarketBonds, - early_close: Option>, + bonds: MarketBonds, + early_close: Option>, } } diff --git a/primitives/src/traits/market_commons_pallet_api.rs b/primitives/src/traits/market_commons_pallet_api.rs index 3b5293d38..c75725295 100644 --- a/primitives/src/traits/market_commons_pallet_api.rs +++ b/primitives/src/traits/market_commons_pallet_api.rs @@ -20,7 +20,7 @@ use crate::{ traits::MarketBuilderTrait, - types::{BaseAsset, Market, PoolId}, + types::{Market, PoolId}, }; use frame_support::{ dispatch::{fmt::Debug, DispatchError, DispatchResult}, @@ -28,17 +28,16 @@ use frame_support::{ storage::PrefixIterator, Parameter, }; -use parity_scale_codec::{FullCodec, HasCompact, MaxEncodedLen}; +use parity_scale_codec::{FullCodec, MaxEncodedLen}; use sp_runtime::traits::{AtLeast32Bit, AtLeast32BitUnsigned}; // Abstraction of the market type, which is not a part of `MarketCommonsPalletApi` because Rust // doesn't support type aliases in traits. -pub type MarketOf = Market< +type MarketOf = Market< ::AccountId, ::Balance, ::BlockNumber, ::Moment, - BaseAsset, ::MarketId, >; @@ -59,7 +58,6 @@ pub trait MarketCommonsPalletApi { + Default + MaybeSerializeDeserialize + MaxEncodedLen - + HasCompact + Member + Parameter; type Moment: AtLeast32Bit + Copy + Default + Parameter + MaxEncodedLen; @@ -105,7 +103,6 @@ pub trait MarketCommonsPalletApi { Self::Balance, Self::BlockNumber, Self::Moment, - BaseAsset, Self::MarketId, >; diff --git a/primitives/src/traits/market_id.rs b/primitives/src/traits/market_id.rs index 1965d408c..cd0007fb5 100644 --- a/primitives/src/traits/market_id.rs +++ b/primitives/src/traits/market_id.rs @@ -1,4 +1,4 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. @@ -20,18 +20,11 @@ use frame_support::{ pallet_prelude::{MaybeSerializeDeserialize, Member}, Parameter, }; -use parity_scale_codec::{HasCompact, MaxEncodedLen}; +use parity_scale_codec::MaxEncodedLen; use sp_runtime::traits::AtLeast32Bit; pub trait MarketId: - AtLeast32Bit - + Copy - + Default - + HasCompact - + MaxEncodedLen - + MaybeSerializeDeserialize - + Member - + Parameter + AtLeast32Bit + Copy + Default + MaxEncodedLen + MaybeSerializeDeserialize + Member + Parameter { } @@ -39,7 +32,6 @@ impl MarketId for T where T: AtLeast32Bit + Copy + Default - + HasCompact + MaxEncodedLen + MaybeSerializeDeserialize + Member diff --git a/primitives/src/traits/market_transition_api.rs b/primitives/src/traits/market_transition_api.rs deleted file mode 100644 index 46a613eaa..000000000 --- a/primitives/src/traits/market_transition_api.rs +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::types::ResultWithWeightInfo; -use frame_support::pallet_prelude::{DispatchResult, Weight}; - -/// API that is used to catch market state transitions. -pub trait MarketTransitionApi { - fn on_proposal(_market_id: &MI) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_activation(_market_id: &MI) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_closure(_market_id: &MI) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_report(_market_id: &MI) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_dispute(_market_id: &MI) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_resolution(_market_id: &MI) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } -} - -#[impl_trait_for_tuples::impl_for_tuples(8)] -#[allow(clippy::let_and_return)] -/// Implementation returns on first error or after successful execution of all elements. -impl MarketTransitionApi for Tuple { - fn on_proposal(market_id: &MI) -> ResultWithWeightInfo { - let mut collective_result = ResultWithWeightInfo::new(Ok(()), Weight::zero()); - for_tuples!( #( - let result = Tuple::on_proposal(market_id); - collective_result.result = result.result; - collective_result.weight = collective_result.weight.saturating_add(result.weight); - if collective_result.result.is_err() { - return collective_result; - } - )* ); - collective_result - } - fn on_activation(market_id: &MI) -> ResultWithWeightInfo { - let mut collective_result = ResultWithWeightInfo::new(Ok(()), Weight::zero()); - for_tuples!( #( - let result = Tuple::on_activation(market_id); - collective_result.result = result.result; - collective_result.weight = collective_result.weight.saturating_add(result.weight); - if collective_result.result.is_err() { - return collective_result; - } - )* ); - collective_result - } - fn on_closure(market_id: &MI) -> ResultWithWeightInfo { - let mut collective_result = ResultWithWeightInfo::new(Ok(()), Weight::zero()); - for_tuples!( #( - let result = Tuple::on_closure(market_id); - collective_result.result = result.result; - collective_result.weight = collective_result.weight.saturating_add(result.weight); - if collective_result.result.is_err() { - return collective_result; - } - )* ); - collective_result - } - fn on_report(market_id: &MI) -> ResultWithWeightInfo { - let mut collective_result = ResultWithWeightInfo::new(Ok(()), Weight::zero()); - for_tuples!( #( - let result = Tuple::on_report(market_id); - collective_result.result = result.result; - collective_result.weight = collective_result.weight.saturating_add(result.weight); - if collective_result.result.is_err() { - return collective_result; - } - )* ); - collective_result - } - fn on_dispute(market_id: &MI) -> ResultWithWeightInfo { - let mut collective_result = ResultWithWeightInfo::new(Ok(()), Weight::zero()); - for_tuples!( #( - let result = Tuple::on_dispute(market_id); - collective_result.result = result.result; - collective_result.weight = collective_result.weight.saturating_add(result.weight); - if collective_result.result.is_err() { - return collective_result; - } - )* ); - collective_result - } - fn on_resolution(market_id: &MI) -> ResultWithWeightInfo { - let mut collective_result = ResultWithWeightInfo::new(Ok(()), Weight::zero()); - for_tuples!( #( - let result = Tuple::on_resolution(market_id); - collective_result.result = result.result; - collective_result.weight = collective_result.weight.saturating_add(result.weight); - if collective_result.result.is_err() { - return collective_result; - } - )* ); - collective_result - } -} - -#[cfg(test)] -mod tests { - use super::*; - use frame_support::pallet_prelude::DispatchError; - - const DEFAULT_ERROR: DispatchResult = Err(DispatchError::Other("unimportant")); - const ONE: Weight = Weight::from_all(1); - const TWO: Weight = Weight::from_all(2); - const THREE: Weight = Weight::from_all(3); - - struct ExecutionPath; - impl MarketTransitionApi for ExecutionPath { - fn on_proposal(_market_id: &u128) -> ResultWithWeightInfo { - panic!("on_proposal"); - } - fn on_activation(_market_id: &u128) -> ResultWithWeightInfo { - panic!("on_activation"); - } - fn on_closure(_market_id: &u128) -> ResultWithWeightInfo { - panic!("on_closure"); - } - fn on_report(_market_id: &u128) -> ResultWithWeightInfo { - panic!("on_report"); - } - fn on_dispute(_market_id: &u128) -> ResultWithWeightInfo { - panic!("on_dispute"); - } - fn on_resolution(_market_id: &u128) -> ResultWithWeightInfo { - panic!("on_resolution"); - } - } - - struct SuccessPath; - impl MarketTransitionApi for SuccessPath { - fn on_proposal(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), ONE) - } - fn on_activation(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), ONE) - } - fn on_closure(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), ONE) - } - fn on_report(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), ONE) - } - fn on_dispute(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), ONE) - } - fn on_resolution(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(Ok(()), ONE) - } - } - - struct FailurePath; - impl MarketTransitionApi for FailurePath { - fn on_proposal(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(DEFAULT_ERROR, TWO) - } - fn on_activation(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(DEFAULT_ERROR, TWO) - } - fn on_closure(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(DEFAULT_ERROR, TWO) - } - fn on_report(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(DEFAULT_ERROR, TWO) - } - fn on_dispute(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(DEFAULT_ERROR, TWO) - } - fn on_resolution(_market_id: &u128) -> ResultWithWeightInfo { - ResultWithWeightInfo::new(DEFAULT_ERROR, TWO) - } - } - - #[test] - #[should_panic(expected = "on_proposal")] - fn correct_execution_path_for_tuples_on_proposal() { - <(ExecutionPath,)>::on_proposal(&0); - } - - #[test] - #[should_panic(expected = "on_activation")] - fn correct_execution_path_for_tuples_on_activation() { - <(ExecutionPath,)>::on_activation(&0); - } - - #[test] - #[should_panic(expected = "on_closure")] - fn correct_execution_path_for_tuples_on_closure() { - <(ExecutionPath,)>::on_closure(&0); - } - - #[test] - #[should_panic(expected = "on_report")] - fn correct_execution_path_for_tuples_on_report() { - <(ExecutionPath,)>::on_report(&0); - } - - #[test] - #[should_panic(expected = "on_dispute")] - fn correct_execution_path_for_tuples_on_dispute() { - <(ExecutionPath,)>::on_dispute(&0); - } - - #[test] - #[should_panic(expected = "on_resolution")] - fn correct_execution_path_for_tuples_on_resolution() { - <(ExecutionPath,)>::on_resolution(&0); - } - - #[test] - fn provides_correct_result_on_proposal() { - let mut result = <(SuccessPath,)>::on_proposal(&0); - assert_eq!(result.result, Ok(())); - assert_eq!(result.weight, ONE); - - result = <(SuccessPath, FailurePath)>::on_proposal(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, THREE); - - result = <(FailurePath, SuccessPath)>::on_proposal(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, TWO); - } - - #[test] - fn provides_correct_result_on_activation() { - let mut result = <(SuccessPath,)>::on_activation(&0); - assert_eq!(result.result, Ok(())); - assert_eq!(result.weight, ONE); - - result = <(SuccessPath, FailurePath)>::on_activation(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, THREE); - - result = <(FailurePath, SuccessPath)>::on_activation(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, TWO); - } - - #[test] - fn provides_correct_result_on_closure() { - let mut result = <(SuccessPath,)>::on_closure(&0); - assert_eq!(result.result, Ok(())); - assert_eq!(result.weight, ONE); - - result = <(SuccessPath, FailurePath)>::on_closure(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, THREE); - - result = <(FailurePath, SuccessPath)>::on_closure(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, TWO); - } - - #[test] - fn provides_correct_result_on_report() { - let mut result = <(SuccessPath,)>::on_report(&0); - assert_eq!(result.result, Ok(())); - assert_eq!(result.weight, ONE); - - result = <(SuccessPath, FailurePath)>::on_report(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, THREE); - - result = <(FailurePath, SuccessPath)>::on_report(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, TWO); - } - - #[test] - fn provides_correct_result_on_dispute() { - let mut result = <(SuccessPath,)>::on_dispute(&0); - assert_eq!(result.result, Ok(())); - assert_eq!(result.weight, ONE); - - result = <(SuccessPath, FailurePath)>::on_dispute(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, THREE); - - result = <(FailurePath, SuccessPath)>::on_dispute(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, TWO); - } - - #[test] - fn provides_correct_result_on_resolution() { - let mut result = <(SuccessPath,)>::on_resolution(&0); - assert_eq!(result.result, Ok(())); - assert_eq!(result.weight, ONE); - - result = <(SuccessPath, FailurePath)>::on_resolution(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, THREE); - - result = <(FailurePath, SuccessPath)>::on_resolution(&0); - assert_eq!(result.result, DEFAULT_ERROR); - assert_eq!(result.weight, TWO); - } -} diff --git a/primitives/src/traits/swaps.rs b/primitives/src/traits/swaps.rs index 415c163bd..cff467ac9 100644 --- a/primitives/src/traits/swaps.rs +++ b/primitives/src/traits/swaps.rs @@ -18,12 +18,12 @@ use crate::types::PoolId; use alloc::vec::Vec; -use frame_support::dispatch::{DispatchError, DispatchResult, Weight}; -use parity_scale_codec::{HasCompact, MaxEncodedLen}; +use frame_support::dispatch::{DispatchError, Weight}; +use sp_runtime::DispatchResult; pub trait Swaps { - type Asset: MaxEncodedLen; - type Balance: HasCompact + MaxEncodedLen; + type Asset; + type Balance; /// Creates a new pool. /// diff --git a/primitives/src/traits/weights.rs b/primitives/src/traits/weights.rs deleted file mode 100644 index 8cc25046b..000000000 --- a/primitives/src/traits/weights.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// Copyright 2023 Parity Technologies (UK) Ltd. - -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -/// Provides `checked_div_per_component` implementation to determine the -/// smallest division result between two `ref_time` and `proof_size`. -/// To be removed once sp-weights is upgraded to polkadot-v0.9.39 -use frame_support::pallet_prelude::Weight; - -pub trait CheckedDivPerComponent { - /// Calculates how many `other` fit into `self`. - /// - /// Divides each component of `self` against the same component of `other`. Returns the minimum - /// of all those divisions. Returns `None` in case **all** components of `other` are zero. - /// - /// This returns `Some` even if some components of `other` are zero as long as there is at least - /// one non-zero component in `other`. The division for this particular component will then - /// yield the maximum value (e.g u64::MAX). This is because we assume not every operation and - /// hence each `Weight` will necessarily use each resource. - fn checked_div_per_component(self, other: &Self) -> Option; -} - -impl CheckedDivPerComponent for Weight { - fn checked_div_per_component(self, other: &Self) -> Option { - let mut all_zero = true; - let ref_time = match self.ref_time().checked_div(other.ref_time()) { - Some(ref_time) => { - all_zero = false; - ref_time - } - None => u64::MAX, - }; - let proof_size = match self.proof_size().checked_div(other.proof_size()) { - Some(proof_size) => { - all_zero = false; - proof_size - } - None => u64::MAX, - }; - if all_zero { - None - } else { - Some(if ref_time < proof_size { ref_time } else { proof_size }) - } - } -} diff --git a/primitives/src/types.rs b/primitives/src/types.rs index 68ce0b1c1..417a71cc5 100644 --- a/primitives/src/types.rs +++ b/primitives/src/types.rs @@ -17,7 +17,8 @@ // along with Zeitgeist. If not, see . pub use crate::{ - assets::*, market::*, max_runtime_usize::*, outcome_report::OutcomeReport, proxy_type::*, + asset::*, market::*, max_runtime_usize::*, outcome_report::OutcomeReport, proxy_type::*, + serde_wrapper::*, }; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Result, Unstructured}; @@ -77,38 +78,10 @@ impl<'a> Arbitrary<'a> for MultiHash { } } -/// ORML adapter. +/// ORML adapter pub type BasicCurrencyAdapter = orml_currencies::BasicCurrencyAdapter; -/// ID type for any asset class. -pub type Assets = Asset; - -/// Asset type representing base assets used by prediction markets. -pub type BaseAsset = BaseAssetClass; - -/// Asset type representing campaign assets. -pub type CampaignAsset = CampaignAssetClass; - -// ID type of the campaign asset class. -pub type CampaignAssetId = u128; - -/// Asset type representing custom assets. -pub type CustomAsset = CustomAssetClass; - -// ID type of the custom asset class. -pub type CustomAssetId = u128; - -// Asset type representing currencies (excluding ZTG). -pub type Currencies = CurrencyClass; - -/// Asset type representing assets used by prediction markets. -pub type MarketAsset = MarketAssetClass; - -/// Asset type representing assets used in parimutuel markets. -pub type ParimutuelAsset = ParimutuelAssetClass; - -/// Asset type representing assets that can be transferred via XCM. -pub type XcmAsset = XcmAssetClass; +pub type CurrencyId = Asset; /// The asset id specifically used for pallet_assets_tx_payment for /// paying transaction fees in different assets. @@ -156,12 +129,6 @@ pub struct ResultWithWeightInfo { pub weight: Weight, } -impl ResultWithWeightInfo { - pub fn new(result: R, weight: Weight) -> Self { - ResultWithWeightInfo { result, weight } - } -} - #[derive( Clone, Copy, diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index 7350447ee..c8cef23a1 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -11,7 +11,6 @@ orml-currencies = { workspace = true } orml-tokens = { workspace = true } orml-traits = { workspace = true } pallet-asset-tx-payment = { workspace = true } -pallet-assets = { workspace = true } pallet-balances = { workspace = true } pallet-bounties = { workspace = true } pallet-collective = { workspace = true } @@ -109,7 +108,6 @@ xcm-executor = { workspace = true, optional = true } common-runtime = { workspace = true } zeitgeist-primitives = { workspace = true } -zrml-asset-router = { workspace = true } zrml-authorized = { workspace = true } zrml-court = { workspace = true } zrml-global-disputes = { workspace = true, optional = true } @@ -186,7 +184,6 @@ runtime-benchmarks = [ "orml-benchmarking", "orml-tokens/runtime-benchmarks", "orml-xtokens?/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", "pallet-author-inherent?/runtime-benchmarks", "pallet-author-mapping?/runtime-benchmarks", "pallet-author-slot-filter?/runtime-benchmarks", @@ -237,7 +234,6 @@ std = [ "orml-currencies/std", "orml-tokens/std", "orml-traits/std", - "pallet-assets/std", "pallet-asset-tx-payment/std", "pallet-balances/std", "pallet-bounties/std", @@ -360,7 +356,6 @@ try-runtime = [ "pallet-preimage/try-runtime", # Money runtime pallets - "pallet-assets/try-runtime", "pallet-asset-tx-payment/try-runtime", "pallet-balances/try-runtime", "pallet-bounties/try-runtime", @@ -387,7 +382,6 @@ try-runtime = [ "orml-xtokens?/try-runtime", # Zeitgeist runtime pallets - "zrml-asset-router/try-runtime", "zrml-authorized/try-runtime", "zrml-court/try-runtime", "zrml-hybrid-router/try-runtime", diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 092184ade..2550140f3 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -18,7 +18,8 @@ use crate::{ xcm_config::config::{battery_station, general_key}, - AccountId, AssetRegistry, Assets, Balance, ExistentialDeposit, Runtime, RuntimeOrigin, System, + AccountId, AssetRegistry, Balance, CurrencyId, ExistentialDeposit, Runtime, RuntimeOrigin, + System, }; use frame_support::{assert_ok, traits::GenesisBuild}; use orml_traits::asset_registry::AssetMetadata; @@ -27,10 +28,10 @@ use xcm::{ latest::{Junction::Parachain, Junctions::X2, MultiLocation}, VersionedMultiLocation, }; -use zeitgeist_primitives::types::{CustomMetadata, XcmAsset}; +use zeitgeist_primitives::types::{Asset, CustomMetadata}; pub(super) struct ExtBuilder { - balances: Vec<(AccountId, Assets, Balance)>, + balances: Vec<(AccountId, CurrencyId, Balance)>, parachain_id: u32, } @@ -41,7 +42,7 @@ impl Default for ExtBuilder { } impl ExtBuilder { - pub fn set_balances(mut self, balances: Vec<(AccountId, Assets, Balance)>) -> Self { + pub fn set_balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { self.balances = balances; self } @@ -53,7 +54,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let native_currency_id = Assets::Ztg; + let native_currency_id = CurrencyId::Ztg; pallet_balances::GenesisConfig:: { balances: self .balances @@ -71,9 +72,6 @@ impl ExtBuilder { .balances .into_iter() .filter(|(_, currency_id, _)| *currency_id != native_currency_id) - .map(|(account_id, currency_id, initial_balance)| { - (account_id, currency_id.try_into().unwrap(), initial_balance) - }) .collect::>(), } .assimilate_storage(&mut t) @@ -106,10 +104,10 @@ pub const BOB: AccountId32 = AccountId32::new([1u8; 32]); pub const PARA_ID_SIBLING: u32 = 3000; /// IDs that are used to represent tokens from other chains -pub const FOREIGN_ZTG_ID: XcmAsset = XcmAsset::ForeignAsset(0); -pub const FOREIGN_PARENT_ID: XcmAsset = XcmAsset::ForeignAsset(1); -pub const FOREIGN_SIBLING_ID: XcmAsset = XcmAsset::ForeignAsset(2); -pub const BTC_ID: XcmAsset = XcmAsset::ForeignAsset(3); +pub const FOREIGN_ZTG_ID: Asset = CurrencyId::ForeignAsset(0); +pub const FOREIGN_PARENT_ID: Asset = CurrencyId::ForeignAsset(1); +pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); +pub const BTC_ID: Asset = CurrencyId::ForeignAsset(3); #[inline] pub(super) const fn ztg(amount: Balance) -> Balance { diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 2ee922bc5..a847389d4 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -17,8 +17,8 @@ // along with Zeitgeist. If not, see . use crate::{ - parameters::ZeitgeistTreasuryAccount, xcm_config::config::battery_station, Assets, DmpQueue, - Runtime, RuntimeOrigin, XcmpQueue, + parameters::ZeitgeistTreasuryAccount, xcm_config::config::battery_station, CurrencyId, + DmpQueue, Runtime, RuntimeOrigin, XcmpQueue, }; use frame_support::{traits::GenesisBuild, weights::Weight}; use polkadot_primitives::{ @@ -102,9 +102,9 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { ExtBuilder::default() .set_balances(vec![ - (ALICE, Assets::Ztg, ztg(10)), - (ALICE, FOREIGN_PARENT_ID.into(), roc(10)), - (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID.into(), roc(1)), + (ALICE, CurrencyId::Ztg, ztg(10)), + (ALICE, FOREIGN_PARENT_ID, roc(10)), + (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, roc(1)), ]) .set_parachain_id(parachain_id) .build() diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index e28c94407..97cbce60b 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -26,97 +26,82 @@ use crate::{ test_net::Zeitgeist, }, xcm_config::config::{battery_station, general_key, AssetConvert}, - Assets, CustomMetadata, ScalarPosition, XcmAsset, + CurrencyId, }; -use core::fmt::Debug; + use frame_support::assert_err; use sp_runtime::traits::Convert as C2; -use test_case::test_case; use xcm::latest::{Junction::*, Junctions::*, MultiLocation}; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; -fn convert_common_native(expected: T) -where - T: Copy + Debug + PartialEq, - AssetConvert: C1 + C2>, -{ +#[test] +fn convert_native() { assert_eq!(battery_station::KEY.to_vec(), vec![0, 1]); // The way Ztg is represented relative within the Zeitgeist runtime let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(battery_station::KEY))); - assert_eq!(>::convert(ztg_location_inner), Ok(expected)); + assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg)); // The canonical way Ztg is represented out in the wild Zeitgeist::execute_with(|| { - assert_eq!(>::convert(expected), Some(foreign_ztg_multilocation())) + assert_eq!( + >::convert(CurrencyId::Ztg), + Some(foreign_ztg_multilocation()) + ) }); } -fn convert_common_non_native( - expected: T, - multilocation: MultiLocation, - register: fn(Option), -) where - T: Copy + Debug + PartialEq, - AssetConvert: C1 + C2>, -{ +#[test] +fn convert_any_registered_parent_multilocation() { Zeitgeist::execute_with(|| { - assert_err!(>::convert(multilocation), multilocation); - assert_eq!(>::convert(expected), None); + assert_err!( + >::convert(foreign_parent_multilocation()), + foreign_parent_multilocation() + ); + + assert_eq!(>::convert(FOREIGN_PARENT_ID), None); + // Register parent as foreign asset in the Zeitgeist parachain - register(None); - assert_eq!(>::convert(multilocation), Ok(expected)); - assert_eq!(>::convert(expected), Some(multilocation)); - }); -} + register_foreign_parent(None); -#[test] -fn convert_native_assets() { - convert_common_native(Assets::Ztg); -} + assert_eq!( + >::convert(foreign_parent_multilocation()), + Ok(FOREIGN_PARENT_ID), + ); -#[test] -fn convert_native_xcm_assets() { - convert_common_native(XcmAsset::Ztg); + assert_eq!( + >::convert(FOREIGN_PARENT_ID), + Some(foreign_parent_multilocation()) + ); + }); } #[test] -fn convert_any_registered_parent_multilocation_assets() { - convert_common_non_native( - Assets::from(FOREIGN_PARENT_ID), - foreign_parent_multilocation(), - register_foreign_parent, - ); -} +fn convert_any_registered_sibling_multilocation() { + Zeitgeist::execute_with(|| { + assert_err!( + >::convert(foreign_sibling_multilocation()), + foreign_sibling_multilocation() + ); -#[test] -fn convert_any_registered_parent_multilocation_xcm_assets() { - convert_common_non_native( - XcmAsset::try_from(Assets::from(FOREIGN_PARENT_ID)).unwrap(), - foreign_parent_multilocation(), - register_foreign_parent, - ); -} + assert_eq!(>::convert(FOREIGN_SIBLING_ID), None); -#[test] -fn convert_any_registered_sibling_multilocation_assets() { - convert_common_non_native( - Assets::from(FOREIGN_SIBLING_ID), - foreign_sibling_multilocation(), - register_foreign_sibling, - ); -} + // Register sibling as foreign asset in the Zeitgeist parachain + register_foreign_sibling(None); -#[test] -fn convert_any_registered_sibling_multilocation_xcm_assets() { - convert_common_non_native( - XcmAsset::try_from(Assets::from(FOREIGN_SIBLING_ID)).unwrap(), - foreign_sibling_multilocation(), - register_foreign_sibling, - ); + assert_eq!( + >::convert(foreign_sibling_multilocation()), + Ok(FOREIGN_SIBLING_ID), + ); + + assert_eq!( + >::convert(FOREIGN_SIBLING_ID), + Some(foreign_sibling_multilocation()) + ); + }); } #[test] @@ -125,46 +110,13 @@ fn convert_unkown_multilocation() { MultiLocation::new(1, X2(Parachain(battery_station::ID), general_key(&[42]))); Zeitgeist::execute_with(|| { - assert!(>::convert(unknown_location).is_err()); + assert!(>::convert(unknown_location).is_err()); }); } -#[test_case( - Assets::CategoricalOutcome(7, 8); - "assets_categorical" -)] -#[test_case( - Assets::ScalarOutcome(7, ScalarPosition::Long); - "assets_scalar" -)] -#[test_case( - Assets::PoolShare(7); - "assets_pool_share" -)] -#[test_case( - Assets::ForeignAsset(7); - "assets_foreign" -)] -#[test_case( - Assets::ParimutuelShare(7, 8); - "assets_parimutuel_share" -)] -#[test_case( - Assets::CampaignAsset(7); - "assets_campaign_asset" -)] -#[test_case( - Assets::CustomAsset(7); - "assets_custom_asset" -)] -#[test_case( - XcmAsset::ForeignAsset(7); - "xcm_assets_foreign" -)] -fn convert_unsupported_asset(asset: T) -where - T: Copy + Debug + PartialEq, - AssetConvert: C2>, -{ - Zeitgeist::execute_with(|| assert_eq!(>::convert(asset), None)); +#[test] +fn convert_unsupported_currency() { + Zeitgeist::execute_with(|| { + assert_eq!(>::convert(CurrencyId::CombinatorialOutcome), None) + }); } diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 109a388dd..20d7350d3 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -26,7 +26,7 @@ use crate::{ test_net::{RococoNet, Sibling, TestNet, Zeitgeist}, }, xcm_config::{config::battery_station, fees::default_per_second}, - AssetManager, AssetRegistry, Balance, Balances, RuntimeOrigin, XTokens, + AssetRegistry, Balance, Balances, CurrencyId, RuntimeOrigin, Tokens, XTokens, ZeitgeistTreasuryAccount, }; @@ -36,7 +36,7 @@ use xcm::latest::{Junction, Junction::*, Junctions::*, MultiLocation, WeightLimi use xcm_emulator::TestExt; use zeitgeist_primitives::{ constants::{BalanceFractionalDecimals, BASE}, - types::{CustomMetadata, XcmAsset, XcmMetadata}, + types::{CustomMetadata, XcmMetadata}, }; #[test] @@ -49,8 +49,8 @@ fn transfer_ztg_to_sibling() { Sibling::execute_with(|| { treasury_initial_balance = - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!(AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), 0); + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), 0); register_foreign_ztg(None); }); @@ -59,7 +59,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(Balances::free_balance(sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - XcmAsset::Ztg, + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -82,14 +82,14 @@ fn transfer_ztg_to_sibling() { }); Sibling::execute_with(|| { - let current_balance = AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB); + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB); // Verify that BOB now has (amount transferred - fee) assert_eq!(current_balance, transfer_amount - ztg_fee()); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), treasury_initial_balance + ztg_fee() ) }); @@ -123,7 +123,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { Sibling::execute_with(|| { assert_eq!(Balances::free_balance(zeitgeist_parachain_account()), 0); - assert_eq!(AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), bob_initial_balance); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), bob_initial_balance); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(BOB), FOREIGN_ZTG_ID, @@ -143,7 +143,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { // Confirm that Bobs's balance is initial balance - amount transferred assert_eq!( - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), + Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), bob_initial_balance - transfer_amount ); }); @@ -181,12 +181,8 @@ fn transfer_btc_sibling_to_zeitgeist() { Zeitgeist::execute_with(|| { register_btc(None); - treasury_initial_balance = - AssetManager::free_balance(BTC_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!( - AssetManager::free_balance(BTC_ID.into(), &ALICE), - zeitgeist_alice_initial_balance, - ); + treasury_initial_balance = Tokens::free_balance(BTC_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(BTC_ID, &ALICE), zeitgeist_alice_initial_balance,); }); Sibling::execute_with(|| { @@ -200,8 +196,8 @@ fn transfer_btc_sibling_to_zeitgeist() { )); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - // Target chain will interpret XcmAsset::Ztg as BTC in this context. - XcmAsset::Ztg, + // Target chain will interpret CurrencyId::Ztg as BTC in this context. + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -232,13 +228,13 @@ fn transfer_btc_sibling_to_zeitgeist() { // Verify that remote Alice now has initial balance + amount transferred - fee assert_eq!( - AssetManager::free_balance(BTC_ID.into(), &ALICE), + Tokens::free_balance(BTC_ID, &ALICE), zeitgeist_alice_initial_balance + expected_adjusted, ); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(BTC_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(BTC_ID, &ZeitgeistTreasuryAccount::get()), // Align decimal fractional places treasury_initial_balance + adjusted_balance(btc(1), btc_fee()) ) @@ -256,7 +252,7 @@ fn transfer_btc_zeitgeist_to_sibling() { transfer_btc_sibling_to_zeitgeist(); Sibling::execute_with(|| { - assert_eq!(AssetManager::free_balance(BTC_ID.into(), &BOB), sibling_bob_initial_balance,); + assert_eq!(Tokens::free_balance(BTC_ID, &BOB), sibling_bob_initial_balance,); }); Zeitgeist::execute_with(|| { @@ -278,7 +274,7 @@ fn transfer_btc_zeitgeist_to_sibling() { )); // Confirm that Alice's balance is initial_balance - amount_transferred - assert_eq!(AssetManager::free_balance(BTC_ID.into(), &ALICE), 0); + assert_eq!(Tokens::free_balance(BTC_ID, &ALICE), 0); }); Sibling::execute_with(|| { @@ -306,7 +302,7 @@ fn transfer_roc_from_relay_chain() { Zeitgeist::execute_with(|| { register_foreign_parent(None); treasury_initial_balance = - AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &ZeitgeistTreasuryAccount::get()); + Tokens::free_balance(FOREIGN_PARENT_ID, &ZeitgeistTreasuryAccount::get()); }); RococoNet::execute_with(|| { @@ -325,10 +321,10 @@ fn transfer_roc_from_relay_chain() { Zeitgeist::execute_with(|| { let expected = transfer_amount - roc_fee(); let expected_adjusted = adjusted_balance(roc(1), expected); - assert_eq!(AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &BOB), expected_adjusted); + assert_eq!(Tokens::free_balance(FOREIGN_PARENT_ID, &BOB), expected_adjusted); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(FOREIGN_PARENT_ID, &ZeitgeistTreasuryAccount::get()), // Align decimal fractional places treasury_initial_balance + adjusted_balance(roc(1), roc_fee()) ) @@ -344,7 +340,7 @@ fn transfer_roc_to_relay_chain() { transfer_roc_from_relay_chain(); Zeitgeist::execute_with(|| { - let initial_balance = AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &ALICE); + let initial_balance = Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE); assert!(initial_balance >= transfer_amount); assert_ok!(XTokens::transfer( @@ -359,7 +355,7 @@ fn transfer_roc_to_relay_chain() { )); assert_eq!( - AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &ALICE), + Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE), initial_balance - transfer_amount_local ) }); @@ -381,8 +377,8 @@ fn transfer_ztg_to_sibling_with_custom_fee() { Sibling::execute_with(|| { treasury_initial_balance = - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!(AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), 0); + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), 0); register_foreign_ztg(None); let custom_metadata = CustomMetadata { @@ -405,7 +401,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { assert_eq!(Balances::free_balance(sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - XcmAsset::Ztg, + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -428,7 +424,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { }); Sibling::execute_with(|| { - let current_balance = AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB); + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB); let custom_fee = calc_fee(default_per_second(10) * 10); // Verify that BOB now has (amount transferred - fee) @@ -436,7 +432,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), treasury_initial_balance + custom_fee ) }); diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 2393a7634..a57a93716 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -30,7 +30,7 @@ use common_runtime::{ }; pub use frame_system::{ Call as SystemCall, CheckEra, CheckGenesis, CheckNonZeroSender, CheckNonce, CheckSpecVersion, - CheckTxVersion, CheckWeight, EnsureNever, + CheckTxVersion, CheckWeight, }; #[cfg(feature = "parachain")] pub use pallet_author_slot_filter::EligibilityValue; @@ -42,17 +42,12 @@ pub use crate::parachain_params::*; pub use crate::parameters::*; use alloc::vec; use frame_support::{ - traits::{ - AsEnsureOriginWithArg, ConstU32, Contains, EitherOfDiverse, EqualPrivilegeOnly, - InstanceFilter, - }, + traits::{ConstU32, Contains, EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter}, weights::{constants::RocksDbWeight, ConstantMultiplier, IdentityFee, Weight}, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureWithSuccess}; +use frame_system::{EnsureRoot, EnsureWithSuccess}; use orml_currencies::Call::transfer; -use pallet_assets::Call::{destroy_accounts, destroy_approvals, finish_destroy}; use pallet_collective::{EnsureProportionAtLeast, PrimeDefaultVote}; -use parity_scale_codec::Compact; use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256}; #[cfg(feature = "std")] use sp_version::NativeVersion; @@ -69,7 +64,7 @@ use zrml_swaps::Call::{ }; #[cfg(feature = "parachain")] use { - frame_support::traits::{Everything, Nothing}, + frame_support::traits::{AsEnsureOriginWithArg, Everything, Nothing}, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds}, xcm_config::{ asset_registry::CustomAssetProcessor, @@ -173,26 +168,6 @@ impl Contains for IsCallable { fn contains(call: &RuntimeCall) -> bool { #[allow(clippy::match_like_matches_macro)] match call { - // Asset destruction is managed. Instead of deleting those dispatchable calls, they are - // filtered here instead to allow root to interact in case of emergency. - RuntimeCall::CampaignAssets(inner_call) => match inner_call { - destroy_accounts { .. } => false, - destroy_approvals { .. } => false, - finish_destroy { .. } => false, - _ => true, - }, - RuntimeCall::CustomAssets(inner_call) => match inner_call { - destroy_accounts { .. } => false, - destroy_approvals { .. } => false, - finish_destroy { .. } => false, - _ => true, - }, - RuntimeCall::MarketAssets(inner_call) => match inner_call { - destroy_accounts { .. } => false, - destroy_approvals { .. } => false, - finish_destroy { .. } => false, - _ => true, - }, RuntimeCall::SimpleDisputes(_) => false, RuntimeCall::LiquidityMining(_) => false, RuntimeCall::PredictionMarkets(inner_call) => match inner_call { diff --git a/runtime/battery-station/src/parameters.rs b/runtime/battery-station/src/parameters.rs index 2cf328b9c..4e531ce4b 100644 --- a/runtime/battery-station/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -22,7 +22,7 @@ clippy::arithmetic_side_effects )] -use super::{CampaignAssetsInstance, Runtime, VERSION}; +use super::{Runtime, VERSION}; use frame_support::{ dispatch::DispatchClass, parameter_types, @@ -35,7 +35,6 @@ use frame_support::{ }; use frame_system::limits::{BlockLength, BlockWeights}; use orml_traits::parameter_type_with_key; -use pallet_assets::WeightInfo; use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; use sp_runtime::{ traits::{AccountIdConversion, Bounded}, @@ -64,46 +63,6 @@ parameter_types! { } parameter_types! { - // Asset-Router - pub DestroyAccountWeight: Weight = - >::WeightInfo::destroy_accounts(1); - pub DestroyApprovalWeight: Weight = - >::WeightInfo::destroy_approvals(1); - pub DestroyFinishWeight: Weight = - >::WeightInfo::finish_destroy(); - - // Assets (Campaign) - pub const CampaignAssetsAccountDeposit: Balance = deposit(1, 16); - pub const CampaignAssetsApprovalDeposit: Balance = ExistentialDeposit::get(); - /// The amount of native currency that is frozen during the whole lifetime - /// if an asset class. Freezing happens at asset class creation. - /// Irrelevant - No origin can successfully call the associated dispatchable call. - pub const CampaignAssetsDeposit: Balance = BASE; - pub const CampaignAssetsStringLimit: u32 = 256; - pub const CampaignAssetsMetadataDepositBase: Balance = deposit(1, 68); - pub const CampaignAssetsMetadataDepositPerByte: Balance = deposit(0, 1); - - // Assets (Custom) - pub const CustomAssetsAccountDeposit: Balance = deposit(1, 16); - pub const CustomAssetsApprovalDeposit: Balance = ExistentialDeposit::get(); - /// The amount of native currency that is frozen during the whole lifetime - /// of an asset class. Freezing happens at asset class creation. - pub const CustomAssetsDeposit: Balance = BASE; - pub const CustomAssetsStringLimit: u32 = 50; - pub const CustomAssetsMetadataDepositBase: Balance = deposit(1, 68); - pub const CustomAssetsMetadataDepositPerByte: Balance = deposit(0, 1); - - // Assets (Market) - pub const MarketAssetsAccountDeposit: Balance = deposit(1, 16); - pub const MarketAssetsApprovalDeposit: Balance = ExistentialDeposit::get(); - /// The amount of native currency that is frozen during the whole lifetime - /// of an asset class. Freezing happens at asset class creation. - /// Irrelevant - No origin can successfully call the associated dispatchable call. - pub const MarketAssetsDeposit: Balance = BASE; - pub const MarketAssetsStringLimit: u32 = 50; - pub const MarketAssetsMetadataDepositBase: Balance = deposit(1, 68); - pub const MarketAssetsMetadataDepositPerByte: Balance = deposit(0, 1); - // Authorized pub const AuthorizedPalletId: PalletId = AUTHORIZED_PALLET_ID; pub const CorrectionPeriod: BlockNumber = BLOCKS_PER_DAY; @@ -244,7 +203,7 @@ parameter_types! { pub const MaxLiquidityTreeDepth: u32 = 9u32; // ORML - pub const GetNativeCurrencyId: Assets = Asset::Ztg; + pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; // Prediction Market parameters /// (Slashable) Bond that is provided for creating an advised market that needs approval. @@ -403,8 +362,6 @@ parameter_types! { .build_or_panic(); // Transaction payment - /// A fee multiplier applied to the calculated fee factor for `CampaignAsset` - pub const CampaignAssetFeeMultiplier: u32 = 100; /// A fee mulitplier for Operational extrinsics to compute “virtual tip” /// to boost their priority. pub const OperationalFeeMultiplier: u8 = 5; @@ -512,17 +469,17 @@ parameter_type_with_key! { // are cleaned up automatically. In case of scalar outcomes, the market account can have dust. // Unless LPs use `pool_exit_with_exact_asset_amount`, there can be some dust pool shares remaining. // Explicit match arms are used to ensure new asset types are respected. - pub ExistentialDeposits: |currency_id: Currencies| -> Balance { + pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Currencies::CategoricalOutcome(_, _) => ExistentialDeposit::get(), - Currencies::ParimutuelShare(_, _) => ExistentialDeposit::get(), - Currencies::PoolShare(_) => ExistentialDeposit::get(), - Currencies::ScalarOutcome(_, _) => ExistentialDeposit::get(), + Asset::CategoricalOutcome(_,_) => ExistentialDeposit::get(), + Asset::CombinatorialOutcome => ExistentialDeposit::get(), + Asset::PoolShare(_) => ExistentialDeposit::get(), + Asset::ScalarOutcome(_,_) => ExistentialDeposit::get(), #[cfg(feature = "parachain")] - Currencies::ForeignAsset(id) => { + Asset::ForeignAsset(id) => { let maybe_metadata = < orml_asset_registry::Pallet as orml_traits::asset_registry::Inspect - >::metadata(&XcmAsset::ForeignAsset(*id)); + >::metadata(&Asset::ForeignAsset(*id)); if let Some(metadata) = maybe_metadata { return metadata.existential_deposit; @@ -531,7 +488,9 @@ parameter_type_with_key! { 1 } #[cfg(not(feature = "parachain"))] - Currencies::ForeignAsset(_) => ExistentialDeposit::get(), + Asset::ForeignAsset(_) => ExistentialDeposit::get(), + Asset::Ztg => ExistentialDeposit::get(), + Asset::ParimutuelShare(_,_) => ExistentialDeposit::get(), } }; } diff --git a/runtime/battery-station/src/xcm_config/asset_registry.rs b/runtime/battery-station/src/xcm_config/asset_registry.rs index 9deb85aa0..92746377d 100644 --- a/runtime/battery-station/src/xcm_config/asset_registry.rs +++ b/runtime/battery-station/src/xcm_config/asset_registry.rs @@ -15,7 +15,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{Balance, XcmAsset}; +use crate::{Balance, CurrencyId}; use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; @@ -29,11 +29,11 @@ use zeitgeist_primitives::types::CustomMetadata; /// Only pre check is to ensure an asset id was passed. pub struct CustomAssetProcessor; -impl AssetProcessor> for CustomAssetProcessor { +impl AssetProcessor> for CustomAssetProcessor { fn pre_register( - id: Option, + id: Option, metadata: AssetMetadata, - ) -> Result<(XcmAsset, AssetMetadata), DispatchError> { + ) -> Result<(CurrencyId, AssetMetadata), DispatchError> { match id { Some(id) => Ok((id, metadata)), None => Err(DispatchError::Other("asset-registry: AssetId is required")), @@ -41,7 +41,7 @@ impl AssetProcessor> for Custom } fn post_register( - _id: XcmAsset, + _id: CurrencyId, _asset_metadata: AssetMetadata, ) -> Result<(), DispatchError> { Ok(()) diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index c68d81f3d..e472ce980 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -17,9 +17,9 @@ use super::fees::{native_per_second, FixedConversionRateProvider}; use crate::{ - AccountId, AssetManager, AssetRegistry, Assets, Balance, MaxAssetsIntoHolding, MaxInstructions, - ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, RuntimeCall, - RuntimeOrigin, UnitWeightCost, UniversalLocation, UnknownTokens, XcmpQueue, + AccountId, AssetManager, AssetRegistry, Balance, CurrencyId, MaxAssetsIntoHolding, + MaxInstructions, ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, + RuntimeCall, RuntimeOrigin, UnitWeightCost, UniversalLocation, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; use alloc::vec::Vec; @@ -50,8 +50,8 @@ use xcm_builder::{ SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, TakeWeightCredit, }; -use xcm_executor::{traits::TransactAsset, Assets as ExecutorAssets, Config}; -use zeitgeist_primitives::{constants::BalanceFractionalDecimals, types::XcmAsset}; +use xcm_executor::{traits::TransactAsset, Assets, Config}; +use zeitgeist_primitives::{constants::BalanceFractionalDecimals, types::Asset}; pub mod battery_station { #[cfg(test)] @@ -155,7 +155,7 @@ impl TakeRevenue for ToTreasury { if let MultiAsset { id: Concrete(location), fun: Fungible(_amount) } = revenue { if let Ok(asset_id) = - >::convert(location) + >::convert(location) { let adj_am = AlignedFractionalMultiAssetTransactor::adjust_fractional_places(&revenue).fun; @@ -211,9 +211,9 @@ pub struct AlignedFractionalTransactAsset< } impl< - AssetRegistry: Inspect, + AssetRegistry: Inspect, FracDecPlaces: Get, - CurrencyIdConvert: Convert>, + CurrencyIdConvert: Convert>, TransactAssetDelegate: TransactAsset, > AlignedFractionalTransactAsset< @@ -224,41 +224,29 @@ impl< > { fn adjust_fractional_places(asset: &MultiAsset) -> MultiAsset { - let (asset_id, amount) = - if let Some(ref asset_id) = CurrencyIdConvert::convert(asset.clone()) { - if let Fungible(amount) = asset.fun { - (*asset_id, amount) - } else { - return asset.clone(); + if let Some(ref asset_id) = CurrencyIdConvert::convert(asset.clone()) { + if let Fungible(amount) = asset.fun { + let mut asset_updated = asset.clone(); + let native_decimals = u32::from(FracDecPlaces::get()); + let metadata = AssetRegistry::metadata(asset_id); + + if let Some(metadata) = metadata { + let decimals = metadata.decimals; + + asset_updated.fun = if decimals > native_decimals { + let power = decimals.saturating_sub(native_decimals); + let adjust_factor = 10u128.saturating_pow(power); + // Floors the adjusted token amount, thus no tokens are generated + Fungible(amount.saturating_div(adjust_factor)) + } else { + let power = native_decimals.saturating_sub(decimals); + let adjust_factor = 10u128.saturating_pow(power); + Fungible(amount.saturating_mul(adjust_factor)) + }; + + return asset_updated; } - } else { - return asset.clone(); - }; - - let currency = if let Ok(currency) = XcmAsset::try_from(asset_id) { - currency - } else { - return asset.clone(); - }; - - let metadata = AssetRegistry::metadata(¤cy); - if let Some(metadata) = metadata { - let mut asset_adjusted = asset.clone(); - let decimals = metadata.decimals; - let native_decimals = u32::from(FracDecPlaces::get()); - - asset_adjusted.fun = if decimals > native_decimals { - let power = decimals.saturating_sub(native_decimals); - let adjust_factor = 10u128.saturating_pow(power); - // Floors the adjusted token amount, thus no tokens are generated - Fungible(amount.saturating_div(adjust_factor)) - } else { - let power = native_decimals.saturating_sub(decimals); - let adjust_factor = 10u128.saturating_pow(power); - Fungible(amount.saturating_mul(adjust_factor)) - }; - - return asset_adjusted; + } } asset.clone() @@ -266,8 +254,8 @@ impl< } impl< - AssetRegistry: Inspect, - CurrencyIdConvert: Convert>, + AssetRegistry: Inspect, + CurrencyIdConvert: Convert>, FracDecPlaces: Get, TransactAssetDelegate: TransactAsset, > TransactAsset @@ -291,7 +279,7 @@ impl< asset: &MultiAsset, location: &MultiLocation, maybe_context: Option<&XcmContext>, - ) -> Result { + ) -> Result { let asset_adjusted = Self::adjust_fractional_places(asset); TransactAssetDelegate::withdraw_asset(&asset_adjusted, location, maybe_context) } @@ -301,7 +289,7 @@ impl< from: &MultiLocation, to: &MultiLocation, context: &XcmContext, - ) -> Result { + ) -> Result { let asset_adjusted = Self::adjust_fractional_places(asset); TransactAssetDelegate::transfer_asset(&asset_adjusted, from, to, context) } @@ -322,17 +310,17 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< UnknownTokens, // This means that this adapter should handle any token that `AssetConvert` can convert // using AssetManager and UnknownTokens in all other cases. - IsNativeConcrete, + IsNativeConcrete, // Our chain's account ID type (we can't get away without mentioning it explicitly). AccountId, // Convert an XCM `MultiLocation` into a local account id. LocationToAccountId, // The AssetId that corresponds to the native currency. - Assets, + CurrencyId, // Struct that provides functions to convert `Asset` <=> `MultiLocation`. AssetConvert, // In case of deposit failure, known assets will be placed in treasury. - DepositToAlternative, + DepositToAlternative, >; /// AssetConvert @@ -344,42 +332,33 @@ pub struct AssetConvert; /// Convert our `Asset` type into its `MultiLocation` representation. /// Other chains need to know how this conversion takes place in order to /// handle it on their side. -impl Convert> for AssetConvert { - fn convert(id: Assets) -> Option { +impl Convert> for AssetConvert { + fn convert(id: CurrencyId) -> Option { match id { - Assets::Ztg => Some(MultiLocation::new( + Asset::Ztg => Some(MultiLocation::new( 1, X2( Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(battery_station::KEY), ), )), - Assets::ForeignAsset(_) => { - let asset = XcmAsset::try_from(id).ok()?; - AssetRegistry::multilocation(&asset).ok()? - } + Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, } } } -impl Convert> for AssetConvert { - fn convert(id: XcmAsset) -> Option { - >>::convert(id.into()) - } -} - /// Convert an incoming `MultiLocation` into a `Asset` if possible. /// Here we need to know the canonical representation of all the tokens we handle in order to /// correctly convert their `MultiLocation` representation into our internal `Asset` type. -impl xcm_executor::traits::Convert for AssetConvert { - fn convert(location: MultiLocation) -> Result { +impl xcm_executor::traits::Convert for AssetConvert { + fn convert(location: MultiLocation) -> Result { match location { MultiLocation { parents: 0, interior: X1(GeneralKey { data, length }) } => { let key = &data[..data.len().min(length as usize)]; if key == battery_station::KEY { - return Ok(Assets::Ztg); + return Ok(CurrencyId::Ztg); } Err(location) @@ -392,28 +371,21 @@ impl xcm_executor::traits::Convert for AssetConvert { if para_id == u32::from(ParachainInfo::parachain_id()) { if key == battery_station::KEY { - return Ok(Assets::Ztg); + return Ok(CurrencyId::Ztg); } return Err(location); } - AssetRegistry::location_to_asset_id(location).ok_or(location).map(|a| a.into()) + AssetRegistry::location_to_asset_id(location).ok_or(location) } - _ => AssetRegistry::location_to_asset_id(location).ok_or(location).map(|a| a.into()), + _ => AssetRegistry::location_to_asset_id(location).ok_or(location), } } } -impl xcm_executor::traits::Convert for AssetConvert { - fn convert(location: MultiLocation) -> Result { - >::convert(location) - .and_then(|asset| asset.try_into().map_err(|_| location)) - } -} - -impl Convert> for AssetConvert { - fn convert(asset: MultiAsset) -> Option { +impl Convert> for AssetConvert { + fn convert(asset: MultiAsset) -> Option { if let MultiAsset { id: Concrete(location), .. } = asset { >::convert(location).ok() } else { @@ -422,8 +394,8 @@ impl Convert> for AssetConvert { } } -impl Convert> for AssetConvert { - fn convert(location: MultiLocation) -> Option { +impl Convert> for AssetConvert { + fn convert(location: MultiLocation) -> Option { >::convert(location).ok() } } diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index bc6178eee..21936a5b1 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{Balance, XcmAsset}; +use crate::{Balance, CurrencyId}; use core::marker::PhantomData; use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND}; use xcm::latest::MultiLocation; @@ -56,7 +56,7 @@ pub struct FixedConversionRateProvider(PhantomData impl< AssetRegistry: orml_traits::asset_registry::Inspect< - AssetId = XcmAsset, + AssetId = CurrencyId, Balance = Balance, CustomMetadata = CustomMetadata, >, diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 8925275e6..03afedb56 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -6,7 +6,6 @@ frame-system = { workspace = true } orml-currencies = { workspace = true } orml-tokens = { workspace = true } pallet-asset-tx-payment = { workspace = true } -pallet-assets = { workspace = true } pallet-author-inherent = { workspace = true, optional = true } pallet-author-mapping = { workspace = true, optional = true } pallet-author-slot-filter = { workspace = true, optional = true } @@ -50,7 +49,6 @@ std = [ "frame-support/std", "orml-currencies/std", "orml-tokens/std", - "pallet-assets/std", "pallet-asset-tx-payment/std", "pallet-author-inherent?/std", "pallet-author-mapping?/std", diff --git a/runtime/common/src/fees.rs b/runtime/common/src/fees.rs index ce52cdac5..062b9925a 100644 --- a/runtime/common/src/fees.rs +++ b/runtime/common/src/fees.rs @@ -40,8 +40,9 @@ macro_rules! impl_fee_types { } pub struct DealWithForeignFees; - impl OnUnbalanced> for DealWithForeignFees { - fn on_unbalanced(fees_and_tips: CreditOf) { + + impl OnUnbalanced> for DealWithForeignFees { + fn on_unbalanced(fees_and_tips: CreditOf) { // We have to manage the mint / burn ratio on the Zeitgeist chain, // but we do not have the responsibility and necessary knowledge to // manage the mint / burn ratio for any other chain. @@ -50,7 +51,7 @@ macro_rules! impl_fee_types { // on_unbalanced is not implemented for other currencies than the native currency // https://github.com/paritytech/substrate/blob/85415fb3a452dba12ff564e6b093048eed4c5aad/frame/treasury/src/lib.rs#L618-L627 // https://github.com/paritytech/substrate/blob/5ea6d95309aaccfa399c5f72e5a14a4b7c6c4ca1/frame/treasury/src/lib.rs#L490 - let res = AssetRouter::resolve( + let res = >::resolve( &TreasuryPalletId::get().into_account_truncating(), fees_and_tips, ); @@ -63,8 +64,6 @@ macro_rules! impl_fee_types { #[macro_export] macro_rules! impl_foreign_fees { () => { - #[cfg(feature = "parachain")] - use frame_support::ensure; use frame_support::{ pallet_prelude::InvalidTransaction, traits::{ @@ -87,7 +86,7 @@ macro_rules! impl_foreign_fees { }; use zeitgeist_primitives::{ math::fixed::{FixedDiv, FixedMul}, - types::{Assets, TxPaymentAssetId}, + types::TxPaymentAssetId, }; #[repr(u8)] @@ -97,13 +96,12 @@ macro_rules! impl_foreign_fees { NoAssetMetadata = 2, NoFeeFactor = 3, NonForeignAssetPaid = 4, - InvalidAssetType = 5, } // It does calculate foreign fees by extending transactions to include an optional // `AssetId` that specifies the asset to be used for payment (defaulting to the native // token on `None`), such that for each transaction the asset id can be specified. - // For real ZTG `None` is used and for DOT `Some(Currencies::ForeignAsset(0))` is used. + // For real ZTG `None` is used and for DOT `Some(Asset::Foreign(0))` is used. pub(crate) fn calculate_fee( native_fee: Balance, @@ -124,64 +122,15 @@ macro_rules! impl_foreign_fees { Ok(converted_fee) } - fn get_fee_factor_campaign_asset( - campaign_asset: CampaignAsset, - ) -> Result { - let ztg_supply = Balances::total_issuance(); - let campaign_asset_supply = AssetManager::total_issuance(campaign_asset.into()); - let fee_multiplier = Balance::from(CampaignAssetFeeMultiplier::get()); - - let ztg_div_campaign_supply = ztg_supply.checked_div(campaign_asset_supply).ok_or( - TransactionValidityError::Invalid(InvalidTransaction::Custom( - CustomTxError::FeeConversionArith as u8, - )), - )?; - - // Use neutral fee multiplier if the ZTG supply is 100x greater than the campaign - // asset supply. - if ztg_div_campaign_supply >= fee_multiplier { - Ok(BASE) - } else { - campaign_asset_supply.saturating_mul(fee_multiplier).bdiv(ztg_supply).map_err( - |_| { - TransactionValidityError::Invalid(InvalidTransaction::Custom( - CustomTxError::FeeConversionArith as u8, - )) - }, - ) - } - } - - #[cfg(not(feature = "parachain"))] - fn get_fee_factor_foreign_asset( - _foreign_asset: Currencies, - ) -> Result { - Err(TransactionValidityError::Invalid(InvalidTransaction::Custom( - CustomTxError::NoForeignAssetsOnStandaloneChain as u8, - ))) - } - #[cfg(feature = "parachain")] - fn get_fee_factor_foreign_asset( - foreign_asset: Currencies, + pub(crate) fn get_fee_factor( + currency_id: CurrencyId, ) -> Result { - ensure!( - foreign_asset.is_foreign_asset(), + let metadata = ::metadata(¤cy_id).ok_or( TransactionValidityError::Invalid(InvalidTransaction::Custom( - CustomTxError::InvalidAssetType as u8, - )) - ); - let metadata_asset: XcmAsset = - Assets::from(foreign_asset).try_into().map_err(|_| { - TransactionValidityError::Invalid(InvalidTransaction::Custom( - CustomTxError::InvalidAssetType as u8, - )) - })?; - - let metadata = ::metadata(&metadata_asset) - .ok_or(TransactionValidityError::Invalid(InvalidTransaction::Custom( CustomTxError::NoAssetMetadata as u8, - )))?; + )), + )?; let fee_factor = metadata.additional.xcm.fee_factor.ok_or(TransactionValidityError::Invalid( InvalidTransaction::Custom(CustomTxError::NoFeeFactor as u8), @@ -189,54 +138,47 @@ macro_rules! impl_foreign_fees { Ok(fee_factor) } - pub(crate) fn get_fee_factor(asset: Assets) -> Result { - if let Ok(campaign_asset) = CampaignAsset::try_from(asset) { - return get_fee_factor_campaign_asset(campaign_asset); - } else if let Ok(currency) = Currencies::try_from(asset) { - return get_fee_factor_foreign_asset(currency); - } - - Err(TransactionValidityError::Invalid(InvalidTransaction::Custom( - CustomTxError::InvalidAssetType as u8, - ))) - } - pub struct TTCBalanceToAssetBalance; - impl BalanceConversion for TTCBalanceToAssetBalance { + impl BalanceConversion for TTCBalanceToAssetBalance { type Error = TransactionValidityError; fn to_asset_balance( native_fee: Balance, - asset: Assets, + asset_id: TxPaymentAssetId, ) -> Result { - let fee_factor = get_fee_factor(asset)?; - let converted_fee = calculate_fee(native_fee, fee_factor)?; - Ok(converted_fee) + #[cfg(feature = "parachain")] + { + let currency_id = Asset::ForeignAsset(asset_id); + let fee_factor = get_fee_factor(currency_id)?; + let converted_fee = calculate_fee(native_fee, fee_factor)?; + Ok(converted_fee) + } + #[cfg(not(feature = "parachain"))] + { + Err(TransactionValidityError::Invalid(InvalidTransaction::Custom( + CustomTxError::NoForeignAssetsOnStandaloneChain as u8, + ))) + } } } pub struct TTCHandleCredit; - impl HandleCredit for TTCHandleCredit { - fn handle_credit(final_fee: CreditOf) { - let asset = final_fee.asset(); - - if CampaignAsset::try_from(asset).is_ok() { - drop(final_fee); - } else if Currencies::try_from(asset).is_ok() { - DealWithForeignFees::on_unbalanced(final_fee); - } + impl HandleCredit for TTCHandleCredit { + fn handle_credit(final_fee: CreditOf) { + // Handle the final fee and tip, e.g. by transferring to the treasury. + DealWithForeignFees::on_unbalanced(final_fee); } } - pub struct TxCharger; - impl pallet_asset_tx_payment::OnChargeAssetTransaction for TxCharger { - type AssetId = Assets; + pub struct TokensTxCharger; + impl pallet_asset_tx_payment::OnChargeAssetTransaction for TokensTxCharger { + type AssetId = TxPaymentAssetId; type Balance = Balance; - type LiquidityInfo = CreditOf; + type LiquidityInfo = CreditOf; fn withdraw_fee( who: &AccountId, - _call: &RuntimeCall, + call: &RuntimeCall, _dispatch_info: &DispatchInfoOf, asset_id: Self::AssetId, native_fee: Self::Balance, @@ -250,13 +192,13 @@ macro_rules! impl_foreign_fees { let converted_fee = TTCBalanceToAssetBalance::to_asset_balance(native_fee, asset_id)? .max(min_converted_fee); - + let currency_id = Asset::ForeignAsset(asset_id); let can_withdraw = - >::can_withdraw(asset_id, who, converted_fee); + >::can_withdraw(currency_id, who, converted_fee); if can_withdraw != WithdrawConsequence::Success { return Err(InvalidTransaction::Payment.into()); } - >::withdraw(asset_id, who, converted_fee) + >::withdraw(currency_id, who, converted_fee) .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment)) } @@ -265,23 +207,35 @@ macro_rules! impl_foreign_fees { _dispatch_info: &DispatchInfoOf, _post_info: &PostDispatchInfoOf, corrected_native_fee: Self::Balance, - _tip: Self::Balance, + tip: Self::Balance, paid: Self::LiquidityInfo, ) -> Result<(), TransactionValidityError> { let min_converted_fee = if corrected_native_fee.is_zero() { Zero::zero() } else { One::one() }; - - let asset = paid.asset(); + let asset_id = match paid.asset() { + Asset::ForeignAsset(asset_id) => asset_id, + _ => { + return Err(TransactionValidityError::Invalid(InvalidTransaction::Custom( + CustomTxError::NonForeignAssetPaid as u8, + ))); + } + }; // Convert the corrected fee and tip into the asset used for payment. let converted_fee = - TTCBalanceToAssetBalance::to_asset_balance(corrected_native_fee, asset)? + TTCBalanceToAssetBalance::to_asset_balance(corrected_native_fee, asset_id)? .max(min_converted_fee); + let converted_tip = TTCBalanceToAssetBalance::to_asset_balance(tip, asset_id)?; + // Calculate how much refund we should return. + let (final_fee, refund) = paid.split(converted_fee); // Refund to the account that paid the fees. If this fails, the account might have dropped // below the existential balance. In that case we don't refund anything. - let (final_fee, refund) = paid.split(converted_fee); - let _ = AssetRouter::resolve(who, refund); + let _ = >::resolve(who, refund); + + // Handle the final fee and tip, e.g. by transferring to the treasury. + // Note: The `corrected_native_fee` already includes the `tip`. TTCHandleCredit::handle_credit(final_fee); + Ok(()) } } @@ -348,12 +302,7 @@ macro_rules! impl_market_creator_fees { macro_rules! fee_tests { () => { use crate::*; - use frame_support::{ - assert_noop, assert_ok, - dispatch::DispatchClass, - traits::{fungible::Unbalanced, fungibles::Create}, - weights::Weight, - }; + use frame_support::{assert_noop, assert_ok, dispatch::DispatchClass, weights::Weight}; use orml_traits::MultiCurrency; use pallet_asset_tx_payment::OnChargeAssetTransaction; use sp_core::H256; @@ -396,126 +345,21 @@ macro_rules! fee_tests { frame_system::GenesisConfig::default().build_storage::().unwrap().into(); t.execute_with(|| { let fee_and_tip_balance = 10 * ExistentialDeposit::get(); - let fees_and_tips = AssetRouter::issue(Asset::ForeignAsset(0), fee_and_tip_balance); + let fees_and_tips = >::issue( + Asset::ForeignAsset(0), + fee_and_tip_balance, + ); assert!( - AssetRouter::free_balance(Asset::ForeignAsset(0), &Treasury::account_id()) - .is_zero() + Tokens::free_balance(Asset::ForeignAsset(0), &Treasury::account_id()).is_zero() ); DealWithForeignFees::on_unbalanced(fees_and_tips); assert_eq!( - AssetRouter::free_balance(Asset::ForeignAsset(0), &Treasury::account_id()), + Tokens::free_balance(Asset::ForeignAsset(0), &Treasury::account_id()), fee_and_tip_balance, ); }); } - #[test] - fn fee_payment_campaign_assets_withdraws_correct_amount() { - let mut t: sp_io::TestExternalities = - frame_system::GenesisConfig::default().build_storage::().unwrap().into(); - t.execute_with(|| { - let asset = Asset::CampaignAsset(0); - let alice = AccountId::from([0u8; 32]); - let initial_balance: Balance = 1_000_000_000_000; - let native_fee: Balance = 1_000_000; - let fee_multiplier: Balance = CampaignAssetFeeMultiplier::get().into(); - - let ztg_supply = initial_balance * fee_multiplier - 1; - let fee_factor = - initial_balance.saturating_mul(fee_multiplier).bdiv(ztg_supply).unwrap(); - let expected_fee = calculate_fee(native_fee, fee_factor).unwrap(); - let mock_call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); - - Balances::set_total_issuance(ztg_supply); - assert_ok!(AssetRouter::create(asset, alice.clone(), true, 1)); - assert_ok!(AssetManager::deposit(asset, &alice, initial_balance)); - - assert_eq!( - TxCharger::withdraw_fee( - &alice, - &mock_call, - &Default::default(), - asset, - native_fee, - 0 - ) - .unwrap() - .peek(), - expected_fee - ); - assert_eq!( - AssetManager::total_balance(asset, &alice), - initial_balance - expected_fee - ); - }); - } - - fn campaign_asset_throttled_fee_common() -> CreditOf { - let asset = Asset::CampaignAsset(0); - let alice = AccountId::from([0u8; 32]); - let initial_balance: Balance = 1_000_000_000_000; - let native_fee: Balance = 1_000_000; - let fee_multiplier: Balance = CampaignAssetFeeMultiplier::get().into(); - - let ztg_supply = initial_balance.bmul(fee_multiplier * initial_balance + 1).unwrap(); - let mock_call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); - - Balances::set_total_issuance(ztg_supply); - assert_ok!(AssetRouter::create(asset, alice.clone(), true, 1)); - assert_ok!(AssetManager::deposit(asset, &alice, initial_balance)); - - let withdrawn = TxCharger::withdraw_fee( - &alice, - &mock_call, - &Default::default(), - asset, - native_fee, - 0, - ) - .unwrap(); - assert_eq!(withdrawn.peek(), native_fee); - assert_eq!(AssetManager::total_balance(asset, &alice), initial_balance - native_fee); - - withdrawn - } - - #[test] - fn fee_payment_campaign_assets_withdraws_correct_amount_throttled() { - let mut t: sp_io::TestExternalities = - frame_system::GenesisConfig::default().build_storage::().unwrap().into(); - t.execute_with(|| { - let _ = campaign_asset_throttled_fee_common(); - }); - } - - #[test] - fn fee_payment_campaign_assets_corrects_reimburses_and_burns_fees_properly() { - let mut t: sp_io::TestExternalities = - frame_system::GenesisConfig::default().build_storage::().unwrap().into(); - t.execute_with(|| { - let asset = Asset::CampaignAsset(0); - let withdrawn = campaign_asset_throttled_fee_common(); - let amount = withdrawn.peek(); - let native_fee_adjusted: Balance = 1_000_000 / 2; - let alice = AccountId::from([0u8; 32]); - let initial_balance: Balance = 1_000_000_000_000; - let fee_multiplier = get_fee_factor(asset).unwrap(); - let fee = calculate_fee(native_fee_adjusted, fee_multiplier).unwrap(); - let expected = initial_balance - fee; - - assert_ok!(TxCharger::correct_and_deposit_fee( - &alice, - &Default::default(), - &Default::default(), - native_fee_adjusted, - 0, - withdrawn - )); - assert_eq!(AssetManager::total_balance(asset, &alice), expected); - assert_eq!(AssetManager::total_issuance(Asset::CampaignAsset(0)), expected); - }); - } - #[test] fn fee_multiplier_can_grow_from_zero() { let minimum_multiplier = MinimumMultiplier::get(); @@ -541,59 +385,65 @@ macro_rules! fee_tests { .unwrap() .into(); t.execute_with(|| { - let alice = AccountId::from([0u8; 32]); - let fee_factor = 143_120_520; - let custom_metadata = CustomMetadata { - xcm: XcmMetadata { fee_factor: Some(fee_factor) }, - ..Default::default() - }; - let meta: AssetMetadata = AssetMetadata { - decimals: 10, - name: "Polkadot".into(), - symbol: "DOT".into(), - existential_deposit: ExistentialDeposit::get(), - location: Some(xcm::VersionedMultiLocation::V3( - xcm::latest::MultiLocation::parent(), - )), - additional: custom_metadata, - }; - let dot = Asset::ForeignAsset(0); - - assert_ok!(AssetRegistry::register_asset( - RuntimeOrigin::root(), - meta.clone(), - Some(dot.try_into().unwrap()) - )); - assert_ok!(AssetManager::deposit(dot, &Treasury::account_id(), BASE)); - - let free_balance_treasury_before = - AssetManager::free_balance(dot, &Treasury::account_id()); - let free_balance_alice_before = AssetManager::free_balance(dot, &alice); - let corrected_native_fee = BASE; - let paid = AssetRouter::issue(dot, 2 * BASE); - let paid_balance = paid.peek(); - let tip = 0u128; - assert_ok!(TxCharger::correct_and_deposit_fee( - &alice, - &Default::default(), - &Default::default(), - corrected_native_fee, - tip, - paid, - )); - - let treasury_gain = AssetManager::free_balance(dot, &Treasury::account_id()) - - free_balance_treasury_before; - let alice_gain = - AssetManager::free_balance(dot, &alice) - free_balance_alice_before; - - let decimals = meta.decimals; - let base = 10u128.checked_pow(decimals).unwrap(); - - let dot_fee = ((corrected_native_fee * fee_factor) + (base / 2)) / base; - assert_eq!(dot_fee, treasury_gain); - assert_eq!(143_120_520, treasury_gain); - assert_eq!(paid_balance - treasury_gain, alice_gain); + { + let alice = AccountId::from([0u8; 32]); + let fee_factor = 143_120_520; + let custom_metadata = CustomMetadata { + xcm: XcmMetadata { fee_factor: Some(fee_factor) }, + ..Default::default() + }; + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Polkadot".into(), + symbol: "DOT".into(), + existential_deposit: ExistentialDeposit::get(), + location: Some(xcm::VersionedMultiLocation::V3(xcm::latest::MultiLocation::parent())), + additional: custom_metadata, + }; + let dot = Asset::ForeignAsset(0); + + assert_ok!(AssetRegistry::register_asset(RuntimeOrigin::root(), meta.clone(), Some(dot))); + + + assert_ok!(>::deposit(dot, &Treasury::account_id(), BASE)); + + let mock_call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); + let mock_dispatch_info = frame_support::dispatch::DispatchInfo { + weight: frame_support::dispatch::Weight::zero(), + class: DispatchClass::Normal, + pays_fee: frame_support::dispatch::Pays::Yes, + }; + let mock_post_info = frame_support::dispatch::PostDispatchInfo { + actual_weight: Some(frame_support::dispatch::Weight::zero()), + pays_fee: frame_support::dispatch::Pays::Yes, + }; + + let free_balance_treasury_before = Tokens::free_balance(dot, &Treasury::account_id()); + let free_balance_alice_before = Tokens::free_balance(dot, &alice); + let corrected_native_fee = BASE; + let paid = >::issue(dot, 2 * BASE); + let paid_balance = paid.peek(); + let tip = 0u128; + assert_ok!(>::correct_and_deposit_fee( + &alice, + &mock_dispatch_info, + &mock_post_info, + corrected_native_fee, + tip, + paid, + )); + + let treasury_gain = Tokens::free_balance(dot, &Treasury::account_id()) - free_balance_treasury_before; + let alice_gain = Tokens::free_balance(dot, &alice) - free_balance_alice_before; + + let decimals = meta.decimals; + let base = 10u128.checked_pow(decimals).unwrap(); + + let dot_fee = ((corrected_native_fee * fee_factor) + (base / 2)) / base; + assert_eq!(dot_fee, treasury_gain); + assert_eq!(143_120_520, treasury_gain); + assert_eq!(paid_balance - treasury_gain, alice_gain); + } }); } @@ -619,7 +469,7 @@ macro_rules! fee_tests { additional: custom_metadata, }; let dot_asset_id = 0u32; - let dot = XcmAsset::ForeignAsset(dot_asset_id); + let dot = Asset::ForeignAsset(dot_asset_id); assert_ok!(AssetRegistry::register_asset( RuntimeOrigin::root(), @@ -627,7 +477,7 @@ macro_rules! fee_tests { Some(dot) )); - assert_eq!(get_fee_factor(dot.into()).unwrap(), 143_120_520u128); + assert_eq!(get_fee_factor(dot).unwrap(), 143_120_520u128); }); } @@ -670,7 +520,7 @@ macro_rules! fee_tests { additional: custom_metadata, }; let dot_asset_id = 0u32; - let dot = XcmAsset::ForeignAsset(dot_asset_id); + let dot = Asset::ForeignAsset(dot_asset_id); assert_ok!(AssetRegistry::register_asset( RuntimeOrigin::root(), @@ -679,7 +529,7 @@ macro_rules! fee_tests { )); assert_noop!( - get_fee_factor(dot.into()), + get_fee_factor(dot), TransactionValidityError::Invalid(InvalidTransaction::Custom(3u8)) ); }); @@ -704,15 +554,15 @@ macro_rules! fee_tests { location: None, additional: custom_metadata, }; - let non_location_token = XcmAsset::ForeignAsset(1); + let non_location_token = Asset::ForeignAsset(1); assert_ok!(AssetRegistry::register_asset( RuntimeOrigin::root(), meta, - Some(Assets::from(non_location_token).try_into().unwrap()) + Some(non_location_token) )); - assert_eq!(get_fee_factor(non_location_token.into()).unwrap(), 10_393); + assert_eq!(get_fee_factor(non_location_token).unwrap(), 10_393); }); } @@ -744,20 +594,29 @@ macro_rules! fee_tests { assert_ok!(AssetRegistry::register_asset( RuntimeOrigin::root(), meta, - Some(dot.try_into().unwrap()) + Some(dot) )); - let fees_and_tips = AssetRouter::issue(dot, 0); - assert_ok!(AssetManager::deposit(dot, &Treasury::account_id(), BASE)); + let fees_and_tips = >::issue(dot, 0); + assert_ok!(>::deposit( + dot, + &Treasury::account_id(), + BASE + )); let mock_call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); + let mock_dispatch_info = frame_support::dispatch::DispatchInfo { + weight: frame_support::dispatch::Weight::zero(), + class: DispatchClass::Normal, + pays_fee: frame_support::dispatch::Pays::Yes, + }; assert_eq!( - TxCharger::withdraw_fee( + >::withdraw_fee( &Treasury::account_id(), &mock_call, - &Default::default(), - dot, + &mock_dispatch_info, + dot_asset_id, BASE / 2, 0, ) @@ -768,5 +627,5 @@ macro_rules! fee_tests { }); } } - }; + } } diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index eff5c92c0..03a5a3c04 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -55,17 +55,12 @@ macro_rules! decl_common_types { use orml_traits::MultiCurrency; use sp_runtime::{generic, DispatchError, DispatchResult, SaturatedConversion}; use zeitgeist_primitives::traits::{DeployPoolApi, DistributeFees, MarketCommonsPalletApi}; - use zrml_market_commons::migrations::MigrateScoringRuleAmmCdaHybridAndMarketId; - use zrml_neo_swaps::migration::MigratePoolReservesToBoundedBTreeMap; pub type Block = generic::Block; type Address = sp_runtime::MultiAddress; - type Migrations = ( - MigrateScoringRuleAmmCdaHybridAndMarketId, - MigratePoolReservesToBoundedBTreeMap, - ); + type Migrations = (); pub type Executive = frame_executive::Executive< Runtime, @@ -94,11 +89,6 @@ macro_rules! decl_common_types { pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; - // Asset instances - type CustomAssetsInstance = pallet_assets::Instance1; - type CampaignAssetsInstance = pallet_assets::Instance2; - type MarketAssetsInstance = pallet_assets::Instance3; - // Governance type AdvisoryCommitteeInstance = pallet_collective::Instance1; type AdvisoryCommitteeMembershipInstance = pallet_membership::Instance1; @@ -285,9 +275,6 @@ macro_rules! create_runtime { Multisig: pallet_multisig::{Call, Event, Pallet, Storage} = 14, Bounties: pallet_bounties::{Call, Event, Pallet, Storage} = 15, AssetTxPayment: pallet_asset_tx_payment::{Event, Pallet} = 16, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event} = 17, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event} = 18, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event} = 19, // Governance Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 20, @@ -322,7 +309,6 @@ macro_rules! create_runtime { NeoSwaps: zrml_neo_swaps::{Call, Event, Pallet, Storage} = 60, Orderbook: zrml_orderbook::{Call, Event, Pallet, Storage} = 61, Parimutuel: zrml_parimutuel::{Call, Event, Pallet, Storage} = 62, - AssetRouter: zrml_asset_router::{Pallet} = 63, HybridRouter: zrml_hybrid_router::{Call, Event, Pallet, Storage} = 64, $($additional_pallets)* @@ -567,7 +553,7 @@ macro_rules! impl_config_traits { #[cfg(feature = "parachain")] impl orml_asset_registry::Config for Runtime { - type AssetId = XcmAsset; + type AssetId = CurrencyId; type AssetProcessor = CustomAssetProcessor; type AuthorityOrigin = AsEnsureOriginWithArg; type Balance = Balance; @@ -578,14 +564,14 @@ macro_rules! impl_config_traits { impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = AssetRouter; + type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type WeightInfo = weights::orml_currencies::WeightInfo; } pub struct CurrencyHooks(sp_std::marker::PhantomData); impl - orml_traits::currency::MutationHooks + orml_traits::currency::MutationHooks for CurrencyHooks { type OnDust = orml_tokens::TransferDust; @@ -602,7 +588,7 @@ macro_rules! impl_config_traits { type Amount = Amount; type Balance = Balance; type CurrencyHooks = CurrencyHooks; - type CurrencyId = Currencies; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = DustRemovalWhitelist; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -622,7 +608,7 @@ macro_rules! impl_config_traits { type AccountIdToMultiLocation = AccountIdToMultiLocation; type Balance = Balance; type BaseXcmWeight = BaseXcmWeight; - type CurrencyId = XcmAsset; + type CurrencyId = CurrencyId; type CurrencyIdConvert = AssetConvert; type RuntimeEvent = RuntimeEvent; type MaxAssetsForTransfer = MaxAssetsForTransfer; @@ -635,109 +621,6 @@ macro_rules! impl_config_traits { type XcmExecutor = xcm_executor::XcmExecutor; } - // Required for runtime benchmarks - pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } - } - - impl pallet_assets::Config for Runtime { - type ApprovalDeposit = CustomAssetsApprovalDeposit; - type AssetAccountDeposit = CustomAssetsAccountDeposit; - type AssetDeposit = CustomAssetsDeposit; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Destroyer = AssetRouter; - type Extra = (); - type ForceOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - type Freezer = (); - type MetadataDepositBase = CustomAssetsMetadataDepositBase; - type MetadataDepositPerByte = CustomAssetsMetadataDepositPerByte; - // TODO(#1176): Figure out sensible number after benchmark on reference machine - type RemoveItemsLimit = ConstU32<{ 50 }>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = CustomAssetsStringLimit; - type WeightInfo = weights::pallet_assets::WeightInfo; - } - - impl pallet_assets::Config for Runtime { - type ApprovalDeposit = CampaignAssetsApprovalDeposit; - type AssetAccountDeposit = CampaignAssetsAccountDeposit; - type AssetDeposit = CampaignAssetsDeposit; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Destroyer = AssetRouter; - type Extra = (); - type ForceOrigin = EnsureRootOrTwoThirdsCouncil; - type Freezer = (); - type MetadataDepositBase = CampaignAssetsMetadataDepositBase; - type MetadataDepositPerByte = CampaignAssetsMetadataDepositPerByte; - // TODO(#1176): Figure out sensible number after benchmark on reference machine - type RemoveItemsLimit = ConstU32<{ 50 }>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = CampaignAssetsStringLimit; - type WeightInfo = weights::pallet_assets::WeightInfo; - } - - // Required for runtime benchmarks - pallet_assets::runtime_benchmarks_enabled! { - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } - } - - impl pallet_assets::Config for Runtime { - type ApprovalDeposit = MarketAssetsApprovalDeposit; - type AssetAccountDeposit = MarketAssetsAccountDeposit; - type AssetDeposit = MarketAssetsDeposit; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Destroyer = AssetRouter; - type Extra = (); - type ForceOrigin = EnsureRootOrAllTechnicalCommittee; - type Freezer = (); - type MetadataDepositBase = MarketAssetsMetadataDepositBase; - type MetadataDepositPerByte = MarketAssetsMetadataDepositPerByte; - // TODO(#1176): Figure out sensible number after benchmark on reference machine - type RemoveItemsLimit = ConstU32<{ 50 }>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = MarketAssetsStringLimit; - type WeightInfo = weights::pallet_assets::WeightInfo; - } - impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; @@ -1095,8 +978,8 @@ macro_rules! impl_config_traits { impl pallet_asset_tx_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type Fungibles = AssetRouter; - type OnChargeAssetTransaction = TxCharger; + type Fungibles = Tokens; + type OnChargeAssetTransaction = TokensTxCharger; } impl pallet_transaction_payment::Config for Runtime { @@ -1167,22 +1050,6 @@ macro_rules! impl_config_traits { #[cfg(feature = "parachain")] impl parachain_info::Config for Runtime {} - impl zrml_asset_router::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyAccountWeight; - type DestroyApprovalWeight = DestroyApprovalWeight; - type DestroyFinishWeight = DestroyFinishWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; - } - impl zrml_authorized::Config for Runtime { type AuthorizedDisputeResolutionOrigin = EnsureRootOrMoreThanHalfAdvisoryCommittee; type Currency = Balances; @@ -1260,12 +1127,7 @@ macro_rules! impl_config_traits { impl zrml_prediction_markets::Config for Runtime { type AdvisoryBond = AdvisoryBond; type AdvisoryBondSlashPercentage = AdvisoryBondSlashPercentage; - type AssetCreator = AssetRouter; - type AssetDestroyer = AssetRouter; type ApproveOrigin = EnsureRootOrMoreThanOneThirdAdvisoryCommittee; - type AssetManager = AssetManager; - #[cfg(feature = "parachain")] - type AssetRegistry = AssetRegistry; type Authorized = Authorized; type Currency = Balances; type Court = Court; @@ -1295,8 +1157,6 @@ macro_rules! impl_config_traits { type MinCategories = MinCategories; type MaxEditReasonLen = MaxEditReasonLen; type MaxRejectReasonLen = MaxRejectReasonLen; - // Can be a tuple of hooks - type OnStateTransition = (Parimutuel,); type OracleBond = OracleBond; type OutsiderBond = OutsiderBond; type PalletId = PmPalletId; @@ -1305,6 +1165,9 @@ macro_rules! impl_config_traits { type RejectOrigin = EnsureRootOrMoreThanTwoThirdsAdvisoryCommittee; type RequestEditOrigin = EnsureRootOrMoreThanOneThirdAdvisoryCommittee; type ResolveOrigin = EnsureRoot; + type AssetManager = AssetManager; + #[cfg(feature = "parachain")] + type AssetRegistry = AssetRegistry; type SimpleDisputes = SimpleDisputes; type Slash = Treasury; type ValidityBond = ValidityBond; @@ -1356,8 +1219,9 @@ macro_rules! impl_config_traits { } impl zrml_swaps::Config for Runtime { - type Asset = Assets; + type Asset = Asset; type RuntimeEvent = RuntimeEvent; + type MultiCurrency = AssetManager; type ExitFee = ExitFee; type MinAssets = MinAssets; type MaxAssets = MaxAssets; @@ -1366,7 +1230,6 @@ macro_rules! impl_config_traits { type MaxWeight = MaxWeight; type MinWeight = MinWeight; type PalletId = SwapsPalletId; - type AssetManager = AssetManager; type WeightInfo = zrml_swaps::weights::WeightInfo; } @@ -1401,14 +1264,12 @@ macro_rules! impl_config_traits { } impl zrml_parimutuel::Config for Runtime { - type AssetCreator = AssetRouter; - type AssetDestroyer = AssetRouter; - type AssetManager = AssetManager; type ExternalFees = MarketCreatorFee; + type RuntimeEvent = RuntimeEvent; type MarketCommons = MarketCommons; + type AssetManager = AssetManager; type MinBetSize = MinBetSize; type PalletId = ParimutuelPalletId; - type RuntimeEvent = RuntimeEvent; type WeightInfo = zrml_parimutuel::weights::WeightInfo; } @@ -1514,7 +1375,6 @@ macro_rules! create_runtime_api { list_benchmark!(list, extra, frame_system, SystemBench::); orml_list_benchmark!(list, extra, orml_currencies, crate::benchmarks::currencies); orml_list_benchmark!(list, extra, orml_tokens, crate::benchmarks::tokens); - list_benchmark!(list, extra, pallet_assets, CustomAssets); list_benchmark!(list, extra, pallet_balances, Balances); list_benchmark!(list, extra, pallet_bounties, Bounties); list_benchmark!(list, extra, pallet_collective, AdvisoryCommittee); @@ -1620,7 +1480,6 @@ macro_rules! create_runtime_api { add_benchmark!(params, batches, frame_system, SystemBench::); orml_add_benchmark!(params, batches, orml_currencies, crate::benchmarks::currencies); orml_add_benchmark!(params, batches, orml_tokens, crate::benchmarks::tokens); - add_benchmark!(params, batches, pallet_assets, CustomAssets); add_benchmark!(params, batches, pallet_balances, Balances); add_benchmark!(params, batches, pallet_bounties, Bounties); add_benchmark!(params, batches, pallet_collective, AdvisoryCommittee); @@ -1930,16 +1789,16 @@ macro_rules! create_runtime_api { asset_in: &Asset, asset_out: &Asset, with_fees: bool, - ) -> Balance { - Swaps::get_spot_price(pool_id, asset_in, asset_out, with_fees).ok().unwrap_or(0) + ) -> SerdeWrapper { + SerdeWrapper(Swaps::get_spot_price(pool_id, asset_in, asset_out, with_fees).ok().unwrap_or(0)) } fn pool_account_id(pool_id: &PoolId) -> AccountId { Swaps::pool_account_id(pool_id) } - fn pool_shares_id(pool_id: PoolId) -> Asset { - Asset::PoolShare(pool_id) + fn pool_shares_id(pool_id: PoolId) -> Asset> { + Asset::PoolShare(SerdeWrapper(pool_id)) } } @@ -2009,7 +1868,7 @@ macro_rules! create_common_benchmark_logic { pub(crate) mod currencies { use super::utils::{lookup_of_account, set_balance}; use crate::{ - AccountId, Amount, AssetManager, Balance, Assets, ExistentialDeposit, + AccountId, Amount, AssetManager, Balance, CurrencyId, ExistentialDeposit, GetNativeCurrencyId, Runtime }; use frame_benchmarking::{account, vec, whitelisted_caller}; @@ -2023,8 +1882,8 @@ macro_rules! create_common_benchmark_logic { }; const SEED: u32 = 0; - const NATIVE: Assets = GetNativeCurrencyId::get(); - const ASSET: Assets = Asset::CategoricalOutcome(0, 0); + const NATIVE: CurrencyId = GetNativeCurrencyId::get(); + const ASSET: CurrencyId = Asset::CategoricalOutcome(0, 0); runtime_benchmarks! { { Runtime, orml_currencies } @@ -2124,15 +1983,15 @@ macro_rules! create_common_benchmark_logic { pub(crate) mod tokens { use super::utils::{lookup_of_account, set_balance as update_balance}; - use crate::{AccountId, Balance, Tokens, Runtime}; + use crate::{AccountId, Balance, CurrencyId, Tokens, Runtime}; use frame_benchmarking::{account, vec, whitelisted_caller}; use frame_system::RawOrigin; use orml_benchmarking::runtime_benchmarks; use orml_traits::MultiCurrency; - use zeitgeist_primitives::{constants::BASE, types::Currencies}; + use zeitgeist_primitives::{constants::BASE, types::Asset}; const SEED: u32 = 0; - const ASSET: Currencies = Currencies::ForeignAsset(7); + const ASSET: CurrencyId = Asset::CategoricalOutcome(0, 0); runtime_benchmarks! { { Runtime, orml_tokens } @@ -2141,7 +2000,7 @@ macro_rules! create_common_benchmark_logic { let amount: Balance = BASE; let from: AccountId = whitelisted_caller(); - update_balance(ASSET.into(), &from, amount); + update_balance(ASSET, &from, amount); let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to.clone()); @@ -2154,7 +2013,7 @@ macro_rules! create_common_benchmark_logic { let amount: Balance = BASE; let from: AccountId = whitelisted_caller(); - update_balance(ASSET.into(), &from, amount); + update_balance(ASSET, &from, amount); let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to); @@ -2165,7 +2024,7 @@ macro_rules! create_common_benchmark_logic { transfer_keep_alive { let from: AccountId = whitelisted_caller(); - update_balance(ASSET.into(), &from, 2 * BASE); + update_balance(ASSET, &from, 2 * BASE); let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to.clone()); @@ -2177,7 +2036,7 @@ macro_rules! create_common_benchmark_logic { force_transfer { let from: AccountId = account("from", 0, SEED); let from_lookup = lookup_of_account(from.clone()); - update_balance(ASSET.into(), &from, 2 * BASE); + update_balance(ASSET, &from, 2 * BASE); let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to.clone()); @@ -2207,7 +2066,7 @@ macro_rules! create_common_benchmark_logic { } pub(crate) mod utils { - use crate::{AccountId, AssetManager, Balance, Assets, Runtime, + use crate::{AccountId, AssetManager, Balance, CurrencyId, Runtime, }; use frame_support::assert_ok; use orml_traits::MultiCurrencyExtended; @@ -2219,7 +2078,7 @@ macro_rules! create_common_benchmark_logic { ::Lookup::unlookup(who) } - pub fn set_balance(currency_id: Assets, who: &AccountId, balance: Balance) { + pub fn set_balance(currency_id: CurrencyId, who: &AccountId, balance: Balance) { assert_ok!(>::update_balance( currency_id, who, diff --git a/runtime/common/src/weights/mod.rs b/runtime/common/src/weights/mod.rs index 27fae644e..e1f0aac08 100644 --- a/runtime/common/src/weights/mod.rs +++ b/runtime/common/src/weights/mod.rs @@ -32,7 +32,6 @@ cfg_if::cfg_if! { pub mod frame_system; pub mod orml_currencies; pub mod orml_tokens; -pub mod pallet_assets; pub mod pallet_balances; pub mod pallet_bounties; pub mod pallet_collective; diff --git a/runtime/common/src/weights/pallet_assets.rs b/runtime/common/src/weights/pallet_assets.rs deleted file mode 100644 index 421d14405..000000000 --- a/runtime/common/src/weights/pallet_assets.rs +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright 2022-2024 Forecasting Technologies LTD. -// Copyright 2021-2022 Zeitgeist PM LLC. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -//! Autogenerated weights for pallet_assets -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: `2024-04-15`, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `zeitgeist-benchmark`, CPU: `AMD EPYC 7601 32-Core Processor` -//! EXECUTION: `Some(Wasm)`, WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` - -// Executed Command: -// ./target/production/zeitgeist -// benchmark -// pallet -// --chain=dev -// --steps=50 -// --repeat=20 -// --pallet=pallet_assets -// --extrinsic=* -// --execution=wasm -// --wasm-execution=compiled -// --heap-pages=4096 -// --template=./misc/frame_weight_template.hbs -// --header=./HEADER_GPL3 -// --output=./runtime/common/src/weights/ - -#![allow(unused_parens)] -#![allow(unused_imports)] - -use core::marker::PhantomData; -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; - -/// Weight functions for pallet_assets (automatically generated) -pub struct WeightInfo(PhantomData); -impl pallet_assets::weights::WeightInfo for WeightInfo { - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - fn create() -> Weight { - // Proof Size summary in bytes: - // Measured: `285` - // Estimated: `5304` - // Minimum execution time: 45_580 nanoseconds. - Weight::from_parts(46_600_000, 5304) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - fn force_create() -> Weight { - // Proof Size summary in bytes: - // Measured: `109` - // Estimated: `2697` - // Minimum execution time: 24_880 nanoseconds. - Weight::from_parts(25_780_000, 2697) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: AssetRouter DestroyAssets (r:1 w:1) - /// Proof: AssetRouter DestroyAssets (max_values: Some(1), max_size: Some(40962), added: 41457, mode: MaxEncodedLen) - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: AssetRouter IndestructibleAssets (r:1 w:0) - /// Proof: AssetRouter IndestructibleAssets (max_values: Some(1), max_size: Some(38914), added: 39409, mode: MaxEncodedLen) - fn start_destroy() -> Weight { - // Proof Size summary in bytes: - // Measured: `452` - // Estimated: `83563` - // Minimum execution time: 37_170 nanoseconds. - Weight::from_parts(38_891_000, 83563) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:51 w:50) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - /// Storage: System Account (r:50 w:50) - /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// The range of component `c` is `[0, 50]`. - fn destroy_accounts(c: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `413 + c * (241 ±0)` - // Estimated: `5286 + c * (5196 ±0)` - // Minimum execution time: 35_950 nanoseconds. - Weight::from_parts(27_443_769, 5286) - // Standard Error: 187_706 - .saturating_add(Weight::from_parts(27_794_683, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(1)) - .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 5196).saturating_mul(c.into())) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Approvals (r:51 w:50) - /// Proof: CustomAssets Approvals (max_values: None, max_size: Some(160), added: 2635, mode: MaxEncodedLen) - /// The range of component `a` is `[0, 50]`. - fn destroy_approvals(a: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `499 + a * (86 ±0)` - // Estimated: `5332 + a * (2635 ±0)` - // Minimum execution time: 29_050 nanoseconds. - Weight::from_parts(47_517_757, 5332) - // Standard Error: 73_418 - .saturating_add(Weight::from_parts(24_955_809, 0).saturating_mul(a.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) - .saturating_add(T::DbWeight::get().writes(1)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) - .saturating_add(Weight::from_parts(0, 2635).saturating_mul(a.into())) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Metadata (r:1 w:0) - /// Proof: CustomAssets Metadata (max_values: None, max_size: Some(152), added: 2627, mode: MaxEncodedLen) - fn finish_destroy() -> Weight { - // Proof Size summary in bytes: - // Measured: `376` - // Estimated: `5324` - // Minimum execution time: 27_720 nanoseconds. - Weight::from_parts(29_560_000, 5324) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:1 w:1) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - fn mint() -> Weight { - // Proof Size summary in bytes: - // Measured: `376` - // Estimated: `5286` - // Minimum execution time: 47_300 nanoseconds. - Weight::from_parts(48_191_000, 5286) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:1 w:1) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - fn burn() -> Weight { - // Proof Size summary in bytes: - // Measured: `481` - // Estimated: `5286` - // Minimum execution time: 56_541 nanoseconds. - Weight::from_parts(57_720_000, 5286) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:2 w:2) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - fn transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `520` - // Estimated: `10482` - // Minimum execution time: 66_921 nanoseconds. - Weight::from_parts(81_670_000, 10482) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:2 w:2) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - fn transfer_keep_alive() -> Weight { - // Proof Size summary in bytes: - // Measured: `520` - // Estimated: `10482` - // Minimum execution time: 70_230 nanoseconds. - Weight::from_parts(71_750_000, 10482) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:2 w:2) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - fn force_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `520` - // Estimated: `10482` - // Minimum execution time: 81_470 nanoseconds. - Weight::from_parts(83_780_000, 10482) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: CustomAssets Asset (r:1 w:0) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:1 w:1) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - fn freeze() -> Weight { - // Proof Size summary in bytes: - // Measured: `481` - // Estimated: `5286` - // Minimum execution time: 31_790 nanoseconds. - Weight::from_parts(32_470_000, 5286) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:0) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:1 w:1) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - fn thaw() -> Weight { - // Proof Size summary in bytes: - // Measured: `481` - // Estimated: `5286` - // Minimum execution time: 31_250 nanoseconds. - Weight::from_parts(32_661_000, 5286) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - fn freeze_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `410` - // Estimated: `2697` - // Minimum execution time: 24_740 nanoseconds. - Weight::from_parts(25_781_000, 2697) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - fn thaw_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `410` - // Estimated: `2697` - // Minimum execution time: 23_900 nanoseconds. - Weight::from_parts(25_160_000, 2697) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Metadata (r:1 w:0) - /// Proof: CustomAssets Metadata (max_values: None, max_size: Some(152), added: 2627, mode: MaxEncodedLen) - fn transfer_ownership() -> Weight { - // Proof Size summary in bytes: - // Measured: `376` - // Estimated: `5324` - // Minimum execution time: 29_690 nanoseconds. - Weight::from_parts(30_700_000, 5324) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - fn set_team() -> Weight { - // Proof Size summary in bytes: - // Measured: `376` - // Estimated: `2697` - // Minimum execution time: 26_960 nanoseconds. - Weight::from_parts(28_210_000, 2697) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:0) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Metadata (r:1 w:1) - /// Proof: CustomAssets Metadata (max_values: None, max_size: Some(152), added: 2627, mode: MaxEncodedLen) - /// The range of component `n` is `[0, 50]`. - /// The range of component `s` is `[0, 50]`. - fn set_metadata(n: u32, s: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `376` - // Estimated: `5324` - // Minimum execution time: 35_650 nanoseconds. - Weight::from_parts(44_501_301, 5324) - // Standard Error: 2_153 - .saturating_add(Weight::from_parts(14_080, 0).saturating_mul(n.into())) - // Standard Error: 2_153 - .saturating_add(Weight::from_parts(8_285, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:0) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Metadata (r:1 w:1) - /// Proof: CustomAssets Metadata (max_values: None, max_size: Some(152), added: 2627, mode: MaxEncodedLen) - fn clear_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `569` - // Estimated: `5324` - // Minimum execution time: 45_190 nanoseconds. - Weight::from_parts(45_860_000, 5324) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:0) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Metadata (r:1 w:1) - /// Proof: CustomAssets Metadata (max_values: None, max_size: Some(152), added: 2627, mode: MaxEncodedLen) - /// The range of component `n` is `[0, 50]`. - /// The range of component `s` is `[0, 50]`. - fn force_set_metadata(n: u32, s: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `183` - // Estimated: `5324` - // Minimum execution time: 23_380 nanoseconds. - Weight::from_parts(29_007_377, 5324) - // Standard Error: 1_825 - .saturating_add(Weight::from_parts(5_450, 0).saturating_mul(n.into())) - // Standard Error: 1_825 - .saturating_add(Weight::from_parts(9_969, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:0) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Metadata (r:1 w:1) - /// Proof: CustomAssets Metadata (max_values: None, max_size: Some(152), added: 2627, mode: MaxEncodedLen) - fn force_clear_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `569` - // Estimated: `5324` - // Minimum execution time: 36_830 nanoseconds. - Weight::from_parts(44_640_000, 5324) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - fn force_asset_status() -> Weight { - // Proof Size summary in bytes: - // Measured: `376` - // Estimated: `2697` - // Minimum execution time: 22_220 nanoseconds. - Weight::from_parts(26_050_000, 2697) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Approvals (r:1 w:1) - /// Proof: CustomAssets Approvals (max_values: None, max_size: Some(160), added: 2635, mode: MaxEncodedLen) - fn approve_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `410` - // Estimated: `5332` - // Minimum execution time: 40_120 nanoseconds. - Weight::from_parts(49_370_000, 5332) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Approvals (r:1 w:1) - /// Proof: CustomAssets Approvals (max_values: None, max_size: Some(160), added: 2635, mode: MaxEncodedLen) - /// Storage: CustomAssets Account (r:2 w:2) - /// Proof: CustomAssets Account (max_values: None, max_size: Some(114), added: 2589, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - fn transfer_approved() -> Weight { - // Proof Size summary in bytes: - // Measured: `687` - // Estimated: `13117` - // Minimum execution time: 95_171 nanoseconds. - Weight::from_parts(106_670_000, 13117) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(5)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Approvals (r:1 w:1) - /// Proof: CustomAssets Approvals (max_values: None, max_size: Some(160), added: 2635, mode: MaxEncodedLen) - fn cancel_approval() -> Weight { - // Proof Size summary in bytes: - // Measured: `577` - // Estimated: `5332` - // Minimum execution time: 52_550 nanoseconds. - Weight::from_parts(54_550_000, 5332) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: CustomAssets Asset (r:1 w:1) - /// Proof: CustomAssets Asset (max_values: None, max_size: Some(222), added: 2697, mode: MaxEncodedLen) - /// Storage: CustomAssets Approvals (r:1 w:1) - /// Proof: CustomAssets Approvals (max_values: None, max_size: Some(160), added: 2635, mode: MaxEncodedLen) - fn force_cancel_approval() -> Weight { - // Proof Size summary in bytes: - // Measured: `577` - // Estimated: `5332` - // Minimum execution time: 53_511 nanoseconds. - Weight::from_parts(55_160_000, 5332) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } -} diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index f2a25adea..a32835f6e 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -11,7 +11,6 @@ orml-currencies = { workspace = true } orml-tokens = { workspace = true } orml-traits = { workspace = true } pallet-asset-tx-payment = { workspace = true } -pallet-assets = { workspace = true } pallet-balances = { workspace = true } pallet-bounties = { workspace = true } pallet-collective = { workspace = true } @@ -108,7 +107,6 @@ xcm-executor = { workspace = true, optional = true } common-runtime = { workspace = true } zeitgeist-primitives = { workspace = true } -zrml-asset-router = { workspace = true } zrml-authorized = { workspace = true } zrml-court = { workspace = true } zrml-global-disputes = { workspace = true, optional = true } @@ -186,7 +184,6 @@ runtime-benchmarks = [ "orml-benchmarking", "orml-tokens/runtime-benchmarks", "orml-xtokens?/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", "pallet-author-inherent?/runtime-benchmarks", "pallet-author-mapping?/runtime-benchmarks", "pallet-author-slot-filter?/runtime-benchmarks", @@ -236,7 +233,6 @@ std = [ "orml-currencies/std", "orml-tokens/std", "orml-traits/std", - "pallet-assets/std", "pallet-asset-tx-payment/std", "pallet-balances/std", "pallet-bounties/std", @@ -350,7 +346,6 @@ try-runtime = [ "pallet-preimage/try-runtime", # Money runtime pallets - "pallet-assets/try-runtime", "pallet-asset-tx-payment/try-runtime", "pallet-balances/try-runtime", "pallet-bounties/try-runtime", @@ -377,7 +372,6 @@ try-runtime = [ "orml-xtokens?/try-runtime", # Zeitgeist runtime pallets - "zrml-asset-router/try-runtime", "zrml-authorized/try-runtime", "zrml-court/try-runtime", "zrml-hybrid-router/try-runtime", diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs index 525a2e369..5343a2bff 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -18,7 +18,8 @@ use crate::{ xcm_config::config::{general_key, zeitgeist}, - AccountId, AssetRegistry, Assets, Balance, ExistentialDeposit, Runtime, RuntimeOrigin, System, + AccountId, AssetRegistry, Balance, CurrencyId, ExistentialDeposit, Runtime, RuntimeOrigin, + System, }; use frame_support::{assert_ok, traits::GenesisBuild}; use orml_traits::asset_registry::AssetMetadata; @@ -27,10 +28,10 @@ use xcm::{ latest::{Junction::Parachain, Junctions::X2, MultiLocation}, VersionedMultiLocation, }; -use zeitgeist_primitives::types::{CustomMetadata, XcmAsset}; +use zeitgeist_primitives::types::{Asset, CustomMetadata}; pub(super) struct ExtBuilder { - balances: Vec<(AccountId, Assets, Balance)>, + balances: Vec<(AccountId, CurrencyId, Balance)>, parachain_id: u32, } @@ -41,7 +42,7 @@ impl Default for ExtBuilder { } impl ExtBuilder { - pub fn set_balances(mut self, balances: Vec<(AccountId, Assets, Balance)>) -> Self { + pub fn set_balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { self.balances = balances; self } @@ -53,7 +54,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let native_currency_id = Assets::Ztg; + let native_currency_id = CurrencyId::Ztg; pallet_balances::GenesisConfig:: { balances: self .balances @@ -71,9 +72,6 @@ impl ExtBuilder { .balances .into_iter() .filter(|(_, currency_id, _)| *currency_id != native_currency_id) - .map(|(account_id, currency_id, initial_balance)| { - (account_id, currency_id.try_into().unwrap(), initial_balance) - }) .collect::>(), } .assimilate_storage(&mut t) @@ -106,11 +104,11 @@ pub const BOB: AccountId32 = AccountId32::new([1u8; 32]); pub const PARA_ID_SIBLING: u32 = 3000; /// IDs that are used to represent tokens from other chains -pub const FOREIGN_ZTG_ID: XcmAsset = XcmAsset::ForeignAsset(0); -pub const FOREIGN_PARENT_ID: XcmAsset = XcmAsset::ForeignAsset(1); -pub const FOREIGN_SIBLING_ID: XcmAsset = XcmAsset::ForeignAsset(2); -pub const BTC_ID: XcmAsset = XcmAsset::ForeignAsset(3); -pub const ETH_ID: XcmAsset = XcmAsset::ForeignAsset(4); +pub const FOREIGN_ZTG_ID: Asset = CurrencyId::ForeignAsset(0); +pub const FOREIGN_PARENT_ID: Asset = CurrencyId::ForeignAsset(1); +pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); +pub const BTC_ID: Asset = CurrencyId::ForeignAsset(3); +pub const ETH_ID: Asset = CurrencyId::ForeignAsset(4); #[inline] pub(super) const fn ztg(amount: Balance) -> Balance { diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs index c8f212d12..11f94529b 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -17,8 +17,8 @@ // along with Zeitgeist. If not, see . use crate::{ - parameters::ZeitgeistTreasuryAccount, xcm_config::config::zeitgeist, Assets, DmpQueue, Runtime, - RuntimeOrigin, XcmpQueue, + parameters::ZeitgeistTreasuryAccount, xcm_config::config::zeitgeist, CurrencyId, DmpQueue, + Runtime, RuntimeOrigin, XcmpQueue, }; use frame_support::{traits::GenesisBuild, weights::Weight}; use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; @@ -99,9 +99,9 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { ExtBuilder::default() .set_balances(vec![ - (ALICE, Assets::Ztg, ztg(10)), - (ALICE, FOREIGN_PARENT_ID.into(), dot(10)), - (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID.into(), dot(10)), + (ALICE, CurrencyId::Ztg, ztg(10)), + (ALICE, FOREIGN_PARENT_ID, dot(10)), + (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, dot(10)), ]) .set_parachain_id(parachain_id) .build() diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs index d23021334..da7e3ee03 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -26,96 +26,81 @@ use crate::{ test_net::Zeitgeist, }, xcm_config::config::{general_key, zeitgeist, AssetConvert}, - Assets, CustomMetadata, ScalarPosition, XcmAsset, + CurrencyId, }; -use core::fmt::Debug; + use frame_support::assert_err; use sp_runtime::traits::Convert as C2; -use test_case::test_case; use xcm::latest::{Junction::*, Junctions::*, MultiLocation}; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; -fn convert_common_native(expected: T) -where - T: Copy + Debug + PartialEq, - AssetConvert: C1 + C2>, -{ +#[test] +fn convert_native() { assert_eq!(zeitgeist::KEY.to_vec(), vec![0, 1]); // The way Ztg is represented relative within the Zeitgeist runtime let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(zeitgeist::KEY))); - assert_eq!(>::convert(ztg_location_inner), Ok(expected)); + assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg)); // The canonical way Ztg is represented out in the wild Zeitgeist::execute_with(|| { - assert_eq!(>::convert(expected), Some(foreign_ztg_multilocation())) + assert_eq!( + >::convert(CurrencyId::Ztg), + Some(foreign_ztg_multilocation()) + ) }); } -fn convert_common_non_native( - expected: T, - multilocation: MultiLocation, - register: fn(Option), -) where - T: Copy + Debug + PartialEq, - AssetConvert: C1 + C2>, -{ +#[test] +fn convert_any_registered_parent_multilocation() { Zeitgeist::execute_with(|| { - assert_err!(>::convert(multilocation), multilocation); - assert_eq!(>::convert(expected), None); + assert_err!( + >::convert(foreign_parent_multilocation()), + foreign_parent_multilocation() + ); + + assert_eq!(>::convert(FOREIGN_PARENT_ID), None); + // Register parent as foreign asset in the Zeitgeist parachain - register(None); - assert_eq!(>::convert(multilocation), Ok(expected)); - assert_eq!(>::convert(expected), Some(multilocation)); - }); -} + register_foreign_parent(None); -#[test] -fn convert_native_assets() { - convert_common_native(Assets::Ztg); -} + assert_eq!( + >::convert(foreign_parent_multilocation()), + Ok(FOREIGN_PARENT_ID), + ); -#[test] -fn convert_native_xcm_assets() { - convert_common_native(XcmAsset::Ztg); + assert_eq!( + >::convert(FOREIGN_PARENT_ID), + Some(foreign_parent_multilocation()) + ); + }); } #[test] -fn convert_any_registered_parent_multilocation_assets() { - convert_common_non_native( - Assets::from(FOREIGN_PARENT_ID), - foreign_parent_multilocation(), - register_foreign_parent, - ); -} +fn convert_any_registered_sibling_multilocation() { + Zeitgeist::execute_with(|| { + assert_err!( + >::convert(foreign_sibling_multilocation()), + foreign_sibling_multilocation() + ); -#[test] -fn convert_any_registered_parent_multilocation_xcm_assets() { - convert_common_non_native( - XcmAsset::try_from(Assets::from(FOREIGN_PARENT_ID)).unwrap(), - foreign_parent_multilocation(), - register_foreign_parent, - ); -} + assert_eq!(>::convert(FOREIGN_SIBLING_ID), None); -#[test] -fn convert_any_registered_sibling_multilocation_assets() { - convert_common_non_native( - Assets::from(FOREIGN_SIBLING_ID), - foreign_sibling_multilocation(), - register_foreign_sibling, - ); -} + // Register sibling as foreign asset in the Zeitgeist parachain + register_foreign_sibling(None); -#[test] -fn convert_any_registered_sibling_multilocation_xcm_assets() { - convert_common_non_native( - XcmAsset::try_from(Assets::from(FOREIGN_SIBLING_ID)).unwrap(), - foreign_sibling_multilocation(), - register_foreign_sibling, - ); + assert_eq!( + >::convert(foreign_sibling_multilocation()), + Ok(FOREIGN_SIBLING_ID), + ); + + assert_eq!( + >::convert(FOREIGN_SIBLING_ID), + Some(foreign_sibling_multilocation()) + ); + }); } #[test] @@ -124,46 +109,13 @@ fn convert_unkown_multilocation() { MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(&[42]))); Zeitgeist::execute_with(|| { - assert!(>::convert(unknown_location).is_err()); + assert!(>::convert(unknown_location).is_err()); }); } -#[test_case( - Assets::CategoricalOutcome(7, 8); - "assets_categorical" -)] -#[test_case( - Assets::ScalarOutcome(7, ScalarPosition::Long); - "assets_scalar" -)] -#[test_case( - Assets::PoolShare(7); - "assets_pool_share" -)] -#[test_case( - Assets::ForeignAsset(7); - "assets_foreign" -)] -#[test_case( - Assets::ParimutuelShare(7, 8); - "assets_parimutuel_share" -)] -#[test_case( - Assets::CampaignAsset(7); - "assets_campaign_asset" -)] -#[test_case( - Assets::CustomAsset(7); - "assets_custom_asset" -)] -#[test_case( - XcmAsset::ForeignAsset(7); - "xcm_assets_foreign" -)] -fn convert_unsupported_asset(asset: T) -where - T: Copy + Debug + PartialEq, - AssetConvert: C2>, -{ - Zeitgeist::execute_with(|| assert_eq!(>::convert(asset), None)); +#[test] +fn convert_unsupported_currency() { + Zeitgeist::execute_with(|| { + assert_eq!(>::convert(CurrencyId::CombinatorialOutcome), None) + }); } diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index bb5d66e3a..2638f76f5 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -26,7 +26,7 @@ use crate::{ test_net::{PolkadotNet, Sibling, TestNet, Zeitgeist}, }, xcm_config::{config::zeitgeist, fees::default_per_second}, - AssetManager, AssetRegistry, Balance, Balances, RuntimeOrigin, XTokens, + AssetRegistry, Balance, Balances, CurrencyId, RuntimeOrigin, Tokens, XTokens, ZeitgeistTreasuryAccount, }; @@ -36,7 +36,7 @@ use xcm::latest::{Junction, Junction::*, Junctions::*, MultiLocation, WeightLimi use xcm_emulator::TestExt; use zeitgeist_primitives::{ constants::{BalanceFractionalDecimals, BASE}, - types::{CustomMetadata, XcmAsset, XcmMetadata}, + types::{CustomMetadata, XcmMetadata}, }; #[test] @@ -49,8 +49,8 @@ fn transfer_ztg_to_sibling() { Sibling::execute_with(|| { treasury_initial_balance = - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!(AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), 0); + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), 0); register_foreign_ztg(None); }); @@ -59,7 +59,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(Balances::free_balance(sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - XcmAsset::Ztg, + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -82,14 +82,14 @@ fn transfer_ztg_to_sibling() { }); Sibling::execute_with(|| { - let current_balance = AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB); + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB); // Verify that BOB now has (amount transferred - fee) assert_eq!(current_balance, transfer_amount - ztg_fee()); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), treasury_initial_balance + ztg_fee() ) }); @@ -123,7 +123,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { Sibling::execute_with(|| { assert_eq!(Balances::free_balance(zeitgeist_parachain_account()), 0); - assert_eq!(AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), bob_initial_balance); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), bob_initial_balance); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(BOB), FOREIGN_ZTG_ID, @@ -143,7 +143,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { // Confirm that Bobs's balance is initial balance - amount transferred assert_eq!( - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), + Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), bob_initial_balance - transfer_amount ); }); @@ -181,12 +181,8 @@ fn transfer_btc_sibling_to_zeitgeist() { Zeitgeist::execute_with(|| { register_btc(None); - treasury_initial_balance = - AssetManager::free_balance(BTC_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!( - AssetManager::free_balance(BTC_ID.into(), &ALICE), - zeitgeist_alice_initial_balance, - ); + treasury_initial_balance = Tokens::free_balance(BTC_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(BTC_ID, &ALICE), zeitgeist_alice_initial_balance,); }); Sibling::execute_with(|| { @@ -200,8 +196,8 @@ fn transfer_btc_sibling_to_zeitgeist() { )); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - // Target chain will interpret XcmAsset::Ztg as BTC in this context. - XcmAsset::Ztg, + // Target chain will interpret CurrencyId::Ztg as BTC in this context. + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -232,13 +228,13 @@ fn transfer_btc_sibling_to_zeitgeist() { // Verify that remote Alice now has initial balance + amount transferred - fee assert_eq!( - AssetManager::free_balance(BTC_ID.into(), &ALICE), + Tokens::free_balance(BTC_ID, &ALICE), zeitgeist_alice_initial_balance + expected_adjusted, ); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(BTC_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(BTC_ID, &ZeitgeistTreasuryAccount::get()), // Align decimal fractional places treasury_initial_balance + adjusted_balance(btc(1), btc_fee()) ) @@ -256,7 +252,7 @@ fn transfer_btc_zeitgeist_to_sibling() { transfer_btc_sibling_to_zeitgeist(); Sibling::execute_with(|| { - assert_eq!(AssetManager::free_balance(BTC_ID.into(), &BOB), sibling_bob_initial_balance,); + assert_eq!(Tokens::free_balance(BTC_ID, &BOB), sibling_bob_initial_balance,); }); Zeitgeist::execute_with(|| { @@ -278,7 +274,7 @@ fn transfer_btc_zeitgeist_to_sibling() { )); // Confirm that Alice's balance is initial_balance - amount_transferred - assert_eq!(AssetManager::free_balance(BTC_ID.into(), &ALICE), 0); + assert_eq!(Tokens::free_balance(BTC_ID, &ALICE), 0); }); Sibling::execute_with(|| { @@ -308,12 +304,8 @@ fn transfer_eth_sibling_to_zeitgeist() { Zeitgeist::execute_with(|| { register_eth(None); - treasury_initial_balance = - AssetManager::free_balance(ETH_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!( - AssetManager::free_balance(ETH_ID.into(), &ALICE), - zeitgeist_alice_initial_balance, - ); + treasury_initial_balance = Tokens::free_balance(ETH_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(ETH_ID, &ALICE), zeitgeist_alice_initial_balance,); }); Sibling::execute_with(|| { @@ -333,8 +325,8 @@ fn transfer_eth_sibling_to_zeitgeist() { )); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - // Target chain will interpret XcmAsset::Ztg as ETH in this context. - XcmAsset::Ztg, + // Target chain will interpret CurrencyId::Ztg as ETH in this context. + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -365,13 +357,13 @@ fn transfer_eth_sibling_to_zeitgeist() { // Verify that remote Alice now has initial balance + amount transferred - fee assert_eq!( - AssetManager::free_balance(ETH_ID.into(), &ALICE), + Tokens::free_balance(ETH_ID, &ALICE), zeitgeist_alice_initial_balance + expected_adjusted, ); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(ETH_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(ETH_ID, &ZeitgeistTreasuryAccount::get()), // Align decimal fractional places treasury_initial_balance + adjusted_balance(eth(1), eth_fee()) ) @@ -389,7 +381,7 @@ fn transfer_eth_zeitgeist_to_sibling() { transfer_eth_sibling_to_zeitgeist(); Sibling::execute_with(|| { - assert_eq!(AssetManager::free_balance(ETH_ID.into(), &BOB), sibling_bob_initial_balance,); + assert_eq!(Tokens::free_balance(ETH_ID, &BOB), sibling_bob_initial_balance,); }); Zeitgeist::execute_with(|| { @@ -411,7 +403,7 @@ fn transfer_eth_zeitgeist_to_sibling() { )); // Confirm that Alice's balance is initial_balance - amount_transferred - assert_eq!(AssetManager::free_balance(ETH_ID.into(), &ALICE), 0); + assert_eq!(Tokens::free_balance(ETH_ID, &ALICE), 0); }); Sibling::execute_with(|| { @@ -453,10 +445,7 @@ fn transfer_dot_from_relay_chain() { }); Zeitgeist::execute_with(|| { - assert_eq!( - AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &BOB), - transfer_amount - dot_fee() - ); + assert_eq!(Tokens::free_balance(FOREIGN_PARENT_ID, &BOB), transfer_amount - dot_fee()); }); } @@ -468,7 +457,7 @@ fn transfer_dot_to_relay_chain() { transfer_dot_from_relay_chain(); Zeitgeist::execute_with(|| { - let initial_balance = AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &ALICE); + let initial_balance = Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE); assert!(initial_balance >= transfer_amount); assert_ok!(XTokens::transfer( @@ -483,7 +472,7 @@ fn transfer_dot_to_relay_chain() { )); assert_eq!( - AssetManager::free_balance(FOREIGN_PARENT_ID.into(), &ALICE), + Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE), initial_balance - transfer_amount ) }); @@ -505,8 +494,8 @@ fn transfer_ztg_to_sibling_with_custom_fee() { Sibling::execute_with(|| { treasury_initial_balance = - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()); - assert_eq!(AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB), 0); + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB), 0); register_foreign_ztg(None); let custom_metadata = CustomMetadata { @@ -529,7 +518,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { assert_eq!(Balances::free_balance(sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( RuntimeOrigin::signed(ALICE), - XcmAsset::Ztg, + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -552,7 +541,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { }); Sibling::execute_with(|| { - let current_balance = AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &BOB); + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB); let custom_fee = calc_fee(default_per_second(10) * 10); // Verify that BOB now has (amount transferred - fee) @@ -563,7 +552,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { // Verify that fees (of foreign currency) have been put into treasury assert_eq!( - AssetManager::free_balance(FOREIGN_ZTG_ID.into(), &ZeitgeistTreasuryAccount::get()), + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), treasury_initial_balance + custom_fee ) }); diff --git a/runtime/zeitgeist/src/lib.rs b/runtime/zeitgeist/src/lib.rs index 4fcde1f80..cef575871 100644 --- a/runtime/zeitgeist/src/lib.rs +++ b/runtime/zeitgeist/src/lib.rs @@ -30,7 +30,7 @@ use common_runtime::{ }; pub use frame_system::{ Call as SystemCall, CheckEra, CheckGenesis, CheckNonZeroSender, CheckNonce, CheckSpecVersion, - CheckTxVersion, CheckWeight, EnsureNever, EnsureSigned, + CheckTxVersion, CheckWeight, }; #[cfg(feature = "parachain")] pub use pallet_author_slot_filter::EligibilityValue; @@ -41,15 +41,11 @@ pub use crate::parachain_params::*; pub use crate::parameters::*; use alloc::vec; use frame_support::{ - traits::{ - AsEnsureOriginWithArg, ConstU32, Contains, EitherOfDiverse, EqualPrivilegeOnly, - InstanceFilter, Nothing, - }, + traits::{ConstU32, Contains, EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter, Nothing}, weights::{constants::RocksDbWeight, ConstantMultiplier, IdentityFee, Weight}, }; use frame_system::{EnsureRoot, EnsureWithSuccess}; use pallet_collective::{EnsureProportionAtLeast, EnsureProportionMoreThan, PrimeDefaultVote}; -use parity_scale_codec::Compact; use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256}; #[cfg(feature = "std")] use sp_version::NativeVersion; @@ -58,7 +54,7 @@ use zeitgeist_primitives::{constants::*, types::*}; use zrml_rikiddo::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; #[cfg(feature = "parachain")] use { - frame_support::traits::Everything, + frame_support::traits::{AsEnsureOriginWithArg, Everything}, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds}, xcm_config::{ asset_registry::CustomAssetProcessor, @@ -116,7 +112,6 @@ impl Contains for IsCallable { kill_prefix, kill_storage, set_code, set_code_without_checks, set_storage, }; use orml_currencies::Call::update_balance; - use pallet_assets::Call::{destroy_accounts, destroy_approvals, finish_destroy}; use pallet_balances::Call::{force_transfer, set_balance}; use pallet_collective::Call::set_members; use pallet_contracts::Call::{ @@ -150,26 +145,6 @@ impl Contains for IsCallable { _ => true, } } - // Asset destruction is managed. Instead of deleting those dispatchable calls, they are - // filtered here instead to allow root to interact in case of emergency. - RuntimeCall::CampaignAssets(inner_call) => match inner_call { - destroy_accounts { .. } => false, - destroy_approvals { .. } => false, - finish_destroy { .. } => false, - _ => true, - }, - RuntimeCall::CustomAssets(inner_call) => match inner_call { - destroy_accounts { .. } => false, - destroy_approvals { .. } => false, - finish_destroy { .. } => false, - _ => true, - }, - RuntimeCall::MarketAssets(inner_call) => match inner_call { - destroy_accounts { .. } => false, - destroy_approvals { .. } => false, - finish_destroy { .. } => false, - _ => true, - }, // Permissioned contracts: Only deployable via utility.dispatch_as(...) RuntimeCall::Contracts(inner_call) => match inner_call { call { .. } => true, diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index a5c1eacf8..250173ea3 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -22,7 +22,7 @@ clippy::arithmetic_side_effects )] -use super::{CampaignAssetsInstance, Runtime, VERSION}; +use super::{Runtime, VERSION}; use frame_support::{ dispatch::DispatchClass, parameter_types, @@ -35,7 +35,6 @@ use frame_support::{ }; use frame_system::limits::{BlockLength, BlockWeights}; use orml_traits::parameter_type_with_key; -use pallet_assets::WeightInfo; use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; use sp_runtime::{ traits::{AccountIdConversion, Bounded}, @@ -64,44 +63,6 @@ parameter_types! { } parameter_types! { - // Asset-Router - pub DestroyAccountWeight: Weight = - >::WeightInfo::destroy_accounts(1); - pub DestroyApprovalWeight: Weight = - >::WeightInfo::destroy_approvals(1); - pub DestroyFinishWeight: Weight = - >::WeightInfo::finish_destroy(); - - // Assets (Campaign) - pub const CampaignAssetsAccountDeposit: Balance = deposit(1, 16); - pub const CampaignAssetsApprovalDeposit: Balance = ExistentialDeposit::get(); - /// The amount of native currency that is frozen during the whole lifetime - /// of an asset class. Freezing happens at asset class creation. - /// Irrelevant - No origin can successfully call the associated dispatchable call. - pub const CampaignAssetsDeposit: Balance = 400 * BASE; - pub const CampaignAssetsStringLimit: u32 = 256; - pub const CampaignAssetsMetadataDepositBase: Balance = deposit(1, 68); - pub const CampaignAssetsMetadataDepositPerByte: Balance = deposit(0, 1); - - // Assets (Custom) - pub const CustomAssetsAccountDeposit: Balance = deposit(1, 16); - pub const CustomAssetsApprovalDeposit: Balance = ExistentialDeposit::get(); - pub const CustomAssetsDeposit: Balance = 400 * BASE; - pub const CustomAssetsStringLimit: u32 = 50; - pub const CustomAssetsMetadataDepositBase: Balance = deposit(1, 68); - pub const CustomAssetsMetadataDepositPerByte: Balance = deposit(0, 1); - - // Assets (Market) - pub const MarketAssetsAccountDeposit: Balance = deposit(1, 16); - pub const MarketAssetsApprovalDeposit: Balance = ExistentialDeposit::get(); - /// The amount of native currency that is frozen during the whole lifetime - /// if an asset class. Freezing happens at asset class creation. - /// Irrelevant - No origin can successfully call the associated dispatchable call. - pub const MarketAssetsDeposit: Balance = 400 * BASE; - pub const MarketAssetsStringLimit: u32 = 50; - pub const MarketAssetsMetadataDepositBase: Balance = deposit(1, 68); - pub const MarketAssetsMetadataDepositPerByte: Balance = deposit(0, 1); - // Authorized pub const AuthorizedPalletId: PalletId = AUTHORIZED_PALLET_ID; pub const CorrectionPeriod: BlockNumber = BLOCKS_PER_DAY; @@ -242,7 +203,7 @@ parameter_types! { pub const MaxLiquidityTreeDepth: u32 = 9u32; // ORML - pub const GetNativeCurrencyId: Assets = Asset::Ztg; + pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; // Prediction Market parameters /// (Slashable) Bond that is provided for creating an advised market that needs approval. @@ -401,8 +362,6 @@ parameter_types! { .build_or_panic(); // Transaction payment - /// A fee multiplier applied to the calculated fee factor for `CampaignAsset` - pub const CampaignAssetFeeMultiplier: u32 = 100; /// A fee mulitplier for Operational extrinsics to compute “virtual tip” /// to boost their priority. pub const OperationalFeeMultiplier: u8 = 5; @@ -510,17 +469,17 @@ parameter_type_with_key! { // are cleaned up automatically. In case of scalar outcomes, the market account can have dust. // Unless LPs use `pool_exit_with_exact_asset_amount`, there can be some dust pool shares remaining. // Explicit match arms are used to ensure new asset types are respected. - pub ExistentialDeposits: |currency_id: Currencies| -> Balance { + pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Currencies::CategoricalOutcome(_, _) => ExistentialDeposit::get(), - Currencies::ParimutuelShare(_, _) => ExistentialDeposit::get(), - Currencies::PoolShare(_) => ExistentialDeposit::get(), - Currencies::ScalarOutcome(_, _) => ExistentialDeposit::get(), + Asset::CategoricalOutcome(_,_) => ExistentialDeposit::get(), + Asset::CombinatorialOutcome => ExistentialDeposit::get(), + Asset::PoolShare(_) => ExistentialDeposit::get(), + Asset::ScalarOutcome(_,_) => ExistentialDeposit::get(), #[cfg(feature = "parachain")] - Currencies::ForeignAsset(id) => { + Asset::ForeignAsset(id) => { let maybe_metadata = < orml_asset_registry::Pallet as orml_traits::asset_registry::Inspect - >::metadata(&XcmAsset::ForeignAsset(*id)); + >::metadata(&Asset::ForeignAsset(*id)); if let Some(metadata) = maybe_metadata { return metadata.existential_deposit; @@ -529,7 +488,9 @@ parameter_type_with_key! { 1 } #[cfg(not(feature = "parachain"))] - Currencies::ForeignAsset(_) => ExistentialDeposit::get(), + Asset::ForeignAsset(_) => ExistentialDeposit::get(), + Asset::Ztg => ExistentialDeposit::get(), + Asset::ParimutuelShare(_, _) => ExistentialDeposit::get(), } }; } diff --git a/runtime/zeitgeist/src/xcm_config/asset_registry.rs b/runtime/zeitgeist/src/xcm_config/asset_registry.rs index 9deb85aa0..92746377d 100644 --- a/runtime/zeitgeist/src/xcm_config/asset_registry.rs +++ b/runtime/zeitgeist/src/xcm_config/asset_registry.rs @@ -15,7 +15,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{Balance, XcmAsset}; +use crate::{Balance, CurrencyId}; use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; @@ -29,11 +29,11 @@ use zeitgeist_primitives::types::CustomMetadata; /// Only pre check is to ensure an asset id was passed. pub struct CustomAssetProcessor; -impl AssetProcessor> for CustomAssetProcessor { +impl AssetProcessor> for CustomAssetProcessor { fn pre_register( - id: Option, + id: Option, metadata: AssetMetadata, - ) -> Result<(XcmAsset, AssetMetadata), DispatchError> { + ) -> Result<(CurrencyId, AssetMetadata), DispatchError> { match id { Some(id) => Ok((id, metadata)), None => Err(DispatchError::Other("asset-registry: AssetId is required")), @@ -41,7 +41,7 @@ impl AssetProcessor> for Custom } fn post_register( - _id: XcmAsset, + _id: CurrencyId, _asset_metadata: AssetMetadata, ) -> Result<(), DispatchError> { Ok(()) diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index 27d6c1e54..f9424eaea 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -18,9 +18,9 @@ use super::fees::{native_per_second, FixedConversionRateProvider}; use crate::{ - AccountId, AssetManager, AssetRegistry, Assets, Balance, MaxAssetsIntoHolding, MaxInstructions, - ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, RuntimeCall, - RuntimeOrigin, UnitWeightCost, UniversalLocation, UnknownTokens, XcmpQueue, + AccountId, AssetManager, AssetRegistry, Balance, CurrencyId, MaxAssetsIntoHolding, + MaxInstructions, ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, + RuntimeCall, RuntimeOrigin, UnitWeightCost, UniversalLocation, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; @@ -52,8 +52,8 @@ use xcm_builder::{ SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, TakeWeightCredit, }; -use xcm_executor::{traits::TransactAsset, Assets as ExecutorAssets, Config}; -use zeitgeist_primitives::{constants::BalanceFractionalDecimals, types::XcmAsset}; +use xcm_executor::{traits::TransactAsset, Assets, Config}; +use zeitgeist_primitives::{constants::BalanceFractionalDecimals, types::Asset}; pub mod zeitgeist { #[cfg(test)] @@ -157,7 +157,7 @@ impl TakeRevenue for ToTreasury { if let MultiAsset { id: Concrete(location), fun: Fungible(_amount) } = revenue { if let Ok(asset_id) = - >::convert(location) + >::convert(location) { let adj_am = AlignedFractionalMultiAssetTransactor::adjust_fractional_places(&revenue).fun; @@ -213,9 +213,9 @@ pub struct AlignedFractionalTransactAsset< } impl< - AssetRegistry: Inspect, + AssetRegistry: Inspect, FracDecPlaces: Get, - CurrencyIdConvert: Convert>, + CurrencyIdConvert: Convert>, TransactAssetDelegate: TransactAsset, > AlignedFractionalTransactAsset< @@ -226,41 +226,29 @@ impl< > { fn adjust_fractional_places(asset: &MultiAsset) -> MultiAsset { - let (asset_id, amount) = - if let Some(ref asset_id) = CurrencyIdConvert::convert(asset.clone()) { - if let Fungible(amount) = asset.fun { - (*asset_id, amount) - } else { - return asset.clone(); + if let Some(ref asset_id) = CurrencyIdConvert::convert(asset.clone()) { + if let Fungible(amount) = asset.fun { + let mut asset_updated = asset.clone(); + let native_decimals = u32::from(FracDecPlaces::get()); + let metadata = AssetRegistry::metadata(asset_id); + + if let Some(metadata) = metadata { + let decimals = metadata.decimals; + + asset_updated.fun = if decimals > native_decimals { + let power = decimals.saturating_sub(native_decimals); + let adjust_factor = 10u128.saturating_pow(power); + // Floors the adjusted token amount, thus no tokens are generated + Fungible(amount.saturating_div(adjust_factor)) + } else { + let power = native_decimals.saturating_sub(decimals); + let adjust_factor = 10u128.saturating_pow(power); + Fungible(amount.saturating_mul(adjust_factor)) + }; + + return asset_updated; } - } else { - return asset.clone(); - }; - - let currency = if let Ok(currency) = XcmAsset::try_from(asset_id) { - currency - } else { - return asset.clone(); - }; - - let metadata = AssetRegistry::metadata(¤cy); - if let Some(metadata) = metadata { - let mut asset_adjusted = asset.clone(); - let decimals = metadata.decimals; - let native_decimals = u32::from(FracDecPlaces::get()); - - asset_adjusted.fun = if decimals > native_decimals { - let power = decimals.saturating_sub(native_decimals); - let adjust_factor = 10u128.saturating_pow(power); - // Floors the adjusted token amount, thus no tokens are generated - Fungible(amount.saturating_div(adjust_factor)) - } else { - let power = native_decimals.saturating_sub(decimals); - let adjust_factor = 10u128.saturating_pow(power); - Fungible(amount.saturating_mul(adjust_factor)) - }; - - return asset_adjusted; + } } asset.clone() @@ -268,8 +256,8 @@ impl< } impl< - AssetRegistry: Inspect, - CurrencyIdConvert: Convert>, + AssetRegistry: Inspect, + CurrencyIdConvert: Convert>, FracDecPlaces: Get, TransactAssetDelegate: TransactAsset, > TransactAsset @@ -293,7 +281,7 @@ impl< asset: &MultiAsset, location: &MultiLocation, maybe_context: Option<&XcmContext>, - ) -> Result { + ) -> Result { let asset_adjusted = Self::adjust_fractional_places(asset); TransactAssetDelegate::withdraw_asset(&asset_adjusted, location, maybe_context) } @@ -303,7 +291,7 @@ impl< from: &MultiLocation, to: &MultiLocation, context: &XcmContext, - ) -> Result { + ) -> Result { let asset_adjusted = Self::adjust_fractional_places(asset); TransactAssetDelegate::transfer_asset(&asset_adjusted, from, to, context) } @@ -324,17 +312,17 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< UnknownTokens, // This means that this adapter should handle any token that `AssetConvert` can convert // using AssetManager and UnknownTokens in all other cases. - IsNativeConcrete, + IsNativeConcrete, // Our chain's account ID type (we can't get away without mentioning it explicitly). AccountId, // Convert an XCM `MultiLocation` into a local account id. LocationToAccountId, // The AssetId that corresponds to the native currency. - Assets, + CurrencyId, // Struct that provides functions to convert `Asset` <=> `MultiLocation`. AssetConvert, // In case of deposit failure, known assets will be placed in treasury. - DepositToAlternative, + DepositToAlternative, >; /// AssetConvert @@ -346,42 +334,33 @@ pub struct AssetConvert; /// Convert our `Asset` type into its `MultiLocation` representation. /// Other chains need to know how this conversion takes place in order to /// handle it on their side. -impl Convert> for AssetConvert { - fn convert(id: Assets) -> Option { +impl Convert> for AssetConvert { + fn convert(id: CurrencyId) -> Option { match id { - Assets::Ztg => Some(MultiLocation::new( + Asset::Ztg => Some(MultiLocation::new( 1, X2( Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(zeitgeist::KEY), ), )), - Assets::ForeignAsset(_) => { - let asset = XcmAsset::try_from(id).ok()?; - AssetRegistry::multilocation(&asset).ok()? - } + Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, } } } -impl Convert> for AssetConvert { - fn convert(id: XcmAsset) -> Option { - >>::convert(id.into()) - } -} - /// Convert an incoming `MultiLocation` into a `Asset` if possible. /// Here we need to know the canonical representation of all the tokens we handle in order to /// correctly convert their `MultiLocation` representation into our internal `Asset` type. -impl xcm_executor::traits::Convert for AssetConvert { - fn convert(location: MultiLocation) -> Result { +impl xcm_executor::traits::Convert for AssetConvert { + fn convert(location: MultiLocation) -> Result { match location { MultiLocation { parents: 0, interior: X1(GeneralKey { data, length }) } => { let key = &data[..data.len().min(length as usize)]; if key == zeitgeist::KEY { - return Ok(Assets::Ztg); + return Ok(CurrencyId::Ztg); } Err(location) @@ -394,28 +373,21 @@ impl xcm_executor::traits::Convert for AssetConvert { if para_id == u32::from(ParachainInfo::parachain_id()) { if key == zeitgeist::KEY { - return Ok(Assets::Ztg); + return Ok(CurrencyId::Ztg); } return Err(location); } - AssetRegistry::location_to_asset_id(location).ok_or(location).map(|a| a.into()) + AssetRegistry::location_to_asset_id(location).ok_or(location) } - _ => AssetRegistry::location_to_asset_id(location).ok_or(location).map(|a| a.into()), + _ => AssetRegistry::location_to_asset_id(location).ok_or(location), } } } -impl xcm_executor::traits::Convert for AssetConvert { - fn convert(location: MultiLocation) -> Result { - >::convert(location) - .and_then(|asset| asset.try_into().map_err(|_| location)) - } -} - -impl Convert> for AssetConvert { - fn convert(asset: MultiAsset) -> Option { +impl Convert> for AssetConvert { + fn convert(asset: MultiAsset) -> Option { if let MultiAsset { id: Concrete(location), .. } = asset { >::convert(location).ok() } else { @@ -424,8 +396,8 @@ impl Convert> for AssetConvert { } } -impl Convert> for AssetConvert { - fn convert(location: MultiLocation) -> Option { +impl Convert> for AssetConvert { + fn convert(location: MultiLocation) -> Option { >::convert(location).ok() } } diff --git a/runtime/zeitgeist/src/xcm_config/fees.rs b/runtime/zeitgeist/src/xcm_config/fees.rs index 0b2f18661..2affbb614 100644 --- a/runtime/zeitgeist/src/xcm_config/fees.rs +++ b/runtime/zeitgeist/src/xcm_config/fees.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{Balance, XcmAsset}; +use crate::{Balance, CurrencyId}; use core::marker::PhantomData; use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND}; use xcm::latest::MultiLocation; @@ -56,7 +56,7 @@ pub struct FixedConversionRateProvider(PhantomData impl< AssetRegistry: orml_traits::asset_registry::Inspect< - AssetId = XcmAsset, + AssetId = CurrencyId, Balance = Balance, CustomMetadata = CustomMetadata, >, diff --git a/scripts/benchmarks/configuration.sh b/scripts/benchmarks/configuration.sh index cfc5d46bd..9f13d1edf 100644 --- a/scripts/benchmarks/configuration.sh +++ b/scripts/benchmarks/configuration.sh @@ -4,9 +4,9 @@ EXTERNAL_WEIGHTS_PATH="./runtime/common/src/weights/" # This script contains the configuration for other benchmarking scripts. export FRAME_PALLETS=( - frame_system pallet_assets pallet_balances pallet_bounties pallet_collective \ - pallet_contracts pallet_democracy pallet_identity pallet_membership pallet_multisig \ - pallet_preimage pallet_proxy pallet_scheduler pallet_timestamp pallet_treasury pallet_utility \ + frame_system pallet_balances pallet_bounties pallet_collective pallet_contracts \ + pallet_democracy pallet_identity pallet_membership pallet_multisig pallet_preimage \ + pallet_proxy pallet_scheduler pallet_timestamp pallet_treasury pallet_utility \ pallet_vesting \ ) # pallet_grandpa ) export FRAME_PALLETS_RUNS="${FRAME_PALLETS_RUNS:-20}" diff --git a/zrml/asset-router/Cargo.toml b/zrml/asset-router/Cargo.toml deleted file mode 100644 index 3a264a4d2..000000000 --- a/zrml/asset-router/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[dependencies] -frame-support = { workspace = true } -frame-system = { workspace = true } -log = { workspace = true } -orml-traits = { workspace = true } -pallet-assets = { workspace = true } -parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } -scale-info = { workspace = true, features = ["derive"] } -sp-runtime = { workspace = true } -zeitgeist-macros = { workspace = true } -zeitgeist-primitives = { workspace = true } - -[dev-dependencies] -orml-tokens = { workspace = true, features = ["default"] } -pallet-balances = { workspace = true, features = ["default"] } -sp-io = { workspace = true, features = ["default"] } -test-case = { workspace = true } -zeitgeist-primitives = { workspace = true, features = ["default", "mock"] } - -[features] -default = ["std"] -runtime-benchmarks = ["pallet-assets/runtime-benchmarks"] -std = [ - "frame-support/std", - "frame-system/std", - "orml-traits/std", - "pallet-assets/std", - "parity-scale-codec/std", - "zeitgeist-primitives/std", -] -try-runtime = [ - "frame-support/try-runtime", -] - -[package] -authors = ["Zeitgeist PM "] -edition = "2021" -name = "zrml-asset-router" -version = "0.4.1" diff --git a/zrml/asset-router/README.md b/zrml/asset-router/README.md deleted file mode 100644 index 34908131e..000000000 --- a/zrml/asset-router/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Asset Router - -The asset router allows to interact with different asset classes using one -overaching asset class. The caller is not required to be aware of which pallet -handles the asset class of the asset in question, as the asset router internally -routes the call to the appropriate pallet as defined in the pallet's -configuration. - -## Overview - -The asset router implements various ORML `MultiCurrency` traits as well as -various `Fungible` traits, thus it can be used in other pallets that require -those implementation (such as ORML Currencies). The asset router also provides -managed asset destruction, that handles asset destruction for all the assets -registered through the `ManagedDestroy` interface whenever on-chain execution -time is available. Finally, the asset router also provides a lazy migration -mechanism for asset types from the `CurrencyType` to the `MarketAssetType`. - -### Terminology - -- _Asset Type_: An asset type is used to represent assets that share the same - purpose. -- _Asset Class_: An asset class is an overarching collection of multible asset - types that share common properties. -- _Tokens_: Tokens are a countable number of instantiations of a specific asset - type that can be moved between accounts. -- _Lazy Migration_: A lazy migration migrates data and the control over the data - from a source to a destination over a prolonged amount of time, usually per - request of the data or after expiry of the data. -- _Managed Asset Destruction_: A mechanism to automatically destroy an asset - type. - -### Managed Asset Destruction - -Once an asset was registered for managed destruction, it's assigned a state and -stored in a sorted list within the `DestroyAssets` storage. Whenever weight is -available in a block, this pallet will process as many assets as possible from -that sorted list. To achieve that, it loops through all assets one by one and -for each asset, it runs through a state machine that ensures that every step -necessary to properly destroy an asset is executed and that the states are -updated accordingly. It might occur that the pallet that does the actual -destruction, i.e. that is invoked by the managed destruction routine to destroy -a specific asset (using the `Destroy` interface), throws an error. In that case -an asset is considered as `Indestructible` and stored in the -`IndestructibleAssets` storage, while also logging the incident. - -### Lazy migration from `CurrencyClass` to `MarketAssetClass` - -As some asset types within `CurrencyType` and `MarketAssetType` map to the same -asset type in the overarching `AssetType`, it is necessary to apply some -additional logic to determine when a function call with an asset of `AssetType` -should be invoked in `Currencies` and when it should be invoked in -`MarketAssets`. The approach this pallet uses is as follows: - -- Try to convert `AssetType` into `MarketAssetType` -- On success, check if `MarketAssetType` exists. - - If it does, invoke the function in `MarketAssets` - - If it does not, try to convert to `CurrencyType`. - - On success, invoke `Currencies` - - On failure, invoke `MarketAssets` -- On failure, continue trying to convert into other known asset types. diff --git a/zrml/asset-router/src/lib.rs b/zrml/asset-router/src/lib.rs deleted file mode 100644 index ec97b3937..000000000 --- a/zrml/asset-router/src/lib.rs +++ /dev/null @@ -1,520 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![feature(proc_macro_hygiene)] -#![doc = include_str!("../README.md")] -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate alloc; - -pub use pallet::*; - -#[macro_use] -mod macros; -#[cfg(test)] -mod mock; -pub mod pallet_impl; -#[cfg(test)] -mod tests; -mod types; - -#[frame_support::pallet] -pub mod pallet { - pub(crate) use super::types::*; - pub(crate) use alloc::collections::BTreeMap; - pub(crate) use core::{fmt::Debug, marker::PhantomData}; - pub(crate) use frame_support::{ - ensure, log, - pallet_prelude::{DispatchError, DispatchResult, Hooks, StorageValue, ValueQuery, Weight}, - require_transactional, - traits::{ - tokens::{ - fungibles::{Create, Destroy, Inspect, Mutate, Transfer, Unbalanced}, - DepositConsequence, WithdrawConsequence, - }, - BalanceStatus as Status, ConstU32, - }, - BoundedVec, Parameter, - }; - pub(crate) use orml_traits::{ - arithmetic::Signed, - currency::{ - MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency, MultiReservableCurrency, - NamedMultiReservableCurrency, TransferAll, - }, - BalanceStatus, LockIdentifier, - }; - pub(crate) use pallet_assets::ManagedDestroy; - use parity_scale_codec::{FullCodec, MaxEncodedLen}; - use scale_info::TypeInfo; - pub(crate) use sp_runtime::{ - traits::{ - AtLeast32BitUnsigned, Bounded, Get, MaybeSerializeDeserialize, Member, Saturating, Zero, - }, - FixedPointOperand, SaturatedConversion, - }; - use zeitgeist_macros::unreachable_non_terminating; - pub(crate) use zeitgeist_primitives::traits::CheckedDivPerComponent; - - pub(crate) const LOG_TARGET: &str = "runtime::asset-router"; - pub(crate) const MAX_ASSET_DESTRUCTIONS_PER_BLOCK: u8 = 128; - pub(crate) const MAX_ASSETS_IN_DESTRUCTION: u32 = 2048; - const MAX_INDESTRUCTIBLE_ASSETS: u32 = 256; - // 1 ms minimum computation time. - pub(crate) const MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT: u64 = 1_000_000_000; - - pub trait AssetTraits: - Create - + Destroy - + Inspect - + Transfer - + Mutate - + Unbalanced - { - } - - impl AssetTraits for G - where - G: Create - + Destroy - + Inspect - + Transfer - + Mutate - + Unbalanced, - T: Config, - { - } - - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching asset type that contains all assets classes. - type AssetType: Copy - + Debug - + Eq - + From - + From - + From - + From - + FullCodec - + MaxEncodedLen - + MaybeSerializeDeserialize - + Ord - + TypeInfo; - - /// The type that represents balances. - type Balance: Parameter - + Member - + AtLeast32BitUnsigned - + Default - + Copy - + MaybeSerializeDeserialize - + MaxEncodedLen - + FixedPointOperand; - - /// Logic that handles campaign assets by providing multiple fungible - /// trait implementations. - type CampaignAssets: AssetTraits; - /// The custom asset type. - type CampaignAssetType: TryFrom - + Copy - + Debug - + Eq - + FullCodec - + MaxEncodedLen - + MaybeSerializeDeserialize - + TypeInfo; - - /// Logic that handles currencies by providing multiple currencies - /// trait implementations. - type Currencies: TransferAll - + MultiCurrencyExtended< - Self::AccountId, - CurrencyId = Self::CurrencyType, - Balance = Self::Balance, - > + MultiLockableCurrency - + MultiReservableCurrency - + NamedMultiReservableCurrency - + Unbalanced; - /// The currency type. - type CurrencyType: TryFrom - + Copy - + Debug - + Eq - + FullCodec - + MaxEncodedLen - + MaybeSerializeDeserialize - + TypeInfo; - - /// Logic that handles custom assets by providing multiple fungible - /// trait implementations. - type CustomAssets: AssetTraits; - /// The custom asset type. - type CustomAssetType: TryFrom - + Copy - + Debug - + Eq - + FullCodec - + MaxEncodedLen - + MaybeSerializeDeserialize - + TypeInfo; - - /// Weight required for destroying one account. - type DestroyAccountWeight: Get; - /// Weight required for destroying one approval. - type DestroyApprovalWeight: Get; - /// Weight required for finishing the asset destruction process. - type DestroyFinishWeight: Get; - - /// Logic that handles market assets by providing multiple fungible - /// trait implementations. - type MarketAssets: AssetTraits; - /// The market asset type. - type MarketAssetType: TryFrom - + Copy - + Debug - + Eq - + FullCodec - + MaxEncodedLen - + MaybeSerializeDeserialize - + TypeInfo; - } - - /// Keeps track of assets that have to be destroyed. - #[pallet::storage] - pub(super) type DestroyAssets = StorageValue<_, DestroyAssetsT, ValueQuery>; - - /// Keeps track of assets that can't be destroyed. - #[pallet::storage] - pub(crate) type IndestructibleAssets = - StorageValue<_, BoundedVec>, ValueQuery>; - - #[pallet::error] - pub enum Error { - /// Cannot convert Amount (MultiCurrencyExtended implementation) into Balance type. - AmountIntoBalanceFailed, - /// Cannot start managed destruction as the asset was marked as indestructible. - AssetIndestructible, - /// Cannot start managed destruction as a destruction for the asset is in progress. - DestructionInProgress, - /// The vector holding all assets to destroy reached it's boundary. - TooManyManagedDestroys, - /// Asset conversion failed. - UnknownAsset, - /// Operation is not supported for given asset - Unsupported, - } - - #[pallet::pallet] - pub struct Pallet(PhantomData); - - #[pallet::hooks] - impl Hooks for Pallet { - fn on_idle(_: T::BlockNumber, mut remaining_weight: Weight) -> Weight { - let max_extra_weight = Self::on_idle_max_extra_weight(); - - if !remaining_weight - .all_gte(max_extra_weight.saturating_add(T::DbWeight::get().reads(1))) - { - return remaining_weight; - }; - - let mut destroy_assets = DestroyAssets::::get(); - if destroy_assets.len() == 0 { - return remaining_weight.saturating_sub(T::DbWeight::get().reads(1)); - } - - remaining_weight = remaining_weight - .saturating_sub(T::DbWeight::get().reads_writes(1, 1)) - .saturating_sub(max_extra_weight); - - remaining_weight = - Self::handle_asset_destruction(remaining_weight, &mut destroy_assets); - - DestroyAssets::::put(destroy_assets); - remaining_weight - } - } - - impl Pallet { - fn handle_asset_destruction( - mut remaining_weight: Weight, - destroy_assets: &mut DestroyAssetsT, - ) -> Weight { - let mut saftey_counter_outer = 0u8; - - 'outer: while let Some(mut asset) = destroy_assets.pop() { - // Only reachable if there is an error in the implementation of pop() for Vec. - unreachable_non_terminating!( - saftey_counter_outer != MAX_ASSET_DESTRUCTIONS_PER_BLOCK, - LOG_TARGET, - break, - "Destruction outer loop iteration guard triggered, iteration: {:?}", - saftey_counter_outer - ); - - let safety_counter_inner_max = DESTRUCTION_STATES; - let mut safety_counter_inner = 0u8; - - while *asset.state() != DestructionState::Destroyed - && *asset.state() != DestructionState::Indestructible - && safety_counter_inner < safety_counter_inner_max - { - match asset.state() { - DestructionState::Accounts => { - handle_asset_destruction!( - &mut asset, - remaining_weight, - destroy_assets, - handle_destroy_accounts, - 'outer - ); - } - DestructionState::Approvals => { - handle_asset_destruction!( - &mut asset, - remaining_weight, - destroy_assets, - handle_destroy_approvals, - 'outer - ); - } - DestructionState::Finalization => { - handle_asset_destruction!( - &mut asset, - remaining_weight, - destroy_assets, - handle_destroy_finish, - 'outer - ); - } - // Next two states should never occur. Just remove the asset. - DestructionState::Destroyed => { - unreachable_non_terminating!( - false, - LOG_TARGET, - "Asset {:?} has invalid state", - asset - ); - } - DestructionState::Indestructible => { - unreachable_non_terminating!( - false, - LOG_TARGET, - "Asset {:?} has invalid state", - asset - ); - } - } - - safety_counter_inner = safety_counter_inner.saturating_add(1); - } - - // Only reachable if there is an error in the destruction state machine. - unreachable_non_terminating!( - safety_counter_inner != safety_counter_inner_max, - LOG_TARGET, - "Destruction inner loop iteration guard triggered, asset: {:?}", - asset - ); - - saftey_counter_outer = saftey_counter_outer.saturating_add(1); - } - - remaining_weight - } - - fn handle_destroy_accounts( - asset: &mut AssetInDestruction, - mut remaining_weight: Weight, - ) -> DestructionResult { - if *asset.state() != DestructionState::Accounts { - return Err(DestructionError::WrongState(remaining_weight)); - } - let destroy_account_weight = T::DestroyAccountWeight::get(); - - let destroy_account_cap = - match remaining_weight.checked_div_per_component(&destroy_account_weight) { - Some(amount) => amount, - None => return Ok(DestructionOk::Incomplete(remaining_weight)), - }; - - match Self::destroy_accounts(*asset.asset(), destroy_account_cap.saturated_into()) { - Ok(destroyed_accounts) => { - // TODO(#1202): More precise weights - remaining_weight = remaining_weight.saturating_sub( - destroy_account_weight - .saturating_mul(destroyed_accounts.into()) - .max(destroy_account_weight), - ); - - if u64::from(destroyed_accounts) != destroy_account_cap { - asset.transit_state(); - Ok(DestructionOk::Complete(remaining_weight)) - } else { - Ok(DestructionOk::Incomplete(remaining_weight)) - } - } - Err(e) => { - // In this case, it is not known how many accounts have been destroyed prior - // to triggering this error. The only safe handling is consuming all the - // remaining weight. - let _ = Self::mark_asset_as_indestructible( - asset, - remaining_weight, - remaining_weight, - e, - ); - // Play it safe, consume all remaining weight. - Err(DestructionError::Indestructible(Weight::zero())) - } - } - } - - fn handle_destroy_approvals( - asset: &mut AssetInDestruction, - mut remaining_weight: Weight, - ) -> DestructionResult { - if *asset.state() != DestructionState::Approvals { - return Err(DestructionError::WrongState(remaining_weight)); - } - let destroy_approval_weight = T::DestroyApprovalWeight::get(); - - let destroy_approval_cap = - match remaining_weight.checked_div_per_component(&destroy_approval_weight) { - Some(amount) => amount, - None => return Ok(DestructionOk::Incomplete(remaining_weight)), - }; - - match Self::destroy_approvals(*asset.asset(), destroy_approval_cap.saturated_into()) { - Ok(destroyed_approvals) => { - // TODO(#1202): More precise weights - remaining_weight = remaining_weight.saturating_sub( - destroy_approval_weight - .saturating_mul(destroyed_approvals.into()) - .max(destroy_approval_weight), - ); - - if u64::from(destroyed_approvals) != destroy_approval_cap { - asset.transit_state(); - Ok(DestructionOk::Complete(remaining_weight)) - } else { - Ok(DestructionOk::Incomplete(remaining_weight)) - } - } - Err(e) => { - // In this case, it is not known how many approvals have been destroyed prior - // to triggering this error. The only safe handling is consuming all the - // remaining weight. - let _ = Self::mark_asset_as_indestructible( - asset, - remaining_weight, - remaining_weight, - e, - ); - // Play it safe, consume all remaining weight. - Err(DestructionError::Indestructible(Weight::zero())) - } - } - } - - fn handle_destroy_finish( - asset: &mut AssetInDestruction, - remaining_weight: Weight, - ) -> DestructionResult { - if *asset.state() != DestructionState::Finalization { - return Err(DestructionError::WrongState(remaining_weight)); - } - let destroy_finish_weight = T::DestroyFinishWeight::get(); - - if remaining_weight.all_gte(destroy_finish_weight) { - // TODO(#1202): More precise weights - if let Err(e) = Self::finish_destroy(*asset.asset()) { - let remaining_weight_err = Self::mark_asset_as_indestructible( - asset, - remaining_weight, - destroy_finish_weight, - e, - ); - return Err(DestructionError::Indestructible(remaining_weight_err)); - } - - asset.transit_state(); - return Ok(DestructionOk::Complete( - remaining_weight.saturating_sub(destroy_finish_weight), - )); - } - - Ok(DestructionOk::Incomplete(remaining_weight)) - } - - fn mark_asset_as_indestructible( - asset: &mut AssetInDestruction, - mut remaining_weight: Weight, - max_weight: Weight, - error: DispatchError, - ) -> Weight { - let asset_inner = *asset.asset(); - - log::error!( - target: LOG_TARGET, - "Error during managed asset account destruction of {:?}: {:?}", - asset_inner, - error - ); - - remaining_weight = remaining_weight.saturating_sub(max_weight); - - if let Err(e) = IndestructibleAssets::::try_mutate(|assets| { - let idx = assets.partition_point(|&asset_in_vec| asset_in_vec < asset_inner); - assets.try_insert(idx, asset_inner) - }) { - log::error!( - target: LOG_TARGET, - "Error during storage of indestructible asset {:?}, dropping asset: {:?}", - asset_inner, - e - ); - } - - asset.transit_indestructible(); - remaining_weight.saturating_sub(T::DbWeight::get().reads_writes(1, 1)) - } - - fn on_idle_max_extra_weight() -> Weight { - let max_proof_size_destructibles: u64 = - AssetInDestruction::::max_encoded_len() - .saturating_mul(MAX_ASSETS_IN_DESTRUCTION.saturated_into()) - .saturated_into(); - let max_proof_size_indestructibles: u64 = T::AssetType::max_encoded_len() - .saturating_mul(MAX_INDESTRUCTIBLE_ASSETS.saturated_into()) - .saturated_into(); - let max_proof_size_total = - max_proof_size_destructibles.saturating_add(max_proof_size_indestructibles); - - Weight::from_parts( - MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, - // Maximum proof size assuming writes on full storage. - max_proof_size_total, - ) - } - - #[inline] - pub(crate) fn log_unsupported(asset: T::AssetType, function: &str) { - log::warn!(target: LOG_TARGET, "Asset {:?} not supported in function {:?}", asset, function); - } - } -} diff --git a/zrml/asset-router/src/macros.rs b/zrml/asset-router/src/macros.rs deleted file mode 100644 index 06dff530c..000000000 --- a/zrml/asset-router/src/macros.rs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -/// This macro converts the invoked asset type into the respective -/// implementation that handles it and finally calls the $method on it. -macro_rules! route_call { - ($currency_id:expr, $currency_method:ident, $asset_method:ident, $($args:expr),*) => { - if let Ok(asset) = T::MarketAssetType::try_from($currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - Ok(T::MarketAssets::$asset_method(asset, $($args),*)) - } else { - if let Ok(currency) = T::CurrencyType::try_from($currency_id) { - Ok(>::$currency_method(currency, $($args),*)) - } else { - Ok(T::MarketAssets::$asset_method(asset, $($args),*)) - } - } - } else if let Ok(asset) = T::CampaignAssetType::try_from($currency_id) { - Ok(T::CampaignAssets::$asset_method(asset, $($args),*)) - } else if let Ok(asset) = T::CustomAssetType::try_from($currency_id) { - Ok(T::CustomAssets::$asset_method(asset, $($args),*)) - } else if let Ok(currency) = T::CurrencyType::try_from($currency_id) { - Ok(>::$currency_method(currency, $($args),*)) - } else { - Err(Error::::UnknownAsset) - } - }; -} - -macro_rules! route_call_with_trait { - ($currency_id:expr, $trait:ident, $method:ident, $($args:expr),*) => { - if let Ok(asset) = T::MarketAssetType::try_from($currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - Ok(>::$method(asset, $($args),*)) - } else { - if let Ok(currency) = T::CurrencyType::try_from($currency_id) { - Ok(>::$method(currency, $($args),*)) - } else { - Ok(>::$method(asset, $($args),*)) - } - } - } else if let Ok(asset) = T::CampaignAssetType::try_from($currency_id) { - Ok(>::$method(asset, $($args),*)) - } else if let Ok(asset) = T::CustomAssetType::try_from($currency_id) { - Ok(>::$method(asset, $($args),*)) - } else if let Ok(currency) = T::CurrencyType::try_from($currency_id) { - Ok(>::$method(currency, $($args),*)) - } else { - Err(Error::::UnknownAsset) - } - }; -} - -/// This macro delegates a call to Currencies if the asset represents a currency, otherwise -/// it returns an error. -macro_rules! only_currency { - ($currency_id:expr, $error:expr, $currency_trait:ident, $currency_method:ident, $($args:expr),+) => { - if let Ok(asset) = T::MarketAssetType::try_from($currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - Self::log_unsupported($currency_id, stringify!($currency_method)); - $error - } else { - if let Ok(currency) = T::CurrencyType::try_from($currency_id) { - >::$currency_method(currency, $($args),+) - } else { - Self::log_unsupported($currency_id, stringify!($currency_method)); - $error - } - } - } - else if let Ok(currency) = T::CurrencyType::try_from($currency_id) { - >::$currency_method(currency, $($args),+) - } else { - Self::log_unsupported($currency_id, stringify!($currency_method)); - $error - } - }; -} - -/// This macro delegates a call to one *Asset instance if the asset does not represent a currency, -/// otherwise it returns an error. -macro_rules! only_asset { - ($asset_id:expr, $error:expr, $asset_trait:ident, $asset_method:ident, $($args:expr),*) => { - if let Ok(asset) = T::MarketAssetType::try_from($asset_id) { - >::$asset_method(asset, $($args),*) - } else if let Ok(asset) = T::CampaignAssetType::try_from($asset_id) { - T::CampaignAssets::$asset_method(asset, $($args),*) - } else if let Ok(asset) = T::CustomAssetType::try_from($asset_id) { - T::CustomAssets::$asset_method(asset, $($args),*) - } else { - Self::log_unsupported($asset_id, stringify!($asset_method)); - $error - } - }; -} - -/// This macro handles the single stages of the asset destruction. -macro_rules! handle_asset_destruction { - ($asset:expr, $remaining_weight:expr, $asset_storage:expr, $asset_method:ident, $outer_loop:tt) => { - let state_before = *($asset.state()); - let call_result = Self::$asset_method($asset, $remaining_weight); - match call_result { - Ok(DestructionOk::Incomplete(weight)) => { - // Should be infallible since the asset was just popped and force inserting - // is not possible. - if let Err(e) = $asset_storage.try_insert($asset_storage.len(), *($asset)) { - log::error!( - target: LOG_TARGET, - "Cannot reintroduce asset {:?} into DestroyAssets storage: {:?}", - $asset, - e - ); - } - - $remaining_weight = weight; - break $outer_loop; - }, - Ok(DestructionOk::Complete(weight)) | Err(DestructionError::WrongState(weight)) => { - $remaining_weight = weight; - }, - Err(DestructionError::Indestructible(weight)) => { - $remaining_weight = weight; - - if state_before != DestructionState::Finalization { - break $outer_loop; - } else { - // In case destruction failed during finalization, there is most likely still - // some weight available. - break; - } - } - } - }; -} diff --git a/zrml/asset-router/src/mock.rs b/zrml/asset-router/src/mock.rs deleted file mode 100644 index 716142b96..000000000 --- a/zrml/asset-router/src/mock.rs +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -extern crate alloc; - -use crate::{self as zrml_asset_router}; -use alloc::{collections::BTreeMap, vec, vec::Vec}; -use frame_support::{ - construct_runtime, - pallet_prelude::{DispatchResult, Weight}, - traits::{AsEnsureOriginWithArg, Everything}, -}; -use frame_system::EnsureSigned; -use orml_traits::parameter_type_with_key; -use pallet_assets::ManagedDestroy; -use parity_scale_codec::Compact; -use sp_runtime::{ - testing::Header, - traits::{parameter_types, BlakeTwo256, ConstU128, ConstU32, IdentityLookup}, -}; -use zeitgeist_primitives::{ - constants::mock::{BlockHashCount, ExistentialDeposit, MaxLocks, MaxReserves, BASE}, - types::{ - AccountIdTest, Amount, Assets, Balance, BlockNumber, BlockTest, CampaignAsset, - CampaignAssetClass, CampaignAssetId, Currencies, CustomAsset, CustomAssetClass, - CustomAssetId, Hash, Index, MarketAsset, UncheckedExtrinsicTest, - }, -}; - -pub(super) const ALICE: AccountIdTest = 0; -pub(super) const BOB: AccountIdTest = 1; -pub(super) const CHARLIE: AccountIdTest = 2; - -pub(super) const CAMPAIGN_ASSET: Assets = Assets::CampaignAsset(0); -pub(super) const CAMPAIGN_ASSET_INTERNAL: CampaignAssetClass = CampaignAssetClass(0); -pub(super) const CUSTOM_ASSET: Assets = Assets::CustomAsset(0); -pub(super) const CUSTOM_ASSET_INTERNAL: CustomAssetClass = CustomAssetClass(0); -pub(super) const MARKET_ASSET: Assets = Assets::CategoricalOutcome(7, 8); -pub(super) const MARKET_ASSET_INTERNAL: MarketAsset = MarketAsset::CategoricalOutcome(7, 8); -pub(super) const CURRENCY: Assets = Assets::ForeignAsset(0); -pub(super) const CURRENCY_OLD_OUTCOME: Assets = Assets::CategoricalOutcome(7, 8); -pub(super) const CURRENCY_INTERNAL: Currencies = Currencies::ForeignAsset(0); - -pub(super) const CAMPAIGN_ASSET_MIN_BALANCE: Balance = 2; -pub(super) const CUSTOM_ASSET_MIN_BALANCE: Balance = 3; -pub(super) const MARKET_ASSET_MIN_BALANCE: Balance = 4; -pub(super) const CURRENCY_MIN_BALANCE: Balance = 5; - -pub(super) const CAMPAIGN_ASSET_INITIAL_AMOUNT: Balance = 10; -pub(super) const CUSTOM_ASSET_INITIAL_AMOUNT: Balance = 20; -pub(super) const MARKET_ASSET_INITIAL_AMOUNT: Balance = 30; -pub(super) const CURRENCY_INITIAL_AMOUNT: Balance = 40; - -pub(super) const DESTROY_WEIGHT: Weight = Weight::from_parts(1000, 0); - -pub(super) type AccountId = ::AccountId; -pub(super) type CustomAssetsInstance = pallet_assets::Instance1; -pub(super) type CampaignAssetsInstance = pallet_assets::Instance2; -pub(super) type MarketAssetsInstance = pallet_assets::Instance3; - -parameter_types! { - pub const DestroyWeight: Weight = DESTROY_WEIGHT; -} - -construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - AssetRouter: zrml_asset_router::{Pallet}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, - } -); - -impl crate::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyWeight; - type DestroyApprovalWeight = DestroyWeight; - type DestroyFinishWeight = DestroyWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; -} - -impl frame_system::Config for Runtime { - type AccountData = pallet_balances::AccountData; - type AccountId = AccountIdTest; - type BaseCallFilter = Everything; - type BlockHashCount = BlockHashCount; - type BlockLength = (); - type BlockNumber = BlockNumber; - type BlockWeights = (); - type RuntimeCall = RuntimeCall; - type DbWeight = (); - type RuntimeEvent = RuntimeEvent; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; - type Lookup = IdentityLookup; - type MaxConsumers = frame_support::traits::ConstU32<16>; - type OnKilledAccount = (); - type OnNewAccount = (); - type RuntimeOrigin = RuntimeOrigin; - type PalletInfo = PalletInfo; - type SS58Prefix = (); - type SystemWeightInfo = (); - type Version = (); - type OnSetCode = (); -} - -parameter_type_with_key! { - pub ExistentialDeposits: |_currency_id: Currencies| -> Balance { - CURRENCY_MIN_BALANCE - }; -} - -impl orml_tokens::Config for Runtime { - type Amount = Amount; - type Balance = Balance; - type CurrencyId = Currencies; - type DustRemovalWhitelist = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposits = ExistentialDeposits; - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type CurrencyHooks = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); -} - -// Required for runtime benchmarks -pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type AssetDeposit = ConstU128<0>; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureSigned; - type Destroyer = AssetRouter; - type Freezer = (); - type MetadataDepositBase = ConstU128<0>; - type MetadataDepositPerByte = ConstU128<0>; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = ConstU32<255>; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type AssetDeposit = ConstU128<0>; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureSigned; - type Destroyer = AssetRouter; - type Freezer = (); - type MetadataDepositBase = ConstU128<0>; - type MetadataDepositPerByte = ConstU128<0>; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = ConstU32<255>; - type WeightInfo = (); -} - -// Required for runtime benchmarks -pallet_assets::runtime_benchmarks_enabled! { - use zeitgeist_primitives::types::CategoryIndex; - - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type AssetDeposit = ConstU128<0>; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureSigned; - type Destroyer = AssetRouter; - type Freezer = (); - type MetadataDepositBase = ConstU128<0>; - type MetadataDepositPerByte = ConstU128<0>; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = ConstU32<255>; - type WeightInfo = (); -} - -impl pallet_balances::Config for Runtime { - type AccountStore = System; - type Balance = Balance; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); -} - -pub(super) struct ExtBuilder { - balances: Vec<(AccountIdTest, Balance)>, -} - -impl Default for ExtBuilder { - fn default() -> Self { - Self { balances: vec![(ALICE, 1_000 * BASE), (BOB, 1_000 * BASE), (CHARLIE, 1_000 * BASE)] } - } -} - -impl ExtBuilder { - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - - pallet_balances::GenesisConfig:: { balances: self.balances } - .assimilate_storage(&mut t) - .unwrap(); - - t.into() - } -} - -#[frame_support::transactional] -pub(super) fn managed_destroy_multi_transactional( - assets: BTreeMap>, -) -> DispatchResult { - AssetRouter::managed_destroy_multi(assets) -} diff --git a/zrml/asset-router/src/pallet_impl/create.rs b/zrml/asset-router/src/pallet_impl/create.rs deleted file mode 100644 index 3e59e1e5d..000000000 --- a/zrml/asset-router/src/pallet_impl/create.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl Create for Pallet { - fn create( - id: Self::AssetId, - admin: T::AccountId, - is_sufficient: bool, - min_balance: Self::Balance, - ) -> DispatchResult { - only_asset!( - id, - Err(Error::::Unsupported.into()), - Create, - create, - admin, - is_sufficient, - min_balance - ) - } -} diff --git a/zrml/asset-router/src/pallet_impl/destroy.rs b/zrml/asset-router/src/pallet_impl/destroy.rs deleted file mode 100644 index 7058b2499..000000000 --- a/zrml/asset-router/src/pallet_impl/destroy.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl Destroy for Pallet { - fn start_destroy(id: Self::AssetId, maybe_check_owner: Option) -> DispatchResult { - only_asset!( - id, - Err(Error::::Unsupported.into()), - Destroy, - start_destroy, - maybe_check_owner - ) - } - - fn destroy_accounts(id: Self::AssetId, max_items: u32) -> Result { - only_asset!(id, Err(Error::::Unsupported.into()), Destroy, destroy_accounts, max_items) - } - - fn destroy_approvals(id: Self::AssetId, max_items: u32) -> Result { - only_asset!(id, Err(Error::::Unsupported.into()), Destroy, destroy_approvals, max_items) - } - - fn finish_destroy(id: Self::AssetId) -> DispatchResult { - only_asset!(id, Err(Error::::Unsupported.into()), Destroy, finish_destroy,) - } -} diff --git a/zrml/asset-router/src/pallet_impl/inspect.rs b/zrml/asset-router/src/pallet_impl/inspect.rs deleted file mode 100644 index 1c19338d4..000000000 --- a/zrml/asset-router/src/pallet_impl/inspect.rs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -// Supertrait of Create and Destroy -impl Inspect for Pallet { - type AssetId = T::AssetType; - type Balance = T::Balance; - - fn total_issuance(asset: Self::AssetId) -> Self::Balance { - route_call!(asset, total_issuance, total_issuance,).unwrap_or(Zero::zero()) - } - - fn minimum_balance(asset: Self::AssetId) -> Self::Balance { - route_call!(asset, minimum_balance, minimum_balance,).unwrap_or(Zero::zero()) - } - - fn balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance { - route_call!(asset, total_balance, balance, who).unwrap_or(Zero::zero()) - } - - fn reducible_balance( - asset: Self::AssetId, - who: &T::AccountId, - keep_alive: bool, - ) -> Self::Balance { - if T::CurrencyType::try_from(asset).is_ok() { - >::free_balance(asset, who) - } else { - only_asset!(asset, Zero::zero(), Inspect, reducible_balance, who, keep_alive) - } - } - - fn can_deposit( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - mint: bool, - ) -> DepositConsequence { - if T::CurrencyType::try_from(asset).is_err() { - return only_asset!( - asset, - DepositConsequence::UnknownAsset, - Inspect, - can_deposit, - who, - amount, - mint - ); - } - - let total_balance = >::total_balance(asset, who); - let min_balance = >::minimum_balance(asset); - - if total_balance.saturating_add(amount) < min_balance { - DepositConsequence::BelowMinimum - } else { - DepositConsequence::Success - } - } - - fn can_withdraw( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> WithdrawConsequence { - if T::CurrencyType::try_from(asset).is_err() { - return only_asset!( - asset, - WithdrawConsequence::UnknownAsset, - Inspect, - can_withdraw, - who, - amount - ); - } - - let can_withdraw = - >::ensure_can_withdraw(asset, who, amount); - - if let Err(_e) = can_withdraw { - return WithdrawConsequence::NoFunds; - } - - let total_balance = >::total_balance(asset, who); - let min_balance = >::minimum_balance(asset); - let remainder = total_balance.saturating_sub(amount); - - if remainder < min_balance { - WithdrawConsequence::ReducedToZero(remainder) - } else { - WithdrawConsequence::Success - } - } - - fn asset_exists(asset: Self::AssetId) -> bool { - if let Ok(currency) = T::CurrencyType::try_from(asset) { - if >::total_issuance(currency) - > Zero::zero() - { - true - } else { - only_asset!(asset, false, Inspect, asset_exists,) - } - } else { - only_asset!(asset, false, Inspect, asset_exists,) - } - } -} diff --git a/zrml/asset-router/src/pallet_impl/managed_destroy.rs b/zrml/asset-router/src/pallet_impl/managed_destroy.rs deleted file mode 100644 index fd22ac6b0..000000000 --- a/zrml/asset-router/src/pallet_impl/managed_destroy.rs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl Pallet { - fn add_asset_to_managed_destruction( - destroy_assets: &mut DestroyAssetsT, - asset: T::AssetType, - maybe_check_owner: Option, - ) -> DispatchResult { - ensure!(Self::asset_exists(asset), Error::::UnknownAsset); - frame_support::ensure!(!destroy_assets.is_full(), Error::::TooManyManagedDestroys); - let asset_to_insert = AssetInDestruction::new(asset); - - let idx = match destroy_assets.binary_search(&asset_to_insert) { - Ok(_) => return Err(Error::::DestructionInProgress.into()), - Err(idx) => { - if IndestructibleAssets::::get().binary_search(&asset).is_ok() { - return Err(Error::::AssetIndestructible.into()); - } - - idx - } - }; - - destroy_assets - .try_insert(idx, asset_to_insert) - .map_err(|_| Error::::TooManyManagedDestroys)?; - - Self::start_destroy(asset, maybe_check_owner)?; - Ok(()) - } -} - -impl ManagedDestroy for Pallet { - fn managed_destroy( - asset: Self::AssetId, - maybe_check_owner: Option, - ) -> DispatchResult { - let mut destroy_assets = DestroyAssets::::get(); - Self::add_asset_to_managed_destruction(&mut destroy_assets, asset, maybe_check_owner)?; - DestroyAssets::::put(destroy_assets); - Ok(()) - } - - fn managed_destroy_multi( - assets: BTreeMap>, - ) -> DispatchResult { - let mut destroy_assets = DestroyAssets::::get(); - - for (asset, maybe_check_owner) in assets { - Self::add_asset_to_managed_destruction(&mut destroy_assets, asset, maybe_check_owner)?; - } - - DestroyAssets::::put(destroy_assets); - Ok(()) - } -} diff --git a/zrml/asset-router/src/pallet_impl/mod.rs b/zrml/asset-router/src/pallet_impl/mod.rs deleted file mode 100644 index d0a94a1c7..000000000 --- a/zrml/asset-router/src/pallet_impl/mod.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -pub mod create; -pub mod destroy; -pub mod inspect; -pub mod managed_destroy; -pub mod multi_currency; -pub mod multi_currency_extended; -pub mod multi_lockable_currency; -pub mod multi_reserveable_currency; -pub mod named_multi_reserveable_currency; -pub mod transfer_all; -pub mod unbalanced; diff --git a/zrml/asset-router/src/pallet_impl/multi_currency.rs b/zrml/asset-router/src/pallet_impl/multi_currency.rs deleted file mode 100644 index 77a87d3a8..000000000 --- a/zrml/asset-router/src/pallet_impl/multi_currency.rs +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl MultiCurrency for Pallet { - type CurrencyId = T::AssetType; - type Balance = T::Balance; - - fn minimum_balance(currency_id: Self::CurrencyId) -> Self::Balance { - let min_balance = route_call!(currency_id, minimum_balance, minimum_balance,); - min_balance.unwrap_or_else(|_b| { - Self::log_unsupported(currency_id, "minimum_balance"); - Self::Balance::zero() - }) - } - - fn total_issuance(currency_id: Self::CurrencyId) -> Self::Balance { - let total_issuance = route_call!(currency_id, total_issuance, total_issuance,); - total_issuance.unwrap_or_else(|_b| { - Self::log_unsupported(currency_id, "total_issuance"); - Self::Balance::zero() - }) - } - - fn total_balance(currency_id: Self::CurrencyId, who: &T::AccountId) -> Self::Balance { - let total_balance = route_call!(currency_id, total_balance, balance, who); - total_balance.unwrap_or_else(|_b| { - Self::log_unsupported(currency_id, "total_balance"); - Self::Balance::zero() - }) - } - - fn free_balance(currency_id: Self::CurrencyId, who: &T::AccountId) -> Self::Balance { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - T::MarketAssets::reducible_balance(asset, who, false) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::free_balance(currency, who) - } else { - T::MarketAssets::reducible_balance(asset, who, false) - } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::reducible_balance(asset, who, false) - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::reducible_balance(asset, who, false) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::free_balance(currency, who) - } else { - Self::log_unsupported(currency_id, "free_balance"); - Self::Balance::zero() - } - } - - fn ensure_can_withdraw( - currency_id: Self::CurrencyId, - who: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - let withdraw_consequence = if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - T::MarketAssets::can_withdraw(asset, who, amount) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return T::Currencies::ensure_can_withdraw(currency, who, amount); - } else { - T::MarketAssets::can_withdraw(asset, who, amount) - } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::can_withdraw(asset, who, amount) - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::can_withdraw(asset, who, amount) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return T::Currencies::ensure_can_withdraw(currency, who, amount); - } else { - return Err(Error::::UnknownAsset.into()); - }; - - withdraw_consequence.into_result().map(|_| ()) - } - - fn transfer( - currency_id: Self::CurrencyId, - from: &T::AccountId, - to: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - T::MarketAssets::transfer(asset, from, to, amount, false).map(|_| ()) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::transfer(currency, from, to, amount) - } else { - T::MarketAssets::transfer(asset, from, to, amount, false).map(|_| ()) - } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::transfer(asset, from, to, amount, false).map(|_| ()) - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::transfer(asset, from, to, amount, false).map(|_| ()) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::transfer(currency, from, to, amount) - } else { - Err(Error::::UnknownAsset.into()) - } - } - - fn deposit( - currency_id: Self::CurrencyId, - who: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - route_call!(currency_id, deposit, mint_into, who, amount)? - } - - fn withdraw( - currency_id: Self::CurrencyId, - who: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - // Resulting balance can be ignored as `burn_from` ensures that the - // requested amount can be burned. - T::MarketAssets::burn_from(asset, who, amount).map(|_| ()) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::withdraw(currency, who, amount) - } else { - T::MarketAssets::burn_from(asset, who, amount).map(|_| ()) - } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::burn_from(asset, who, amount).map(|_| ()) - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::burn_from(asset, who, amount).map(|_| ()) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::withdraw(currency, who, amount) - } else { - Err(Error::::UnknownAsset.into()) - } - } - - fn can_slash(currency_id: Self::CurrencyId, who: &T::AccountId, value: Self::Balance) -> bool { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - // Resulting balance can be ignored as `burn_from` ensures that the - // requested amount can be burned. - T::MarketAssets::reducible_balance(asset, who, false) >= value - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::can_slash(currency, who, value) - } else { - T::MarketAssets::reducible_balance(asset, who, false) >= value - } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::reducible_balance(asset, who, false) >= value - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::reducible_balance(asset, who, false) >= value - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::can_slash(currency, who, value) - } else { - Self::log_unsupported(currency_id, "can_slash"); - false - } - } - - fn slash( - currency_id: Self::CurrencyId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Self::Balance { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - // Resulting balance can be ignored as `burn_from` ensures that the - // requested amount can be burned. - T::MarketAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::slash(currency, who, amount) - } else { - T::MarketAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) - } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::slash(currency, who, amount) - } else { - Self::log_unsupported(currency_id, "slash"); - amount - } - } -} diff --git a/zrml/asset-router/src/pallet_impl/multi_currency_extended.rs b/zrml/asset-router/src/pallet_impl/multi_currency_extended.rs deleted file mode 100644 index 70ea1f499..000000000 --- a/zrml/asset-router/src/pallet_impl/multi_currency_extended.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl Pallet { - fn update_balance_asset( - currency_id: >::CurrencyId, - who: &T::AccountId, - by_amount: >::Amount, - ) -> DispatchResult { - if by_amount.is_zero() { - return Ok(()); - } - - // Ensure that no overflows happen during abs(). - let by_amount_abs = - if by_amount == >::Amount::min_value() { - return Err(Error::::AmountIntoBalanceFailed.into()); - } else { - by_amount.abs() - }; - - let by_balance = - TryInto::<>::Balance>::try_into(by_amount_abs) - .map_err(|_| Error::::AmountIntoBalanceFailed)?; - if by_amount.is_positive() { - Self::deposit(currency_id, who, by_balance) - } else { - Self::withdraw(currency_id, who, by_balance).map(|_| ()) - } - } -} - -impl MultiCurrencyExtended for Pallet { - type Amount = >::Amount; - - fn update_balance( - currency_id: Self::CurrencyId, - who: &T::AccountId, - by_amount: Self::Amount, - ) -> DispatchResult { - if by_amount.is_zero() { - return Ok(()); - } - - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - // Route "pre new asset system" market assets to `CurrencyType` - if T::MarketAssets::asset_exists(asset) { - Self::update_balance_asset(currency_id, who, by_amount) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::update_balance(currency, who, by_amount) - } else { - Self::update_balance_asset(currency_id, who, by_amount) - } - } else if let Ok(_asset) = T::CampaignAssetType::try_from(currency_id) { - Self::update_balance_asset(currency_id, who, by_amount) - } else if let Ok(_asset) = T::CustomAssetType::try_from(currency_id) { - Self::update_balance_asset(currency_id, who, by_amount) - } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - T::Currencies::update_balance(currency, who, by_amount) - } else { - Err(Error::::UnknownAsset.into()) - } - } -} diff --git a/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs b/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs deleted file mode 100644 index 55e9d5779..000000000 --- a/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl MultiLockableCurrency for Pallet { - type Moment = T::BlockNumber; - - fn set_lock( - lock_id: LockIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - return Err(Error::::Unsupported.into()); - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::set_lock( - lock_id, currency, who, amount, - ); - } - - Err(Error::::Unsupported.into()) - } - - fn extend_lock( - lock_id: LockIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - return Err(Error::::Unsupported.into()); - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::extend_lock( - lock_id, currency, who, amount, - ); - } - - Err(Error::::Unsupported.into()) - } - - fn remove_lock( - lock_id: LockIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - ) -> DispatchResult { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - return Err(Error::::Unsupported.into()); - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::remove_lock( - lock_id, currency, who, - ); - } - - Err(Error::::Unsupported.into()) - } -} diff --git a/zrml/asset-router/src/pallet_impl/multi_reserveable_currency.rs b/zrml/asset-router/src/pallet_impl/multi_reserveable_currency.rs deleted file mode 100644 index a6bed8360..000000000 --- a/zrml/asset-router/src/pallet_impl/multi_reserveable_currency.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl MultiReservableCurrency for Pallet { - fn can_reserve( - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> bool { - only_currency!(currency_id, false, MultiReservableCurrency, can_reserve, who, value) - } - - fn slash_reserved( - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> Self::Balance { - only_currency!(currency_id, value, MultiReservableCurrency, slash_reserved, who, value) - } - - fn reserved_balance(currency_id: Self::CurrencyId, who: &T::AccountId) -> Self::Balance { - only_currency!(currency_id, Zero::zero(), MultiReservableCurrency, reserved_balance, who) - } - - fn reserve( - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> DispatchResult { - only_currency!( - currency_id, - Err(Error::::Unsupported.into()), - MultiReservableCurrency, - reserve, - who, - value - ) - } - - fn unreserve( - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> Self::Balance { - only_currency!(currency_id, value, MultiReservableCurrency, unreserve, who, value) - } - - fn repatriate_reserved( - currency_id: Self::CurrencyId, - slashed: &T::AccountId, - beneficiary: &T::AccountId, - value: Self::Balance, - status: BalanceStatus, - ) -> Result { - only_currency!( - currency_id, - Err(Error::::Unsupported.into()), - MultiReservableCurrency, - repatriate_reserved, - slashed, - beneficiary, - value, - status - ) - } -} diff --git a/zrml/asset-router/src/pallet_impl/named_multi_reserveable_currency.rs b/zrml/asset-router/src/pallet_impl/named_multi_reserveable_currency.rs deleted file mode 100644 index c1f70393d..000000000 --- a/zrml/asset-router/src/pallet_impl/named_multi_reserveable_currency.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl NamedMultiReservableCurrency for Pallet { - type ReserveIdentifier = - >::ReserveIdentifier; - - fn reserved_balance_named( - id: &Self::ReserveIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - ) -> Self::Balance { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - Self::log_unsupported(currency_id, "reserved_balance_named"); - return Zero::zero(); - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::reserved_balance_named( - id, currency, who, - ); - } - - Self::log_unsupported(currency_id, "reserved_balance_named"); - Zero::zero() - } - - fn reserve_named( - id: &Self::ReserveIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> DispatchResult { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - return Err(Error::::Unsupported.into()); - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::reserve_named( - id, currency, who, value, - ); - } - - Err(Error::::Unsupported.into()) - } - - fn unreserve_named( - id: &Self::ReserveIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> Self::Balance { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - Self::log_unsupported(currency_id, "unreserve_named"); - return value; - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::unreserve_named( - id, currency, who, value, - ); - } - - Self::log_unsupported(currency_id, "unreserve_named"); - value - } - - fn slash_reserved_named( - id: &Self::ReserveIdentifier, - currency_id: Self::CurrencyId, - who: &T::AccountId, - value: Self::Balance, - ) -> Self::Balance { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - Self::log_unsupported(currency_id, "slash_reserved_named"); - return value; - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::slash_reserved_named( - id, currency, who, value - ); - } - - Self::log_unsupported(currency_id, "slash_reserved_named"); - value - } - - fn repatriate_reserved_named( - id: &Self::ReserveIdentifier, - currency_id: Self::CurrencyId, - slashed: &T::AccountId, - beneficiary: &T::AccountId, - value: Self::Balance, - status: Status, - ) -> Result { - if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { - if T::MarketAssets::asset_exists(asset) { - return Err(Error::::Unsupported.into()); - } - } - if let Ok(currency) = T::CurrencyType::try_from(currency_id) { - return >::repatriate_reserved_named( - id, currency, slashed, beneficiary, value, status - ); - } - - Err(Error::::Unsupported.into()) - } -} diff --git a/zrml/asset-router/src/pallet_impl/transfer_all.rs b/zrml/asset-router/src/pallet_impl/transfer_all.rs deleted file mode 100644 index 0dd0f829f..000000000 --- a/zrml/asset-router/src/pallet_impl/transfer_all.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; - -impl TransferAll for Pallet { - #[require_transactional] - fn transfer_all(source: &T::AccountId, dest: &T::AccountId) -> DispatchResult { - // Only transfers assets maintained in orml-tokens, not implementable for pallet-assets - >::transfer_all(source, dest) - } -} diff --git a/zrml/asset-router/src/pallet_impl/unbalanced.rs b/zrml/asset-router/src/pallet_impl/unbalanced.rs deleted file mode 100644 index fc91c047a..000000000 --- a/zrml/asset-router/src/pallet_impl/unbalanced.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::pallet::*; -use frame_support::traits::tokens::fungibles::Unbalanced; - -impl Unbalanced for Pallet { - fn set_balance( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> DispatchResult { - route_call_with_trait!(asset, Unbalanced, set_balance, who, amount)? - } - - fn set_total_issuance(asset: Self::AssetId, amount: Self::Balance) { - let _ = route_call_with_trait!(asset, Unbalanced, set_total_issuance, amount); - } - - fn decrease_balance( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Result { - route_call_with_trait!(asset, Unbalanced, decrease_balance, who, amount)? - } - - fn decrease_balance_at_most( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Self::Balance { - route_call_with_trait!(asset, Unbalanced, decrease_balance_at_most, who, amount) - .unwrap_or(Zero::zero()) - } - - fn increase_balance( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Result { - route_call_with_trait!(asset, Unbalanced, increase_balance, who, amount)? - } - - fn increase_balance_at_most( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Self::Balance { - route_call_with_trait!(asset, Unbalanced, increase_balance_at_most, who, amount) - .unwrap_or(Zero::zero()) - } -} diff --git a/zrml/asset-router/src/tests/create.rs b/zrml/asset-router/src/tests/create.rs deleted file mode 100644 index 4b81382ac..000000000 --- a/zrml/asset-router/src/tests/create.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use frame_support::traits::tokens::fungibles::Inspect; - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert!(AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(CUSTOM_ASSET)); - assert!(!AssetRouter::asset_exists(MARKET_ASSET)); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert!(AssetRouter::asset_exists(CUSTOM_ASSET)); - assert!(!AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(MARKET_ASSET)); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert!(AssetRouter::asset_exists(MARKET_ASSET)); - assert!(!AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(CUSTOM_ASSET)); - }); -} - -#[test] -fn routes_currencies_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - AssetRouter::create(CURRENCY, ALICE, true, CURRENCY_MIN_BALANCE), - Error::::Unsupported - ); - }); -} diff --git a/zrml/asset-router/src/tests/custom_types.rs b/zrml/asset-router/src/tests/custom_types.rs deleted file mode 100644 index 0faf7bc68..000000000 --- a/zrml/asset-router/src/tests/custom_types.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::{AssetInDestruction, DestructionState}; - -type Aid = AssetInDestruction; - -#[test] -fn asset_in_destruction_created_properly() { - let aid = Aid::new(2); - assert_eq!(*aid.asset(), 2); - assert_eq!(*aid.state(), DestructionState::Accounts); -} - -#[test] -fn asset_in_destruction_transitions_states_properly() { - let mut aid = Aid::new(2); - - aid.transit_state(); - assert_eq!(*aid.state(), DestructionState::Approvals); - - aid.transit_state(); - assert_eq!(*aid.state(), DestructionState::Finalization); - - aid.transit_state(); - assert_eq!(*aid.state(), DestructionState::Destroyed); - - aid.transit_state(); - assert_eq!(*aid.state(), DestructionState::Destroyed); -} - -#[test] -fn asset_in_destruction_indestructible_state_works() { - let mut aid = Aid::new(2); - - aid.transit_indestructible(); - assert_eq!(*aid.state(), DestructionState::Indestructible); - - aid.transit_state(); - assert_eq!(*aid.state(), DestructionState::Indestructible); -} - -#[test] -fn asset_in_destruction_ordering_works() { - // Order by destruction state first. - let asset_1 = Aid::new(0); - let mut asset_2 = asset_1; - assert_eq!(asset_2.transit_state(), Some(&DestructionState::Approvals)); - let mut asset_3 = asset_2; - assert_eq!(asset_3.transit_state(), Some(&DestructionState::Finalization)); - let mut asset_4 = asset_3; - assert_eq!(asset_4.transit_state(), Some(&DestructionState::Destroyed)); - let mut asset_5 = asset_1; - asset_5.transit_indestructible(); - - let mut asset_vec = vec![asset_5, asset_4, asset_3, asset_2, asset_1]; - let mut expected = vec![asset_1, asset_2, asset_3, asset_4, asset_5]; - asset_vec.sort(); - assert_eq!(asset_vec, expected); - - // On equal destruction state, order by asset id. - let mut asset_dif_id_1 = Aid::new(1); - asset_dif_id_1.transit_state(); - let mut asset_dif_id_2 = Aid::new(2); - asset_dif_id_2.transit_state(); - - asset_vec.push(asset_dif_id_1); - asset_vec.push(asset_dif_id_2); - asset_vec.sort(); - expected = vec![asset_1, asset_dif_id_2, asset_dif_id_1, asset_2, asset_3, asset_4, asset_5]; - assert_eq!(asset_vec, expected); -} diff --git a/zrml/asset-router/src/tests/destroy.rs b/zrml/asset-router/src/tests/destroy.rs deleted file mode 100644 index cca618b9b..000000000 --- a/zrml/asset-router/src/tests/destroy.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use frame_support::traits::tokens::fungibles::Inspect; - -fn test_helper(asset: Assets, initial_amount: ::Balance) { - assert_ok!(>::deposit( - asset, - &ALICE, - initial_amount - )); - assert!(AssetRouter::asset_exists(asset)); - assert_ok!(AssetRouter::start_destroy(asset, None)); - assert_eq!(AssetRouter::destroy_accounts(asset, 100), Ok(1)); - assert_eq!(AssetRouter::destroy_approvals(asset, 100), Ok(1)); - assert_ok!(AssetRouter::finish_destroy(asset)); - assert!(!AssetRouter::asset_exists(asset)); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE,)); - assert_ok!( - pallet_assets::Call::::approve_transfer { - id: CAMPAIGN_ASSET_INTERNAL.into(), - delegate: BOB, - amount: 1 - } - .dispatch_bypass_filter(Signed(ALICE).into()) - ); - - test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE,)); - assert_ok!( - pallet_assets::Call::::approve_transfer { - id: CUSTOM_ASSET_INTERNAL.into(), - delegate: BOB, - amount: 1 - } - .dispatch_bypass_filter(Signed(ALICE).into()) - ); - - test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE,)); - assert_ok!( - pallet_assets::Call::::approve_transfer { - id: MARKET_ASSET_INTERNAL, - delegate: BOB, - amount: 1 - } - .dispatch_bypass_filter(Signed(ALICE).into()) - ); - - test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_currencies_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(>::deposit( - CURRENCY, - &ALICE, - CURRENCY_INITIAL_AMOUNT - )); - assert_noop!(AssetRouter::start_destroy(CURRENCY, None), Error::::Unsupported); - assert_noop!(AssetRouter::destroy_accounts(CURRENCY, 100), Error::::Unsupported); - assert_noop!(AssetRouter::destroy_approvals(CURRENCY, 100), Error::::Unsupported); - assert_noop!(AssetRouter::finish_destroy(CURRENCY), Error::::Unsupported); - }); -} diff --git a/zrml/asset-router/src/tests/inspect.rs b/zrml/asset-router/src/tests/inspect.rs deleted file mode 100644 index e762a3115..000000000 --- a/zrml/asset-router/src/tests/inspect.rs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use frame_support::traits::tokens::fungibles::Inspect; - -fn test_helper(asset: Assets, initial_amount: ::Balance) { - assert_ok!(>::deposit( - asset, - &ALICE, - initial_amount - )); - assert!(AssetRouter::asset_exists(asset)); - assert_eq!(AssetRouter::total_issuance(asset), initial_amount); - assert_eq!(AssetRouter::balance(asset, &ALICE), initial_amount); - assert_eq!(AssetRouter::reducible_balance(asset, &ALICE, false), initial_amount); - assert_eq!( - AssetRouter::can_withdraw(asset, &ALICE, initial_amount), - WithdrawConsequence::ReducedToZero(0) - ); - assert_eq!(AssetRouter::can_deposit(asset, &ALICE, 1, true), DepositConsequence::Success); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - use orml_traits::MultiCurrency; - - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE,)); - assert_eq!( - >::minimum_balance(CAMPAIGN_ASSET), - CAMPAIGN_ASSET_MIN_BALANCE - ); - test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT); - assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - use orml_traits::MultiCurrency; - - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE,)); - assert_eq!( - >::minimum_balance(CUSTOM_ASSET), - CUSTOM_ASSET_MIN_BALANCE - ); - test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT); - assert_eq!( - >::total_issuance(CAMPAIGN_ASSET_INTERNAL), - 0 - ); - assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - use orml_traits::MultiCurrency; - - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE,)); - assert_eq!( - >::minimum_balance(MARKET_ASSET), - MARKET_ASSET_MIN_BALANCE - ); - test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT); - assert_eq!( - >::total_issuance(CAMPAIGN_ASSET_INTERNAL), - 0 - ); - assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); - }); -} - -#[test] -fn routes_currencies_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_eq!(AssetRouter::minimum_balance(CURRENCY), CURRENCY_MIN_BALANCE); - assert_eq!(AssetRouter::minimum_balance(CURRENCY_OLD_OUTCOME), CURRENCY_MIN_BALANCE); - - test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT); - test_helper(CURRENCY_OLD_OUTCOME, CURRENCY_INITIAL_AMOUNT); - - assert_eq!( - >::total_issuance(CAMPAIGN_ASSET_INTERNAL), - 0 - ); - assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); - }); -} diff --git a/zrml/asset-router/src/tests/managed_destroy.rs b/zrml/asset-router/src/tests/managed_destroy.rs deleted file mode 100644 index 1c2700ffb..000000000 --- a/zrml/asset-router/src/tests/managed_destroy.rs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use crate::{ - AssetInDestruction, DestroyAssets, DestructionState, IndestructibleAssets, Weight, - MAX_ASSET_DESTRUCTIONS_PER_BLOCK, MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, -}; -use frame_support::{ - traits::{tokens::fungibles::Inspect, Get}, - weights::RuntimeDbWeight, - BoundedVec, -}; -use pallet_assets::ManagedDestroy; - -#[test] -fn adds_assets_properly() { - ExtBuilder::default().build().execute_with(|| { - let campaign_asset = AssetInDestruction::new(CAMPAIGN_ASSET); - let custom_asset = AssetInDestruction::new(CUSTOM_ASSET); - - assert_noop!( - AssetRouter::managed_destroy(CAMPAIGN_ASSET, None), - Error::::UnknownAsset - ); - - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::managed_destroy(CAMPAIGN_ASSET, None)); - assert_noop!( - AssetRouter::managed_destroy(CAMPAIGN_ASSET, None), - Error::::DestructionInProgress - ); - assert_eq!(DestroyAssets::::get(), vec![campaign_asset]); - - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::managed_destroy(CUSTOM_ASSET, None)); - let mut expected = vec![campaign_asset, custom_asset]; - expected.sort(); - assert_eq!(DestroyAssets::::get(), expected); - - IndestructibleAssets::::put(BoundedVec::truncate_from(vec![ - CAMPAIGN_ASSET, - CUSTOM_ASSET, - ])); - DestroyAssets::::kill(); - assert_noop!( - AssetRouter::managed_destroy(CAMPAIGN_ASSET, None), - Error::::AssetIndestructible - ); - assert_noop!( - AssetRouter::managed_destroy(CUSTOM_ASSET, None), - Error::::AssetIndestructible - ); - }); -} - -#[test] -fn adds_multi_assets_properly() { - ExtBuilder::default().build().execute_with(|| { - let assets = BTreeMap::from([(CAMPAIGN_ASSET, None), (CUSTOM_ASSET, None)]); - let campaign_asset = AssetInDestruction::new(CAMPAIGN_ASSET); - let custom_asset = AssetInDestruction::new(CUSTOM_ASSET); - - assert_noop!( - managed_destroy_multi_transactional(assets.clone()), - Error::::UnknownAsset - ); - - for (asset, _) in assets.clone() { - assert_ok!(AssetRouter::create(asset, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - } - - assert_ok!(managed_destroy_multi_transactional(assets.clone())); - - for (asset, _) in assets.clone() { - assert_noop!( - AssetRouter::managed_destroy(asset, None), - Error::::DestructionInProgress - ); - } - - assert_noop!( - managed_destroy_multi_transactional(assets.clone()), - Error::::DestructionInProgress - ); - let mut expected = vec![campaign_asset, custom_asset]; - expected.sort(); - assert_eq!(DestroyAssets::::get(), expected); - - IndestructibleAssets::::put(BoundedVec::truncate_from(vec![ - CAMPAIGN_ASSET, - CUSTOM_ASSET, - ])); - DestroyAssets::::kill(); - assert_noop!( - managed_destroy_multi_transactional(assets), - Error::::AssetIndestructible - ); - }); -} - -#[test] -fn destroys_assets_fully_works_properly() { - ExtBuilder::default().build().execute_with(|| { - let assets_raw = [(CAMPAIGN_ASSET, None), (CUSTOM_ASSET, None), (MARKET_ASSET, None)]; - let assets = BTreeMap::from_iter(assets_raw.to_vec()); - - for (asset, _) in &assets_raw[..] { - assert_ok!(AssetRouter::create(*asset, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - } - - assert_ok!( - pallet_assets::Call::::approve_transfer { - id: CAMPAIGN_ASSET_INTERNAL.into(), - delegate: BOB, - amount: 1 - } - .dispatch_bypass_filter(Signed(ALICE).into()) - ); - - assert_ok!(managed_destroy_multi_transactional(assets.clone())); - assert_eq!(DestroyAssets::::get().len(), 3); - - let available_weight = (2 * MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT).into(); - let remaining_weight = AssetRouter::on_idle(0, available_weight); - assert!(!AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(CUSTOM_ASSET)); - assert!(!AssetRouter::asset_exists(MARKET_ASSET)); - assert_eq!(IndestructibleAssets::::get(), vec![]); - assert_eq!(DestroyAssets::::get(), vec![]); - - let mut consumed_weight = available_weight - 3u64 * 3u64 * DESTROY_WEIGHT; - // Consider safety buffer for extra execution time and storage proof size - consumed_weight = consumed_weight - .saturating_sub(Weight::from_parts(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, 45_824)); - assert_eq!(remaining_weight, consumed_weight); - }) -} - -#[test] -fn destroys_assets_partially_properly() { - ExtBuilder::default().build().execute_with(|| { - let assets_raw = [(CAMPAIGN_ASSET, None), (CUSTOM_ASSET, None), (MARKET_ASSET, None)]; - let assets = BTreeMap::from_iter(assets_raw.to_vec()); - - for (asset, _) in &assets_raw[..] { - assert_ok!(AssetRouter::create(*asset, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - } - - assert_ok!(managed_destroy_multi_transactional(assets.clone())); - assert_eq!(DestroyAssets::::get().len(), 3); - - let mut available_weight: Weight = - Weight::from_all(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT) + 2u64 * DESTROY_WEIGHT; - // Make on_idle only partially delete the first asset - let _ = AssetRouter::on_idle(0, available_weight); - assert_eq!(DestroyAssets::::get().len(), 3); - - // Now delete each asset one by one by supplying exactly the required weight - available_weight = Weight::from_all(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT) + DESTROY_WEIGHT; - let _ = AssetRouter::on_idle(0, available_weight); - assert_eq!(DestroyAssets::::get().len(), 2); - - available_weight = - Weight::from_all(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT) + 3u64 * DESTROY_WEIGHT; - let _ = AssetRouter::on_idle(0, available_weight); - assert_eq!(DestroyAssets::::get().len(), 1); - - let _ = AssetRouter::on_idle(0, available_weight); - assert_eq!(DestroyAssets::::get().len(), 0); - - assert!(!AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(CUSTOM_ASSET)); - assert!(!AssetRouter::asset_exists(MARKET_ASSET)); - }) -} - -#[test] -fn properly_handles_indestructible_assets() { - ExtBuilder::default().build().execute_with(|| { - let assets_raw = vec![CAMPAIGN_ASSET, CUSTOM_ASSET, MARKET_ASSET]; - let mut destroy_assets = DestroyAssets::::get(); - let available_weight = (4 * MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT).into(); - - for asset in assets_raw { - destroy_assets.force_push(AssetInDestruction::new(asset)); - } - - destroy_assets.sort(); - - let setup_state = || { - assert_ok!(AssetRouter::create( - *destroy_assets[0].asset(), - ALICE, - true, - CAMPAIGN_ASSET_MIN_BALANCE - )); - assert_ok!(AssetRouter::create( - *destroy_assets[2].asset(), - ALICE, - true, - CAMPAIGN_ASSET_MIN_BALANCE - )); - assert_ok!(AssetRouter::start_destroy(*destroy_assets[0].asset(), None)); - assert_ok!(AssetRouter::start_destroy(*destroy_assets[2].asset(), None)); - }; - - // [1] Asset is indestructible and not in Finalization state, - // i.e. weight consumption bounded but unknown. - setup_state(); - DestroyAssets::::put(destroy_assets.clone()); - assert_eq!(DestroyAssets::::get().len(), 3); - let remaining_weight = AssetRouter::on_idle(0, available_weight); - assert_eq!(DestroyAssets::::get().len(), 1); - assert_eq!(remaining_weight, 0.into()); - - // Destroy remaining assets - let _ = AssetRouter::on_idle(0, available_weight); - assert_eq!(DestroyAssets::::get().len(), 0); - assert_eq!(IndestructibleAssets::::get().len(), 1); - - assert!(!AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(CUSTOM_ASSET)); - assert!(!AssetRouter::asset_exists(MARKET_ASSET)); - - // [2] Asset is indestructible and in Finalization state, - // i.e. weight consumption bounded and known. - DestroyAssets::::kill(); - IndestructibleAssets::::kill(); - setup_state(); - destroy_assets[1].transit_state(); - destroy_assets[1].transit_state(); - DestroyAssets::::put(destroy_assets); - assert_eq!(DestroyAssets::::get().len(), 3); - let remaining_weight = AssetRouter::on_idle(0, available_weight); - let mut consumed_weight = available_weight - 2u32 * 3u32 * DESTROY_WEIGHT - DESTROY_WEIGHT; - // Consider safety buffer for extra execution time and storage proof size - consumed_weight = consumed_weight - .saturating_sub(Weight::from_parts(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, 45_824)); - assert_eq!(remaining_weight, consumed_weight); - assert_eq!(DestroyAssets::::get().len(), 0); - assert_eq!(IndestructibleAssets::::get().len(), 1); - - assert!(!AssetRouter::asset_exists(CAMPAIGN_ASSET)); - assert!(!AssetRouter::asset_exists(CUSTOM_ASSET)); - assert!(!AssetRouter::asset_exists(MARKET_ASSET)); - }) -} - -#[test] -fn does_not_execute_on_insufficient_weight() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::managed_destroy(CAMPAIGN_ASSET, None)); - assert_eq!(DestroyAssets::::get().len(), 1); - - let db_weight: RuntimeDbWeight = ::DbWeight::get(); - let mut available_weight = Weight::from_parts(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, 45_824) - + db_weight.reads(1) - - 1u64.into(); - let mut remaining_weight = AssetRouter::on_idle(0, available_weight); - assert_eq!(available_weight, remaining_weight); - assert_eq!(DestroyAssets::::get().len(), 1); - - available_weight += Weight::from_all(1u64) + db_weight.writes(1); - let mut remaining_weight_expected: Weight = 0u64.into(); - remaining_weight = AssetRouter::on_idle(0, available_weight); - assert_eq!(remaining_weight_expected, remaining_weight); - assert_eq!(DestroyAssets::::get().len(), 1); - - remaining_weight_expected = 1u64.into(); - available_weight += 3u64 * DESTROY_WEIGHT + remaining_weight_expected; - remaining_weight = AssetRouter::on_idle(0, available_weight); - assert_eq!(remaining_weight_expected, remaining_weight); - assert_eq!(DestroyAssets::::get().len(), 0); - }) -} - -#[test] -fn does_skip_and_remove_assets_in_invalid_state() { - ExtBuilder::default().build().execute_with(|| { - let mut campaign_asset = AssetInDestruction::new(CAMPAIGN_ASSET); - campaign_asset.transit_state(); - campaign_asset.transit_state(); - assert_eq!(*campaign_asset.transit_state().unwrap(), DestructionState::Destroyed); - let mut custom_asset = AssetInDestruction::new(CUSTOM_ASSET); - custom_asset.transit_indestructible(); - - let assets_raw = BoundedVec::truncate_from(vec![campaign_asset, custom_asset]); - DestroyAssets::::put(assets_raw); - let db_weight: RuntimeDbWeight = ::DbWeight::get(); - let available_weight = Weight::from_parts(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, 45_824) - + db_weight.reads_writes(1, 1) - + DESTROY_WEIGHT; - - let remaining_weight = AssetRouter::on_idle(0, available_weight); - // No destroy routine was called - assert_eq!(remaining_weight, DESTROY_WEIGHT); - // Asset in invalid states got removed - assert_eq!(DestroyAssets::::get().len(), 0); - }); -} - -#[test] -#[should_panic(expected = "Destruction outer loop iteration guard triggered")] -fn does_trigger_on_idle_outer_loop_safety_guard() { - ExtBuilder::default().build().execute_with(|| { - for asset_num in 0..=MAX_ASSET_DESTRUCTIONS_PER_BLOCK { - let asset = Assets::CampaignAsset(asset_num as u128); - assert_ok!(AssetRouter::create(asset, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::managed_destroy(asset, None)); - } - - let db_weight: RuntimeDbWeight = ::DbWeight::get(); - let available_weight = Weight::from_parts(MIN_ON_IDLE_EXTRA_COMPUTATION_WEIGHT, 45_824) - + db_weight.reads(1) - + DESTROY_WEIGHT * 3 * (MAX_ASSET_DESTRUCTIONS_PER_BLOCK + 1) as u64; - - let _ = AssetRouter::on_idle(0, available_weight); - }); -} diff --git a/zrml/asset-router/src/tests/mod.rs b/zrml/asset-router/src/tests/mod.rs deleted file mode 100644 index 48a23763d..000000000 --- a/zrml/asset-router/src/tests/mod.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::{mock::*, Error}; -use alloc::collections::BTreeMap; -use frame_support::{ - assert_noop, assert_ok, - dispatch::RawOrigin::Signed, - traits::{ - tokens::{ - fungibles::{Create, Destroy}, - DepositConsequence, WithdrawConsequence, - }, - OnIdle, UnfilteredDispatchable, - }, -}; -use orml_traits::{ - BalanceStatus, MultiCurrencyExtended, MultiLockableCurrency, MultiReservableCurrency, - NamedMultiReservableCurrency, -}; -use zeitgeist_primitives::types::Assets; - -mod create; -mod custom_types; -mod destroy; -mod inspect; -mod managed_destroy; -mod multi_currency; -mod multi_lockable_currency; -mod multi_reservable_currency; -mod named_multi_reservable_currency; -mod unbalanced; diff --git a/zrml/asset-router/src/tests/multi_currency.rs b/zrml/asset-router/src/tests/multi_currency.rs deleted file mode 100644 index 0e6802305..000000000 --- a/zrml/asset-router/src/tests/multi_currency.rs +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use orml_traits::MultiCurrency; -use test_case::test_case; -use zeitgeist_primitives::types::{Amount, Balance}; - -fn test_helper( - asset: Assets, - initial_amount: ::Balance, - min_balance: ::Balance, -) { - assert_eq!(AssetRouter::minimum_balance(asset), min_balance); - assert_ok!(AssetRouter::deposit(asset, &ALICE, initial_amount)); - assert_eq!(AssetRouter::total_issuance(asset), initial_amount); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount); - assert_eq!(AssetRouter::free_balance(asset, &ALICE), initial_amount); - assert_ok!(AssetRouter::ensure_can_withdraw(asset, &ALICE, initial_amount)); - assert!(AssetRouter::ensure_can_withdraw(asset, &ALICE, initial_amount + 1).is_err()); - assert_ok!(AssetRouter::transfer(asset, &ALICE, &BOB, min_balance)); - assert_eq!(AssetRouter::free_balance(asset, &BOB), min_balance); - assert_eq!(AssetRouter::free_balance(asset, &ALICE), initial_amount - min_balance); - assert_ok!(AssetRouter::withdraw(asset, &ALICE, 1)); - assert_eq!(AssetRouter::free_balance(asset, &ALICE), initial_amount - min_balance - 1); - assert!(AssetRouter::can_slash(asset, &ALICE, 1)); - assert_eq!(AssetRouter::slash(asset, &ALICE, 1), 0); - assert_eq!(AssetRouter::free_balance(asset, &ALICE), initial_amount - min_balance - 2); - assert_ok!(AssetRouter::update_balance( - asset, - &ALICE, - >::Amount::from(1u8) - - >::Amount::from(2u8) - )); - assert_eq!(AssetRouter::free_balance(asset, &ALICE), initial_amount - min_balance - 3); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::traits::tokens::fungibles::Inspect; - - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - - test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT, CAMPAIGN_ASSET_MIN_BALANCE); - - assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::traits::tokens::fungibles::Inspect; - - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); - - test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT, CUSTOM_ASSET_MIN_BALANCE); - - assert_eq!( - >::total_issuance(CAMPAIGN_ASSET_INTERNAL), - 0 - ); - assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::traits::tokens::fungibles::Inspect; - - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE)); - - test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT, MARKET_ASSET_MIN_BALANCE); - - assert_eq!( - >::total_issuance(CAMPAIGN_ASSET_INTERNAL), - 0 - ); - assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); - }); -} - -#[test] -fn routes_currencies_correctly() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::traits::tokens::fungibles::Inspect; - - test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT, CURRENCY_MIN_BALANCE); - test_helper(CURRENCY_OLD_OUTCOME, CURRENCY_INITIAL_AMOUNT, CURRENCY_MIN_BALANCE); - - assert_eq!( - >::total_issuance(CAMPAIGN_ASSET_INTERNAL), - 0 - ); - assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); - assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); - }); -} - -#[test_case(0, Some(0); "zero")] -#[test_case(Amount::max_value(), Some(Amount::max_value().unsigned_abs() as Balance); "max")] -#[test_case(Amount::min_value(), None; "min")] -#[test_case(Amount::min_value() + 1, Some((Amount::min_value() + 1).unsigned_abs() as Balance); "min_plus_one")] -fn update_balance_handles_overflows_correctly(update: Amount, expected: Option) { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - - if update.is_negative() { - assert_ok!(AssetRouter::update_balance(CAMPAIGN_ASSET, &ALICE, Amount::max_value())); - } - - if let Some(expected_inner) = expected { - assert_ok!(AssetRouter::update_balance(CAMPAIGN_ASSET, &ALICE, update)); - - if update.is_negative() { - assert_eq!( - AssetRouter::free_balance(CAMPAIGN_ASSET, &ALICE), - Amount::max_value() as Balance - expected_inner - ); - } else { - assert_eq!(AssetRouter::free_balance(CAMPAIGN_ASSET, &ALICE), expected_inner); - } - } else { - assert_noop!( - AssetRouter::update_balance(CAMPAIGN_ASSET, &ALICE, update), - Error::::AmountIntoBalanceFailed - ); - } - }); -} diff --git a/zrml/asset-router/src/tests/multi_lockable_currency.rs b/zrml/asset-router/src/tests/multi_lockable_currency.rs deleted file mode 100644 index 20497d243..000000000 --- a/zrml/asset-router/src/tests/multi_lockable_currency.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use orml_traits::MultiCurrency; -use test_case::test_case; - -fn unroutable_test_helper(asset: Assets) { - assert_noop!( - AssetRouter::set_lock(Default::default(), asset, &ALICE, 1), - Error::::Unsupported - ); - assert_noop!( - AssetRouter::extend_lock(Default::default(), asset, &ALICE, 1), - Error::::Unsupported - ); - assert_noop!( - AssetRouter::remove_lock(Default::default(), asset, &ALICE), - Error::::Unsupported - ); -} - -#[test_case(CURRENCY; "foreign")] -#[test_case(CURRENCY_OLD_OUTCOME; "old_outcome")] -fn routes_currencies_correctly(currency_id: Assets) { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::deposit(currency_id, &ALICE, CURRENCY_INITIAL_AMOUNT)); - assert_ok!(AssetRouter::set_lock(Default::default(), currency_id, &ALICE, 1)); - assert_eq!( - orml_tokens::Accounts::::get::< - u128, - ::CurrencyId, - >(ALICE, currency_id.try_into().unwrap()) - .frozen, - 1 - ); - assert_ok!(AssetRouter::extend_lock(Default::default(), currency_id, &ALICE, 2)); - assert_eq!( - orml_tokens::Accounts::::get::< - u128, - ::CurrencyId, - >(ALICE, currency_id.try_into().unwrap()) - .frozen, - 2 - ); - assert_ok!(AssetRouter::remove_lock(Default::default(), currency_id, &ALICE)); - assert_eq!( - orml_tokens::Accounts::::get::< - u128, - ::CurrencyId, - >(ALICE, currency_id.try_into().unwrap()) - .frozen, - 0 - ); - }); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(CAMPAIGN_ASSET); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(CUSTOM_ASSET); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(MARKET_ASSET); - }); -} diff --git a/zrml/asset-router/src/tests/multi_reservable_currency.rs b/zrml/asset-router/src/tests/multi_reservable_currency.rs deleted file mode 100644 index 029ce57d6..000000000 --- a/zrml/asset-router/src/tests/multi_reservable_currency.rs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use orml_traits::MultiCurrency; -use test_case::test_case; - -fn unroutable_test_helper(asset: Assets, initial_amount: ::Balance) { - assert_ok!(AssetRouter::deposit(asset, &ALICE, initial_amount)); - assert!(!AssetRouter::can_reserve(asset, &ALICE, initial_amount)); - assert_noop!( - AssetRouter::reserve(asset, &ALICE, initial_amount), - Error::::Unsupported - ); - assert_eq!(AssetRouter::reserved_balance(asset, &ALICE), 0); - assert_eq!(AssetRouter::slash_reserved(asset, &ALICE, 1), 1); - assert_noop!( - AssetRouter::repatriate_reserved(asset, &ALICE, &BOB, 1, BalanceStatus::Reserved), - Error::::Unsupported - ); - assert_eq!(AssetRouter::unreserve(asset, &ALICE, 1), 1); -} - -#[test_case(CURRENCY; "foreign")] -#[test_case(CURRENCY_OLD_OUTCOME; "old_outcome")] -fn routes_currencies_correctly(currency_id: Assets) { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::deposit(currency_id, &ALICE, CURRENCY_INITIAL_AMOUNT)); - - assert!(AssetRouter::can_reserve(currency_id, &ALICE, CURRENCY_INITIAL_AMOUNT)); - assert!(!AssetRouter::can_reserve(currency_id, &ALICE, CURRENCY_INITIAL_AMOUNT + 1)); - assert_ok!(AssetRouter::reserve(currency_id, &ALICE, CURRENCY_INITIAL_AMOUNT)); - assert_eq!(AssetRouter::reserved_balance(currency_id, &ALICE), CURRENCY_INITIAL_AMOUNT); - assert_eq!(AssetRouter::slash_reserved(currency_id, &ALICE, 1), 0); - assert_eq!( - AssetRouter::repatriate_reserved( - currency_id, - &ALICE, - &BOB, - CURRENCY_MIN_BALANCE, - BalanceStatus::Reserved - ) - .unwrap(), - 0 - ); - assert_eq!(AssetRouter::reserved_balance(currency_id, &BOB), CURRENCY_MIN_BALANCE); - assert_eq!( - AssetRouter::reserved_balance(currency_id, &ALICE), - CURRENCY_INITIAL_AMOUNT - CURRENCY_MIN_BALANCE - 1 - ); - assert_eq!(AssetRouter::unreserve(currency_id, &ALICE, 1), 0); - assert_eq!( - AssetRouter::reserved_balance(currency_id, &ALICE), - CURRENCY_INITIAL_AMOUNT - CURRENCY_MIN_BALANCE - 2 - ); - }); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT); - }); -} diff --git a/zrml/asset-router/src/tests/named_multi_reservable_currency.rs b/zrml/asset-router/src/tests/named_multi_reservable_currency.rs deleted file mode 100644 index 94f05ef5c..000000000 --- a/zrml/asset-router/src/tests/named_multi_reservable_currency.rs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use orml_traits::MultiCurrency; -use test_case::test_case; - -fn unroutable_test_helper(asset: Assets, initial_amount: ::Balance) { - assert_ok!(AssetRouter::deposit(asset, &ALICE, initial_amount)); - assert_noop!( - AssetRouter::reserve_named(&Default::default(), asset, &ALICE, initial_amount), - Error::::Unsupported - ); - assert_eq!(AssetRouter::slash_reserved_named(&Default::default(), asset, &ALICE, 1), 1); - assert_noop!( - AssetRouter::repatriate_reserved_named( - &Default::default(), - asset, - &ALICE, - &BOB, - 1, - BalanceStatus::Reserved - ), - Error::::Unsupported - ); - assert_eq!(AssetRouter::unreserve_named(&Default::default(), asset, &ALICE, 1), 1); - assert_eq!(AssetRouter::reserved_balance_named(&Default::default(), asset, &ALICE), 0); -} - -#[test_case(CURRENCY; "foreign")] -#[test_case(CURRENCY_OLD_OUTCOME; "old_outcome")] -fn routes_currencies_correctly(currency_id: Assets) { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::deposit(currency_id, &ALICE, CURRENCY_INITIAL_AMOUNT)); - assert_ok!(AssetRouter::reserve_named( - &Default::default(), - currency_id, - &ALICE, - CURRENCY_INITIAL_AMOUNT - )); - assert_eq!( - AssetRouter::reserved_balance_named(&Default::default(), currency_id, &ALICE), - CURRENCY_INITIAL_AMOUNT - ); - assert_eq!( - AssetRouter::slash_reserved_named(&Default::default(), currency_id, &ALICE, 1), - 0 - ); - assert_eq!( - AssetRouter::repatriate_reserved_named( - &Default::default(), - currency_id, - &ALICE, - &BOB, - CURRENCY_MIN_BALANCE, - BalanceStatus::Reserved - ) - .unwrap(), - 0 - ); - assert_eq!( - AssetRouter::reserved_balance_named(&Default::default(), currency_id, &BOB), - CURRENCY_MIN_BALANCE - ); - assert_eq!( - AssetRouter::reserved_balance_named(&Default::default(), currency_id, &ALICE), - CURRENCY_INITIAL_AMOUNT - CURRENCY_MIN_BALANCE - 1 - ); - assert_eq!(AssetRouter::unreserve_named(&Default::default(), currency_id, &ALICE, 1), 0); - assert_eq!( - AssetRouter::reserved_balance_named(&Default::default(), currency_id, &ALICE), - CURRENCY_INITIAL_AMOUNT - CURRENCY_MIN_BALANCE - 2 - ); - }); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE,)); - - unroutable_test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT); - }); -} diff --git a/zrml/asset-router/src/tests/unbalanced.rs b/zrml/asset-router/src/tests/unbalanced.rs deleted file mode 100644 index 91b78ffad..000000000 --- a/zrml/asset-router/src/tests/unbalanced.rs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -#![cfg(test)] - -use super::*; -use frame_support::traits::tokens::fungibles::Unbalanced; -use orml_traits::MultiCurrency; - -fn test_helper( - asset: Assets, - initial_amount: ::Balance, - min_balance: ::Balance, -) { - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, 1)); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount + 1); - assert_ok!(AssetRouter::decrease_balance(asset, &ALICE, 1)); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount); - assert_eq!(AssetRouter::increase_balance_at_most(asset, &ALICE, 1), 1); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount + 1); - let to_decrease = initial_amount + 2 - min_balance; - assert_eq!( - AssetRouter::decrease_balance_at_most(asset, &ALICE, to_decrease), - initial_amount + 1 - ); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), 0); - AssetRouter::set_total_issuance(asset, 1337); - assert_eq!(AssetRouter::total_issuance(asset), 1337); -} - -#[test] -fn routes_campaign_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::deposit(CAMPAIGN_ASSET, &ALICE, CAMPAIGN_ASSET_INITIAL_AMOUNT)); - - test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT, CAMPAIGN_ASSET_MIN_BALANCE); - - assert_eq!(AssetRouter::total_issuance(CUSTOM_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(MARKET_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CURRENCY), 0); - }); -} - -#[test] -#[should_panic] -fn campaign_assets_panic_on_set_balance() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - let _ = AssetRouter::set_balance(CAMPAIGN_ASSET, &ALICE, 42); - }); -} - -#[test] -fn routes_custom_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::deposit(CUSTOM_ASSET, &ALICE, CUSTOM_ASSET_INITIAL_AMOUNT)); - - test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT, CUSTOM_ASSET_MIN_BALANCE); - - assert_eq!(AssetRouter::total_issuance(CAMPAIGN_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(MARKET_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CURRENCY), 0); - }); -} - -#[test] -#[should_panic] -fn custom_assets_panic_on_set_balance() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); - let _ = AssetRouter::set_balance(CUSTOM_ASSET, &ALICE, 42); - }); -} - -#[test] -fn routes_market_assets_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE)); - assert_ok!(AssetRouter::deposit(MARKET_ASSET, &ALICE, MARKET_ASSET_INITIAL_AMOUNT)); - - test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT, MARKET_ASSET_MIN_BALANCE); - - assert_eq!(AssetRouter::total_issuance(CAMPAIGN_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CUSTOM_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CURRENCY), 0); - }); -} - -#[test] -#[should_panic] -fn market_assets_panic_on_set_balance() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE)); - let _ = AssetRouter::set_balance(MARKET_ASSET, &ALICE, 42); - }); -} - -#[test] -fn routes_currencies_correctly() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::set_balance(CURRENCY, &ALICE, CURRENCY_INITIAL_AMOUNT)); - test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT, CURRENCY_MIN_BALANCE); - - assert_eq!(AssetRouter::total_issuance(CAMPAIGN_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CUSTOM_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(MARKET_ASSET), 0); - }); -} diff --git a/zrml/asset-router/src/types.rs b/zrml/asset-router/src/types.rs deleted file mode 100644 index 91ec53a22..000000000 --- a/zrml/asset-router/src/types.rs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use crate::{BoundedVec, Config, ConstU32, Weight, MAX_ASSETS_IN_DESTRUCTION}; -use core::cmp::Ordering; -use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use scale_info::TypeInfo; - -pub(crate) type DestroyAssetsT = BoundedVec< - AssetInDestruction<::AssetType>, - ConstU32<{ MAX_ASSETS_IN_DESTRUCTION }>, ->; - -pub(crate) enum DestructionOk { - Complete(Weight), - Incomplete(Weight), -} - -pub(crate) enum DestructionError { - Indestructible(Weight), - WrongState(Weight), -} - -pub(crate) type DestructionResult = Result; - -#[derive( - Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Decode, Encode, MaxEncodedLen, TypeInfo, -)] -pub(crate) enum DestructionState { - Accounts, - Approvals, - Finalization, - Destroyed, - Indestructible, -} -pub(crate) const DESTRUCTION_STATES: u8 = 5; - -#[derive(Clone, Copy, Encode, Eq, Debug, Decode, MaxEncodedLen, PartialEq, TypeInfo)] -pub(crate) struct AssetInDestruction { - asset: A, - state: DestructionState, -} - -impl PartialOrd for AssetInDestruction -where - A: Eq + Ord + PartialEq + PartialOrd, -{ - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -// Ordering for binary search of assets in destruction. -// Prioritize asset state first, then asset. -impl Ord for AssetInDestruction -where - A: Eq + Ord + PartialEq + PartialOrd, -{ - fn cmp(&self, other: &Self) -> Ordering { - match self.state.cmp(&other.state) { - Ordering::Equal => { - // Since asset destruction will always pop from the vector, sorting has to be reverse. - match self.asset.cmp(&other.asset) { - Ordering::Equal => Ordering::Equal, - Ordering::Less => Ordering::Greater, - Ordering::Greater => Ordering::Less, - } - } - Ordering::Less => Ordering::Less, - Ordering::Greater => Ordering::Greater, - } - } -} - -impl AssetInDestruction { - pub(crate) fn new(asset: A) -> Self { - AssetInDestruction { asset, state: DestructionState::Accounts } - } - - pub(crate) fn asset(&self) -> &A { - &self.asset - } - - pub(crate) fn state(&self) -> &DestructionState { - &self.state - } - - pub(crate) fn transit_indestructible(&mut self) { - self.state = DestructionState::Indestructible; - } - - // Returns the new state on change, None otherwise - pub(crate) fn transit_state(&mut self) -> Option<&DestructionState> { - let state_before = self.state; - - self.state = match self.state { - DestructionState::Accounts => DestructionState::Approvals, - DestructionState::Approvals => DestructionState::Finalization, - DestructionState::Destroyed => DestructionState::Destroyed, - DestructionState::Finalization => DestructionState::Destroyed, - DestructionState::Indestructible => DestructionState::Indestructible, - }; - - if state_before != self.state { Some(&self.state) } else { None } - } -} diff --git a/zrml/authorized/src/lib.rs b/zrml/authorized/src/lib.rs index 1e5644cb6..f155bf38f 100644 --- a/zrml/authorized/src/lib.rs +++ b/zrml/authorized/src/lib.rs @@ -49,8 +49,8 @@ mod pallet { use zeitgeist_primitives::{ traits::{DisputeApi, DisputeMaxWeightApi, DisputeResolutionApi}, types::{ - AuthorityReport, BaseAsset, GlobalDisputeItem, Market, MarketDisputeMechanism, - MarketStatus, OutcomeReport, ResultWithWeightInfo, + AuthorityReport, GlobalDisputeItem, Market, MarketDisputeMechanism, MarketStatus, + OutcomeReport, ResultWithWeightInfo, }, }; use zrml_market_commons::MarketCommonsPalletApi; @@ -72,7 +72,6 @@ mod pallet { BalanceOf, ::BlockNumber, MomentOf, - BaseAsset, MarketIdOf, >; @@ -372,13 +371,13 @@ where use frame_support::traits::Get; use sp_runtime::{traits::AccountIdConversion, Perbill}; use zeitgeist_primitives::types::{ - BaseAsset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, + Asset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, ScoringRule, }; Market { + base_asset: Asset::Ztg, market_id: Default::default(), - base_asset: BaseAsset::Ztg, creation: MarketCreation::Permissionless, creator_fee: Perbill::zero(), creator: T::PalletId::get().into_account_truncating(), diff --git a/zrml/authorized/src/weights.rs b/zrml/authorized/src/weights.rs index 2132a798b..13d00c1be 100644 --- a/zrml/authorized/src/weights.rs +++ b/zrml/authorized/src/weights.rs @@ -87,10 +87,10 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: Authorized AuthorizedOutcomeReports (max_values: None, max_size: Some(49), added: 2524, mode: MaxEncodedLen) fn authorize_market_outcome_existing_report() -> Weight { // Proof Size summary in bytes: - // Measured: `626` - // Estimated: `5691` - // Minimum execution time: 35_520 nanoseconds. - Weight::from_parts(43_000_000, 5691) + // Measured: `577` + // Estimated: `5677` + // Minimum execution time: 35_410 nanoseconds. + Weight::from_parts(36_251_000, 5677) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -105,7 +105,7 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: Authorized AuthorizedOutcomeReports (max_values: None, max_size: Some(49), added: 2524, mode: MaxEncodedLen) fn on_resolution_weight() -> Weight { // Proof Size summary in bytes: - // Measured: `250` + // Measured: `217` // Estimated: `2524` // Minimum execution time: 10_190 nanoseconds. Weight::from_parts(12_490_000, 2524) @@ -123,7 +123,7 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: Authorized AuthorizedOutcomeReports (max_values: None, max_size: Some(49), added: 2524, mode: MaxEncodedLen) fn get_auto_resolve_weight() -> Weight { // Proof Size summary in bytes: - // Measured: `250` + // Measured: `217` // Estimated: `2524` // Minimum execution time: 9_550 nanoseconds. Weight::from_parts(11_820_000, 2524).saturating_add(T::DbWeight::get().reads(1)) diff --git a/zrml/court/src/benchmarks.rs b/zrml/court/src/benchmarks.rs index f463facfc..bd60950b3 100644 --- a/zrml/court/src/benchmarks.rs +++ b/zrml/court/src/benchmarks.rs @@ -41,7 +41,7 @@ use sp_runtime::{ use zeitgeist_primitives::{ traits::{DisputeApi, DisputeResolutionApi}, types::{ - BaseAsset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, + Asset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, OutcomeReport, Report, ScoringRule, }, }; @@ -55,7 +55,7 @@ where { Market { market_id: 0u8.into(), - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: account("creator", 0, 0), diff --git a/zrml/court/src/lib.rs b/zrml/court/src/lib.rs index d3c83f8c2..3bd7dd9b9 100644 --- a/zrml/court/src/lib.rs +++ b/zrml/court/src/lib.rs @@ -29,6 +29,7 @@ use crate::{ }; use alloc::{ collections::{BTreeMap, BTreeSet}, + format, vec::Vec, }; use core::marker::PhantomData; @@ -65,7 +66,7 @@ use zeitgeist_primitives::{ math::checked_ops_res::{CheckedAddRes, CheckedRemRes, CheckedSubRes}, traits::{DisputeApi, DisputeMaxWeightApi, DisputeResolutionApi}, types::{ - BaseAsset, GlobalDisputeItem, Market, MarketDisputeMechanism, MarketStatus, OutcomeReport, + GlobalDisputeItem, Market, MarketDisputeMechanism, MarketStatus, OutcomeReport, ResultWithWeightInfo, }, }; @@ -224,7 +225,6 @@ mod pallet { BalanceOf, ::BlockNumber, MomentOf, - BaseAsset, MarketIdOf, >; pub(crate) type HashOf = ::Hash; diff --git a/zrml/court/src/tests.rs b/zrml/court/src/tests.rs index b0c80d6dc..42dd23c72 100644 --- a/zrml/court/src/tests.rs +++ b/zrml/court/src/tests.rs @@ -54,9 +54,9 @@ use zeitgeist_primitives::{ }, traits::DisputeApi, types::{ - AccountIdTest, BaseAsset, Deadlines, GlobalDisputeItem, Market, MarketBonds, - MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, - OutcomeReport, Report, ScoringRule, + AccountIdTest, Asset, Deadlines, GlobalDisputeItem, Market, MarketBonds, MarketCreation, + MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, OutcomeReport, Report, + ScoringRule, }, }; use zrml_market_commons::{Error as MError, MarketCommonsPalletApi}; @@ -67,7 +67,7 @@ const ORACLE_REPORT: OutcomeReport = OutcomeReport::Scalar(u128::MAX); const DEFAULT_MARKET: MarketOf = Market { market_id: 0, - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: 0, diff --git a/zrml/court/src/weights.rs b/zrml/court/src/weights.rs index 54512e245..078b9d1ea 100644 --- a/zrml/court/src/weights.rs +++ b/zrml/court/src/weights.rs @@ -137,7 +137,7 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: Balances Locks (max_values: None, max_size: Some(1299), added: 3774, mode: MaxEncodedLen) fn exit_court_remove() -> Weight { // Proof Size summary in bytes: - // Measured: `340` + // Measured: `307` // Estimated: `6500` // Minimum execution time: 43_340 nanoseconds. Weight::from_parts(52_540_000, 6500) @@ -150,7 +150,7 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: Balances Locks (max_values: None, max_size: Some(1299), added: 3774, mode: MaxEncodedLen) fn exit_court_set() -> Weight { // Proof Size summary in bytes: - // Measured: `340` + // Measured: `307` // Estimated: `6500` // Minimum execution time: 40_611 nanoseconds. Weight::from_parts(50_010_000, 6500) @@ -301,12 +301,12 @@ impl WeightInfoZeitgeist for WeightInfo { /// The range of component `j` is `[1, 1000]`. fn handle_inflation(j: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + j * (267 ±0)` - // Estimated: `96996 + j * (2607 ±0)` - // Minimum execution time: 40_780 nanoseconds. - Weight::from_parts(41_230_000, 96996) - // Standard Error: 31_831 - .saturating_add(Weight::from_parts(21_157_879, 0).saturating_mul(j.into())) + // Measured: `0 + j * (243 ±0)` + // Estimated: `72996 + j * (2607 ±0)` + // Minimum execution time: 33_280 nanoseconds. + Weight::from_parts(34_480_000, 72996) + // Standard Error: 9_174 + .saturating_add(Weight::from_parts(19_968_654, 0).saturating_mul(j.into())) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(j.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(j.into()))) @@ -429,7 +429,7 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: Court Courts (max_values: None, max_size: Some(349), added: 2824, mode: MaxEncodedLen) fn get_auto_resolve() -> Weight { // Proof Size summary in bytes: - // Measured: `456` + // Measured: `423` // Estimated: `5339` // Minimum execution time: 12_640 nanoseconds. Weight::from_parts(15_900_000, 5339).saturating_add(T::DbWeight::get().reads(2)) diff --git a/zrml/global-disputes/src/utils.rs b/zrml/global-disputes/src/utils.rs index dabebc965..a593280cd 100644 --- a/zrml/global-disputes/src/utils.rs +++ b/zrml/global-disputes/src/utils.rs @@ -24,7 +24,6 @@ type MarketOf = zeitgeist_primitives::types::Market< BalanceOf, ::BlockNumber, MomentOf, - zeitgeist_primitives::types::BaseAsset, MarketIdOf, >; @@ -38,7 +37,7 @@ where zeitgeist_primitives::types::Market { market_id: Default::default(), - base_asset: zeitgeist_primitives::types::BaseAsset::Ztg, + base_asset: zeitgeist_primitives::types::Asset::Ztg, creation: zeitgeist_primitives::types::MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: T::GlobalDisputesPalletId::get().into_account_truncating(), diff --git a/zrml/global-disputes/src/weights.rs b/zrml/global-disputes/src/weights.rs index 7185025ae..3b7541a1f 100644 --- a/zrml/global-disputes/src/weights.rs +++ b/zrml/global-disputes/src/weights.rs @@ -144,10 +144,10 @@ impl WeightInfoZeitgeist for WeightInfo { /// The range of component `w` is `[1, 10]`. fn add_vote_outcome(_w: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `777 + w * (32 ±0)` - // Estimated: `11515` - // Minimum execution time: 70_410 nanoseconds. - Weight::from_parts(98_017_145, 11515) + // Measured: `690 + w * (32 ±0)` + // Estimated: `11501` + // Minimum execution time: 69_591 nanoseconds. + Weight::from_parts(88_511_398, 11501) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } diff --git a/zrml/hybrid-router/Cargo.toml b/zrml/hybrid-router/Cargo.toml index 8c4c2b95f..81a24316b 100644 --- a/zrml/hybrid-router/Cargo.toml +++ b/zrml/hybrid-router/Cargo.toml @@ -13,7 +13,6 @@ zrml-market-commons = { workspace = true } orml-asset-registry = { workspace = true, optional = true } orml-currencies = { workspace = true, optional = true } orml-tokens = { workspace = true, optional = true } -pallet-assets = { workspace = true, optional = true } pallet-balances = { workspace = true, optional = true } pallet-randomness-collective-flip = { workspace = true, optional = true } pallet-timestamp = { workspace = true, optional = true } @@ -23,7 +22,6 @@ serde = { workspace = true, optional = true } sp-io = { workspace = true, optional = true } xcm = { workspace = true, optional = true } xcm-builder = { workspace = true, optional = true } -zrml-asset-router = { workspace = true, optional = true } zrml-authorized = { workspace = true, optional = true } zrml-court = { workspace = true, optional = true } zrml-global-disputes = { workspace = true, optional = true } @@ -44,7 +42,6 @@ mock = [ "orml-asset-registry/default", "orml-currencies/default", "orml-tokens/default", - "pallet-assets/default", "pallet-balances/default", "pallet-randomness-collective-flip/default", "pallet-timestamp/default", @@ -54,7 +51,6 @@ mock = [ "sp-io/default", "xcm/default", "zeitgeist-primitives/mock", - "zrml-asset-router/default", "zrml-market-commons/default", "zrml-neo-swaps/default", "zrml-orderbook/default", @@ -74,7 +70,6 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "xcm-builder/runtime-benchmarks", - "pallet-assets?/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", "zrml-prediction-markets/runtime-benchmarks", ] diff --git a/zrml/hybrid-router/src/benchmarking.rs b/zrml/hybrid-router/src/benchmarking.rs index 24e7f5c7d..1aa8718c0 100644 --- a/zrml/hybrid-router/src/benchmarking.rs +++ b/zrml/hybrid-router/src/benchmarking.rs @@ -38,10 +38,7 @@ use zeitgeist_primitives::{ constants::{base_multiples::*, CENT}, math::fixed::{BaseProvider, FixedDiv, ZeitgeistBase}, traits::{CompleteSetOperationsApi, DeployPoolApi, HybridRouterOrderbookApi}, - types::{ - Asset, BaseAssetClass, Market, MarketCreation, MarketPeriod, MarketStatus, MarketType, - ScoringRule, - }, + types::{Asset, Market, MarketCreation, MarketPeriod, MarketStatus, MarketType, ScoringRule}, }; use zrml_market_commons::MarketCommonsPalletApi; @@ -68,11 +65,7 @@ fn create_spot_prices(asset_count: u16) -> Vec> { amounts } -fn create_market( - caller: T::AccountId, - base_asset: BaseAssetClass, - asset_count: u16, -) -> MarketIdOf +fn create_market(caller: T::AccountId, base_asset: AssetOf, asset_count: u16) -> MarketIdOf where T: Config, { @@ -101,7 +94,7 @@ where fn create_market_and_deploy_pool( caller: T::AccountId, - base_asset: BaseAssetClass, + base_asset: AssetOf, asset_count: u16, amount: BalanceOf, ) -> MarketIdOf @@ -109,8 +102,8 @@ where T: Config, { let market_id = create_market::(caller.clone(), base_asset, asset_count); - let total_cost = amount + T::AssetManager::minimum_balance(base_asset.into()); - assert_ok!(T::AssetManager::deposit(base_asset.into(), &caller, total_cost)); + let total_cost = amount + T::AssetManager::minimum_balance(base_asset); + assert_ok!(T::AssetManager::deposit(base_asset, &caller, total_cost)); assert_ok_with_transaction!(T::CompleteSetOperations::buy_complete_set( caller.clone(), market_id, @@ -133,7 +126,7 @@ mod benchmarks { #[benchmark] fn buy(n: Linear<2, 16>, o: Linear<0, 10>) { let buyer: T::AccountId = whitelisted_caller(); - let base_asset = BaseAssetClass::Ztg; + let base_asset = Asset::Ztg; let asset_count = n.try_into().unwrap(); let market_id = create_market_and_deploy_pool::( buyer.clone(), @@ -144,7 +137,7 @@ mod benchmarks { let asset = Asset::CategoricalOutcome(market_id, 0u16); let amount_in = _1000.saturated_into(); - assert_ok!(T::AssetManager::deposit(base_asset.into(), &buyer, amount_in)); + assert_ok!(T::AssetManager::deposit(base_asset, &buyer, amount_in)); let spot_prices = create_spot_prices::(asset_count); let first_spot_price = spot_prices[0]; @@ -153,7 +146,7 @@ mod benchmarks { let orders = (0u128..o as u128).collect::>(); let maker_asset = asset; let maker_amount = _20.saturated_into(); - let taker_asset: AssetOf = base_asset.into(); + let taker_asset = base_asset; let taker_amount: BalanceOf = _11.saturated_into(); assert!(taker_amount.bdiv_floor(maker_amount).unwrap() > first_spot_price); for (i, order_id) in orders.iter().enumerate() { @@ -187,14 +180,14 @@ mod benchmarks { let buyer_limit_order = T::Orderbook::order(o as u128).unwrap(); assert_eq!(buyer_limit_order.market_id, market_id); assert_eq!(buyer_limit_order.maker, buyer); - assert_eq!(buyer_limit_order.maker_asset, base_asset.into()); + assert_eq!(buyer_limit_order.maker_asset, base_asset); assert_eq!(buyer_limit_order.taker_asset, asset); } #[benchmark] fn sell(n: Linear<2, 10>, o: Linear<0, 10>) { let seller: T::AccountId = whitelisted_caller(); - let base_asset = BaseAssetClass::Ztg; + let base_asset = Asset::Ztg; let asset_count = n.try_into().unwrap(); let market_id = create_market_and_deploy_pool::( seller.clone(), @@ -209,15 +202,15 @@ mod benchmarks { // seller base asset amount needs to exist, // otherwise repatriate_reserved_named from order book fails // with DeadAccount for base asset repatriate to seller beneficiary - let min_balance = T::AssetManager::minimum_balance(base_asset.into()); - assert_ok!(T::AssetManager::deposit(base_asset.into(), &seller, min_balance)); + let min_balance = T::AssetManager::minimum_balance(base_asset); + assert_ok!(T::AssetManager::deposit(base_asset, &seller, min_balance)); let spot_prices = create_spot_prices::(asset_count); let first_spot_price = spot_prices[0]; let min_price = _1_100.saturated_into(); let orders = (0u128..o as u128).collect::>(); - let maker_asset: AssetOf = base_asset.into(); + let maker_asset: AssetOf = base_asset; let maker_amount: BalanceOf = _9.saturated_into(); let taker_asset = asset; let taker_amount = _100.saturated_into(); @@ -255,7 +248,7 @@ mod benchmarks { assert_eq!(seller_limit_order.market_id, market_id); assert_eq!(seller_limit_order.maker, seller); assert_eq!(seller_limit_order.maker_asset, asset); - assert_eq!(seller_limit_order.taker_asset, base_asset.into()); + assert_eq!(seller_limit_order.taker_asset, base_asset); } impl_benchmark_test_suite!( diff --git a/zrml/hybrid-router/src/lib.rs b/zrml/hybrid-router/src/lib.rs index 1155ee832..4892585f4 100644 --- a/zrml/hybrid-router/src/lib.rs +++ b/zrml/hybrid-router/src/lib.rs @@ -64,7 +64,7 @@ mod pallet { }, orderbook::{Order, OrderId}, traits::{HybridRouterAmmApi, HybridRouterOrderbookApi}, - types::{Asset, BaseAsset}, + types::Asset, }; use zrml_market_commons::MarketCommonsPalletApi; @@ -424,7 +424,7 @@ mod pallet { mut remaining: BalanceOf, who: &AccountIdOf, market_id: MarketIdOf, - base_asset: BaseAsset, + base_asset: AssetOf, asset: AssetOf, price_limit: BalanceOf, ) -> Result, DispatchError> { @@ -440,7 +440,7 @@ mod pallet { Err(_) => continue, }; - let order_price = order.price(base_asset.into())?; + let order_price = order.price(base_asset)?; match tx_type { TxType::Buy => { @@ -595,8 +595,8 @@ mod pallet { ensure!(asset_count as usize == assets.len(), Error::::AssetCountMismatch); let (asset_in, asset_out) = match tx_type { - TxType::Buy => (market.base_asset.into(), asset), - TxType::Sell => (asset, market.base_asset.into()), + TxType::Buy => (market.base_asset, asset), + TxType::Sell => (asset, market.base_asset), }; T::AssetManager::ensure_can_withdraw(asset_in, &who, amount_in)?; @@ -637,7 +637,7 @@ mod pallet { if !remaining.is_zero() { let (maker_asset, maker_amount, taker_asset, taker_amount) = match tx_type { TxType::Buy => { - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let maker_amount = remaining; let taker_asset = asset; let taker_amount = remaining.bdiv_ceil(price_limit)?; @@ -646,7 +646,7 @@ mod pallet { TxType::Sell => { let maker_asset = asset; let maker_amount = remaining; - let taker_asset = market.base_asset.into(); + let taker_asset = market.base_asset; let taker_amount = price_limit.bmul_floor(remaining)?; (maker_asset, maker_amount, taker_asset, taker_amount) } diff --git a/zrml/hybrid-router/src/mock.rs b/zrml/hybrid-router/src/mock.rs index feb7f3718..2682f950f 100644 --- a/zrml/hybrid-router/src/mock.rs +++ b/zrml/hybrid-router/src/mock.rs @@ -27,46 +27,41 @@ use crate::{AssetOf, BalanceOf, MarketIdOf}; use core::marker::PhantomData; use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, - traits::{AsEnsureOriginWithArg, Contains, Everything, NeverEnsureOrigin}, + traits::{Contains, Everything, NeverEnsureOrigin}, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; +use frame_system::{EnsureRoot, EnsureSignedBy}; #[cfg(feature = "parachain")] use orml_asset_registry::AssetMetadata; use orml_traits::MultiCurrency; -use parity_scale_codec::Compact; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, ConstU32, Get, IdentityLookup, Zero}, + traits::{BlakeTwo256, Get, IdentityLookup, Zero}, Perbill, Percent, SaturatedConversion, }; #[cfg(feature = "parachain")] use zeitgeist_primitives::types::Asset; use zeitgeist_primitives::{ constants::mock::{ - AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AssetsAccountDeposit, - AssetsApprovalDeposit, AssetsDeposit, AssetsMetadataDepositBase, - AssetsMetadataDepositPerByte, AssetsStringLimit, AuthorizedPalletId, BlockHashCount, - BlocksPerYear, CloseEarlyBlockPeriod, CloseEarlyDisputeBond, + AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AuthorizedPalletId, + BlockHashCount, BlocksPerYear, CloseEarlyBlockPeriod, CloseEarlyDisputeBond, CloseEarlyProtectionBlockPeriod, CloseEarlyProtectionTimeFramePeriod, CloseEarlyRequestBond, CloseEarlyTimeFramePeriod, CorrectionPeriod, CourtPalletId, - DestroyAccountWeight, DestroyApprovalWeight, DestroyFinishWeight, ExistentialDeposit, - ExistentialDeposits, GdVotingPeriod, GetNativeCurrencyId, GlobalDisputeLockId, - GlobalDisputesPalletId, HybridRouterPalletId, InflationPeriod, LiquidityMiningPalletId, - LockId, MaxAppeals, MaxApprovals, MaxCourtParticipants, MaxCreatorFee, MaxDelegations, - MaxDisputeDuration, MaxDisputes, MaxEditReasonLen, MaxGlobalDisputeVotes, MaxGracePeriod, - MaxLiquidityTreeDepth, MaxLocks, MaxMarketLifetime, MaxOracleDuration, MaxOrders, - MaxOwners, MaxRejectReasonLen, MaxReserves, MaxSelectedDraws, MaxYearlyInflation, - MinCategories, MinDisputeDuration, MinJurorStake, MinOracleDuration, MinOutcomeVoteAmount, - MinimumPeriod, NeoMaxSwapFee, NeoSwapsPalletId, OrderbookPalletId, OutcomeBond, - OutcomeFactor, OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, + ExistentialDeposit, ExistentialDeposits, GdVotingPeriod, GetNativeCurrencyId, + GlobalDisputeLockId, GlobalDisputesPalletId, HybridRouterPalletId, InflationPeriod, + LiquidityMiningPalletId, LockId, MaxAppeals, MaxApprovals, MaxCourtParticipants, + MaxCreatorFee, MaxDelegations, MaxDisputeDuration, MaxDisputes, MaxEditReasonLen, + MaxGlobalDisputeVotes, MaxGracePeriod, MaxLiquidityTreeDepth, MaxLocks, MaxMarketLifetime, + MaxOracleDuration, MaxOrders, MaxOwners, MaxRejectReasonLen, MaxReserves, MaxSelectedDraws, + MaxYearlyInflation, MinCategories, MinDisputeDuration, MinJurorStake, MinOracleDuration, + MinOutcomeVoteAmount, MinimumPeriod, NeoMaxSwapFee, NeoSwapsPalletId, OrderbookPalletId, + OutcomeBond, OutcomeFactor, OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, SimpleDisputesPalletId, TreasuryPalletId, VotePeriod, VotingOutcomeFee, BASE, CENT, MAX_ASSETS, }, traits::DistributeFees, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, CurrencyId, + Hash, Index, MarketId, Moment, UncheckedExtrinsicTest, }, }; @@ -153,10 +148,6 @@ impl Contains for DustRemovalWhitelist { } } -pub(super) type CustomAssetsInstance = pallet_assets::Instance1; -pub(super) type CampaignAssetsInstance = pallet_assets::Instance2; -pub(super) type MarketAssetsInstance = pallet_assets::Instance3; - construct_runtime!( pub enum Runtime where @@ -165,16 +156,12 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { HybridRouter: zrml_hybrid_router::{Pallet, Call, Storage, Event}, + AssetManager: orml_currencies::{Call, Pallet, Storage}, Orderbook: zrml_orderbook::{Call, Event, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, NeoSwaps: zrml_neo_swaps::{Call, Event, Pallet}, Authorized: zrml_authorized::{Event, Pallet, Storage}, Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, Court: zrml_court::{Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - AssetManager: orml_currencies::{Call, Pallet, Storage}, LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, MarketCommons: zrml_market_commons::{Pallet, Storage}, PredictionMarkets: zrml_prediction_markets::{Event, Pallet, Storage}, @@ -203,122 +190,6 @@ impl crate::Config for Runtime { type WeightInfo = zrml_hybrid_router::weights::WeightInfo; } -pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } -} - -pallet_assets::runtime_benchmarks_enabled! { - use zeitgeist_primitives::types::CategoryIndex; - - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl zrml_asset_router::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyAccountWeight; - type DestroyApprovalWeight = DestroyApprovalWeight; - type DestroyFinishWeight = DestroyFinishWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; -} - impl zrml_orderbook::Config for Runtime { type AssetManager = AssetManager; type ExternalFees = ExternalFees; @@ -346,8 +217,6 @@ impl zrml_prediction_markets::Config for Runtime { type AdvisoryBond = AdvisoryBond; type AdvisoryBondSlashPercentage = AdvisoryBondSlashPercentage; type ApproveOrigin = EnsureSignedBy; - type AssetCreator = AssetRouter; - type AssetDestroyer = AssetRouter; #[cfg(feature = "parachain")] type AssetRegistry = MockRegistry; type Authorized = Authorized; @@ -378,7 +247,6 @@ impl zrml_prediction_markets::Config for Runtime { type MinCategories = MinCategories; type MaxEditReasonLen = MaxEditReasonLen; type MaxRejectReasonLen = MaxRejectReasonLen; - type OnStateTransition = (); type OracleBond = OracleBond; type OutsiderBond = OutsiderBond; type PalletId = PmPalletId; @@ -469,7 +337,7 @@ impl frame_system::Config for Runtime { impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = AssetRouter; + type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type WeightInfo = (); } @@ -477,7 +345,7 @@ impl orml_currencies::Config for Runtime { impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Currencies; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = DustRemovalWhitelist; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -564,7 +432,7 @@ impl pallet_treasury::Config for Runtime { #[cfg(feature = "parachain")] zrml_prediction_markets::impl_mock_registry! { MockRegistry, - zeitgeist_primitives::types::XcmAsset, + CurrencyId, Balance, zeitgeist_primitives::types::CustomMetadata } @@ -604,8 +472,8 @@ impl ExtBuilder { use frame_support::traits::GenesisBuild; orml_tokens::GenesisConfig:: { balances: vec![ - (ALICE, FOREIGN_ASSET.try_into().unwrap(), INITIAL_BALANCE), - (FEE_ACCOUNT, FOREIGN_ASSET.try_into().unwrap(), INITIAL_BALANCE), + (ALICE, FOREIGN_ASSET, INITIAL_BALANCE), + (FEE_ACCOUNT, FOREIGN_ASSET, INITIAL_BALANCE), ], } .assimilate_storage(&mut t) @@ -616,7 +484,7 @@ impl ExtBuilder { }; orml_asset_registry_mock::GenesisConfig { metadata: vec![( - FOREIGN_ASSET.try_into().unwrap(), + FOREIGN_ASSET, AssetMetadata { decimals: 18, name: "MKL".as_bytes().to_vec(), diff --git a/zrml/hybrid-router/src/tests/buy.rs b/zrml/hybrid-router/src/tests/buy.rs index fb3630b5c..6c5a36f82 100644 --- a/zrml/hybrid-router/src/tests/buy.rs +++ b/zrml/hybrid-router/src/tests/buy.rs @@ -16,6 +16,7 @@ // along with Zeitgeist. If not, see . use super::*; +use zeitgeist_primitives::types::Asset; #[test] fn buy_from_amm_and_then_fill_specified_order() { @@ -34,7 +35,7 @@ fn buy_from_amm_and_then_fill_specified_order() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; let order_maker_amount = _12; @@ -87,7 +88,7 @@ fn buy_from_amm_and_then_fill_specified_order() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: 85665315968, taker_asset: BASE_ASSET, taker_amount: unfilled_base_asset_amount, @@ -115,7 +116,7 @@ fn buy_from_amm_if_specified_order_has_higher_prices_than_the_amm() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let order_maker_amount = _4; @@ -153,7 +154,7 @@ fn buy_from_amm_if_specified_order_has_higher_prices_than_the_amm() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _4, taker_asset: BASE_ASSET, taker_amount: _2, @@ -178,7 +179,7 @@ fn buy_fill_multiple_orders_if_amm_spot_price_higher_than_order_prices() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; let order_maker_amount = _1; @@ -237,7 +238,7 @@ fn buy_fill_specified_order_partially_if_amm_spot_price_higher() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let order_maker_amount = _8; @@ -276,7 +277,7 @@ fn buy_fill_specified_order_partially_if_amm_spot_price_higher() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _4, taker_asset: BASE_ASSET, taker_amount: _2, @@ -301,7 +302,7 @@ fn buy_fails_if_asset_not_equal_to_order_book_maker_asset() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let order_maker_amount = _1; assert_ok!(AssetManager::deposit(BASE_ASSET, &CHARLIE, order_maker_amount)); @@ -311,7 +312,7 @@ fn buy_fails_if_asset_not_equal_to_order_book_maker_asset() { market_id, BASE_ASSET, order_maker_amount, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), _2, )); @@ -354,7 +355,7 @@ fn buy_fails_if_order_price_above_max_price() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let order_maker_amount = _1; @@ -362,7 +363,7 @@ fn buy_fails_if_order_price_above_max_price() { assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), market_id, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), order_maker_amount, BASE_ASSET, _2, @@ -407,7 +408,7 @@ fn buy_from_amm() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let max_price = _3_4.saturated_into::>(); let orders = vec![]; @@ -456,7 +457,7 @@ fn buy_max_price_lower_than_amm_spot_price_results_in_place_order() { let market = Markets::::get(market_id).unwrap(); let base_asset = market.base_asset; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; //* max_price is just 1 smaller than the spot price of the AMM //* this results in no buy on the AMM, but places an order on the order book @@ -483,7 +484,7 @@ fn buy_max_price_lower_than_amm_spot_price_results_in_place_order() { Order { market_id, maker: ALICE, - maker_asset: base_asset.into(), + maker_asset: base_asset, maker_amount: _2, taker_asset: asset, taker_amount: _4, @@ -510,7 +511,7 @@ fn buy_from_amm_but_low_amount() { let market = Markets::::get(market_id).unwrap(); let base_asset = market.base_asset; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; //* max_price is just 1 larger than the spot price of the AMM //* this results in a low buy amount_in on the AMM @@ -550,7 +551,7 @@ fn buy_from_amm_but_low_amount() { Order { market_id, maker: ALICE, - maker_asset: base_asset.into(), + maker_asset: base_asset, maker_amount: 19999999970, taker_asset: asset, taker_amount: 39999999933, @@ -575,7 +576,7 @@ fn buy_from_amm_only() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let max_price = _3_4.saturated_into::>(); let orders = vec![]; @@ -623,7 +624,7 @@ fn buy_places_limit_order_no_pool() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -648,7 +649,7 @@ fn buy_places_limit_order_no_pool() { Order { market_id, maker: ALICE, - maker_asset: base_asset.into(), + maker_asset: base_asset, maker_amount: 10 * BASE, taker_asset: asset, taker_amount: 20 * BASE, @@ -670,7 +671,7 @@ fn buy_fails_if_balance_too_low() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; assert_ok!(Balances::set_balance(RuntimeOrigin::root(), ALICE, amount - 1, 0)); @@ -710,7 +711,7 @@ fn buy_emits_event() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _1000 * 100; assert_ok!(AssetManager::deposit(BASE_ASSET, &ALICE, amount_in)); @@ -780,7 +781,7 @@ fn buy_fails_if_asset_count_mismatch() { let asset_count = 2; assert_ne!(required_asset_count, asset_count); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 2 * BASE; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -814,7 +815,7 @@ fn buy_fails_if_price_limit_too_high() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; let max_price = (BASE + 1).saturated_into::>(); let orders = vec![]; @@ -848,7 +849,7 @@ fn buy_succeeds_for_place_order_below_minimum_balance_soft_failure() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 1; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -887,7 +888,7 @@ fn buy_succeeds_for_numerical_soft_failure() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _1_100; let max_price = (_3_4).saturated_into::>(); @@ -912,7 +913,7 @@ fn buy_succeeds_for_numerical_soft_failure() { maker: ALICE, maker_asset: BASE_ASSET, maker_amount: _1_100, - taker_asset: Assets::CategoricalOutcome(market_id, 0), + taker_asset: Asset::CategoricalOutcome(market_id, 0), taker_amount: 133333334, } ); @@ -935,7 +936,7 @@ fn buy_just_one_unit_from_amm() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 1; let order_maker_amount = _2; @@ -943,7 +944,7 @@ fn buy_just_one_unit_from_amm() { assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), market_id, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), order_maker_amount, BASE_ASSET, _1, @@ -956,6 +957,8 @@ fn buy_just_one_unit_from_amm() { let max_price = (_1_2 + 1).saturated_into::>(); let orders = vec![order_id]; let strategy = Strategy::LimitOrder; + // Prevent ED error by giving Alice some extra tokens. + assert_ok!(AssetManager::deposit(asset, &ALICE, _1)); assert_ok!(HybridRouter::buy( RuntimeOrigin::signed(ALICE), market_id, @@ -973,7 +976,7 @@ fn buy_just_one_unit_from_amm() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _2, taker_asset: BASE_ASSET, taker_amount: _1, @@ -998,7 +1001,7 @@ fn buy_succeeds_for_fill_order_below_minimum_balance_soft_failure() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 1; let order_maker_amount = _2; @@ -1006,7 +1009,7 @@ fn buy_succeeds_for_fill_order_below_minimum_balance_soft_failure() { assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), market_id, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), order_maker_amount, BASE_ASSET, _1, @@ -1019,6 +1022,8 @@ fn buy_succeeds_for_fill_order_below_minimum_balance_soft_failure() { let max_price = _3_4.saturated_into::>(); let orders = vec![order_id]; let strategy = Strategy::LimitOrder; + // Prevent ED error by giving Alice some extra tokens. + assert_ok!(AssetManager::deposit(asset, &ALICE, _1)); assert_ok!(HybridRouter::buy( RuntimeOrigin::signed(ALICE), market_id, @@ -1036,7 +1041,7 @@ fn buy_succeeds_for_fill_order_below_minimum_balance_soft_failure() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _2, taker_asset: BASE_ASSET, taker_amount: _1, @@ -1061,7 +1066,7 @@ fn buy_succeeds_for_place_order_partial_fill_near_full_fill_not_allowed() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _1 - 1; let order_maker_amount = _2; @@ -1069,7 +1074,7 @@ fn buy_succeeds_for_place_order_partial_fill_near_full_fill_not_allowed() { assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), market_id, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), order_maker_amount, BASE_ASSET, _1, @@ -1099,7 +1104,7 @@ fn buy_succeeds_for_place_order_partial_fill_near_full_fill_not_allowed() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _2, taker_asset: BASE_ASSET, taker_amount: _1, @@ -1124,7 +1129,7 @@ fn buy_only_executes_first_order_from_orders_vector() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _1; let order_maker_amount = _2; @@ -1132,7 +1137,7 @@ fn buy_only_executes_first_order_from_orders_vector() { assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), market_id, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), order_maker_amount, BASE_ASSET, _1, @@ -1143,7 +1148,7 @@ fn buy_only_executes_first_order_from_orders_vector() { assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(DAVE), market_id, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), order_maker_amount, BASE_ASSET, _1, @@ -1176,7 +1181,7 @@ fn buy_only_executes_first_order_from_orders_vector() { Order { market_id, maker: CHARLIE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _2, taker_asset: BASE_ASSET, taker_amount: _1, @@ -1190,7 +1195,7 @@ fn buy_skips_fill_order_if_order_not_present_and_places_new_order() { ExtBuilder::default().build().execute_with(|| { let market_id = 0; let mut market = market_mock::(MARKET_CREATOR); - market.base_asset = BASE_ASSET.try_into().unwrap(); + market.base_asset = BASE_ASSET; let required_asset_count = match &market.market_type { MarketType::Scalar(_) => panic!("Categorical market type is expected!"), MarketType::Categorical(categories) => *categories, @@ -1199,7 +1204,7 @@ fn buy_skips_fill_order_if_order_not_present_and_places_new_order() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![42]; @@ -1223,7 +1228,7 @@ fn buy_skips_fill_order_if_order_not_present_and_places_new_order() { maker: ALICE, maker_asset: BASE_ASSET, maker_amount: 10 * BASE, - taker_asset: Assets::CategoricalOutcome(market_id, 0), + taker_asset: Asset::CategoricalOutcome(market_id, 0), taker_amount: 20 * BASE, } ); @@ -1243,7 +1248,7 @@ fn buy_fails_if_max_orders_exceeded() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; let max_price = (BASE / 2).saturated_into::>(); let orders = (0u128..100u128 + 1u128).collect::>(); @@ -1277,7 +1282,7 @@ fn buy_fails_if_amount_is_zero() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 0; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -1311,7 +1316,7 @@ fn buy_fails_if_cancel_strategy_applied() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -1337,7 +1342,7 @@ fn buy_fails_if_market_does_not_exist() { ExtBuilder::default().build().execute_with(|| { let market_id = 0; let asset_count = 2; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; diff --git a/zrml/hybrid-router/src/tests/mod.rs b/zrml/hybrid-router/src/tests/mod.rs index 1abce4120..4c42c9e25 100644 --- a/zrml/hybrid-router/src/tests/mod.rs +++ b/zrml/hybrid-router/src/tests/mod.rs @@ -27,8 +27,8 @@ use zeitgeist_primitives::{ constants::{base_multiples::*, BASE, CENT}, orderbook::Order, types::{ - AccountIdTest, Assets, Deadlines, MarketCreation, MarketPeriod, MarketStatus, MarketType, - MultiHash, ScoringRule, + AccountIdTest, Asset, Deadlines, MarketCreation, MarketId, MarketPeriod, MarketStatus, + MarketType, MultiHash, ScoringRule, }, }; use zrml_market_commons::{Error as MError, MarketCommonsPalletApi, Markets}; @@ -39,13 +39,13 @@ mod buy; mod sell; #[cfg(not(feature = "parachain"))] -const BASE_ASSET: Assets = Assets::Ztg; +const BASE_ASSET: Asset = Asset::Ztg; #[cfg(feature = "parachain")] -const BASE_ASSET: Assets = FOREIGN_ASSET; +const BASE_ASSET: Asset = FOREIGN_ASSET; fn create_market( creator: AccountIdTest, - base_asset: Assets, + base_asset: AssetOf, market_type: MarketType, scoring_rule: ScoringRule, ) -> MarketIdOf { @@ -54,7 +54,7 @@ fn create_market( metadata[1] = 0x30; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(creator), - base_asset.try_into().unwrap(), + base_asset, Perbill::zero(), EVE, MarketPeriod::Block(0..2), @@ -74,7 +74,7 @@ fn create_market( fn create_market_and_deploy_pool( creator: AccountIdOf, - base_asset: Assets, + base_asset: AssetOf, market_type: MarketType, amount: BalanceOf, spot_prices: Vec>, diff --git a/zrml/hybrid-router/src/tests/sell.rs b/zrml/hybrid-router/src/tests/sell.rs index a1c383945..837b4bac2 100644 --- a/zrml/hybrid-router/src/tests/sell.rs +++ b/zrml/hybrid-router/src/tests/sell.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use super::*; -use frame_support::traits::fungibles::Unbalanced; +use zeitgeist_primitives::types::Asset; #[test] fn sell_to_amm_and_then_fill_specified_order() { @@ -35,7 +35,7 @@ fn sell_to_amm_and_then_fill_specified_order() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; let order_maker_amount = _6; @@ -52,7 +52,7 @@ fn sell_to_amm_and_then_fill_specified_order() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let min_price = _1_4.saturated_into::>(); let strategy = Strategy::LimitOrder; @@ -92,7 +92,7 @@ fn sell_to_amm_and_then_fill_specified_order() { maker: CHARLIE, maker_asset: BASE_ASSET, maker_amount: 52804047165, - taker_asset: Assets::CategoricalOutcome(market_id, 0), + taker_asset: Asset::CategoricalOutcome(market_id, 0), taker_amount: unfilled_base_asset_amount, } ); @@ -118,7 +118,7 @@ fn sell_to_amm_if_specified_order_has_lower_prices_than_the_amm() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _1; let order_maker_amount = _1; @@ -135,7 +135,7 @@ fn sell_to_amm_if_specified_order_has_lower_prices_than_the_amm() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount,)); let min_price = _1_4.saturated_into::>(); let strategy = Strategy::LimitOrder; @@ -162,7 +162,7 @@ fn sell_to_amm_if_specified_order_has_lower_prices_than_the_amm() { maker: CHARLIE, maker_asset: BASE_ASSET, maker_amount: _1, - taker_asset: Assets::CategoricalOutcome(market_id, 0), + taker_asset: Asset::CategoricalOutcome(market_id, 0), taker_amount: _2, } ); @@ -185,7 +185,7 @@ fn sell_fill_multiple_orders_if_amm_spot_price_lower_than_order_prices() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; let order_maker_amount = _1_2; @@ -210,7 +210,7 @@ fn sell_fill_multiple_orders_if_amm_spot_price_lower_than_order_prices() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let min_price = _1_4.saturated_into::>(); let strategy = Strategy::LimitOrder; @@ -246,7 +246,7 @@ fn sell_fill_specified_order_partially_if_amm_spot_price_lower() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let order_maker_amount = _4; @@ -265,7 +265,7 @@ fn sell_fill_specified_order_partially_if_amm_spot_price_lower() { assert_eq!(order_ids.len(), 1); let order_id = order_ids[0]; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount,)); let min_price = _1_4.saturated_into::>(); let orders = vec![order_id]; @@ -289,7 +289,7 @@ fn sell_fill_specified_order_partially_if_amm_spot_price_lower() { maker: CHARLIE, maker_asset: BASE_ASSET, maker_amount: _3, - taker_asset: Assets::CategoricalOutcome(market_id, 0), + taker_asset: Asset::CategoricalOutcome(market_id, 0), taker_amount: _6, } ); @@ -312,11 +312,11 @@ fn sell_fails_if_asset_not_equal_to_order_book_taker_asset() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; let maker_amount = _1; - assert_ok!(AssetRouter::increase_balance(asset, &CHARLIE, maker_amount,)); + assert_ok!(AssetManager::deposit(asset, &CHARLIE, maker_amount,)); assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), @@ -331,7 +331,7 @@ fn sell_fails_if_asset_not_equal_to_order_book_taker_asset() { assert_eq!(order_ids.len(), 1); let order_id = order_ids[0]; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let min_price = _1_4.saturated_into::>(); let orders = vec![order_id]; @@ -368,7 +368,7 @@ fn sell_fails_if_order_price_below_min_price() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; let order_maker_amount = _1; @@ -378,7 +378,7 @@ fn sell_fails_if_order_price_below_min_price() { market_id, BASE_ASSET, order_maker_amount, - Assets::CategoricalOutcome(market_id, 0), + Asset::CategoricalOutcome(market_id, 0), amount, )); @@ -386,7 +386,7 @@ fn sell_fails_if_order_price_below_min_price() { assert_eq!(order_ids.len(), 1); let order_id = order_ids[0]; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, 5 * amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, 5 * amount,)); let min_price = _3_4.saturated_into::>(); let orders = vec![order_id]; @@ -423,10 +423,10 @@ fn sell_to_amm() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount,)); let min_price = _1_4.saturated_into::>(); let orders = vec![]; @@ -475,10 +475,10 @@ fn sell_min_price_higher_than_amm_spot_price_results_in_place_order() { let market = Markets::::get(market_id).unwrap(); let base_asset = market.base_asset; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount,)); //* spot price of the AMM is 1 smaller than the min_price //* this results in no sell on the AMM, but places an order on the order book @@ -507,7 +507,7 @@ fn sell_min_price_higher_than_amm_spot_price_results_in_place_order() { maker: ALICE, maker_asset: asset, maker_amount: _2, - taker_asset: base_asset.into(), + taker_asset: base_asset, taker_amount: _1, } ); @@ -532,10 +532,10 @@ fn sell_to_amm_but_low_amount() { let market = Markets::::get(market_id).unwrap(); let base_asset = market.base_asset; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); //* min_price is just 1 smaller than the spot price of the AMM //* this results in a low sell amount_in on the AMM @@ -577,7 +577,7 @@ fn sell_to_amm_but_low_amount() { maker: ALICE, maker_asset: asset, maker_amount: 19999999942, - taker_asset: base_asset.into(), + taker_asset: base_asset, taker_amount: 9999999969, } ); @@ -600,12 +600,10 @@ fn sell_succeeds_for_numerical_soft_failure() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _1000 * 100; - // increase_balance does not set total issuance - AssetRouter::set_total_issuance(asset, amount_in); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let min_price = (_1_100 / 1000).saturated_into::>(); let orders = vec![]; @@ -627,7 +625,7 @@ fn sell_succeeds_for_numerical_soft_failure() { Order { market_id, maker: ALICE, - maker_asset: Assets::CategoricalOutcome(market_id, 0), + maker_asset: Asset::CategoricalOutcome(market_id, 0), maker_amount: _1000 * 100, taker_asset: BASE_ASSET, taker_amount: _1, @@ -652,10 +650,10 @@ fn sell_to_amm_only() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount,)); let min_price = _1_4.saturated_into::>(); let orders = vec![]; @@ -703,10 +701,10 @@ fn sell_places_limit_order_no_pool() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount,)); let min_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -733,7 +731,7 @@ fn sell_places_limit_order_no_pool() { maker: ALICE, maker_asset: asset, maker_amount: 10 * BASE, - taker_asset: base_asset.into(), + taker_asset: base_asset, taker_amount: 5 * BASE, } ); @@ -753,10 +751,10 @@ fn sell_fails_if_balance_too_low() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount - 1,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount - 1,)); let min_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -794,7 +792,7 @@ fn sell_emits_event() { swap_fee, ); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = _1000 * 100; let min_price = _1_100.saturated_into::>(); @@ -820,9 +818,7 @@ fn sell_emits_event() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - // increase_balance does not set total issuance - AssetRouter::set_total_issuance(asset, amount_in); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let strategy = Strategy::LimitOrder; assert_ok!(HybridRouter::sell( @@ -868,10 +864,10 @@ fn sell_fails_if_asset_count_mismatch() { let asset_count = 2; assert_ne!(required_asset_count, asset_count); - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = 2 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -905,7 +901,7 @@ fn sell_fails_if_amount_is_zero() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = 0; let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -939,9 +935,9 @@ fn sell_fails_if_cancel_strategy_applied() { Markets::::insert(market_id, market); let asset_count = required_asset_count; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; let strategy = Strategy::ImmediateOrCancel; @@ -966,9 +962,9 @@ fn sell_fails_if_market_does_not_exist() { ExtBuilder::default().build().execute_with(|| { let market_id = 0; let asset_count = 2; - let asset = Assets::CategoricalOutcome(market_id, 0); + let asset = Asset::CategoricalOutcome(market_id, 0); let amount_in = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetManager::deposit(asset, &ALICE, amount_in,)); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; let strategy = Strategy::ImmediateOrCancel; diff --git a/zrml/hybrid-router/src/utils.rs b/zrml/hybrid-router/src/utils.rs index 0dcc0e1ed..808296e26 100644 --- a/zrml/hybrid-router/src/utils.rs +++ b/zrml/hybrid-router/src/utils.rs @@ -21,13 +21,13 @@ use crate::{AccountIdOf, BalanceOf, MarketIdOf}; use frame_system::pallet_prelude::BlockNumberFor; use zeitgeist_primitives::{ traits::MarketCommonsPalletApi, - types::{BaseAsset, Market}, + types::{Asset, Market}, }; pub(crate) type MomentOf = <::MarketCommons as MarketCommonsPalletApi>::Moment; pub(crate) type MarketOf = - Market, BalanceOf, BlockNumberFor, MomentOf, BaseAsset, MarketIdOf>; + Market, BalanceOf, BlockNumberFor, MomentOf, MarketIdOf>; pub(crate) fn market_mock(creator: T::AccountId) -> MarketOf where @@ -37,14 +37,14 @@ where use zeitgeist_primitives::{ constants::mock::PmPalletId, types::{ - BaseAssetClass, Deadlines, MarketBonds, MarketCreation, MarketDisputeMechanism, - MarketPeriod, MarketStatus, MarketType, ScoringRule, + Deadlines, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, + MarketStatus, MarketType, ScoringRule, }, }; zeitgeist_primitives::types::Market { market_id: 0u8.into(), - base_asset: BaseAssetClass::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: Perbill::zero(), creator, diff --git a/zrml/liquidity-mining/src/tests.rs b/zrml/liquidity-mining/src/tests.rs index 68363ff8c..671d52f3f 100644 --- a/zrml/liquidity-mining/src/tests.rs +++ b/zrml/liquidity-mining/src/tests.rs @@ -32,8 +32,8 @@ use frame_support::{ }; use frame_system::RawOrigin; use zeitgeist_primitives::types::{ - BaseAsset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, - MarketPeriod, MarketStatus, MarketType, ScoringRule, + Asset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, + MarketStatus, MarketType, ScoringRule, }; use zrml_market_commons::Markets; @@ -204,7 +204,7 @@ fn create_default_market(market_id: u128, period: Range) { market_id, Market { market_id: Default::default(), - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: 0, diff --git a/zrml/market-commons/src/lib.rs b/zrml/market-commons/src/lib.rs index 3b2e1af6c..93082ef61 100644 --- a/zrml/market-commons/src/lib.rs +++ b/zrml/market-commons/src/lib.rs @@ -42,7 +42,7 @@ mod pallet { traits::{Hooks, StorageVersion, Time}, Blake2_128Concat, Parameter, }; - use parity_scale_codec::{FullCodec, HasCompact, MaxEncodedLen}; + use parity_scale_codec::{FullCodec, MaxEncodedLen}; use sp_runtime::{ traits::{ AtLeast32Bit, AtLeast32BitUnsigned, MaybeSerializeDeserialize, Member, Saturating, @@ -52,26 +52,19 @@ mod pallet { use zeitgeist_primitives::{ math::checked_ops_res::CheckedAddRes, traits::MarketBuilderTrait, - types::{ - BaseAsset, Deadlines, EarlyClose, Market, MarketBonds, MarketPeriod, PoolId, Report, - }, + types::{Asset, Deadlines, EarlyClose, Market, MarketBonds, MarketPeriod, PoolId, Report}, }; /// The current storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(11); pub(crate) type AccountIdOf = ::AccountId; + pub(crate) type AssetOf = Asset>; pub(crate) type BalanceOf = ::Balance; pub(crate) type BlockNumberOf = ::BlockNumber; pub(crate) type MarketIdOf = ::MarketId; - pub(crate) type MarketOf = Market< - AccountIdOf, - BalanceOf, - BlockNumberOf, - MomentOf, - BaseAsset, - MarketIdOf, - >; + pub(crate) type MarketOf = + Market, BalanceOf, BlockNumberOf, MomentOf, MarketIdOf>; pub(crate) type MomentOf = <::Timestamp as frame_support::traits::Time>::Moment; pub(crate) type DeadlinesOf = Deadlines>; pub(crate) type EarlyCloseOf = EarlyClose, MomentOf>; @@ -97,7 +90,6 @@ mod pallet { type MarketId: AtLeast32Bit + Copy + Default - + HasCompact + MaxEncodedLen + MaybeSerializeDeserialize + Member @@ -208,7 +200,6 @@ mod pallet { Self::Balance, Self::BlockNumber, Self::Moment, - BaseAsset, Self::MarketId, >, { diff --git a/zrml/market-commons/src/migrations.rs b/zrml/market-commons/src/migrations.rs index 2569b4a79..7bcc6e2e5 100644 --- a/zrml/market-commons/src/migrations.rs +++ b/zrml/market-commons/src/migrations.rs @@ -15,376 +15,3 @@ // // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . - -use crate::{AccountIdOf, BalanceOf, BlockNumberOf, Config, MomentOf, Pallet as MarketCommons}; -use alloc::vec::Vec; -use core::marker::PhantomData; -use frame_support::{ - dispatch::Weight, - log, - traits::{Get, OnRuntimeUpgrade, StorageVersion}, -}; -use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use scale_info::TypeInfo; -use sp_runtime::{Perbill, RuntimeDebug, Saturating}; -use zeitgeist_primitives::types::{ - BaseAsset, Deadlines, EarlyClose, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, - MarketPeriod, MarketStatus, MarketType, OutcomeReport, Report, ScoringRule, -}; - -#[cfg(feature = "try-runtime")] -use { - crate::MarketIdOf, - alloc::{collections::BTreeMap, format}, - frame_support::migration::storage_key_iter, -}; - -#[cfg(any(feature = "try-runtime", feature = "test"))] -use frame_support::Blake2_128Concat; - -#[cfg(any(feature = "try-runtime", test))] -const MARKET_COMMONS: &[u8] = b"MarketCommons"; -#[cfg(any(feature = "try-runtime", test))] -const MARKETS: &[u8] = b"Markets"; - -#[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] -pub struct OldMarket { - pub base_asset: A, - pub creator: AI, - pub creation: MarketCreation, - pub creator_fee: Perbill, - pub oracle: AI, - pub metadata: Vec, - pub market_type: MarketType, - pub period: MarketPeriod, - pub deadlines: Deadlines, - pub scoring_rule: OldScoringRule, - pub status: MarketStatus, - pub report: Option>, - pub resolved_outcome: Option, - pub dispute_mechanism: Option, - pub bonds: MarketBonds, - pub early_close: Option>, -} - -type OldMarketOf = - OldMarket, BalanceOf, BlockNumberOf, MomentOf, BaseAsset>; - -#[derive(TypeInfo, Clone, Copy, Encode, Eq, Decode, MaxEncodedLen, PartialEq, RuntimeDebug)] -pub enum OldScoringRule { - Lmsr, - Orderbook, - Parimutuel, -} - -const MARKET_COMMONS_REQUIRED_STORAGE_VERSION: u16 = 10; -const MARKET_COMMONS_NEXT_STORAGE_VERSION: u16 = 11; - -#[cfg(feature = "try-runtime")] -#[frame_support::storage_alias] -pub(crate) type Markets = - StorageMap, Blake2_128Concat, MarketIdOf, OldMarketOf>; - -pub struct MigrateScoringRuleAmmCdaHybridAndMarketId(PhantomData); - -/// Migrates AMM and CDA markets to the new combined scoring rule and adds the market's ID to the -/// struct. -impl OnRuntimeUpgrade for MigrateScoringRuleAmmCdaHybridAndMarketId -where - T: Config, -{ - fn on_runtime_upgrade() -> Weight { - let mut total_weight = T::DbWeight::get().reads(1); - let market_commons_version = StorageVersion::get::>(); - if market_commons_version != MARKET_COMMONS_REQUIRED_STORAGE_VERSION { - log::info!( - "MigrateScoringRuleAmmCdaHybridAndMarketId: market-commons version is {:?}, but \ - {:?} is required", - market_commons_version, - MARKET_COMMONS_REQUIRED_STORAGE_VERSION, - ); - return total_weight; - } - log::info!("MigrateScoringRuleAmmCdaHybridAndMarketId: Starting..."); - - let mut translated = 0u64; - crate::Markets::::translate::, _>(|market_id, old_market| { - translated.saturating_inc(); - let scoring_rule = match old_market.scoring_rule { - OldScoringRule::Lmsr => ScoringRule::AmmCdaHybrid, - OldScoringRule::Orderbook => ScoringRule::AmmCdaHybrid, - OldScoringRule::Parimutuel => ScoringRule::Parimutuel, - }; - let new_market = Market { - market_id, - base_asset: old_market.base_asset, - creator: old_market.creator, - creation: old_market.creation, - creator_fee: old_market.creator_fee, - oracle: old_market.oracle, - metadata: old_market.metadata, - market_type: old_market.market_type, - period: old_market.period, - deadlines: old_market.deadlines, - scoring_rule, - status: old_market.status, - report: old_market.report, - resolved_outcome: old_market.resolved_outcome, - dispute_mechanism: old_market.dispute_mechanism, - bonds: old_market.bonds, - early_close: old_market.early_close, - }; - Some(new_market) - }); - log::info!("MigrateScoringRuleAmmCdaHybridAndMarketId: Upgraded {} markets.", translated); - total_weight = - total_weight.saturating_add(T::DbWeight::get().reads_writes(translated, translated)); - - StorageVersion::new(MARKET_COMMONS_NEXT_STORAGE_VERSION).put::>(); - total_weight = total_weight.saturating_add(T::DbWeight::get().writes(1)); - log::info!("MigrateScoringRuleAmmCdaHybridAndMarketId: Done!"); - total_weight - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { - let old_markets = storage_key_iter::, OldMarketOf, Blake2_128Concat>( - MARKET_COMMONS, - MARKETS, - ) - .collect::>(); - let markets = Markets::::iter_keys().count(); - let decodable_markets = Markets::::iter_values().count(); - if markets == decodable_markets { - log::info!("All {} markets could successfully be decoded.", markets); - } else { - log::error!( - "Can only decode {} of {} markets - others will be dropped.", - decodable_markets, - markets - ); - } - - Ok(old_markets.encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(previous_state: Vec) -> Result<(), &'static str> { - let old_markets: BTreeMap, OldMarketOf> = - Decode::decode(&mut &previous_state[..]).unwrap(); - let old_market_count = old_markets.len(); - let new_market_count = crate::Markets::::iter().count(); - assert_eq!(old_market_count, new_market_count); - for (market_id, new_market) in crate::Markets::::iter() { - let old_market = old_markets - .get(&market_id) - .expect(&format!("Market {:?} not found", market_id)[..]); - assert_eq!(market_id, new_market.market_id); - assert_eq!(old_market.base_asset, new_market.base_asset); - assert_eq!(old_market.creator, new_market.creator); - assert_eq!(old_market.creation, new_market.creation); - assert_eq!(old_market.creator_fee, new_market.creator_fee); - assert_eq!(old_market.oracle, new_market.oracle); - assert_eq!(old_market.metadata, new_market.metadata); - assert_eq!(old_market.market_type, new_market.market_type); - assert_eq!(old_market.period, new_market.period); - assert_eq!(old_market.deadlines, new_market.deadlines); - assert_eq!(old_market.status, new_market.status); - assert_eq!(old_market.report, new_market.report); - assert_eq!(old_market.resolved_outcome, new_market.resolved_outcome); - assert_eq!(old_market.dispute_mechanism, new_market.dispute_mechanism); - assert_eq!(old_market.bonds, new_market.bonds); - assert_eq!(old_market.early_close, new_market.early_close); - } - log::info!( - "MigrateScoringRuleAmmCdaHybridAndMarketId: Post-upgrade market count is {}!", - new_market_count - ); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - mock::{ExtBuilder, Runtime}, - MarketOf, - }; - use alloc::fmt::Debug; - use frame_support::{ - migration::put_storage_value, storage_root, Blake2_128Concat, StorageHasher, - }; - use parity_scale_codec::Encode; - use sp_runtime::{Perbill, StateVersion}; - use test_case::test_case; - use zeitgeist_primitives::types::{BaseAssetClass, Bond, EarlyCloseState, MarketId}; - - #[test] - fn on_runtime_upgrade_increments_the_storage_version() { - ExtBuilder::default().build().execute_with(|| { - set_up_version(); - MigrateScoringRuleAmmCdaHybridAndMarketId::::on_runtime_upgrade(); - assert_eq!( - StorageVersion::get::>(), - MARKET_COMMONS_NEXT_STORAGE_VERSION - ); - }); - } - - #[test_case(OldScoringRule::Orderbook, ScoringRule::AmmCdaHybrid)] - #[test_case(OldScoringRule::Lmsr, ScoringRule::AmmCdaHybrid)] - #[test_case(OldScoringRule::Parimutuel, ScoringRule::Parimutuel)] - fn on_runtime_upgrade_works_as_expected( - old_scoring_rule: OldScoringRule, - new_scoring_rule: ScoringRule, - ) { - ExtBuilder::default().build().execute_with(|| { - set_up_version(); - let (old_markets, new_markets) = - construct_old_new_tuple(old_scoring_rule, new_scoring_rule); - populate_test_data::>( - MARKET_COMMONS, - MARKETS, - old_markets, - ); - MigrateScoringRuleAmmCdaHybridAndMarketId::::on_runtime_upgrade(); - assert_eq!(crate::Markets::::get(0).unwrap(), new_markets[0]); - assert_eq!(crate::Markets::::get(1).unwrap(), new_markets[1]); - assert_eq!(crate::Markets::::get(2).unwrap(), new_markets[2]); - }); - } - - #[test] - fn on_runtime_upgrade_is_noop_if_versions_are_not_correct() { - ExtBuilder::default().build().execute_with(|| { - StorageVersion::new(MARKET_COMMONS_NEXT_STORAGE_VERSION) - .put::>(); - let market = Market { - market_id: 7, - base_asset: BaseAssetClass::Ztg, - creator: 1, - creation: MarketCreation::Permissionless, - creator_fee: Perbill::from_rational(2u32, 3u32), - oracle: 4, - metadata: vec![0x05; 50], - market_type: MarketType::Categorical(999), - period: MarketPeriod::, MomentOf>::Block(6..7), - deadlines: Deadlines { grace_period: 7, oracle_duration: 8, dispute_duration: 9 }, - scoring_rule: ScoringRule::AmmCdaHybrid, - status: MarketStatus::Active, - report: Some(Report { at: 13, by: 14, outcome: OutcomeReport::Categorical(10) }), - resolved_outcome: None, - dispute_mechanism: Some(MarketDisputeMechanism::Court), - bonds: MarketBonds { - creation: Some(Bond::new(11, 12)), - oracle: None, - outsider: None, - dispute: None, - close_dispute: None, - close_request: None, - }, - early_close: None, - }; - crate::Markets::::insert(333, market); - let tmp = storage_root(StateVersion::V1); - MigrateScoringRuleAmmCdaHybridAndMarketId::::on_runtime_upgrade(); - assert_eq!(tmp, storage_root(StateVersion::V1)); - }); - } - - fn set_up_version() { - StorageVersion::new(MARKET_COMMONS_REQUIRED_STORAGE_VERSION) - .put::>(); - } - - fn construct_old_new_tuple( - old_scoring_rule: OldScoringRule, - new_scoring_rule: ScoringRule, - ) -> (Vec>, Vec>) { - let base_asset = BaseAsset::Ztg; - let creation = MarketCreation::Advised; - let creator_fee = Perbill::from_rational(2u32, 3u32); - let oracle = 4; - let metadata = vec![5; 50]; - let market_type = MarketType::Scalar(6..=7); - let period = MarketPeriod::Block(8..9); - let deadlines = Deadlines { grace_period: 10, oracle_duration: 11, dispute_duration: 12 }; - let status = MarketStatus::Resolved; - let report = Some(Report { at: 13, by: 14, outcome: OutcomeReport::Categorical(15) }); - let resolved_outcome = Some(OutcomeReport::Categorical(16)); - let dispute_mechanism = Some(MarketDisputeMechanism::Court); - let bonds = MarketBonds { - creation: Some(Bond { who: 17, value: 18, is_settled: true }), - oracle: Some(Bond { who: 19, value: 20, is_settled: true }), - outsider: Some(Bond { who: 21, value: 22, is_settled: true }), - dispute: Some(Bond { who: 23, value: 24, is_settled: true }), - close_request: Some(Bond { who: 25, value: 26, is_settled: true }), - close_dispute: Some(Bond { who: 27, value: 28, is_settled: true }), - }; - let early_close = Some(EarlyClose { - old: MarketPeriod::Block(29..30), - new: MarketPeriod::Block(31..32), - state: EarlyCloseState::Disputed, - }); - let sentinels = (0..3).map(|i| 10 - i); - let old_markets = sentinels - .clone() - .map(|sentinel| OldMarket { - base_asset, - creator: sentinel, - creation: creation.clone(), - creator_fee, - oracle, - metadata: metadata.clone(), - market_type: market_type.clone(), - period: period.clone(), - deadlines, - scoring_rule: old_scoring_rule, - status, - report: report.clone(), - resolved_outcome: resolved_outcome.clone(), - dispute_mechanism: dispute_mechanism.clone(), - bonds: bonds.clone(), - early_close: early_close.clone(), - }) - .collect(); - let new_markets = sentinels - .enumerate() - .map(|(index, sentinel)| Market { - market_id: index as u128, - base_asset, - creator: sentinel, - creation: creation.clone(), - creator_fee, - oracle, - metadata: metadata.clone(), - market_type: market_type.clone(), - period: period.clone(), - deadlines, - scoring_rule: new_scoring_rule, - status, - report: report.clone(), - resolved_outcome: resolved_outcome.clone(), - dispute_mechanism: dispute_mechanism.clone(), - bonds: bonds.clone(), - early_close: early_close.clone(), - }) - .collect(); - (old_markets, new_markets) - } - - #[allow(unused)] - fn populate_test_data(pallet: &[u8], prefix: &[u8], data: Vec) - where - H: StorageHasher, - K: TryFrom + Encode, - V: Encode + Clone, - >::Error: Debug, - { - for (key, value) in data.iter().enumerate() { - let storage_hash = K::try_from(key).unwrap().using_encoded(H::hash).as_ref().to_vec(); - put_storage_value::(pallet, prefix, &storage_hash, (*value).clone()); - } - } -} diff --git a/zrml/market-commons/src/tests.rs b/zrml/market-commons/src/tests.rs index a7d26af88..a2ba2d317 100644 --- a/zrml/market-commons/src/tests.rs +++ b/zrml/market-commons/src/tests.rs @@ -28,7 +28,7 @@ use sp_runtime::{DispatchError, Perbill}; use zeitgeist_primitives::{ traits::{MarketBuilderTrait, MarketCommonsPalletApi}, types::{ - BaseAsset, Deadlines, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, + Asset, Deadlines, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, ScoringRule, }, }; @@ -37,7 +37,7 @@ use zeitgeist_primitives::{ fn create_market_builder(oracle: AccountIdOf) -> MarketBuilder { let mut market_builder = MarketBuilder::new(); market_builder - .base_asset(BaseAsset::Ztg) + .base_asset(Asset::Ztg) .creation(MarketCreation::Permissionless) .creator_fee(Perbill::zero()) .creator(0) diff --git a/zrml/market-commons/src/types/market_builder.rs b/zrml/market-commons/src/types/market_builder.rs index c121f19e0..f70979c65 100644 --- a/zrml/market-commons/src/types/market_builder.rs +++ b/zrml/market-commons/src/types/market_builder.rs @@ -16,16 +16,16 @@ // along with Zeitgeist. If not, see . use crate::{ - AccountIdOf, BalanceOf, BlockNumberOf, Config, DeadlinesOf, EarlyCloseOf, Error, MarketBondsOf, - MarketIdOf, MarketOf, MarketPeriodOf, MomentOf, ReportOf, + AccountIdOf, AssetOf, BalanceOf, BlockNumberOf, Config, DeadlinesOf, EarlyCloseOf, Error, + MarketBondsOf, MarketIdOf, MarketOf, MarketPeriodOf, MomentOf, ReportOf, }; use alloc::vec::Vec; use sp_runtime::{DispatchError, Perbill}; use zeitgeist_primitives::{ traits::MarketBuilderTrait, types::{ - BaseAsset, Market, MarketCreation, MarketDisputeMechanism, MarketStatus, MarketType, - OutcomeReport, ScoringRule, + Market, MarketCreation, MarketDisputeMechanism, MarketStatus, MarketType, OutcomeReport, + ScoringRule, }, }; @@ -36,7 +36,7 @@ where T: Config, { market_id: Option>, - base_asset: Option, + base_asset: Option>, creator: Option>, creation: Option, creator_fee: Option, @@ -112,14 +112,8 @@ where } impl - MarketBuilderTrait< - AccountIdOf, - BalanceOf, - BlockNumberOf, - MomentOf, - BaseAsset, - MarketIdOf, - > for MarketBuilder + MarketBuilderTrait, BalanceOf, BlockNumberOf, MomentOf, MarketIdOf> + for MarketBuilder where T: Config, { @@ -147,7 +141,7 @@ where impl_builder_methods! { market_id: MarketIdOf, - base_asset: BaseAsset, + base_asset: AssetOf, creator: AccountIdOf, creation: MarketCreation, creator_fee: Perbill, diff --git a/zrml/neo-swaps/Cargo.toml b/zrml/neo-swaps/Cargo.toml index 85e982808..c7611f358 100644 --- a/zrml/neo-swaps/Cargo.toml +++ b/zrml/neo-swaps/Cargo.toml @@ -19,7 +19,6 @@ env_logger = { workspace = true, optional = true } orml-asset-registry = { workspace = true, optional = true } orml-currencies = { workspace = true, optional = true } orml-tokens = { workspace = true, optional = true } -pallet-assets = { workspace = true, optional = true } pallet-balances = { workspace = true, optional = true } pallet-randomness-collective-flip = { workspace = true, optional = true } pallet-timestamp = { workspace = true, optional = true } @@ -30,7 +29,6 @@ sp-api = { workspace = true, optional = true } sp-io = { workspace = true, optional = true } xcm = { workspace = true, optional = true } xcm-builder = { workspace = true, optional = true } -zrml-asset-router = { workspace = true, optional = true } zrml-authorized = { workspace = true, optional = true } zrml-court = { workspace = true, optional = true } zrml-global-disputes = { workspace = true, optional = true } @@ -61,13 +59,11 @@ mock = [ "orml-asset-registry/default", "orml-currencies/default", "orml-tokens/default", - "pallet-assets/default", "pallet-balances/default", "pallet-timestamp/default", "sp-api/default", "sp-io/default", "zrml-court/std", - "zrml-asset-router/std", "zrml-authorized/std", "zrml-liquidity-mining/std", "zrml-simple-disputes/std", @@ -83,10 +79,8 @@ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", - "pallet-assets?/runtime-benchmarks", - "pallet-xcm/runtime-benchmarks", "xcm-builder/runtime-benchmarks", - "zrml-prediction-markets/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", ] std = [ "frame-benchmarking?/std", diff --git a/zrml/neo-swaps/src/benchmarking.rs b/zrml/neo-swaps/src/benchmarking.rs index ad55064b0..1557f349c 100644 --- a/zrml/neo-swaps/src/benchmarking.rs +++ b/zrml/neo-swaps/src/benchmarking.rs @@ -181,7 +181,7 @@ where { let market = Market { market_id: 0u8.into(), - base_asset: base_asset.try_into().unwrap(), + base_asset, creation: MarketCreation::Permissionless, creator_fee: Perbill::zero(), creator: caller.clone(), diff --git a/zrml/neo-swaps/src/lib.rs b/zrml/neo-swaps/src/lib.rs index 6519c130c..1a0518581 100644 --- a/zrml/neo-swaps/src/lib.rs +++ b/zrml/neo-swaps/src/lib.rs @@ -888,14 +888,14 @@ mod pallet { let pool_account_id = Self::pool_account_id(&market_id); let mut reserves = BTreeMap::new(); for (&amount_in, &asset) in amounts_in.iter().zip(market.outcome_assets().iter()) { - T::MultiCurrency::transfer(asset.into(), &who, &pool_account_id, amount_in)?; - let _ = reserves.insert(asset.into(), amount_in); + T::MultiCurrency::transfer(asset, &who, &pool_account_id, amount_in)?; + let _ = reserves.insert(asset, amount_in); } let collateral = market.base_asset; let pool = Pool { account_id: pool_account_id.clone(), reserves: reserves.clone().try_into().map_err(|_| Error::::Unexpected)?, - collateral: collateral.into(), + collateral, liquidity_parameter, liquidity_shares_manager: LiquidityTree::new(who.clone(), amount)?, swap_fee, @@ -906,7 +906,7 @@ mod pallet { pool.collateral, &who, &pool.account_id, - T::MultiCurrency::minimum_balance(collateral.into()), + T::MultiCurrency::minimum_balance(collateral), )?; Pools::::insert(market_id, pool); Self::deposit_event(Event::::PoolDeployed { @@ -914,7 +914,7 @@ mod pallet { market_id, account_id: pool_account_id, reserves, - collateral: collateral.into(), + collateral, liquidity_parameter, pool_shares_amount: amount, swap_fee, diff --git a/zrml/neo-swaps/src/macros.rs b/zrml/neo-swaps/src/macros.rs index c8ea923a6..0c7bbb986 100644 --- a/zrml/neo-swaps/src/macros.rs +++ b/zrml/neo-swaps/src/macros.rs @@ -50,7 +50,6 @@ macro_rules! create_b_tree_map { /// their expected stake. /// - `total_fees`: The sum of all fees (both lazy and distributed) in the pool's liquidity tree. #[macro_export] -#[cfg(test)] macro_rules! assert_pool_state { ( $market_id:expr, @@ -107,7 +106,6 @@ macro_rules! assert_pool_state { /// Asserts that `account` has the specified `balances` of `assets`. #[macro_export] -#[cfg(test)] macro_rules! assert_balances { ($account:expr, $assets:expr, $balances:expr $(,)?) => { assert_eq!( @@ -116,7 +114,7 @@ macro_rules! assert_balances { "assert_balances: Assets and balances length mismatch" ); for (&asset, &expected_balance) in $assets.iter().zip($balances.iter()) { - let actual_balance = AssetManager::free_balance(asset.try_into().unwrap(), &$account); + let actual_balance = AssetManager::free_balance(asset, &$account); assert_eq!( actual_balance, expected_balance, "assert_balances: Balance mismatch for asset {:?}", @@ -128,7 +126,6 @@ macro_rules! assert_balances { /// Asserts that `account` has the specified `balance` of `asset`. #[macro_export] -#[cfg(test)] macro_rules! assert_balance { ($account:expr, $asset:expr, $balance:expr $(,)?) => { assert_balances!($account, [$asset], [$balance]); @@ -137,7 +134,6 @@ macro_rules! assert_balance { /// Asserts that `abs(left - right) < precision`. #[macro_export] -#[cfg(test)] macro_rules! assert_approx { ($left:expr, $right:expr, $precision:expr $(,)?) => { match (&$left, &$right, &$precision) { diff --git a/zrml/neo-swaps/src/mock.rs b/zrml/neo-swaps/src/mock.rs index 610bc955f..af8009a9b 100644 --- a/zrml/neo-swaps/src/mock.rs +++ b/zrml/neo-swaps/src/mock.rs @@ -28,47 +28,44 @@ use crate::{consts::*, AssetOf, MarketIdOf}; use core::marker::PhantomData; use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, - traits::{AsEnsureOriginWithArg, Contains, Everything, NeverEnsureOrigin}, + traits::{Contains, Everything, NeverEnsureOrigin}, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; +use frame_system::{EnsureRoot, EnsureSignedBy}; #[cfg(feature = "parachain")] use orml_asset_registry::AssetMetadata; use orml_traits::MultiCurrency; -use parity_scale_codec::Compact; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, ConstU32, Get, IdentityLookup, Zero}, + traits::{BlakeTwo256, Get, IdentityLookup, Zero}, DispatchResult, Perbill, Percent, SaturatedConversion, }; +#[cfg(feature = "parachain")] +use zeitgeist_primitives::types::Asset; use zeitgeist_primitives::{ constants::{ base_multiples::*, mock::{ - AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AssetsAccountDeposit, - AssetsApprovalDeposit, AssetsDeposit, AssetsMetadataDepositBase, - AssetsMetadataDepositPerByte, AssetsStringLimit, AuthorizedPalletId, BlockHashCount, - BlocksPerYear, CloseEarlyBlockPeriod, CloseEarlyDisputeBond, + AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AuthorizedPalletId, + BlockHashCount, BlocksPerYear, CloseEarlyBlockPeriod, CloseEarlyDisputeBond, CloseEarlyProtectionBlockPeriod, CloseEarlyProtectionTimeFramePeriod, CloseEarlyRequestBond, CloseEarlyTimeFramePeriod, CorrectionPeriod, CourtPalletId, - DestroyAccountWeight, DestroyApprovalWeight, DestroyFinishWeight, ExistentialDeposit, - ExistentialDeposits, GdVotingPeriod, GetNativeCurrencyId, GlobalDisputeLockId, - GlobalDisputesPalletId, InflationPeriod, LiquidityMiningPalletId, LockId, MaxAppeals, - MaxApprovals, MaxCourtParticipants, MaxCreatorFee, MaxDelegations, MaxDisputeDuration, - MaxDisputes, MaxEditReasonLen, MaxGlobalDisputeVotes, MaxGracePeriod, - MaxLiquidityTreeDepth, MaxLocks, MaxMarketLifetime, MaxOracleDuration, MaxOwners, - MaxRejectReasonLen, MaxReserves, MaxSelectedDraws, MaxYearlyInflation, MinCategories, - MinDisputeDuration, MinJurorStake, MinOracleDuration, MinOutcomeVoteAmount, - MinimumPeriod, NeoMaxSwapFee, NeoSwapsPalletId, OutcomeBond, OutcomeFactor, - OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, SimpleDisputesPalletId, - TreasuryPalletId, VotePeriod, VotingOutcomeFee, BASE, CENT, + ExistentialDeposit, ExistentialDeposits, GdVotingPeriod, GetNativeCurrencyId, + GlobalDisputeLockId, GlobalDisputesPalletId, InflationPeriod, LiquidityMiningPalletId, + LockId, MaxAppeals, MaxApprovals, MaxCourtParticipants, MaxCreatorFee, MaxDelegations, + MaxDisputeDuration, MaxDisputes, MaxEditReasonLen, MaxGlobalDisputeVotes, + MaxGracePeriod, MaxLiquidityTreeDepth, MaxLocks, MaxMarketLifetime, MaxOracleDuration, + MaxOwners, MaxRejectReasonLen, MaxReserves, MaxSelectedDraws, MaxYearlyInflation, + MinCategories, MinDisputeDuration, MinJurorStake, MinOracleDuration, + MinOutcomeVoteAmount, MinimumPeriod, NeoMaxSwapFee, NeoSwapsPalletId, OutcomeBond, + OutcomeFactor, OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, + SimpleDisputesPalletId, TreasuryPalletId, VotePeriod, VotingOutcomeFee, BASE, CENT, }, }, math::fixed::FixedMul, traits::{DeployPoolApi, DistributeFees}, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, CurrencyId, + Hash, Index, MarketId, Moment, UncheckedExtrinsicTest, }, }; use zrml_neo_swaps::BalanceOf; @@ -84,7 +81,7 @@ pub const SUDO: AccountIdTest = 123456; pub const EXTERNAL_FEES: Balance = CENT; #[cfg(feature = "parachain")] -pub const FOREIGN_ASSET: Assets = Assets::ForeignAsset(1); +pub const FOREIGN_ASSET: Asset = Asset::ForeignAsset(1); parameter_types! { pub const FeeAccount: AccountIdTest = FEE_ACCOUNT; @@ -164,10 +161,6 @@ impl Contains for DustRemovalWhitelist { } } -pub(super) type CustomAssetsInstance = pallet_assets::Instance1; -pub(super) type CampaignAssetsInstance = pallet_assets::Instance2; -pub(super) type MarketAssetsInstance = pallet_assets::Instance3; - construct_runtime!( pub enum Runtime where @@ -176,15 +169,11 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { NeoSwaps: zrml_neo_swaps::{Call, Event, Pallet}, - AssetManager: orml_currencies::{Call, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, Authorized: zrml_authorized::{Event, Pallet, Storage}, Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, Court: zrml_court::{Event, Pallet, Storage}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, + AssetManager: orml_currencies::{Call, Pallet, Storage}, LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, MarketCommons: zrml_market_commons::{Pallet, Storage}, PredictionMarkets: zrml_prediction_markets::{Event, Pallet, Storage}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage}, @@ -209,130 +198,12 @@ impl crate::Config for Runtime { type WeightInfo = zrml_neo_swaps::weights::WeightInfo; } -pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } -} - -pallet_assets::runtime_benchmarks_enabled! { - use zeitgeist_primitives::types::CategoryIndex; - - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl zrml_asset_router::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyAccountWeight; - type DestroyApprovalWeight = DestroyApprovalWeight; - type DestroyFinishWeight = DestroyFinishWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; -} - impl pallet_randomness_collective_flip::Config for Runtime {} impl zrml_prediction_markets::Config for Runtime { type AdvisoryBond = AdvisoryBond; type AdvisoryBondSlashPercentage = AdvisoryBondSlashPercentage; type ApproveOrigin = EnsureSignedBy; - type AssetCreator = AssetRouter; - type AssetDestroyer = AssetRouter; #[cfg(feature = "parachain")] type AssetRegistry = MockRegistry; type Authorized = Authorized; @@ -363,7 +234,6 @@ impl zrml_prediction_markets::Config for Runtime { type MinCategories = MinCategories; type MaxEditReasonLen = MaxEditReasonLen; type MaxRejectReasonLen = MaxRejectReasonLen; - type OnStateTransition = (); type OracleBond = OracleBond; type OutsiderBond = OutsiderBond; type PalletId = PmPalletId; @@ -454,7 +324,7 @@ impl frame_system::Config for Runtime { impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = AssetRouter; + type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type WeightInfo = (); } @@ -462,7 +332,7 @@ impl orml_currencies::Config for Runtime { impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Currencies; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = DustRemovalWhitelist; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -549,7 +419,7 @@ impl pallet_treasury::Config for Runtime { #[cfg(feature = "parachain")] zrml_prediction_markets::impl_mock_registry! { MockRegistry, - zeitgeist_primitives::types::XcmAsset, + CurrencyId, Balance, zeitgeist_primitives::types::CustomMetadata } @@ -580,7 +450,7 @@ impl ExtBuilder { { use frame_support::traits::GenesisBuild; orml_tokens::GenesisConfig:: { - balances: vec![(ALICE, FOREIGN_ASSET.try_into().unwrap(), 100_000_000_001 * _1)], + balances: vec![(ALICE, FOREIGN_ASSET, 100_000_000_001 * _1)], } .assimilate_storage(&mut t) .unwrap(); @@ -590,7 +460,7 @@ impl ExtBuilder { }; orml_asset_registry_mock::GenesisConfig { metadata: vec![( - FOREIGN_ASSET.try_into().unwrap(), + FOREIGN_ASSET, AssetMetadata { decimals: 18, name: "MKL".as_bytes().to_vec(), diff --git a/zrml/neo-swaps/src/tests/deploy_pool.rs b/zrml/neo-swaps/src/tests/deploy_pool.rs index ac02e5955..8d7f4fdec 100644 --- a/zrml/neo-swaps/src/tests/deploy_pool.rs +++ b/zrml/neo-swaps/src/tests/deploy_pool.rs @@ -90,7 +90,6 @@ fn deploy_pool_works_with_scalar_marktes() { ExtBuilder::default().build().execute_with(|| { let alice_before = AssetManager::free_balance(BASE_ASSET, &ALICE); let amount = _100; - let expected_amounts = [amount, 101755598229]; let spot_prices = vec![_1_6, _5_6 + 1]; let swap_fee = CENT; let market_id: MarketId = 0; @@ -98,6 +97,14 @@ fn deploy_pool_works_with_scalar_marktes() { Asset::ScalarOutcome(market_id, ScalarPosition::Long), Asset::ScalarOutcome(market_id, ScalarPosition::Short), ]; + // Deploy some funds in the pool account to ensure that rogue funds don't screw up price + // calculatings. + let rogue_funds = _100; + assert_ok!(AssetManager::deposit( + assets[0], + &Pallet::::pool_account_id(&market_id), + rogue_funds + )); let _ = create_market_and_deploy_pool( ALICE, BASE_ASSET, @@ -107,31 +114,8 @@ fn deploy_pool_works_with_scalar_marktes() { swap_fee, ); let pool = Pools::::get(market_id).unwrap(); - let mut reserves = BTreeMap::new(); - reserves.insert(assets[0], expected_amounts[0]); - reserves.insert(assets[1], expected_amounts[1]); - System::assert_last_event( - Event::PoolDeployed { - who: ALICE, - market_id, - account_id: pool.account_id, - reserves, - collateral: pool.collateral, - liquidity_parameter: pool.liquidity_parameter, - pool_shares_amount: amount, - swap_fee, - } - .into(), - ); - // Deploy some funds in the pool account to ensure that rogue funds don't screw up price - // calculatings. - let rogue_funds = _100; - assert_ok!(AssetManager::deposit( - assets[0], - &Pallet::::pool_account_id(&market_id), - rogue_funds - )); let expected_liquidity = 558110626551; + let expected_amounts = [amount, 101755598229]; let buffer = AssetManager::minimum_balance(pool.collateral); assert_eq!(pool.assets(), assets); assert_approx!(pool.liquidity_parameter, expected_liquidity, 1_000); @@ -161,6 +145,22 @@ fn deploy_pool_works_with_scalar_marktes() { let price_sum = pool.assets().iter().map(|&a| pool.calculate_spot_price(a).unwrap()).sum::(); assert_eq!(price_sum, _1); + let mut reserves = BTreeMap::new(); + reserves.insert(assets[0], expected_amounts[0]); + reserves.insert(assets[1], expected_amounts[1]); + System::assert_last_event( + Event::PoolDeployed { + who: ALICE, + market_id, + account_id: pool.account_id, + reserves, + collateral: pool.collateral, + liquidity_parameter: pool.liquidity_parameter, + pool_shares_amount: amount, + swap_fee, + } + .into(), + ); }); } @@ -429,7 +429,7 @@ fn deploy_pool_fails_on_insufficient_funds() { vec![_3_4, _1_4], CENT ), - pallet_assets::Error::::BalanceLow + orml_tokens::Error::::BalanceTooLow ); }); } diff --git a/zrml/neo-swaps/src/tests/join.rs b/zrml/neo-swaps/src/tests/join.rs index a230bef0b..1e6bc0183 100644 --- a/zrml/neo-swaps/src/tests/join.rs +++ b/zrml/neo-swaps/src/tests/join.rs @@ -208,7 +208,6 @@ fn join_fails_on_insufficient_funds() { vec![_1_2, _1_2], CENT, ); - assert_noop!( NeoSwaps::join( RuntimeOrigin::signed(ALICE), @@ -216,7 +215,7 @@ fn join_fails_on_insufficient_funds() { _100, vec![u128::MAX, u128::MAX] ), - pallet_assets::Error::::NoAccount + orml_tokens::Error::::BalanceTooLow ); }); } diff --git a/zrml/neo-swaps/src/tests/mod.rs b/zrml/neo-swaps/src/tests/mod.rs index 6c8f9c98c..8dc8eb78d 100644 --- a/zrml/neo-swaps/src/tests/mod.rs +++ b/zrml/neo-swaps/src/tests/mod.rs @@ -34,20 +34,20 @@ use zeitgeist_primitives::{ constants::{base_multiples::*, CENT}, math::fixed::{FixedDiv, FixedMul}, types::{ - AccountIdTest, Asset, Assets, Deadlines, MarketCreation, MarketId, MarketPeriod, - MarketStatus, MarketType, MultiHash, ScalarPosition, ScoringRule, + AccountIdTest, Asset, Deadlines, MarketCreation, MarketId, MarketPeriod, MarketStatus, + MarketType, MultiHash, ScalarPosition, ScoringRule, }, }; use zrml_market_commons::{MarketCommonsPalletApi, Markets}; #[cfg(not(feature = "parachain"))] -const BASE_ASSET: Assets = Assets::Ztg; +const BASE_ASSET: Asset = Asset::Ztg; #[cfg(feature = "parachain")] -const BASE_ASSET: Assets = FOREIGN_ASSET; +const BASE_ASSET: Asset = FOREIGN_ASSET; fn create_market( creator: AccountIdTest, - base_asset: Assets, + base_asset: Asset, market_type: MarketType, scoring_rule: ScoringRule, ) -> MarketId { @@ -56,7 +56,7 @@ fn create_market( metadata[1] = 0x30; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(creator), - base_asset.try_into().unwrap(), + base_asset, Perbill::zero(), EVE, MarketPeriod::Block(0..2), @@ -76,7 +76,7 @@ fn create_market( fn create_market_and_deploy_pool( creator: AccountIdOf, - base_asset: Assets, + base_asset: Asset, market_type: MarketType, amount: BalanceOf, spot_prices: Vec>, @@ -104,7 +104,7 @@ fn deposit_complete_set( amount: BalanceOf, ) { let market = MarketCommons::market(&market_id).unwrap(); - assert_ok!(AssetManager::deposit(market.base_asset.into(), &account, amount)); + assert_ok!(AssetManager::deposit(market.base_asset, &account, amount)); assert_ok!(::CompleteSetOperations::buy_complete_set( RuntimeOrigin::signed(account), market_id, diff --git a/zrml/neo-swaps/src/tests/sell.rs b/zrml/neo-swaps/src/tests/sell.rs index dfbd415c8..5c1b9dd60 100644 --- a/zrml/neo-swaps/src/tests/sell.rs +++ b/zrml/neo-swaps/src/tests/sell.rs @@ -352,7 +352,7 @@ fn sell_fails_on_insufficient_funds() { amount_in, u128::MAX, ), - pallet_assets::Error::::BalanceLow, + orml_tokens::Error::::BalanceTooLow, ); }); } diff --git a/zrml/neo-swaps/src/types/max_assets.rs b/zrml/neo-swaps/src/types/max_assets.rs index 3a2595770..823147c7b 100644 --- a/zrml/neo-swaps/src/types/max_assets.rs +++ b/zrml/neo-swaps/src/types/max_assets.rs @@ -1,4 +1,4 @@ -// Copyright 2024 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // // This file is part of Zeitgeist. // diff --git a/zrml/neo-swaps/src/weights.rs b/zrml/neo-swaps/src/weights.rs index c03925ef2..d6c42e513 100644 --- a/zrml/neo-swaps/src/weights.rs +++ b/zrml/neo-swaps/src/weights.rs @@ -68,8 +68,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) /// Storage: System Account (r:3 w:3) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:129 w:129) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:128 w:128) @@ -92,9 +90,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: MarketCommons Markets (r:1 w:0) /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: NeoSwaps Pools (r:1 w:1) - /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:129 w:129) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:3 w:3) @@ -119,9 +114,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: MarketCommons Markets (r:1 w:0) /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: NeoSwaps Pools (r:1 w:1) - /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:256 w:256) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:0) @@ -144,9 +136,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: MarketCommons Markets (r:1 w:0) /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: NeoSwaps Pools (r:1 w:1) - /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:256 w:256) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:0) @@ -169,9 +158,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: MarketCommons Markets (r:1 w:0) /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: NeoSwaps Pools (r:1 w:1) - /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:256 w:256) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:0) @@ -194,9 +180,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: MarketCommons Markets (r:1 w:0) /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: NeoSwaps Pools (r:1 w:1) - /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:256 w:256) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:0) @@ -232,9 +215,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: MarketCommons Markets (r:1 w:0) /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: NeoSwaps Pools (r:1 w:1) - /// Proof: NeoSwaps Pools (max_values: None, max_size: Some(144746), added: 147221, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:128 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:256 w:256) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) diff --git a/zrml/orderbook/Cargo.toml b/zrml/orderbook/Cargo.toml index 0fe4dcc09..bd8508c76 100644 --- a/zrml/orderbook/Cargo.toml +++ b/zrml/orderbook/Cargo.toml @@ -8,43 +8,37 @@ orml-traits = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } sp-runtime = { workspace = true } -zeitgeist-macros = { workspace = true } zeitgeist-primitives = { workspace = true } # Mock env_logger = { workspace = true, optional = true } orml-currencies = { workspace = true, optional = true } orml-tokens = { workspace = true, optional = true } -pallet-assets = { workspace = true, optional = true } pallet-balances = { workspace = true, optional = true } pallet-timestamp = { workspace = true, optional = true } sp-io = { workspace = true, optional = true } -zrml-asset-router = { workspace = true, optional = true } zrml-market-commons = { workspace = true, optional = true } [dev-dependencies] test-case = { workspace = true } -zrml-orderbook = { workspace = true, features = ["default", "mock"] } +zrml-orderbook = { workspace = true, features = ["mock", "default"] } [features] default = ["std"] mock = [ - "env_logger/default", - "orml-currencies/default", "orml-tokens/default", - "pallet-assets/default", "pallet-balances/default", "pallet-timestamp/default", + "zrml-market-commons/default", + "orml-currencies/default", "sp-io/default", "zeitgeist-primitives/mock", - "zrml-asset-router", - "zrml-market-commons/default", + "env_logger/default", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", - "pallet-assets?/runtime-benchmarks", ] std = [ "frame-benchmarking?/std", diff --git a/zrml/orderbook/fuzz/orderbook_v1_full_workflow.rs b/zrml/orderbook/fuzz/orderbook_v1_full_workflow.rs index a23fa0330..90863f7fa 100644 --- a/zrml/orderbook/fuzz/orderbook_v1_full_workflow.rs +++ b/zrml/orderbook/fuzz/orderbook_v1_full_workflow.rs @@ -19,7 +19,7 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use zeitgeist_primitives::types::{Asset, ScalarPosition}; +use zeitgeist_primitives::types::{Asset, ScalarPosition, SerdeWrapper}; use zrml_orderbook::mock::{ExtBuilder, Orderbook, RuntimeOrigin}; #[cfg(feature = "arbitrary")] @@ -92,7 +92,7 @@ fn asset(seed: (u128, u16)) -> Asset { if seed1 % 2 == 0 { ScalarPosition::Long } else { ScalarPosition::Short }; Asset::ScalarOutcome(seed0, scalar_position) } - 2 => Asset::PoolShare(seed0), + 2 => Asset::PoolShare(SerdeWrapper(seed0)), _ => Asset::Ztg, } } diff --git a/zrml/orderbook/src/benchmarks.rs b/zrml/orderbook/src/benchmarks.rs index 751f990aa..d42b67710 100644 --- a/zrml/orderbook/src/benchmarks.rs +++ b/zrml/orderbook/src/benchmarks.rs @@ -48,7 +48,7 @@ fn order_common_parameters( &'static str, > { let market = market_mock::(); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let acc = generate_funded_account::(seed, maker_asset)?; let maker_amount: BalanceOf = BASE.saturating_mul(1_000).saturated_into(); let taker_amount: BalanceOf = BASE.saturating_mul(1_000).saturated_into(); @@ -84,7 +84,7 @@ benchmarks! { let taker_asset = Asset::CategoricalOutcome::>(market_id, 0); let (_, _, order_id) = place_default_order::(Some(0), taker_asset)?; let caller = generate_funded_account::(None, taker_asset)?; - let maker_asset = T::MarketCommons::market(&market_id).unwrap().base_asset.into(); + let maker_asset = T::MarketCommons::market(&market_id).unwrap().base_asset; let caller = generate_funded_account::(None, maker_asset)?; }: fill_order(RawOrigin::Signed(caller), order_id, None) diff --git a/zrml/orderbook/src/lib.rs b/zrml/orderbook/src/lib.rs index e2cc1c892..f97fc938c 100644 --- a/zrml/orderbook/src/lib.rs +++ b/zrml/orderbook/src/lib.rs @@ -22,7 +22,7 @@ extern crate alloc; use crate::weights::*; -use alloc::vec; +use alloc::{vec, vec::Vec}; use core::marker::PhantomData; use frame_support::{ ensure, @@ -33,18 +33,18 @@ use frame_support::{ transactional, PalletId, Twox64Concat, }; use frame_system::{ensure_signed, pallet_prelude::OriginFor}; -use orml_traits::{ - BalanceStatus, MultiCurrency, MultiReservableCurrency, NamedMultiReservableCurrency, -}; +use orml_traits::{BalanceStatus, MultiCurrency, NamedMultiReservableCurrency}; pub use pallet::*; -use sp_runtime::traits::{AccountIdConversion, Get, Zero}; -use zeitgeist_macros::unreachable_non_terminating; +use sp_runtime::traits::{Get, Zero}; use zeitgeist_primitives::{ hybrid_router_api_types::{ApiError, ExternalFee, OrderbookSoftFail, OrderbookTrade}, - math::checked_ops_res::{CheckedAddRes, CheckedSubRes}, + math::{ + checked_ops_res::{CheckedAddRes, CheckedSubRes}, + fixed::FixedMulDiv, + }, orderbook::{Order, OrderId}, traits::{DistributeFees, HybridRouterOrderbookApi, MarketCommonsPalletApi}, - types::{Asset, BaseAsset, MarketStatus, ScoringRule}, + types::{Asset, Market, MarketStatus, MarketType, ScalarPosition, ScoringRule}, }; #[cfg(feature = "runtime-benchmarks")] @@ -97,16 +97,24 @@ mod pallet { /// The current storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + pub(crate) type AccountIdOf = ::AccountId; pub(crate) type AssetOf = Asset>; pub(crate) type BalanceOf = <::AssetManager as MultiCurrency< ::AccountId, >>::Balance; + pub(crate) type ExternalFeeOf = ExternalFee, BalanceOf>; pub(crate) type MarketIdOf = <::MarketCommons as MarketCommonsPalletApi>::MarketId; - pub(crate) type AccountIdOf = ::AccountId; + pub(crate) type MarketOf = Market< + AccountIdOf, + BalanceOf, + ::BlockNumber, + MomentOf, + MarketIdOf, + >; + pub(crate) type MomentOf = <::MarketCommons as MarketCommonsPalletApi>::Moment; pub(crate) type OrderOf = Order, BalanceOf, MarketIdOf>; pub(crate) type OrderbookTradeOf = OrderbookTrade, BalanceOf>; - pub(crate) type ExternalFeeOf = ExternalFee, BalanceOf>; #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -242,6 +250,30 @@ mod pallet { } impl Pallet { + /// The reserve ID of the order book pallet. + #[inline] + pub fn reserve_id() -> [u8; 8] { + T::PalletId::get().0 + } + + pub fn outcome_assets(market_id: MarketIdOf, market: &MarketOf) -> Vec> { + match market.market_type { + MarketType::Categorical(categories) => { + let mut assets = Vec::new(); + for i in 0..categories { + assets.push(Asset::CategoricalOutcome(market_id, i)); + } + assets + } + MarketType::Scalar(_) => { + vec![ + Asset::ScalarOutcome(market_id, ScalarPosition::Long), + Asset::ScalarOutcome(market_id, ScalarPosition::Short), + ] + } + } + } + /// Reduces the reserved maker and requested taker amount /// by the amount the maker and taker actually filled. fn decrease_order_amounts( @@ -254,16 +286,20 @@ mod pallet { Ok(()) } - /// The order account for a specific order id. - #[inline] - pub(crate) fn order_account(order_id: OrderId) -> AccountIdOf { - T::PalletId::get().into_sub_account_truncating(order_id) - } - - /// The reserve ID of the order book pallet. - #[inline] - pub(crate) fn reserve_id() -> [u8; 8] { - T::PalletId::get().0 + /// Calculates the amount that the taker is going to get from the maker's amount. + fn get_taker_fill( + order_data: &OrderOf, + maker_fill: BalanceOf, + ) -> Result, DispatchError> { + // the maker_full_fill is the maximum amount of what the maker wants to have + let maker_full_fill = order_data.taker_amount; + // the taker_full_fill is the maximum amount of what the taker wants to have + let taker_full_fill = order_data.maker_amount; + // rounding down: the taker will always get a little bit less than what they asked for. + // This ensures that the reserve of the maker + // is always enough to repatriate successfully! + // `maker_full_fill` is ensured to be never zero in `ensure_ratio_quotient_valid` + maker_fill.bmul_bdiv_floor(taker_full_fill, maker_full_fill) } fn ensure_ratio_quotient_valid(order_data: &OrderOf) -> DispatchResult { @@ -282,29 +318,24 @@ mod pallet { let maker = &order_data.maker; ensure!(who == *maker, Error::::NotOrderCreator); - let order_account = Self::order_account(order_id); - let asset = order_data.maker_asset; - let amount = order_data.maker_amount; - - if !T::AssetManager::reserved_balance_named(&Self::reserve_id(), asset, maker).is_zero() - { - let missing = - T::AssetManager::unreserve_named(&Self::reserve_id(), asset, maker, amount); - - unreachable_non_terminating!( - missing.is_zero(), - LOG_TARGET, - "Could not unreserve all of the amount. reserve_id: {:?}, asset: {:?} who: \ - {:?}, amount: {:?}, missing: {:?}", - Self::reserve_id(), - asset, - maker, - amount, - missing, - ); - } else { - T::AssetManager::transfer(asset, &order_account, maker, amount)?; - } + + let missing = T::AssetManager::unreserve_named( + &Self::reserve_id(), + order_data.maker_asset, + maker, + order_data.maker_amount, + ); + + debug_assert!( + missing.is_zero(), + "Could not unreserve all of the amount. reserve_id: {:?}, asset: {:?} who: {:?}, \ + amount: {:?}, missing: {:?}", + Self::reserve_id(), + order_data.maker_asset, + maker, + order_data.maker_amount, + missing, + ); >::remove(order_id); @@ -322,30 +353,25 @@ mod pallet { /// Returns the adjusted maker fill and the external fee. fn charge_external_fees( order_data: &OrderOf, - base_asset: BaseAsset, + base_asset: AssetOf, maker_fill: BalanceOf, taker: &AccountIdOf, taker_fill: BalanceOf, ) -> Result<(BalanceOf, ExternalFeeOf), DispatchError> { - let maker_asset_is_base_asset = order_data.maker_asset == base_asset.into(); - let base_asset_fill = if maker_asset_is_base_asset { + let maker_asset_is_base = order_data.maker_asset == base_asset; + let base_asset_fill = if maker_asset_is_base { taker_fill } else { - unreachable_non_terminating!( - order_data.taker_asset == base_asset.into(), - LOG_TARGET, - "Order {:?} does not contain a base asset", - order_data - ); + debug_assert!(order_data.taker_asset == base_asset); maker_fill }; let fee_amount = T::ExternalFees::distribute( order_data.market_id, - base_asset.into(), + base_asset, taker, base_asset_fill, ); - if maker_asset_is_base_asset { + if maker_asset_is_base { Ok((maker_fill, ExternalFeeOf:: { account: taker.clone(), amount: fee_amount })) } else { Ok(( @@ -363,12 +389,6 @@ mod pallet { ) -> Result, DispatchError> { let mut order_data = >::get(order_id).ok_or(Error::::OrderDoesNotExist)?; let market = T::MarketCommons::market(&order_data.market_id)?; - unreachable_non_terminating!( - market.scoring_rule == ScoringRule::AmmCdaHybrid, - LOG_TARGET, - "The call to place_order already ensured the scoring rule amm and order book \ - hybrid.", - ); ensure!(market.status == MarketStatus::Active, Error::::MarketIsNotActive); let base_asset = market.base_asset; @@ -383,41 +403,18 @@ mod pallet { let maker_asset = order_data.maker_asset; let taker_asset = order_data.taker_asset; - // the reserve of the maker should always be enough - // to repatriate successfully, e.g. taker gets a little bit less - // it should always ensure that the maker's request (maker_fill) is fully filled - let (taker_fill, _maker_fill) = - order_data.taker_and_maker_fill_from_taker_amount(maker_fill)?; - let order_account = Self::order_account(order_id); - - if !T::AssetManager::reserved_balance_named(&Self::reserve_id(), maker_asset, &maker) - .is_zero() - { - let missing = T::AssetManager::repatriate_reserved_named( - &Self::reserve_id(), - maker_asset, - &maker, - &taker, - taker_fill, - BalanceStatus::Free, - )?; - - unreachable_non_terminating!( - missing.is_zero(), - LOG_TARGET, - "Could not repatriate all of the amount. reserve_id: {:?}, asset: {:?} who: \ - {:?}, amount: {:?}, missing: {:?}", - Self::reserve_id(), - maker_asset, - maker, - taker_fill, - missing, - ); - } else { - T::AssetManager::transfer(maker_asset, &order_account, &taker, taker_fill)?; - } + let taker_fill = Self::get_taker_fill(&order_data, maker_fill)?; // if base asset: fund the full amount, but charge base asset fees from taker later + T::AssetManager::repatriate_reserved_named( + &Self::reserve_id(), + maker_asset, + &maker, + &taker, + taker_fill, + BalanceStatus::Free, + )?; + // always charge fees from the base asset and not the outcome asset let (maybe_adjusted_maker_fill, external_fee) = Self::charge_external_fees( &order_data, @@ -478,19 +475,17 @@ mod pallet { market.scoring_rule == ScoringRule::AmmCdaHybrid, Error::::InvalidScoringRule ); + let base_asset = market.base_asset; - let outcome_asset = if maker_asset == base_asset.into() { + let outcome_asset = if maker_asset == base_asset { taker_asset } else { - ensure!(taker_asset == base_asset.into(), Error::::MarketBaseAssetNotPresent); + ensure!(taker_asset == base_asset, Error::::MarketBaseAssetNotPresent); maker_asset }; - - let outcome_asset_converted = - outcome_asset.try_into().map_err(|_| Error::::InvalidOutcomeAsset)?; let market_assets = market.outcome_assets(); market_assets - .binary_search(&outcome_asset_converted) + .binary_search(&outcome_asset) .map_err(|_| Error::::InvalidOutcomeAsset)?; ensure!( @@ -506,18 +501,7 @@ mod pallet { let next_order_id = order_id.checked_add_res(&1)?; // fees are always only charged in the base asset in fill_order - // reserving the maker_asset is preferred (depends on other pallet support) - if T::AssetManager::can_reserve(maker_asset, &who, maker_amount) { - T::AssetManager::reserve_named( - &Self::reserve_id(), - maker_asset, - &who, - maker_amount, - )?; - } else { - let order_account = Self::order_account(order_id); - T::AssetManager::transfer(maker_asset, &who, &order_account, maker_amount)?; - } + T::AssetManager::reserve_named(&Self::reserve_id(), maker_asset, &who, maker_amount)?; let order = Order { market_id, diff --git a/zrml/orderbook/src/mock.rs b/zrml/orderbook/src/mock.rs index 83f33231c..e5b9f08f3 100644 --- a/zrml/orderbook/src/mock.rs +++ b/zrml/orderbook/src/mock.rs @@ -18,35 +18,25 @@ #![cfg(feature = "mock")] -use crate as orderbook; +use crate as orderbook_v1; use crate::{AssetOf, BalanceOf, MarketIdOf}; use core::marker::PhantomData; -use frame_support::{ - construct_runtime, - pallet_prelude::Get, - parameter_types, - traits::{AsEnsureOriginWithArg, Everything}, -}; -use frame_system::{EnsureRoot, EnsureSigned}; +use frame_support::{construct_runtime, pallet_prelude::Get, parameter_types, traits::Everything}; use orml_traits::MultiCurrency; -use parity_scale_codec::Compact; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, ConstU32, IdentityLookup, Zero}, + traits::{BlakeTwo256, IdentityLookup, Zero}, Perbill, SaturatedConversion, }; use zeitgeist_primitives::{ constants::mock::{ - AssetsAccountDeposit, AssetsApprovalDeposit, AssetsDeposit, AssetsMetadataDepositBase, - AssetsMetadataDepositPerByte, AssetsStringLimit, BlockHashCount, DestroyAccountWeight, - DestroyApprovalWeight, DestroyFinishWeight, ExistentialDeposit, ExistentialDeposits, - GetNativeCurrencyId, MaxLocks, MaxReserves, MinimumPeriod, OrderbookPalletId, BASE, CENT, + BlockHashCount, ExistentialDeposit, ExistentialDeposits, GetNativeCurrencyId, MaxLocks, + MaxReserves, MinimumPeriod, OrderbookPalletId, BASE, CENT, }, traits::DistributeFees, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, CurrencyId, + Hash, Index, MarketId, Moment, UncheckedExtrinsicTest, }, }; @@ -63,10 +53,6 @@ parameter_types! { pub const FeeAccount: AccountIdTest = MARKET_CREATOR; } -type CustomAssetsInstance = pallet_assets::Instance1; -type CampaignAssetsInstance = pallet_assets::Instance2; -type MarketAssetsInstance = pallet_assets::Instance3; - pub fn fee_percentage() -> Perbill { Perbill::from_rational(EXTERNAL_FEES, BASE) } @@ -111,17 +97,13 @@ construct_runtime!( NodeBlock = BlockTest, UncheckedExtrinsic = UncheckedExtrinsicTest, { - AssetManager: orml_currencies::{Call, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, MarketCommons: zrml_market_commons::{Pallet, Storage}, - Orderbook: orderbook::{Call, Event, Pallet}, + Orderbook: orderbook_v1::{Call, Event, Pallet}, System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, Tokens: orml_tokens::{Config, Event, Pallet, Storage}, + AssetManager: orml_currencies::{Call, Pallet, Storage}, + Timestamp: pallet_timestamp::{Pallet}, } ); @@ -131,7 +113,7 @@ impl crate::Config for Runtime { type RuntimeEvent = RuntimeEvent; type MarketCommons = MarketCommons; type PalletId = OrderbookPalletId; - type WeightInfo = orderbook::weights::WeightInfo; + type WeightInfo = orderbook_v1::weights::WeightInfo; } impl frame_system::Config for Runtime { @@ -163,7 +145,7 @@ impl frame_system::Config for Runtime { impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = AssetRouter; + type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type WeightInfo = (); } @@ -171,7 +153,7 @@ impl orml_currencies::Config for Runtime { impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Currencies; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = Everything; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -182,106 +164,6 @@ impl orml_tokens::Config for Runtime { type WeightInfo = (); } -pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } -} - -pallet_assets::runtime_benchmarks_enabled! { - use zeitgeist_primitives::types::CategoryIndex; - - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; @@ -301,22 +183,6 @@ impl pallet_timestamp::Config for Runtime { type WeightInfo = (); } -impl zrml_asset_router::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyAccountWeight; - type DestroyApprovalWeight = DestroyApprovalWeight; - type DestroyFinishWeight = DestroyFinishWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; -} - impl zrml_market_commons::Config for Runtime { type Balance = Balance; type MarketId = MarketId; diff --git a/zrml/orderbook/src/tests.rs b/zrml/orderbook/src/tests.rs index f037b408f..d37b70c77 100644 --- a/zrml/orderbook/src/tests.rs +++ b/zrml/orderbook/src/tests.rs @@ -17,7 +17,7 @@ // along with Zeitgeist. If not, see . use crate::{mock::*, utils::market_mock, Error, Event, Order, Orders}; -use frame_support::{assert_noop, assert_ok, traits::fungibles::Create}; +use frame_support::{assert_noop, assert_ok}; use orml_tokens::Error as AError; use orml_traits::{MultiCurrency, MultiReservableCurrency}; use pallet_balances::Error as BError; @@ -26,7 +26,7 @@ use test_case::test_case; use zeitgeist_primitives::{ constants::BASE, hybrid_router_api_types::ExternalFee, - types::{Asset, BaseAsset, MarketStatus, MarketType, ScalarPosition, ScoringRule}, + types::{Asset, MarketStatus, MarketType, ScalarPosition, ScoringRule}, }; use zrml_market_commons::{Error as MError, MarketCommonsPalletApi, Markets}; @@ -45,7 +45,7 @@ fn place_order_fails_with_wrong_scoring_rule(scoring_rule: ScoringRule) { Orderbook::place_order( RuntimeOrigin::signed(ALICE), market_id, - market.base_asset.into(), + market.base_asset, 10 * BASE, Asset::CategoricalOutcome(market_id, 2), 25 * BASE, @@ -74,7 +74,7 @@ fn place_order_fails_if_market_status_not_active(status: MarketStatus) { Orderbook::place_order( RuntimeOrigin::signed(ALICE), market_id, - market.base_asset.into(), + market.base_asset, 10 * BASE, Asset::CategoricalOutcome(0, 2), 25 * BASE, @@ -95,7 +95,7 @@ fn fill_order_fails_if_market_status_not_active(status: MarketStatus) { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -128,7 +128,7 @@ fn fill_order_fails_if_amount_too_high_for_order() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -157,7 +157,7 @@ fn fill_order_fails_if_amount_is_below_minimum_balance() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -190,7 +190,7 @@ fn place_order_fails_if_amount_is_below_minimum_balance() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); assert_noop!( @@ -226,7 +226,7 @@ fn fill_order_fails_if_balance_too_low() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -259,7 +259,7 @@ fn fill_order_fails_if_partial_fill_near_full_fill_not_allowed() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -274,7 +274,7 @@ fn fill_order_fails_if_partial_fill_near_full_fill_not_allowed() { taker_amount, )); - assert_ok!(AssetManager::deposit(taker_asset, &BOB, taker_amount)); + AssetManager::deposit(taker_asset, &BOB, taker_amount).unwrap(); assert_noop!( Orderbook::fill_order( @@ -294,7 +294,7 @@ fn fill_order_removes_order() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -324,7 +324,7 @@ fn fill_order_partially_fills_order() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let order_id = 0u128; @@ -370,37 +370,6 @@ fn fill_order_partially_fills_order() { }); } -#[test] -fn fill_order_does_work_with_reserves_after_funding_order_account() { - ExtBuilder::default().build().execute_with(|| { - let market_id = 0u128; - let mut market = market_mock::(); - market.base_asset = BaseAsset::Ztg; - Markets::::insert(market_id, market.clone()); - - let maker_asset = market.base_asset.into(); - let taker_asset = Asset::CategoricalOutcome(0, 2); - let taker_amount = 10 * BASE; - let maker_amount = 250 * BASE; - - assert_ok!(AssetManager::deposit(maker_asset, &ALICE, maker_amount)); - assert_ok!(AssetManager::deposit(taker_asset, &BOB, taker_amount)); - assert_ok!(Orderbook::place_order( - RuntimeOrigin::signed(ALICE), - market_id, - maker_asset, - maker_amount, - taker_asset, - taker_amount, - )); - - let reserved_funds = AssetManager::reserved_balance(maker_asset, &ALICE); - assert_eq!(reserved_funds, maker_amount); - assert_ok!(AssetManager::deposit(maker_asset, &Orderbook::order_account(0), BASE)); - assert_ok!(Orderbook::fill_order(RuntimeOrigin::signed(BOB), 0, None)); - }); -} - #[test] fn place_order_fails_if_market_base_asset_not_present() { ExtBuilder::default().build().execute_with(|| { @@ -434,7 +403,7 @@ fn place_order_fails_if_invalid_outcome_asset() { assert_eq!(market.market_type, MarketType::Categorical(64u16)); let maker_asset = Asset::ScalarOutcome(0, ScalarPosition::Long); - let taker_asset = market.base_asset.into(); + let taker_asset = market.base_asset; assert_noop!( Orderbook::place_order( @@ -480,7 +449,7 @@ fn place_order_fails_if_maker_has_insufficient_funds() { Markets::::insert(market_id, market.clone()); let maker = ALICE; - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let alice_free_maker_amount = AssetManager::free_balance(maker_asset, &maker); @@ -516,16 +485,11 @@ fn it_fails_order_does_not_exist() { }); } -#[test_case(true; "with_reservable_asset")] -#[test_case(false; "with_non_reservable_asset")] -fn it_places_orders(reservable_maker_asset: bool) { +#[test] +fn it_places_orders() { ExtBuilder::default().build().execute_with(|| { let market_id = 0u128; - let mut market = market_mock::(); - if !reservable_maker_asset { - market.base_asset = BaseAsset::CampaignAsset(0); - assert_ok!(AssetRouter::create(market.base_asset.into(), ALICE, true, 1)); - } + let market = market_mock::(); Markets::::insert(market_id, market.clone()); let taker_asset_0 = Asset::CategoricalOutcome(0, 2); @@ -533,24 +497,18 @@ fn it_places_orders(reservable_maker_asset: bool) { let taker_amount = 10 * BASE; let maker_amount = 250 * BASE; - assert_ok!(AssetManager::deposit(market.base_asset.into(), &ALICE, maker_amount)); + assert_ok!(AssetManager::deposit(market.base_asset, &ALICE, maker_amount)); assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(ALICE), market_id, - market.base_asset.into(), + market.base_asset, maker_amount, taker_asset_0, taker_amount, )); - let reserved_funds = if reservable_maker_asset { - AssetManager::reserved_balance(market.base_asset.into(), &ALICE) - } else { - let order_account = Orderbook::order_account(0); - assert_eq!(AssetManager::free_balance(market.base_asset.into(), &BOB), 0); - AssetManager::free_balance(market.base_asset.into(), &order_account) - }; + let reserved_funds = AssetManager::reserved_balance(market.base_asset, &ALICE); assert_eq!(reserved_funds, maker_amount); let maker_asset = Asset::CategoricalOutcome(0, 1); @@ -564,7 +522,7 @@ fn it_places_orders(reservable_maker_asset: bool) { market_id, maker_asset, maker_amount, - market.base_asset.into(), + market.base_asset, taker_amount, )); @@ -581,7 +539,7 @@ fn it_fills_order_fully_maker_outcome_asset() { Markets::::insert(market_id, market.clone()); let maker_asset = Asset::CategoricalOutcome(0, 1); - let taker_asset = market.base_asset.into(); + let taker_asset = market.base_asset; let maker_amount = 100 * BASE; let taker_amount = 500 * BASE; @@ -634,33 +592,26 @@ fn it_fills_order_fully_maker_outcome_asset() { assert_eq!(alice_maker_asset_free, INITIAL_BALANCE); assert_eq!(alice_taker_asset_free, maker_amount); - let bob_taker_asset_free = AssetManager::free_balance(market.base_asset.into(), &BOB); + let bob_taker_asset_free = AssetManager::free_balance(market.base_asset, &BOB); let bob_maker_asset_free = AssetManager::free_balance(maker_asset, &BOB); assert_eq!(bob_taker_asset_free, INITIAL_BALANCE + taker_amount - taker_fees); assert_eq!(bob_maker_asset_free, 0); }); } -#[test_case(true; "with_reservable_asset")] -#[test_case(false; "with_non_reservable_asset")] -fn it_fills_order_fully_maker_base_asset(reservable_maker_asset: bool) { +#[test] +fn it_fills_order_fully_maker_base_asset() { ExtBuilder::default().build().execute_with(|| { let market_id = 0u128; - let mut market = market_mock::(); - let taker_amount = 10 * BASE; - let maker_amount = 50 * BASE; - - if !reservable_maker_asset { - market.base_asset = BaseAsset::CampaignAsset(0); - assert_ok!(AssetRouter::create(market.base_asset.into(), BOB, true, 1)); - assert_ok!(AssetManager::deposit(market.base_asset.into(), &BOB, maker_amount)); - } - + let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 1); + let taker_amount = 10 * BASE; + let maker_amount = 50 * BASE; + assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(BOB), market_id, @@ -670,14 +621,8 @@ fn it_fills_order_fully_maker_base_asset(reservable_maker_asset: bool) { taker_amount, )); - let reserved_funds = if reservable_maker_asset { - AssetManager::reserved_balance(market.base_asset.into(), &BOB) - } else { - let order_account = Orderbook::order_account(0); - assert_eq!(AssetManager::free_balance(market.base_asset.into(), &BOB), 0); - AssetManager::free_balance(market.base_asset.into(), &order_account) - }; - assert_eq!(reserved_funds, maker_amount); + let reserved_bob = AssetManager::reserved_balance(maker_asset, &BOB); + assert_eq!(reserved_bob, maker_amount); let order_id = 0u128; assert_ok!(AssetManager::deposit(taker_asset, &ALICE, taker_amount)); @@ -707,48 +652,31 @@ fn it_fills_order_fully_maker_base_asset(reservable_maker_asset: bool) { let alice_taker_asset_free = AssetManager::free_balance(taker_asset, &ALICE); let maker_fees = calculate_fee::(maker_amount); let maker_amount_minus_fees = maker_amount - maker_fees; - - if reservable_maker_asset { - assert_eq!(alice_maker_asset_free, INITIAL_BALANCE + maker_amount_minus_fees); - } else { - assert_eq!(alice_maker_asset_free, maker_amount_minus_fees); - } - + assert_eq!(alice_maker_asset_free, INITIAL_BALANCE + maker_amount_minus_fees); assert_eq!(alice_taker_asset_free, 0); let bob_bal = AssetManager::free_balance(maker_asset, &BOB); let bob_shares = AssetManager::free_balance(taker_asset, &BOB); - - if reservable_maker_asset { - assert_eq!(bob_bal, INITIAL_BALANCE - maker_amount); - } else { - assert_eq!(bob_bal, 0); - } - + assert_eq!(bob_bal, INITIAL_BALANCE - maker_amount); assert_eq!(bob_shares, taker_amount); }); } -#[test_case(true; "with_reservable_asset")] -#[test_case(false; "with_non_reservable_asset")] -fn it_fills_order_partially_maker_base_asset(reservable_maker_asset: bool) { +#[test] +fn it_fills_order_partially_maker_base_asset() { ExtBuilder::default().build().execute_with(|| { let market_id = 0u128; - let mut market = market_mock::(); - let maker_amount = 500 * BASE; - let taker_amount = 100 * BASE; - - if !reservable_maker_asset { - market.base_asset = BaseAsset::CampaignAsset(0); - assert_ok!(AssetRouter::create(market.base_asset.into(), BOB, true, 1)); - } - + let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 1); + let maker_amount = 500 * BASE; + let taker_amount = 100 * BASE; + assert_ok!(AssetManager::deposit(maker_asset, &BOB, maker_amount)); + assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(BOB), market_id, @@ -758,14 +686,8 @@ fn it_fills_order_partially_maker_base_asset(reservable_maker_asset: bool) { taker_amount, )); - let reserved_funds = if reservable_maker_asset { - AssetManager::reserved_balance(market.base_asset.into(), &BOB) - } else { - let order_account = Orderbook::order_account(0); - assert_eq!(AssetManager::free_balance(market.base_asset.into(), &BOB), 0); - AssetManager::free_balance(market.base_asset.into(), &order_account) - }; - assert_eq!(reserved_funds, maker_amount); + let reserved_bob = AssetManager::reserved_balance(maker_asset, &BOB); + assert_eq!(reserved_bob, maker_amount); let order_id = 0u128; assert_ok!(AssetManager::deposit(taker_asset, &ALICE, taker_amount)); @@ -825,34 +747,16 @@ fn it_fills_order_partially_maker_base_asset(reservable_maker_asset: bool) { Perquintill::from_rational(alice_portion, taker_amount).mul_floor(maker_amount); let filled_maker_amount_minus_fees = filled_maker_amount - calculate_fee::(filled_maker_amount); - - if reservable_maker_asset { - assert_eq!(alice_maker_asset_free, INITIAL_BALANCE + filled_maker_amount_minus_fees); - } else { - assert_eq!(alice_maker_asset_free, filled_maker_amount_minus_fees); - } - + assert_eq!(alice_maker_asset_free, INITIAL_BALANCE + filled_maker_amount_minus_fees); assert_eq!(alice_taker_asset_free, alice_taker_asset_free_left); let bob_maker_asset_free = AssetManager::free_balance(maker_asset, &BOB); let bob_taker_asset_free = AssetManager::free_balance(taker_asset, &BOB); - - if reservable_maker_asset { - assert_eq!(bob_maker_asset_free, INITIAL_BALANCE); - } else { - assert_eq!(bob_maker_asset_free, 0); - } - + assert_eq!(bob_maker_asset_free, INITIAL_BALANCE); assert_eq!(bob_taker_asset_free, alice_portion); - if reservable_maker_asset { - let reserved_bob = AssetManager::reserved_balance(maker_asset, &BOB); - assert_eq!(reserved_bob, unfilled_maker_amount); - } else { - let order_account = Orderbook::order_account(0); - let remaining = AssetManager::free_balance(maker_asset, &order_account); - assert_eq!(remaining, unfilled_maker_amount); - } + let reserved_bob = AssetManager::reserved_balance(maker_asset, &BOB); + assert_eq!(reserved_bob, unfilled_maker_amount); }); } @@ -864,7 +768,7 @@ fn it_fills_order_partially_maker_outcome_asset() { Markets::::insert(market_id, market.clone()); let maker_asset = Asset::CategoricalOutcome(0, 1); - let taker_asset = market.base_asset.into(); + let taker_asset = market.base_asset; let maker_amount = 100 * BASE; let taker_amount = 500 * BASE; @@ -886,7 +790,7 @@ fn it_fills_order_partially_maker_outcome_asset() { let order_id = 0u128; let market_creator_free_balance_before = - AssetManager::free_balance(market.base_asset.into(), &MARKET_CREATOR); + AssetManager::free_balance(market.base_asset, &MARKET_CREATOR); // instead of buying 500 of the base asset, Alice buys 70 shares let alice_portion = 70 * BASE; @@ -894,7 +798,7 @@ fn it_fills_order_partially_maker_outcome_asset() { assert_ok!(Orderbook::fill_order(RuntimeOrigin::signed(ALICE), order_id, portion,)); let market_creator_free_balance_after = - AssetManager::free_balance(market.base_asset.into(), &MARKET_CREATOR); + AssetManager::free_balance(market.base_asset, &MARKET_CREATOR); let external_fee_amount = calculate_fee::(70 * BASE); assert_eq!( market_creator_free_balance_after - market_creator_free_balance_before, @@ -956,25 +860,19 @@ fn it_fills_order_partially_maker_outcome_asset() { }); } -#[test_case(true; "with_reservable_asset")] -#[test_case(false; "with_non_reservable_asset")] -fn it_removes_order(reservable_maker_asset: bool) { +#[test] +fn it_removes_order() { ExtBuilder::default().build().execute_with(|| { let market_id = 0u128; - let mut market = market_mock::(); - let taker_amount = 25 * BASE; - let maker_amount = 10 * BASE; - - if !reservable_maker_asset { - market.base_asset = BaseAsset::CampaignAsset(0); - assert_ok!(AssetRouter::create(market.base_asset.into(), ALICE, true, 1)); - assert_ok!(AssetManager::deposit(market.base_asset.into(), &ALICE, maker_amount)); - } - + let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); + let taker_amount = 25 * BASE; + let maker_amount = 10 * BASE; + assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(ALICE), market_id, @@ -984,13 +882,7 @@ fn it_removes_order(reservable_maker_asset: bool) { taker_amount, )); - let reserved_funds = if reservable_maker_asset { - AssetManager::reserved_balance(market.base_asset.into(), &ALICE) - } else { - let order_account = Orderbook::order_account(0); - assert_eq!(AssetManager::free_balance(market.base_asset.into(), &BOB), 0); - AssetManager::free_balance(market.base_asset.into(), &order_account) - }; + let reserved_funds = AssetManager::reserved_balance(market.base_asset, &ALICE); assert_eq!(reserved_funds, maker_amount); let order_id = 0u128; @@ -1000,16 +892,12 @@ fn it_removes_order(reservable_maker_asset: bool) { Order { market_id, maker: ALICE, maker_asset, maker_amount, taker_asset, taker_amount } ); + let reserved_funds = AssetManager::reserved_balance(market.base_asset, &ALICE); + assert_eq!(reserved_funds, maker_amount); + assert_ok!(Orderbook::remove_order(RuntimeOrigin::signed(ALICE), order_id)); - let reserved_funds = if reservable_maker_asset { - AssetManager::reserved_balance(market.base_asset.into(), &ALICE) - } else { - let order_account = Orderbook::order_account(0); - let alice_balance = AssetManager::free_balance(market.base_asset.into(), &ALICE); - assert_eq!(alice_balance, maker_amount); - AssetManager::free_balance(market.base_asset.into(), &order_account) - }; + let reserved_funds = AssetManager::reserved_balance(market.base_asset, &ALICE); assert_eq!(reserved_funds, 0); assert!(Orders::::get(order_id).is_none()); @@ -1023,7 +911,7 @@ fn remove_order_emits_event() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let taker_amount = 25 * BASE; @@ -1053,7 +941,7 @@ fn remove_order_fails_if_not_order_creator() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let taker_amount = 25 * BASE; @@ -1077,39 +965,6 @@ fn remove_order_fails_if_not_order_creator() { }); } -#[test] -fn remove_order_does_work_with_reserves_after_funding_order_account() { - ExtBuilder::default().build().execute_with(|| { - let market_id = 0u128; - let mut market = market_mock::(); - market.base_asset = BaseAsset::Ztg; - Markets::::insert(market_id, market.clone()); - - let maker_asset = market.base_asset.into(); - let taker_asset = Asset::CategoricalOutcome(0, 2); - let taker_amount = 10 * BASE; - let maker_amount = 250 * BASE; - - assert_ok!(AssetManager::deposit(maker_asset, &ALICE, maker_amount)); - assert_ok!(AssetManager::deposit(taker_asset, &BOB, taker_amount)); - assert_ok!(Orderbook::place_order( - RuntimeOrigin::signed(ALICE), - market_id, - maker_asset, - maker_amount, - taker_asset, - taker_amount, - )); - - let mut reserved_funds = AssetManager::reserved_balance(maker_asset, &ALICE); - assert_eq!(reserved_funds, maker_amount); - assert_ok!(AssetManager::deposit(maker_asset, &Orderbook::order_account(0), BASE)); - assert_ok!(Orderbook::remove_order(RuntimeOrigin::signed(ALICE), 0)); - reserved_funds = AssetManager::reserved_balance(maker_asset, &ALICE); - assert_eq!(reserved_funds, 0); - }); -} - #[test] fn place_order_emits_event() { ExtBuilder::default().build().execute_with(|| { @@ -1117,7 +972,7 @@ fn place_order_emits_event() { let market = market_mock::(); Markets::::insert(market_id, market.clone()); - let maker_asset = market.base_asset.into(); + let maker_asset = market.base_asset; let taker_asset = Asset::CategoricalOutcome(0, 2); let taker_amount = 25 * BASE; diff --git a/zrml/orderbook/src/utils.rs b/zrml/orderbook/src/utils.rs index 6504fa01f..0e83c12a1 100644 --- a/zrml/orderbook/src/utils.rs +++ b/zrml/orderbook/src/utils.rs @@ -20,18 +20,15 @@ use crate::*; use sp_runtime::traits::AccountIdConversion; use zeitgeist_primitives::types::{ - BaseAsset, Deadlines, Market, MarketCreation, MarketDisputeMechanism, MarketPeriod, - MarketStatus, MarketType, ScoringRule, + Asset, Deadlines, Market, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, + MarketType, ScoringRule, }; -type MomentOf = <::MarketCommons as MarketCommonsPalletApi>::Moment; - type MarketOf = Market< ::AccountId, BalanceOf, ::BlockNumber, MomentOf, - BaseAsset, MarketIdOf, >; @@ -41,7 +38,7 @@ where { Market { market_id: Default::default(), - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: T::PalletId::get().into_account_truncating(), diff --git a/zrml/orderbook/src/weights.rs b/zrml/orderbook/src/weights.rs index be82826e6..420e8ea95 100644 --- a/zrml/orderbook/src/weights.rs +++ b/zrml/orderbook/src/weights.rs @@ -73,9 +73,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: Orderbook Orders (r:1 w:1) /// Proof: Orderbook Orders (max_values: None, max_size: Some(142), added: 2617, mode: MaxEncodedLen) /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:1 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Balances Reserves (r:1 w:1) /// Proof: Balances Reserves (max_values: None, max_size: Some(1249), added: 3724, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) @@ -92,9 +89,6 @@ impl WeightInfoZeitgeist for WeightInfo { .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:1 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Orderbook NextOrderId (r:1 w:1) /// Proof: Orderbook NextOrderId (max_values: Some(1), max_size: Some(16), added: 511, mode: MaxEncodedLen) /// Storage: Balances Reserves (r:1 w:1) diff --git a/zrml/parimutuel/Cargo.toml b/zrml/parimutuel/Cargo.toml index 6c0721295..4db93d8f4 100644 --- a/zrml/parimutuel/Cargo.toml +++ b/zrml/parimutuel/Cargo.toml @@ -3,11 +3,9 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } orml-traits = { workspace = true } -pallet-assets = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } sp-runtime = { workspace = true } -zeitgeist-macros = { workspace = true } zeitgeist-primitives = { workspace = true } zrml-market-commons = { workspace = true } @@ -19,7 +17,6 @@ pallet-balances = { workspace = true, features = ["default"] } pallet-timestamp = { workspace = true, features = ["default"] } sp-io = { workspace = true, features = ["default"] } zeitgeist-primitives = { workspace = true, features = ["mock", "default"] } -zrml-asset-router = { workspace = true, features = ["default"] } test-case = { workspace = true } @@ -29,14 +26,12 @@ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", ] std = [ "frame-benchmarking?/std", "frame-support/std", "frame-system/std", "orml-traits/std", - "pallet-assets/std", "parity-scale-codec/std", "sp-runtime/std", "zeitgeist-primitives/std", diff --git a/zrml/parimutuel/src/benchmarking.rs b/zrml/parimutuel/src/benchmarking.rs index b45816e8c..bf70b76f3 100644 --- a/zrml/parimutuel/src/benchmarking.rs +++ b/zrml/parimutuel/src/benchmarking.rs @@ -23,17 +23,11 @@ use crate::{utils::*, Pallet as Parimutuel, *}; use frame_benchmarking::v2::*; -use frame_support::{ - assert_ok, - traits::{fungibles::Inspect, Get}, -}; +use frame_support::traits::Get; use frame_system::RawOrigin; use orml_traits::MultiCurrency; use sp_runtime::{SaturatedConversion, Saturating}; -use zeitgeist_primitives::{ - traits::MarketTransitionApi, - types::{MarketStatus, MarketType, OutcomeReport}, -}; +use zeitgeist_primitives::types::{Asset, MarketStatus, MarketType, OutcomeReport}; use zrml_market_commons::MarketCommonsPalletApi; fn setup_market(market_type: MarketType) -> MarketIdOf { @@ -48,12 +42,12 @@ fn setup_market(market_type: MarketType) -> MarketIdOf { fn buy_asset( market_id: MarketIdOf, - asset: ParimutuelShareOf, + asset: AssetOf, buyer: &T::AccountId, amount: BalanceOf, ) { let market = T::MarketCommons::market(&market_id).unwrap(); - T::AssetManager::deposit(market.base_asset.into(), buyer, amount).unwrap(); + T::AssetManager::deposit(market.base_asset, buyer, amount).unwrap(); Parimutuel::::buy(RawOrigin::Signed(buyer.clone()).into(), asset, amount).unwrap(); } @@ -68,10 +62,10 @@ mod benchmarks { let market_id = setup_market::(MarketType::Categorical(64u16)); let amount = T::MinBetSize::get().saturating_mul(10u128.saturated_into::>()); - let asset = ParimutuelShareOf::::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let market = T::MarketCommons::market(&market_id).unwrap(); - T::AssetManager::deposit(market.base_asset.into(), &buyer, amount).unwrap(); + T::AssetManager::deposit(market.base_asset, &buyer, amount).unwrap(); #[extrinsic_call] buy(RawOrigin::Signed(buyer), asset, amount); @@ -81,16 +75,15 @@ mod benchmarks { fn claim_rewards() { // max category index is worst case let market_id = setup_market::(MarketType::Categorical(64u16)); - assert_ok!(Parimutuel::::on_activation(&market_id).result); let winner = whitelisted_caller(); - let winner_asset = ParimutuelShareOf::::Share(market_id, 0u16); + let winner_asset = Asset::ParimutuelShare(market_id, 0u16); let winner_amount = T::MinBetSize::get().saturating_mul(20u128.saturated_into::>()); buy_asset::(market_id, winner_asset, &winner, winner_amount); let loser = whitelisted_caller(); - let loser_asset = ParimutuelShareOf::::Share(market_id, 1u16); + let loser_asset = Asset::ParimutuelShare(market_id, 1u16); let loser_amount = T::MinBetSize::get().saturating_mul(10u128.saturated_into::>()); buy_asset::(market_id, loser_asset, &loser, loser_amount); @@ -109,18 +102,17 @@ mod benchmarks { fn claim_refunds() { // max category index is worst case let market_id = setup_market::(MarketType::Categorical(64u16)); - assert_ok!(Parimutuel::::on_activation(&market_id).result); let loser_0 = whitelisted_caller(); let loser_0_index = 0u16; - let loser_0_asset = ParimutuelShareOf::::Share(market_id, loser_0_index); + let loser_0_asset = Asset::ParimutuelShare(market_id, loser_0_index); let loser_0_amount = T::MinBetSize::get().saturating_mul(20u128.saturated_into::>()); buy_asset::(market_id, loser_0_asset, &loser_0, loser_0_amount); let loser_1 = whitelisted_caller(); let loser_1_index = 1u16; - let loser_1_asset = ParimutuelShareOf::::Share(market_id, loser_1_index); + let loser_1_asset = Asset::ParimutuelShare(market_id, loser_1_index); let loser_1_amount = T::MinBetSize::get().saturating_mul(10u128.saturated_into::>()); buy_asset::(market_id, loser_1_asset, &loser_1, loser_1_amount); @@ -131,8 +123,8 @@ mod benchmarks { let resolved_outcome = OutcomeReport::Categorical(resolved_index); assert_ne!(resolved_index, loser_0_index); assert_ne!(resolved_index, loser_1_index); - let resolved_asset = ParimutuelShareOf::::Share(market_id, resolved_index); - let resolved_issuance_asset = T::AssetManager::total_issuance(resolved_asset.into()); + let resolved_asset = Asset::ParimutuelShare(market_id, resolved_index); + let resolved_issuance_asset = T::AssetManager::total_issuance(resolved_asset); assert!(resolved_issuance_asset.is_zero()); market.resolved_outcome = Some(resolved_outcome); Ok(()) @@ -142,55 +134,6 @@ mod benchmarks { claim_refunds(RawOrigin::Signed(loser_0), loser_0_asset); } - #[benchmark] - fn on_activation() { - let market_id = setup_market::(MarketType::Categorical(64u16)); - - #[block] - { - Parimutuel::::on_activation(&market_id); - } - - for asset_idx in 0..64 { - let asset = ParimutuelShareOf::::Share(Zero::zero(), asset_idx).into(); - assert!(T::AssetCreator::asset_exists(asset)); - } - } - - #[benchmark] - fn on_resolution() { - let market_id = setup_market::(MarketType::Categorical(64u16)); - assert_ok!(Parimutuel::::on_activation(&market_id).result); - - for asset_idx in 0..64 { - let asset = ParimutuelShareOf::::Share(Zero::zero(), asset_idx).into(); - assert!(T::AssetCreator::asset_exists(asset)); - } - - T::MarketCommons::mutate_market(&market_id, |market| { - market.status = MarketStatus::Resolved; - let resolved_outcome = OutcomeReport::Categorical(0u16); - market.resolved_outcome = Some(resolved_outcome); - Ok(()) - })?; - - #[block] - { - Parimutuel::::on_resolution(&market_id); - } - - #[cfg(test)] - { - use frame_support::{pallet_prelude::Weight, traits::OnIdle}; - - crate::mock::AssetRouter::on_idle(Zero::zero(), Weight::MAX); - for asset_idx in 0..64 { - let asset = ParimutuelShareOf::::Share(Zero::zero(), asset_idx).into(); - assert!(!T::AssetCreator::asset_exists(asset)); - } - } - } - impl_benchmark_test_suite!( Parimutuel, crate::mock::ExtBuilder::default().build(), diff --git a/zrml/parimutuel/src/lib.rs b/zrml/parimutuel/src/lib.rs index c04b70900..81953d92c 100644 --- a/zrml/parimutuel/src/lib.rs +++ b/zrml/parimutuel/src/lib.rs @@ -18,8 +18,6 @@ #![doc = include_str!("../README.md")] #![cfg_attr(not(feature = "std"), no_std)] -extern crate alloc; - mod benchmarking; mod mock; mod tests; @@ -31,16 +29,12 @@ pub use pallet::*; #[frame_support::pallet] mod pallet { use crate::weights::WeightInfoZeitgeist; - use alloc::collections::BTreeMap; use core::marker::PhantomData; use frame_support::{ ensure, log, pallet_prelude::{Decode, DispatchError, Encode, TypeInfo}, require_transactional, - traits::{ - fungibles::{Create, Inspect}, - Get, IsType, StorageVersion, - }, + traits::{Get, IsType, StorageVersion}, PalletId, RuntimeDebug, }; use frame_system::{ @@ -48,36 +42,25 @@ mod pallet { pallet_prelude::{BlockNumberFor, OriginFor}, }; use orml_traits::MultiCurrency; - use pallet_assets::ManagedDestroy; use sp_runtime::{ traits::{AccountIdConversion, CheckedSub, Zero}, DispatchResult, }; - use zeitgeist_macros::unreachable_non_terminating; use zeitgeist_primitives::{ math::fixed::FixedMulDiv, - traits::{DistributeFees, MarketTransitionApi}, - types::{ - Asset, BaseAsset, Market, MarketAssetClass, MarketStatus, MarketType, OutcomeReport, - ParimutuelAssetClass, ResultWithWeightInfo, ScoringRule, - }, + traits::DistributeFees, + types::{Asset, Market, MarketStatus, MarketType, OutcomeReport, ScoringRule}, }; use zrml_market_commons::MarketCommonsPalletApi; #[pallet::config] pub trait Config: frame_system::Config { - /// The module handling the creation of market assets. - type AssetCreator: Create, Balance = BalanceOf>; - /// The api to handle different asset classes. type AssetManager: MultiCurrency>; - /// The module handling the destruction of market assets. - type AssetDestroyer: ManagedDestroy, Balance = BalanceOf>; - /// The way how fees are taken from the market base asset. type ExternalFees: DistributeFees< - Asset = AssetOf, + Asset = Asset>, AccountId = AccountIdOf, Balance = BalanceOf, MarketId = MarketIdOf, @@ -108,21 +91,14 @@ mod pallet { const LOG_TARGET: &str = "runtime::zrml-parimutuel"; pub(crate) type AssetOf = Asset>; - pub(crate) type ParimutuelShareOf = ParimutuelAssetClass>; pub(crate) type AccountIdOf = ::AccountId; pub(crate) type BalanceOf = <::AssetManager as MultiCurrency>>::Balance; pub(crate) type MarketIdOf = <::MarketCommons as MarketCommonsPalletApi>::MarketId; pub(crate) type MomentOf = <::MarketCommons as MarketCommonsPalletApi>::Moment; - pub(crate) type MarketOf = Market< - AccountIdOf, - BalanceOf, - BlockNumberFor, - MomentOf, - BaseAsset, - MarketIdOf, - >; + pub(crate) type MarketOf = + Market, BalanceOf, BlockNumberFor, MomentOf, MarketIdOf>; #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -164,51 +140,38 @@ mod pallet { /// There was no buyer for the winning outcome or all winners already claimed their rewards. /// Use the `refund` extrinsic to get the initial bet back, /// in case there was no buyer for the winning outcome. - #[codec(index = 0)] NoRewardShareOutstanding, /// The market is not active. - #[codec(index = 1)] MarketIsNotActive, /// The specified amount is below the minimum bet size. - #[codec(index = 2)] AmountBelowMinimumBetSize, + /// The specified asset is not a parimutuel share. + NotParimutuelOutcome, /// The specified asset was not found in the market assets. - #[codec(index = 4)] InvalidOutcomeAsset, /// The scoring rule is not parimutuel. - #[codec(index = 5)] InvalidScoringRule, /// The specified amount can not be transferred. - #[codec(index = 6)] InsufficientBalance, /// The market is not resolved yet. - #[codec(index = 7)] MarketIsNotResolvedYet, /// An unexpected error occured. This should never happen! /// There was an internal coding mistake. - #[codec(index = 8)] Unexpected, /// There is no resolved outcome present for the market. - #[codec(index = 9)] NoResolvedOutcome, /// The refund is not allowed. - #[codec(index = 10)] RefundNotAllowed, /// There is no balance to refund. - #[codec(index = 11)] RefundableBalanceIsZero, /// There is no reward, because there are no winning shares. - #[codec(index = 12)] NoWinningShares, /// Only categorical markets are allowed for parimutuels. - #[codec(index = 13)] NotCategorical, /// There is no reward to distribute. - #[codec(index = 14)] NoRewardToDistribute, /// Action cannot be completed because an unexpected error has occurred. This should be /// reported to protocol maintainers. - #[codec(index = 15)] InconsistentState(InconsistentStateError), } @@ -238,7 +201,7 @@ mod pallet { #[frame_support::transactional] pub fn buy( origin: OriginFor, - asset: ParimutuelShareOf, + asset: Asset>, #[pallet::compact] amount: BalanceOf, ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -273,10 +236,7 @@ mod pallet { #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::claim_refunds())] #[frame_support::transactional] - pub fn claim_refunds( - origin: OriginFor, - refund_asset: ParimutuelShareOf, - ) -> DispatchResult { + pub fn claim_refunds(origin: OriginFor, refund_asset: AssetOf) -> DispatchResult { let who = ensure_signed(origin)?; Self::do_claim_refunds(who, refund_asset)?; @@ -331,36 +291,29 @@ mod pallet { Ok(()) } - pub fn market_assets_contains( - market: &MarketOf, - asset: &ParimutuelShareOf, - ) -> DispatchResult { - let index = match asset { - ParimutuelShareOf::::Share(_, idx) => *idx, - }; - - match market.market_type { - MarketType::Categorical(categories) => { - ensure!(index < categories, Error::::InvalidOutcomeAsset); - Ok(()) + pub fn market_assets_contains(market: &MarketOf, asset: &AssetOf) -> DispatchResult { + if let Asset::ParimutuelShare(_, i) = asset { + match market.market_type { + MarketType::Categorical(categories) => { + ensure!(*i < categories, Error::::InvalidOutcomeAsset); + return Ok(()); + } + MarketType::Scalar(_) => return Err(Error::::NotCategorical.into()), } - MarketType::Scalar(_) => Err(Error::::NotCategorical.into()), } + Err(Error::::NotParimutuelOutcome.into()) } #[require_transactional] - fn do_buy( - who: T::AccountId, - asset: ParimutuelShareOf, - amount: BalanceOf, - ) -> DispatchResult { + fn do_buy(who: T::AccountId, asset: AssetOf, amount: BalanceOf) -> DispatchResult { let market_id = match asset { - ParimutuelShareOf::::Share(market_id, _) => market_id, + Asset::ParimutuelShare(market_id, _) => market_id, + _ => return Err(Error::::NotParimutuelOutcome.into()), }; let market = T::MarketCommons::market(&market_id)?; let base_asset = market.base_asset; ensure!( - T::AssetManager::ensure_can_withdraw(base_asset.into(), &who, amount).is_ok(), + T::AssetManager::ensure_can_withdraw(base_asset, &who, amount).is_ok(), Error::::InsufficientBalance ); ensure!(market.status == MarketStatus::Active, Error::::MarketIsNotActive); @@ -371,23 +324,23 @@ mod pallet { ); Self::market_assets_contains(&market, &asset)?; - let external_fees = - T::ExternalFees::distribute(market_id, base_asset.into(), &who, amount); + let external_fees = T::ExternalFees::distribute(market_id, base_asset, &who, amount); let amount_minus_fees = amount.checked_sub(&external_fees).ok_or(Error::::Unexpected)?; ensure!( amount_minus_fees >= T::MinBetSize::get(), Error::::AmountBelowMinimumBetSize ); + let pot_account = Self::pot_account(market_id); - T::AssetManager::transfer(base_asset.into(), &who, &pot_account, amount_minus_fees)?; - T::AssetManager::deposit(asset.into(), &who, amount_minus_fees)?; + T::AssetManager::transfer(market.base_asset, &who, &pot_account, amount_minus_fees)?; + T::AssetManager::deposit(asset, &who, amount_minus_fees)?; Self::deposit_event(Event::OutcomeBought { market_id, buyer: who, - asset: asset.into(), + asset, amount_minus_fees, fees: external_fees, }); @@ -443,7 +396,7 @@ mod pallet { } let pot_account = Self::pot_account(market_id); - let pot_total = T::AssetManager::free_balance(market.base_asset.into(), &pot_account); + let pot_total = T::AssetManager::free_balance(market.base_asset, &pot_account); let payoff = pot_total.bmul_bdiv(winning_balance, outcome_total)?; Self::check_values(winning_balance, pot_total, outcome_total, payoff)?; @@ -452,27 +405,10 @@ mod pallet { T::AssetManager::withdraw(winning_asset, &who, withdrawn_asset_balance)?; - let remaining_bal = - T::AssetManager::free_balance(market.base_asset.into(), &pot_account); + let remaining_bal = T::AssetManager::free_balance(market.base_asset, &pot_account); let base_asset_payoff = payoff.min(remaining_bal); - T::AssetManager::transfer( - market.base_asset.into(), - &pot_account, - &who, - base_asset_payoff, - )?; - - if outcome_total == winning_balance { - let destroy_result = T::AssetDestroyer::managed_destroy(winning_asset, None); - unreachable_non_terminating!( - destroy_result.is_ok(), - LOG_TARGET, - "Can't destroy winning outcome asset {:?}: {:?}", - winning_asset, - destroy_result.err() - ); - } + T::AssetManager::transfer(market.base_asset, &pot_account, &who, base_asset_payoff)?; Self::deposit_event(Event::RewardsClaimed { market_id, @@ -486,12 +422,10 @@ mod pallet { } #[require_transactional] - fn do_claim_refunds( - who: T::AccountId, - refund_asset: ParimutuelShareOf, - ) -> DispatchResult { + fn do_claim_refunds(who: T::AccountId, refund_asset: AssetOf) -> DispatchResult { let market_id = match refund_asset { - ParimutuelShareOf::::Share(market_id, _) => market_id, + Asset::ParimutuelShare(market_id, _) => market_id, + _ => return Err(Error::::NotParimutuelOutcome.into()), }; let market = T::MarketCommons::market(&market_id)?; Self::ensure_parimutuel_market_resolved(&market)?; @@ -500,10 +434,9 @@ mod pallet { let outcome_total = T::AssetManager::total_issuance(winning_asset); ensure!(outcome_total == >::zero(), Error::::RefundNotAllowed); - let refund_asset_general: AssetOf = refund_asset.into(); - let refund_balance = T::AssetManager::free_balance(refund_asset_general, &who); + let refund_balance = T::AssetManager::free_balance(refund_asset, &who); ensure!(!refund_balance.is_zero(), Error::::RefundableBalanceIsZero); - if refund_asset_general == winning_asset { + if refund_asset == winning_asset { log::debug!( target: LOG_TARGET, "Since we were checking the total issuance of the winning asset to be zero, if \ @@ -513,10 +446,10 @@ mod pallet { debug_assert!(false); } - T::AssetManager::withdraw(refund_asset_general, &who, refund_balance)?; + T::AssetManager::withdraw(refund_asset, &who, refund_balance)?; let pot_account = Self::pot_account(market_id); - let pot_total = T::AssetManager::free_balance(market.base_asset.into(), &pot_account); + let pot_total = T::AssetManager::free_balance(market.base_asset, &pot_account); if pot_total < refund_balance { log::debug!( target: LOG_TARGET, @@ -526,128 +459,16 @@ mod pallet { } let refund_balance = refund_balance.min(pot_total); - T::AssetManager::transfer( - market.base_asset.into(), - &pot_account, - &who, - refund_balance, - )?; - - if T::AssetCreator::total_issuance(refund_asset_general).is_zero() { - let destroy_result = T::AssetDestroyer::managed_destroy(refund_asset_general, None); - unreachable_non_terminating!( - destroy_result.is_ok(), - LOG_TARGET, - "Can't destroy losing outcome asset {:?}: {:?}", - refund_asset_general, - destroy_result - ); - } + T::AssetManager::transfer(market.base_asset, &pot_account, &who, refund_balance)?; Self::deposit_event(Event::BalanceRefunded { market_id, - asset: refund_asset_general, + asset: refund_asset, refunded_balance: refund_balance, sender: who.clone(), }); Ok(()) } - - fn get_assets_to_destroy( - market: &MarketOf, - filter: F, - ) -> BTreeMap, Option> - where - F: Copy + FnOnce(MarketAssetClass>) -> bool, - { - BTreeMap::, Option>::from_iter( - market - .outcome_assets() - .into_iter() - .filter(|asset| filter(*asset)) - .map(|asset| (AssetOf::::from(asset), None)), - ) - } - } - - impl MarketTransitionApi> for Pallet { - fn on_activation(market_id: &MarketIdOf) -> ResultWithWeightInfo { - let market_result = T::MarketCommons::market(market_id); - - let market = match market_result { - Ok(market) if market.scoring_rule == ScoringRule::Parimutuel => market, - Err(e) => { - return ResultWithWeightInfo::new(Err(e), T::DbWeight::get().reads(1)); - } - _ => { - return ResultWithWeightInfo::new(Ok(()), T::DbWeight::get().reads(1)); - } - }; - - for outcome in market.outcome_assets() { - let admin = Self::pot_account(*market_id); - let is_sufficient = true; - let min_balance = 1u8; - if let Err(e) = T::AssetCreator::create( - outcome.into(), - admin, - is_sufficient, - min_balance.into(), - ) { - return ResultWithWeightInfo::new(Err(e), T::WeightInfo::on_activation()); - } - } - - ResultWithWeightInfo::new(Ok(()), T::WeightInfo::on_activation()) - } - - fn on_resolution(market_id: &MarketIdOf) -> ResultWithWeightInfo { - let market_result = T::MarketCommons::market(market_id); - - let market = match market_result { - Ok(market) if market.scoring_rule == ScoringRule::Parimutuel => market, - Err(e) => { - return ResultWithWeightInfo::new(Err(e), T::DbWeight::get().reads(1)); - } - _ => { - return ResultWithWeightInfo::new(Ok(()), T::DbWeight::get().reads(1)); - } - }; - - let winning_asset_option = market.resolved_outcome_into_asset(); - let winning_asset = if let Some(winning_asset) = winning_asset_option { - winning_asset - } else { - unreachable_non_terminating!( - winning_asset_option.is_some(), - LOG_TARGET, - "Resolved market with id {:?} does not have a resolved outcome", - market_id, - ); - return ResultWithWeightInfo::new(Ok(()), T::DbWeight::get().reads(1)); - }; - - let outcome_total = T::AssetManager::total_issuance(winning_asset.into()); - let assets_to_destroy = if outcome_total.is_zero() { - Self::get_assets_to_destroy(&market, |asset| { - T::AssetCreator::total_issuance(asset.into()).is_zero() - }) - } else { - Self::get_assets_to_destroy(&market, |asset| asset != winning_asset) - }; - - let destroy_result = - T::AssetDestroyer::managed_destroy_multi(assets_to_destroy.clone()); - unreachable_non_terminating!( - destroy_result.is_ok(), - LOG_TARGET, - "Can't destroy losing outcome assets {:?}: {:?}", - assets_to_destroy, - destroy_result - ); - - ResultWithWeightInfo::new(Ok(()), T::WeightInfo::on_resolution()) - } } } diff --git a/zrml/parimutuel/src/mock.rs b/zrml/parimutuel/src/mock.rs index 0d8fab509..fa78bc29c 100644 --- a/zrml/parimutuel/src/mock.rs +++ b/zrml/parimutuel/src/mock.rs @@ -23,15 +23,8 @@ use crate as zrml_parimutuel; use crate::{AssetOf, BalanceOf, MarketIdOf}; use alloc::{vec, vec::Vec}; use core::marker::PhantomData; -use frame_support::{ - construct_runtime, - pallet_prelude::{ConstU32, Get}, - parameter_types, - traits::{AsEnsureOriginWithArg, Everything}, -}; -use frame_system::{EnsureRoot, EnsureSigned}; +use frame_support::{construct_runtime, pallet_prelude::Get, parameter_types, traits::Everything}; use orml_traits::MultiCurrency; -use parity_scale_codec::Compact; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, @@ -39,16 +32,13 @@ use sp_runtime::{ }; use zeitgeist_primitives::{ constants::mock::{ - AssetsAccountDeposit, AssetsApprovalDeposit, AssetsDeposit, AssetsMetadataDepositBase, - AssetsMetadataDepositPerByte, AssetsStringLimit, BlockHashCount, DestroyAccountWeight, - DestroyApprovalWeight, DestroyFinishWeight, ExistentialDeposits, GetNativeCurrencyId, - MaxReserves, MinBetSize, MinimumPeriod, ParimutuelPalletId, BASE, CENT, + BlockHashCount, ExistentialDeposits, GetNativeCurrencyId, MaxReserves, MinBetSize, + MinimumPeriod, ParimutuelPalletId, BASE, CENT, }, traits::DistributeFees, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, CurrencyId, + Hash, Index, MarketId, Moment, UncheckedExtrinsicTest, }, }; @@ -101,10 +91,6 @@ where } } -type CustomAssetsInstance = pallet_assets::Instance1; -type CampaignAssetsInstance = pallet_assets::Instance2; -type MarketAssetsInstance = pallet_assets::Instance3; - construct_runtime!( pub enum Runtime where @@ -112,27 +98,21 @@ construct_runtime!( NodeBlock = BlockTest, UncheckedExtrinsic = UncheckedExtrinsicTest, { - AssetManager: orml_currencies::{Call, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, + Parimutuel: zrml_parimutuel::{Event, Pallet, Storage}, Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, + AssetManager: orml_currencies::{Call, Pallet, Storage}, + Tokens: orml_tokens::{Config, Event, Pallet, Storage}, MarketCommons: zrml_market_commons::{Pallet, Storage}, - Parimutuel: zrml_parimutuel::{Event, Pallet, Storage}, System: frame_system::{Call, Config, Event, Pallet, Storage}, Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, } ); impl crate::Config for Runtime { - type AssetCreator = AssetRouter; - type AssetDestroyer = AssetRouter; - type AssetManager = AssetManager; type ExternalFees = ExternalFees; type RuntimeEvent = RuntimeEvent; type MarketCommons = MarketCommons; + type AssetManager = AssetManager; type MinBetSize = MinBetSize; type PalletId = ParimutuelPalletId; type WeightInfo = crate::weights::WeightInfo; @@ -165,106 +145,6 @@ impl frame_system::Config for Runtime { type OnSetCode = (); } -pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } -} - -pallet_assets::runtime_benchmarks_enabled! { - use zeitgeist_primitives::types::CategoryIndex; - - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; @@ -277,9 +157,22 @@ impl pallet_balances::Config for Runtime { type WeightInfo = (); } +impl zrml_market_commons::Config for Runtime { + type Balance = Balance; + type MarketId = MarketId; + type Timestamp = Timestamp; +} + +impl pallet_timestamp::Config for Runtime { + type MinimumPeriod = MinimumPeriod; + type Moment = Moment; + type OnTimestampSet = (); + type WeightInfo = (); +} + impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = AssetRouter; + type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type WeightInfo = (); } @@ -287,7 +180,7 @@ impl orml_currencies::Config for Runtime { impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Currencies; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = Everything; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -298,35 +191,6 @@ impl orml_tokens::Config for Runtime { type WeightInfo = (); } -impl zrml_asset_router::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyAccountWeight; - type DestroyApprovalWeight = DestroyApprovalWeight; - type DestroyFinishWeight = DestroyFinishWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; -} - -impl zrml_market_commons::Config for Runtime { - type Balance = Balance; - type MarketId = MarketId; - type Timestamp = Timestamp; -} - -impl pallet_timestamp::Config for Runtime { - type MinimumPeriod = MinimumPeriod; - type Moment = Moment; - type OnTimestampSet = (); - type WeightInfo = (); -} - pub struct ExtBuilder { balances: Vec<(AccountIdTest, Balance)>, } diff --git a/zrml/parimutuel/src/tests/buy.rs b/zrml/parimutuel/src/tests/buy.rs index 782767b8c..fcee01f23 100644 --- a/zrml/parimutuel/src/tests/buy.rs +++ b/zrml/parimutuel/src/tests/buy.rs @@ -15,12 +15,14 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . +#![cfg(test)] + use crate::{mock::*, utils::*, *}; use core::ops::RangeInclusive; use frame_support::{assert_noop, assert_ok}; use orml_traits::MultiCurrency; use test_case::test_case; -use zeitgeist_primitives::types::{MarketStatus, MarketType, ParimutuelAsset, ScoringRule}; +use zeitgeist_primitives::types::{Asset, MarketStatus, MarketType, ScoringRule}; use zrml_market_commons::{Error as MError, Markets}; #[test] @@ -31,7 +33,7 @@ fn buy_emits_event() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount)); @@ -40,14 +42,7 @@ fn buy_emits_event() { assert_eq!(amount, amount_minus_fees + fees); System::assert_last_event( - Event::OutcomeBought { - market_id, - buyer: ALICE, - asset: asset.into(), - amount_minus_fees, - fees, - } - .into(), + Event::OutcomeBought { market_id, buyer: ALICE, asset, amount_minus_fees, fees }.into(), ); }); } @@ -62,12 +57,12 @@ fn buy_balances_change_correctly() { let base_asset = market.base_asset; - let free_alice_before = AssetManager::free_balance(base_asset.into(), &ALICE); - let free_creator_before = AssetManager::free_balance(base_asset.into(), &market.creator); + let free_alice_before = AssetManager::free_balance(base_asset, &ALICE); + let free_creator_before = AssetManager::free_balance(base_asset, &market.creator); let free_pot_before = - AssetManager::free_balance(base_asset.into(), &Parimutuel::pot_account(market_id)); + AssetManager::free_balance(base_asset, &Parimutuel::pot_account(market_id)); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount)); @@ -75,23 +70,37 @@ fn buy_balances_change_correctly() { let fees = 1000000000; assert_eq!(amount, amount_minus_fees + fees); + assert_eq!(AssetManager::free_balance(base_asset, &ALICE), free_alice_before - amount); assert_eq!( - AssetManager::free_balance(base_asset.into(), &ALICE), - free_alice_before - amount - ); - assert_eq!( - AssetManager::free_balance(base_asset.into(), &Parimutuel::pot_account(market_id)) + AssetManager::free_balance(base_asset, &Parimutuel::pot_account(market_id)) - free_pot_before, amount_minus_fees ); - assert_eq!(AssetManager::free_balance(asset.into(), &ALICE), amount_minus_fees); + assert_eq!(AssetManager::free_balance(asset, &ALICE), amount_minus_fees); assert_eq!( - AssetManager::free_balance(base_asset.into(), &market.creator) - free_creator_before, + AssetManager::free_balance(base_asset, &market.creator) - free_creator_before, fees ); }); } +#[test] +fn buy_fails_if_asset_not_parimutuel_share() { + ExtBuilder::default().build().execute_with(|| { + let market_id = 0; + let mut market = market_mock::(MARKET_CREATOR); + market.status = MarketStatus::Active; + Markets::::insert(market_id, market.clone()); + + let asset = Asset::CategoricalOutcome(market_id, 0u16); + let amount = ::MinBetSize::get(); + assert_noop!( + Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount), + Error::::NotParimutuelOutcome + ); + }); +} + #[test_case(ScoringRule::AmmCdaHybrid; "amm_cda_hybrid")] fn buy_fails_if_invalid_scoring_rule(scoring_rule: ScoringRule) { ExtBuilder::default().build().execute_with(|| { @@ -102,7 +111,7 @@ fn buy_fails_if_invalid_scoring_rule(scoring_rule: ScoringRule) { Markets::::insert(market_id, market.clone()); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = ::MinBetSize::get(); assert_noop!( Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount), @@ -124,7 +133,7 @@ fn buy_fails_if_market_status_is_not_active(status: MarketStatus) { Markets::::insert(market_id, market.clone()); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = ::MinBetSize::get(); assert_noop!( Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount), @@ -143,7 +152,7 @@ fn buy_fails_if_market_type_is_scalar() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = ::MinBetSize::get() + ::MinBetSize::get(); assert_noop!( @@ -161,10 +170,10 @@ fn buy_fails_if_insufficient_balance() { market.status = MarketStatus::Active; Markets::::insert(market_id, market.clone()); - let free_alice = AssetManager::free_balance(market.base_asset.into(), &ALICE); - AssetManager::slash(market.base_asset.into(), &ALICE, free_alice); + let free_alice = AssetManager::free_balance(market.base_asset, &ALICE); + AssetManager::slash(market.base_asset, &ALICE, free_alice); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = ::MinBetSize::get(); assert_noop!( Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount), @@ -181,7 +190,7 @@ fn buy_fails_if_below_minimum_bet_size() { market.status = MarketStatus::Active; Markets::::insert(market_id, market.clone()); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = ::MinBetSize::get() - 1; assert_noop!( Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount), @@ -195,7 +204,7 @@ fn buy_fails_if_market_does_not_exist() { ExtBuilder::default().build().execute_with(|| { let market_id = 0; - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = ::MinBetSize::get(); assert_noop!( Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount), diff --git a/zrml/parimutuel/src/tests/claim.rs b/zrml/parimutuel/src/tests/claim.rs index 3ac7d390f..972473596 100644 --- a/zrml/parimutuel/src/tests/claim.rs +++ b/zrml/parimutuel/src/tests/claim.rs @@ -15,16 +15,15 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . +#![cfg(test)] + use crate::{mock::*, utils::*, *}; use core::ops::RangeInclusive; -use frame_support::{assert_noop, assert_ok, traits::fungibles::Create}; +use frame_support::{assert_noop, assert_ok}; use orml_traits::MultiCurrency; use sp_runtime::Percent; use test_case::test_case; -use zeitgeist_primitives::{ - traits::MarketTransitionApi, - types::{MarketStatus, MarketType, OutcomeReport, ParimutuelAsset, ScoringRule}, -}; +use zeitgeist_primitives::types::{Asset, MarketStatus, MarketType, OutcomeReport, ScoringRule}; use zrml_market_commons::{Error as MError, Markets}; #[test] @@ -35,12 +34,11 @@ fn claim_rewards_emits_event() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let winner_asset = ParimutuelAsset::Share(market_id, 0u16); - AssetRouter::create(winner_asset.into(), Default::default(), true, 1).unwrap(); + let winner_asset = Asset::ParimutuelShare(market_id, 0u16); let winner_amount = 20 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), winner_asset, winner_amount)); - let loser_asset = ParimutuelAsset::Share(market_id, 1u16); + let loser_asset = Asset::ParimutuelShare(market_id, 1u16); let loser_amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(BOB), loser_asset, loser_amount)); @@ -57,7 +55,7 @@ fn claim_rewards_emits_event() { System::assert_last_event( Event::RewardsClaimed { market_id, - asset: winner_asset.into(), + asset: winner_asset, withdrawn_asset_balance, base_asset_payoff: actual_payoff, sender: ALICE, @@ -75,15 +73,14 @@ fn claim_rewards_categorical_changes_balances_correctly() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let winner_asset = ParimutuelAsset::Share(market_id, 0u16); - AssetRouter::create(winner_asset.into(), Default::default(), true, 1).unwrap(); + let winner_asset = Asset::ParimutuelShare(market_id, 0u16); let winner_amount_0 = 20 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), winner_asset, winner_amount_0)); let winner_amount_1 = 30 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(CHARLIE), winner_asset, winner_amount_1)); - let loser_asset = ParimutuelAsset::Share(market_id, 1u16); + let loser_asset = Asset::ParimutuelShare(market_id, 1u16); let loser_amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(BOB), loser_asset, loser_amount)); @@ -106,66 +103,52 @@ fn claim_rewards_categorical_changes_balances_correctly() { assert_eq!(Percent::from_percent(60) * actual_payoff, actual_payoff_charlie); assert_eq!(actual_payoff_alice + actual_payoff_charlie, actual_payoff); - let free_winner_asset_alice_before = - AssetManager::free_balance(winner_asset.into(), &ALICE); + let free_winner_asset_alice_before = AssetManager::free_balance(winner_asset, &ALICE); let winner_amount_0_minus_fees = winner_amount_0 - Percent::from_percent(1) * winner_amount_0; assert_eq!(free_winner_asset_alice_before, winner_amount_0_minus_fees); - let free_base_asset_alice_before = - AssetManager::free_balance(market.base_asset.into(), &ALICE); - let free_base_asset_pot_before = AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id), - ); + let free_base_asset_alice_before = AssetManager::free_balance(market.base_asset, &ALICE); + let free_base_asset_pot_before = + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)); assert_eq!(free_base_asset_pot_before, total_pot_amount - total_fees); assert_ok!(Parimutuel::claim_rewards(RuntimeOrigin::signed(ALICE), market_id)); assert_eq!( - free_winner_asset_alice_before - - AssetManager::free_balance(winner_asset.into(), &ALICE), + free_winner_asset_alice_before - AssetManager::free_balance(winner_asset, &ALICE), winner_amount_0_minus_fees ); assert_eq!( - AssetManager::free_balance(market.base_asset.into(), &ALICE) - - free_base_asset_alice_before, + AssetManager::free_balance(market.base_asset, &ALICE) - free_base_asset_alice_before, actual_payoff_alice ); assert_eq!( - AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id) - ), + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)), actual_payoff_charlie ); - let free_winner_asset_charlie_before = - AssetManager::free_balance(winner_asset.into(), &CHARLIE); + let free_winner_asset_charlie_before = AssetManager::free_balance(winner_asset, &CHARLIE); let winner_amount_1_minus_fees = winner_amount_1 - Percent::from_percent(1) * winner_amount_1; assert_eq!(free_winner_asset_charlie_before, winner_amount_1_minus_fees); let free_base_asset_charlie_before = - AssetManager::free_balance(market.base_asset.into(), &CHARLIE); + AssetManager::free_balance(market.base_asset, &CHARLIE); assert_ok!(Parimutuel::claim_rewards(RuntimeOrigin::signed(CHARLIE), market_id)); assert_eq!( - free_winner_asset_charlie_before - - AssetManager::free_balance(winner_asset.into(), &CHARLIE), + free_winner_asset_charlie_before - AssetManager::free_balance(winner_asset, &CHARLIE), winner_amount_1_minus_fees ); assert_eq!( - AssetManager::free_balance(market.base_asset.into(), &CHARLIE) + AssetManager::free_balance(market.base_asset, &CHARLIE) - free_base_asset_charlie_before, actual_payoff_charlie ); assert_eq!( - AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id) - ), + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)), 0 ); }); @@ -261,11 +244,11 @@ fn claim_rewards_categorical_fails_if_no_winner() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let winner_asset = ParimutuelAsset::Share(market_id, 0u16); + let winner_asset = Asset::ParimutuelShare(market_id, 0u16); let winner_amount = 20 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), winner_asset, winner_amount)); - let loser_asset = ParimutuelAsset::Share(market_id, 1u16); + let loser_asset = Asset::ParimutuelShare(market_id, 1u16); let loser_amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(BOB), loser_asset, loser_amount)); @@ -291,11 +274,11 @@ fn claim_rewards_categorical_fails_if_no_winning_shares() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let winner_asset = ParimutuelAsset::Share(market_id, 0u16); + let winner_asset = Asset::ParimutuelShare(market_id, 0u16); let winner_amount = 20 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), winner_asset, winner_amount)); - let loser_asset = ParimutuelAsset::Share(market_id, 1u16); + let loser_asset = Asset::ParimutuelShare(market_id, 1u16); let loser_amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(BOB), loser_asset, loser_amount)); @@ -320,13 +303,12 @@ fn claim_refunds_works() { market.market_type = MarketType::Categorical(10u16); market.status = MarketStatus::Active; Markets::::insert(market_id, market); - assert_ok!(Parimutuel::on_activation(&market_id).result); - let alice_asset = ParimutuelAsset::Share(market_id, 0u16); + let alice_asset = Asset::ParimutuelShare(market_id, 0u16); let alice_amount = 20 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), alice_asset, alice_amount)); - let bob_asset = ParimutuelAsset::Share(market_id, 1u16); + let bob_asset = Asset::ParimutuelShare(market_id, 1u16); let bob_amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(BOB), bob_asset, bob_amount)); @@ -347,46 +329,33 @@ fn claim_refunds_works() { let alice_amount_minus_fees = alice_amount - alice_paid_fees; let bob_amount_minus_fees = bob_amount - bob_paid_fees; - let free_base_asset_alice_before = - AssetManager::free_balance(market.base_asset.into(), &ALICE); - let free_base_asset_bob_before = AssetManager::free_balance(market.base_asset.into(), &BOB); - let free_base_asset_pot_before = AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id), - ); + let free_base_asset_alice_before = AssetManager::free_balance(market.base_asset, &ALICE); + let free_base_asset_bob_before = AssetManager::free_balance(market.base_asset, &BOB); + let free_base_asset_pot_before = + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)); assert_ok!(Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), alice_asset)); assert_eq!( - AssetManager::free_balance(market.base_asset.into(), &ALICE) - - free_base_asset_alice_before, + AssetManager::free_balance(market.base_asset, &ALICE) - free_base_asset_alice_before, alice_amount_minus_fees ); assert_eq!( - AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id) - ), + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)), free_base_asset_pot_before - alice_amount_minus_fees ); assert_eq!( - AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id) - ), + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)), bob_amount_minus_fees ); assert_ok!(Parimutuel::claim_refunds(RuntimeOrigin::signed(BOB), bob_asset)); assert_eq!( - AssetManager::free_balance(market.base_asset.into(), &BOB) - free_base_asset_bob_before, + AssetManager::free_balance(market.base_asset, &BOB) - free_base_asset_bob_before, bob_amount_minus_fees ); assert_eq!( - AssetManager::free_balance( - market.base_asset.into(), - &Parimutuel::pot_account(market_id) - ), + AssetManager::free_balance(market.base_asset, &Parimutuel::pot_account(market_id)), 0 ); }); diff --git a/zrml/parimutuel/src/tests/mod.rs b/zrml/parimutuel/src/tests/mod.rs index 454cec9af..52de08fb9 100644 --- a/zrml/parimutuel/src/tests/mod.rs +++ b/zrml/parimutuel/src/tests/mod.rs @@ -17,7 +17,6 @@ #![cfg(test)] -mod assets; mod buy; mod claim; mod refund; diff --git a/zrml/parimutuel/src/tests/refund.rs b/zrml/parimutuel/src/tests/refund.rs index e5bd80863..09cf0c0d7 100644 --- a/zrml/parimutuel/src/tests/refund.rs +++ b/zrml/parimutuel/src/tests/refund.rs @@ -15,16 +15,35 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . +#![cfg(test)] + use crate::{mock::*, utils::*, *}; use frame_support::{assert_noop, assert_ok}; use sp_runtime::Percent; use test_case::test_case; -use zeitgeist_primitives::{ - traits::MarketTransitionApi, - types::{MarketStatus, MarketType, OutcomeReport, ParimutuelAsset, ScoringRule}, -}; +use zeitgeist_primitives::types::{Asset, MarketStatus, MarketType, OutcomeReport, ScoringRule}; use zrml_market_commons::Markets; +#[test] +fn refund_fails_if_not_parimutuel_outcome() { + ExtBuilder::default().build().execute_with(|| { + let market_id = 0; + let mut market = market_mock::(MARKET_CREATOR); + market.market_type = MarketType::Categorical(10u16); + market.resolved_outcome = Some(OutcomeReport::Categorical(0u16)); + market.status = MarketStatus::Resolved; + Markets::::insert(market_id, market); + + assert_noop!( + Parimutuel::claim_refunds( + RuntimeOrigin::signed(ALICE), + Asset::CategoricalOutcome(market_id, 0u16) + ), + Error::::NotParimutuelOutcome + ); + }); +} + #[test_case(MarketStatus::Active; "active")] #[test_case(MarketStatus::Proposed; "proposed")] #[test_case(MarketStatus::Closed; "closed")] @@ -38,7 +57,7 @@ fn refund_fails_if_market_not_resolved(status: MarketStatus) { market.status = status; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); assert_noop!( Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset), Error::::MarketIsNotResolvedYet @@ -58,7 +77,7 @@ fn refund_fails_if_invalid_scoring_rule(scoring_rule: ScoringRule) { market.scoring_rule = scoring_rule; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); assert_noop!( Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset), Error::::InvalidScoringRule @@ -76,7 +95,7 @@ fn refund_fails_if_invalid_outcome_asset() { market.status = MarketStatus::Resolved; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 20u16); + let asset = Asset::ParimutuelShare(market_id, 20u16); assert_noop!( Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset), Error::::InvalidOutcomeAsset @@ -94,7 +113,7 @@ fn refund_fails_if_no_resolved_outcome() { market.resolved_outcome = None; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); assert_noop!( Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset), Error::::NoResolvedOutcome @@ -111,7 +130,7 @@ fn refund_fails_if_refund_not_allowed() { market.status = MarketStatus::Active; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount)); @@ -120,7 +139,7 @@ fn refund_fails_if_refund_not_allowed() { market.status = MarketStatus::Resolved; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); assert_noop!( Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset), Error::::RefundNotAllowed @@ -136,9 +155,8 @@ fn refund_fails_if_refundable_balance_is_zero() { market.market_type = MarketType::Categorical(10u16); market.status = MarketStatus::Active; Markets::::insert(market_id, market); - assert_ok!(Parimutuel::on_activation(&market_id).result); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = 2 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount)); @@ -147,7 +165,7 @@ fn refund_fails_if_refundable_balance_is_zero() { market.status = MarketStatus::Resolved; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); assert_ok!(Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset)); // already refunded above @@ -166,9 +184,8 @@ fn refund_emits_event() { market.market_type = MarketType::Categorical(10u16); market.status = MarketStatus::Active; Markets::::insert(market_id, market); - assert_ok!(Parimutuel::on_activation(&market_id).result); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); let amount = 10 * ::MinBetSize::get(); assert_ok!(Parimutuel::buy(RuntimeOrigin::signed(ALICE), asset, amount)); @@ -177,7 +194,7 @@ fn refund_emits_event() { market.status = MarketStatus::Resolved; Markets::::insert(market_id, market); - let asset = ParimutuelAsset::Share(market_id, 0u16); + let asset = Asset::ParimutuelShare(market_id, 0u16); assert_ok!(Parimutuel::claim_refunds(RuntimeOrigin::signed(ALICE), asset)); let amount_minus_fees = amount - (Percent::from_percent(1) * amount); @@ -185,7 +202,7 @@ fn refund_emits_event() { System::assert_last_event( Event::BalanceRefunded { market_id, - asset: asset.into(), + asset, refunded_balance: amount_minus_fees, sender: ALICE, } diff --git a/zrml/parimutuel/src/utils.rs b/zrml/parimutuel/src/utils.rs index b8a99edcd..35b0422f6 100644 --- a/zrml/parimutuel/src/utils.rs +++ b/zrml/parimutuel/src/utils.rs @@ -23,13 +23,13 @@ where use frame_support::traits::Get; use sp_runtime::{traits::AccountIdConversion, Perbill}; use zeitgeist_primitives::types::{ - BaseAsset, Deadlines, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, + Asset, Deadlines, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, ScoringRule, }; zeitgeist_primitives::types::Market { market_id: Default::default(), - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: Perbill::zero(), creator, diff --git a/zrml/parimutuel/src/weights.rs b/zrml/parimutuel/src/weights.rs index de83ae773..490bcdb54 100644 --- a/zrml/parimutuel/src/weights.rs +++ b/zrml/parimutuel/src/weights.rs @@ -52,8 +52,6 @@ pub trait WeightInfoZeitgeist { fn buy() -> Weight; fn claim_rewards() -> Weight; fn claim_refunds() -> Weight; - fn on_activation() -> Weight; - fn on_resolution() -> Weight; } /// Weight functions for zrml_parimutuel (automatically generated) @@ -63,97 +61,51 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:1 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:1 w:1) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) fn buy() -> Weight { // Proof Size summary in bytes: - // Measured: `1940` - // Estimated: `13590` - // Minimum execution time: 132_371 nanoseconds. - Weight::from_parts(162_240_000, 13590) - .saturating_add(T::DbWeight::get().reads(5)) + // Measured: `1815` + // Estimated: `10876` + // Minimum execution time: 134_190 nanoseconds. + Weight::from_parts(155_681_000, 10876) + .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:1 w:1) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: MarketAssets Account (r:1 w:1) - /// Proof: MarketAssets Account (max_values: None, max_size: Some(117), added: 2592, mode: MaxEncodedLen) + /// Proof: MarketCommons Markets (max_values: None, max_size: Some(678), added: 3153, mode: MaxEncodedLen) + /// Storage: Tokens TotalIssuance (r:1 w:1) + /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) + /// Storage: Tokens Accounts (r:1 w:1) + /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// Storage: AssetRouter DestroyAssets (r:1 w:1) - /// Proof: AssetRouter DestroyAssets (max_values: Some(1), max_size: Some(40962), added: 41457, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:1 w:0) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) - /// Storage: AssetRouter IndestructibleAssets (r:1 w:0) - /// Proof: AssetRouter IndestructibleAssets (max_values: Some(1), max_size: Some(38914), added: 39409, mode: MaxEncodedLen) fn claim_rewards() -> Weight { // Proof Size summary in bytes: - // Measured: `3241` - // Estimated: `94450` - // Minimum execution time: 159_601 nanoseconds. - Weight::from_parts(222_111_000, 94450) - .saturating_add(T::DbWeight::get().reads(7)) - .saturating_add(T::DbWeight::get().writes(4)) + // Measured: `2312` + // Estimated: `10876` + // Minimum execution time: 127_580 nanoseconds. + Weight::from_parts(180_511_000, 10876) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:1) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: MarketAssets Account (r:1 w:1) - /// Proof: MarketAssets Account (max_values: None, max_size: Some(117), added: 2592, mode: MaxEncodedLen) + /// Proof: MarketCommons Markets (max_values: None, max_size: Some(678), added: 3153, mode: MaxEncodedLen) + /// Storage: Tokens TotalIssuance (r:2 w:1) + /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) + /// Storage: Tokens Accounts (r:1 w:1) + /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// Storage: AssetRouter DestroyAssets (r:1 w:1) - /// Proof: AssetRouter DestroyAssets (max_values: Some(1), max_size: Some(40962), added: 41457, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:1 w:0) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) - /// Storage: AssetRouter IndestructibleAssets (r:1 w:0) - /// Proof: AssetRouter IndestructibleAssets (max_values: Some(1), max_size: Some(38914), added: 39409, mode: MaxEncodedLen) fn claim_refunds() -> Weight { // Proof Size summary in bytes: - // Measured: `3544` - // Estimated: `97150` - // Minimum execution time: 193_471 nanoseconds. - Weight::from_parts(222_400_000, 97150) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:64 w:64) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - fn on_activation() -> Weight { - // Proof Size summary in bytes: - // Measured: `1203` - // Estimated: `175967` - // Minimum execution time: 592_941 nanoseconds. - Weight::from_parts(720_612_000, 175967) - .saturating_add(T::DbWeight::get().reads(65)) - .saturating_add(T::DbWeight::get().writes(64)) - } - /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:64 w:64) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: AssetRouter DestroyAssets (r:1 w:1) - /// Proof: AssetRouter DestroyAssets (max_values: Some(1), max_size: Some(40962), added: 41457, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:64 w:0) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) - /// Storage: AssetRouter IndestructibleAssets (r:1 w:0) - /// Proof: AssetRouter IndestructibleAssets (max_values: Some(1), max_size: Some(38914), added: 39409, mode: MaxEncodedLen) - fn on_resolution() -> Weight { - // Proof Size summary in bytes: - // Measured: `18393` - // Estimated: `417985` - // Minimum execution time: 1_162_074 nanoseconds. - Weight::from_parts(1_508_734_000, 417985) - .saturating_add(T::DbWeight::get().reads(131)) - .saturating_add(T::DbWeight::get().writes(65)) + // Measured: `2312` + // Estimated: `13394` + // Minimum execution time: 119_110 nanoseconds. + Weight::from_parts(132_660_000, 13394) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } } diff --git a/zrml/prediction-markets/Cargo.toml b/zrml/prediction-markets/Cargo.toml index a2a8121cb..066928568 100644 --- a/zrml/prediction-markets/Cargo.toml +++ b/zrml/prediction-markets/Cargo.toml @@ -3,7 +3,6 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } orml-traits = { workspace = true } -pallet-assets = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } serde = { workspace = true, optional = true } @@ -30,7 +29,6 @@ pallet-treasury = { workspace = true, optional = true } sp-api = { workspace = true, optional = true } sp-io = { workspace = true, optional = true } xcm = { workspace = true, optional = true } -zrml-asset-router = { workspace = true, optional = true } zrml-prediction-markets-runtime-api = { workspace = true, optional = true } [dev-dependencies] @@ -41,12 +39,9 @@ zrml-prediction-markets = { workspace = true, features = ["mock", "default"] } [features] default = ["std"] mock = [ - "env_logger/default", - "orml-asset-registry/default", "orml-currencies/default", "orml-tokens/default", - "pallet-assets/default", - "pallet-balances/default", + "pallet-balances", "pallet-randomness-collective-flip/default", "pallet-timestamp/default", "pallet-treasury/default", @@ -54,9 +49,10 @@ mock = [ "sp-api/default", "sp-io/default", "zeitgeist-primitives/mock", - "zrml-asset-router/default", "zrml-prediction-markets-runtime-api/default", "xcm/default", + "orml-asset-registry/default", + "env_logger/default", ] parachain = [] runtime-benchmarks = [ @@ -64,7 +60,6 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "orml-asset-registry?/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "zeitgeist-primitives/mock", ] @@ -74,7 +69,6 @@ std = [ "frame-system/std", "orml-asset-registry?/std", "orml-traits/std", - "pallet-assets/std", "parity-scale-codec/std", 'scale-info/std', "serde?/std", diff --git a/zrml/prediction-markets/fuzz/pm_full_workflow.rs b/zrml/prediction-markets/fuzz/pm_full_workflow.rs index f3799a127..506b9e5cd 100644 --- a/zrml/prediction-markets/fuzz/pm_full_workflow.rs +++ b/zrml/prediction-markets/fuzz/pm_full_workflow.rs @@ -26,7 +26,7 @@ use sp_arithmetic::Perbill; use zeitgeist_primitives::{ constants::mock::MaxCreatorFee, types::{ - BaseAsset, Deadlines, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketType, + Asset, Deadlines, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketType, MultiHash, OutcomeReport, ScoringRule, }, }; @@ -48,7 +48,7 @@ fuzz_target!(|data: Data| { let fee = Perbill::from_parts(bounded_parts.try_into().unwrap()); let _ = PredictionMarkets::create_market( RuntimeOrigin::signed(data.create_scalar_market_origin.into()), - BaseAsset::Ztg, + Asset::Ztg, fee, data.create_scalar_market_oracle.into(), MarketPeriod::Block(data.create_scalar_market_period), diff --git a/zrml/prediction-markets/runtime-api/src/lib.rs b/zrml/prediction-markets/runtime-api/src/lib.rs index 4a488b52b..b90dcaac9 100644 --- a/zrml/prediction-markets/runtime-api/src/lib.rs +++ b/zrml/prediction-markets/runtime-api/src/lib.rs @@ -1,4 +1,4 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. @@ -19,12 +19,12 @@ #![doc = include_str!("../README.md")] #![cfg_attr(not(feature = "std"), no_std)] -use parity_scale_codec::{Codec, HasCompact, MaxEncodedLen}; +use parity_scale_codec::{Codec, MaxEncodedLen}; use zeitgeist_primitives::types::Asset; sp_api::decl_runtime_apis! { pub trait PredictionMarketsApi where - MarketId: Codec + HasCompact + MaxEncodedLen, + MarketId: Codec + MaxEncodedLen, Hash: Codec, { fn market_outcome_share_id(market_id: MarketId, outcome: u16) -> Asset; diff --git a/zrml/prediction-markets/src/benchmarks.rs b/zrml/prediction-markets/src/benchmarks.rs index 01903a795..61d18b4c1 100644 --- a/zrml/prediction-markets/src/benchmarks.rs +++ b/zrml/prediction-markets/src/benchmarks.rs @@ -46,8 +46,8 @@ use zeitgeist_primitives::{ math::fixed::{BaseProvider, ZeitgeistBase}, traits::DisputeApi, types::{ - Asset, BaseAsset, Deadlines, MarketCreation, MarketDisputeMechanism, MarketPeriod, - MarketStatus, MarketType, MultiHash, OutcomeReport, ScoringRule, + Asset, Deadlines, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, + MarketType, MultiHash, OutcomeReport, ScoringRule, }, }; use zrml_authorized::Pallet as AuthorizedPallet; @@ -97,7 +97,7 @@ fn create_market_common( let (caller, oracle, deadlines, metadata) = create_market_common_parameters::(dispute_mechanism.is_some())?; Call::::create_market { - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creator_fee, oracle, period, @@ -491,7 +491,7 @@ benchmarks! { } }: _( RawOrigin::Signed(caller), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), oracle, period, @@ -515,7 +515,7 @@ benchmarks! { let (caller, oracle, deadlines, metadata) = create_market_common_parameters::(true)?; Call::::create_market { - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creator_fee: Perbill::zero(), oracle: oracle.clone(), period: period.clone(), @@ -547,7 +547,7 @@ benchmarks! { }; }: _( RawOrigin::Signed(caller), - BaseAsset::Ztg, + Asset::Ztg, market_id, oracle, period, @@ -856,7 +856,7 @@ benchmarks! { let end: MomentOf = 1_000_000u64.saturated_into(); let (caller, oracle, _, metadata) = create_market_common_parameters::(false)?; Call::::create_market { - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creator_fee: Perbill::zero(), oracle: caller.clone(), period: MarketPeriod::Timestamp(start..end), @@ -1288,7 +1288,7 @@ benchmarks! { let m in 0..63; // Number of markets closing on the same block. let n in 2..T::MaxCategories::get() as u32; // Number of assets in the market. - let base_asset = BaseAsset::Ztg; + let base_asset = Asset::Ztg; let range_start = (5 * MILLISECS_PER_BLOCK) as u64; let range_end = (100 * MILLISECS_PER_BLOCK) as u64; let period = MarketPeriod::Timestamp(range_start..range_end); @@ -1298,7 +1298,7 @@ benchmarks! { let amount = (10u128 * BASE).saturated_into(); ::AssetManager::deposit( - base_asset.into(), + base_asset, &caller, amount, )?; diff --git a/zrml/prediction-markets/src/lib.rs b/zrml/prediction-markets/src/lib.rs index abefb9275..d9eef6771 100644 --- a/zrml/prediction-markets/src/lib.rs +++ b/zrml/prediction-markets/src/lib.rs @@ -35,7 +35,7 @@ pub use pallet::*; #[frame_support::pallet] mod pallet { use crate::weights::*; - use alloc::{collections::BTreeMap, format, vec, vec::Vec}; + use alloc::{format, vec, vec::Vec}; use core::{cmp, marker::PhantomData}; use frame_support::{ dispatch::{DispatchResultWithPostInfo, Pays, Weight}, @@ -44,22 +44,16 @@ mod pallet { require_transactional, storage::{with_transaction, TransactionOutcome}, traits::{ - fungibles::{Create, Inspect}, - tokens::BalanceStatus, - Currency, EnsureOrigin, Get, Hooks, Imbalance, IsType, NamedReservableCurrency, - OnUnbalanced, StorageVersion, + tokens::BalanceStatus, Currency, EnsureOrigin, Get, Hooks, Imbalance, IsType, + NamedReservableCurrency, OnUnbalanced, StorageVersion, }, transactional, Blake2_128Concat, BoundedVec, PalletId, Twox64Concat, }; use frame_system::{ensure_signed, pallet_prelude::OriginFor}; - use pallet_assets::ManagedDestroy; use sp_runtime::traits::AccountIdConversion; #[cfg(feature = "parachain")] - use { - orml_traits::asset_registry::Inspect as RegistryInspect, - zeitgeist_primitives::types::{CustomMetadata, XcmAsset}, - }; + use {orml_traits::asset_registry::Inspect, zeitgeist_primitives::types::CustomMetadata}; use orml_traits::{MultiCurrency, NamedMultiReservableCurrency}; use sp_arithmetic::per_things::{Perbill, Percent}; @@ -71,13 +65,13 @@ mod pallet { constants::MILLISECS_PER_BLOCK, traits::{ CompleteSetOperationsApi, DeployPoolApi, DisputeApi, DisputeMaxWeightApi, - DisputeResolutionApi, MarketBuilderTrait, MarketTransitionApi, + DisputeResolutionApi, MarketBuilderTrait, }, types::{ - Asset, BaseAsset, Bond, Deadlines, EarlyClose, EarlyCloseState, GlobalDisputeItem, - Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, - MarketStatus, MarketType, MultiHash, OutcomeReport, Report, ResultWithWeightInfo, - ScalarPosition, ScoringRule, + Asset, Bond, Deadlines, EarlyClose, EarlyCloseState, GlobalDisputeItem, Market, + MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, + MarketType, MultiHash, OutcomeReport, Report, ResultWithWeightInfo, ScalarPosition, + ScoringRule, }, }; use zrml_global_disputes::{types::InitialItem, GlobalDisputesPalletApi}; @@ -92,6 +86,7 @@ mod pallet { /// the automatic market openings and closings from a chain stall. /// Currently 10 blocks is 2 minutes (assuming block time is 12 seconds). pub(crate) const MAX_RECOVERY_TIME_FRAMES: TimeFrame = 10; + pub(crate) type AccountIdOf = ::AccountId; pub(crate) type AssetOf = Asset>; pub(crate) type BalanceOf = ::Balance; @@ -102,14 +97,8 @@ mod pallet { pub(crate) type InitialItemOf = InitialItem, BalanceOf>; pub(crate) type MarketBondsOf = MarketBonds, BalanceOf>; pub(crate) type MarketIdOf = ::MarketId; - pub(crate) type MarketOf = Market< - AccountIdOf, - BalanceOf, - BlockNumberOf, - MomentOf, - BaseAsset, - MarketIdOf, - >; + pub(crate) type MarketOf = + Market, BalanceOf, BlockNumberOf, MomentOf, MarketIdOf>; pub(crate) type MarketPeriodOf = MarketPeriod, MomentOf>; pub(crate) type MomentOf = <::Timestamp as frame_support::traits::Time>::Moment; @@ -449,27 +438,11 @@ mod pallet { Error::::MarketEditRequestAlreadyInProgress ); m.status = new_status; - - if m.is_redeemable() { - for outcome in m.outcome_assets() { - let admin = Self::market_account(market_id); - let is_sufficient = true; - let min_balance = 1u8; - T::AssetCreator::create( - outcome.into(), - admin, - is_sufficient, - min_balance.into(), - )?; - } - } - Ok(()) })?; Self::unreserve_creation_bond(&market_id)?; - T::OnStateTransition::on_activation(&market_id).result?; Self::deposit_event(Event::MarketApproved(market_id, new_status)); // The ApproveOrigin should not pay fees for providing this service let default_weight: Option = None; @@ -603,7 +576,6 @@ mod pallet { Ok(()) })?; - T::OnStateTransition::on_dispute(&market_id).result?; Self::deposit_event(Event::MarketDisputed(market_id, MarketStatus::Disputed, who)); Ok((Some(weight)).into()) } @@ -619,7 +591,7 @@ mod pallet { #[transactional] pub fn create_market( origin: OriginFor, - base_asset: BaseAsset, + base_asset: AssetOf, creator_fee: Perbill, oracle: T::AccountId, period: MarketPeriodOf, @@ -671,7 +643,7 @@ mod pallet { #[transactional] pub fn edit_market( origin: OriginFor, - base_asset: BaseAsset, + base_asset: AssetOf, market_id: MarketIdOf, oracle: T::AccountId, period: MarketPeriodOf, @@ -759,7 +731,7 @@ mod pallet { // Ensure the market account has enough to pay out - if this is // ever not true then we have an accounting problem. ensure!( - T::AssetManager::free_balance(market.base_asset.into(), &market_account) + T::AssetManager::free_balance(market.base_asset, &market_account) >= winning_balance, Error::::InsufficientFundsInMarketAccount, ); @@ -813,7 +785,7 @@ mod pallet { // Ensure the market account has enough to pay out - if this is // ever not true then we have an accounting problem. ensure!( - T::AssetManager::free_balance(market.base_asset.into(), &market_account) + T::AssetManager::free_balance(market.base_asset, &market_account) >= long_payout.saturating_add(short_payout), Error::::InsufficientFundsInMarketAccount, ); @@ -839,25 +811,18 @@ mod pallet { // Pay out the winner. let remaining_bal = - T::AssetManager::free_balance(market.base_asset.into(), &market_account); + T::AssetManager::free_balance(market.base_asset, &market_account); let actual_payout = payout.min(remaining_bal); T::AssetManager::transfer( - market.base_asset.into(), + market.base_asset, &market_account, &sender, actual_payout, )?; - // The if-check prevents scalar markets to emit events even if sender only owns one // of the outcome tokens. if balance != BalanceOf::::zero() { - if T::AssetManager::total_issuance(currency_id).is_zero() { - // Ensure managed_destroy does not error during lazy migration because - // it tried to delete an old outcome asset from orml-tokens - let _ = T::AssetDestroyer::managed_destroy(currency_id, None); - } - Self::deposit_event(Event::TokensRedeemed( market_id, currency_id, @@ -1066,7 +1031,6 @@ mod pallet { m.status = MarketStatus::Disputed; Ok(()) })?; - T::OnStateTransition::on_dispute(&market_id).result?; } // global disputes uses DisputeResolution API to control its resolution @@ -1094,7 +1058,7 @@ mod pallet { #[pallet::call_index(17)] pub fn create_market_and_deploy_pool( origin: OriginFor, - base_asset: BaseAsset, + base_asset: AssetOf, creator_fee: Perbill, oracle: T::AccountId, period: MarketPeriodOf, @@ -1547,15 +1511,8 @@ mod pallet { /// The origin that is allowed to approve / reject pending advised markets. type ApproveOrigin: EnsureOrigin; - /// The module handling the creation of market assets. - type AssetCreator: Create, Balance = BalanceOf>; - - /// The module handling the destruction of market assets. - type AssetDestroyer: ManagedDestroy, Balance = BalanceOf>; - - /// The module managing collateral and market assets. - type AssetManager: MultiCurrency, CurrencyId = AssetOf> - + NamedMultiReservableCurrency< + /// Shares of outcome assets and native currency + type AssetManager: NamedMultiReservableCurrency< Self::AccountId, Balance = BalanceOf, CurrencyId = AssetOf, @@ -1563,8 +1520,8 @@ mod pallet { >; #[cfg(feature = "parachain")] - type AssetRegistry: RegistryInspect< - AssetId = XcmAsset, + type AssetRegistry: Inspect< + AssetId = Asset>, Balance = BalanceOf, CustomMetadata = CustomMetadata, >; @@ -1725,9 +1682,6 @@ mod pallet { /// The origin that is allowed to reject pending advised markets. type RejectOrigin: EnsureOrigin; - /// Additional handler during state transitions. - type OnStateTransition: MarketTransitionApi>; - /// The base amount of currency that must be bonded to ensure the oracle reports /// in a timely manner. #[pallet::constant] @@ -1946,6 +1900,7 @@ mod pallet { #[pallet::hooks] impl Hooks for Pallet { + // TODO(#792): Remove outcome assets for accounts! Delete "resolved" assets of `orml_tokens` with storage migration. fn on_initialize(now: T::BlockNumber) -> Weight { let mut total_weight: Weight = Weight::zero(); @@ -2118,7 +2073,7 @@ mod pallet { #[require_transactional] fn do_create_market( who: T::AccountId, - base_asset: BaseAsset, + base_asset: AssetOf, creator_fee: Perbill, oracle: T::AccountId, period: MarketPeriodOf, @@ -2170,33 +2125,32 @@ mod pallet { let (market_id, market) = >::build_market(market_builder)?; let market_account = Self::market_account(market_id); - match market.status { - MarketStatus::Active => { - if market.is_redeemable() { - for outcome in market.outcome_assets() { - let admin = market_account.clone(); - let is_sufficient = true; - let min_balance = 1u8; - T::AssetCreator::create( - outcome.into(), - admin, - is_sufficient, - min_balance.into(), - )?; - } - } - - T::OnStateTransition::on_activation(&market_id).result? - } - MarketStatus::Proposed => T::OnStateTransition::on_proposal(&market_id).result?, - _ => (), - } let ids_amount: u32 = Self::insert_auto_close(&market_id)?; + Self::deposit_event(Event::MarketCreated(market_id, market_account, market)); + Ok((ids_amount, market_id)) } + pub fn outcome_assets(market_id: MarketIdOf, market: &MarketOf) -> Vec> { + match market.market_type { + MarketType::Categorical(categories) => { + let mut assets = Vec::new(); + for i in 0..categories { + assets.push(Asset::CategoricalOutcome(market_id, i)); + } + assets + } + MarketType::Scalar(_) => { + vec![ + Asset::ScalarOutcome(market_id, ScalarPosition::Long), + Asset::ScalarOutcome(market_id, ScalarPosition::Short), + ] + } + } + } + fn insert_auto_close(market_id: &MarketIdOf) -> Result { let market = >::market(market_id)?; @@ -2311,7 +2265,7 @@ mod pallet { let market_account = Self::market_account(market_id); ensure!( - T::AssetManager::free_balance(market.base_asset.into(), &market_account) >= amount, + T::AssetManager::free_balance(market.base_asset, &market_account) >= amount, "Market account does not have sufficient reserves.", ); @@ -2322,14 +2276,14 @@ mod pallet { // Ensures that the sender has sufficient amount of each // share in the set. ensure!( - T::AssetManager::free_balance((*asset).into(), &who) >= amount, + T::AssetManager::free_balance(*asset, &who) >= amount, Error::::InsufficientShareBalance, ); } // write last. for asset in assets.iter() { - let missing = T::AssetManager::slash((*asset).into(), &who, amount); + let missing = T::AssetManager::slash(*asset, &who, amount); debug_assert!( missing.is_zero(), "Could not slash all of the amount. asset {:?}, who: {:?}, amount: {:?}.", @@ -2339,7 +2293,7 @@ mod pallet { ); } - T::AssetManager::transfer(market.base_asset.into(), &market_account, &who, amount)?; + T::AssetManager::transfer(market.base_asset, &market_account, &who, amount)?; Self::deposit_event(Event::SoldCompleteSet(market_id, amount, who)); @@ -2355,18 +2309,18 @@ mod pallet { ensure!(amount != BalanceOf::::zero(), Error::::ZeroAmount); let market = >::market(&market_id)?; ensure!( - T::AssetManager::free_balance(market.base_asset.into(), &who) >= amount, + T::AssetManager::free_balance(market.base_asset, &who) >= amount, Error::::NotEnoughBalance ); ensure!(market.is_redeemable(), Error::::InvalidScoringRule); Self::ensure_market_is_active(&market)?; let market_account = Self::market_account(market_id); - T::AssetManager::transfer(market.base_asset.into(), &who, &market_account, amount)?; + T::AssetManager::transfer(market.base_asset, &who, &market_account, amount)?; let assets = market.outcome_assets(); for asset in assets.iter() { - T::AssetManager::deposit((*asset).into(), &who, amount)?; + T::AssetManager::deposit(*asset, &who, amount)?; } Self::deposit_event(Event::BoughtCompleteSet(market_id, amount, who)); @@ -2549,12 +2503,9 @@ mod pallet { market.status = MarketStatus::Closed; Ok(()) })?; - - let mut total_weight = T::DbWeight::get().reads_writes(1, 2); - let on_state_transition_result = T::OnStateTransition::on_closure(market_id); - on_state_transition_result.result?; - total_weight = total_weight.saturating_add(on_state_transition_result.weight); + let mut total_weight = T::DbWeight::get().reads_writes(1, 1); Self::deposit_event(Event::MarketClosed(*market_id)); + total_weight = total_weight.saturating_add(T::DbWeight::get().writes(1)); Ok(total_weight) } @@ -2799,44 +2750,20 @@ mod pallet { // Following call should return weight consumed by it. T::LiquidityMining::distribute_market_incentives(market_id)?; - let mut updated_market = market.clone(); - + // NOTE: Currently we don't clean up outcome assets. + // TODO(#792): Remove outcome assets for accounts! Delete "resolved" assets of `orml_tokens` with storage migration. >::mutate_market(market_id, |m| { m.status = MarketStatus::Resolved; m.resolved_outcome = Some(resolved_outcome.clone()); - updated_market = m.clone(); Ok(()) })?; - let winning_outcome = updated_market.resolved_outcome_into_asset(); - if market.is_redeemable() { - if let Some(winning_outcome_inner) = winning_outcome { - // Destroy losing assets. - let assets_to_destroy = BTreeMap::, Option>::from_iter( - market - .outcome_assets() - .into_iter() - .filter(|outcome| *outcome != winning_outcome_inner) - .map(|asset| (AssetOf::::from(asset), None)), - ); - // Ensure managed_destroy_multi does not error during lazy migration because - // it tried to delete an old outcome asset from orml-tokens - let _ = T::AssetDestroyer::managed_destroy_multi(assets_to_destroy); - } - } - - let on_state_transition_result = T::OnStateTransition::on_resolution(market_id); - on_state_transition_result.result?; - total_weight = total_weight.saturating_add(on_state_transition_result.weight); - total_weight = - total_weight.saturating_add(Self::calculate_internal_resolve_weight(market)); - Self::deposit_event(Event::MarketResolved( *market_id, MarketStatus::Resolved, resolved_outcome, )); - Ok(total_weight) + Ok(total_weight.saturating_add(Self::calculate_internal_resolve_weight(market))) } /// The reserve ID of the prediction-markets pallet. @@ -2940,7 +2867,7 @@ mod pallet { fn construct_market( market_id: Option>, - base_asset: BaseAsset, + base_asset: AssetOf, creator: T::AccountId, creator_fee: Perbill, oracle: T::AccountId, @@ -2956,21 +2883,16 @@ mod pallet { bonds: MarketBondsOf, ) -> Result, DispatchError> { let valid_base_asset = match base_asset { - BaseAsset::CampaignAsset(idx) => { - T::AssetCreator::asset_exists(BaseAsset::CampaignAsset(idx).into()) - } - BaseAsset::Ztg => true, + Asset::Ztg => true, #[cfg(feature = "parachain")] - BaseAsset::ForeignAsset(id) => { - if let Some(metadata) = T::AssetRegistry::metadata(&XcmAsset::ForeignAsset(id)) - { + Asset::ForeignAsset(fa) => { + if let Some(metadata) = T::AssetRegistry::metadata(&Asset::ForeignAsset(fa)) { metadata.additional.allow_as_base_asset } else { return Err(Error::::UnregisteredForeignAsset.into()); } } - #[cfg(not(feature = "parachain"))] - BaseAsset::ForeignAsset(_) => false, + _ => false, }; ensure!(creator_fee <= T::MaxCreatorFee::get(), Error::::FeeTooHigh); @@ -3074,7 +2996,6 @@ mod pallet { Ok(()) })?; - T::OnStateTransition::on_report(&market_id).result?; let market = >::market(&market_id)?; let block_after_dispute_duration = report.at.saturating_add(market.deadlines.dispute_duration); @@ -3101,7 +3022,6 @@ mod pallet { market.status = MarketStatus::Reported; Ok(()) })?; - T::OnStateTransition::on_report(&market_id).result?; let market = >::market(&market_id)?; Self::on_resolution(&market_id, &market)?; Ok(Some(T::WeightInfo::report_trusted_market()).into()) diff --git a/zrml/prediction-markets/src/mock.rs b/zrml/prediction-markets/src/mock.rs index 392a7d2df..f371ebf0b 100644 --- a/zrml/prediction-markets/src/mock.rs +++ b/zrml/prediction-markets/src/mock.rs @@ -24,61 +24,43 @@ use crate as prediction_markets; use frame_support::{ - construct_runtime, ord_parameter_types, - pallet_prelude::Weight, - parameter_types, - storage::unhashed::put, - traits::{ - AsEnsureOriginWithArg, Everything, GenesisBuild, NeverEnsureOrigin, OnFinalize, OnIdle, - OnInitialize, - }, + construct_runtime, ord_parameter_types, parameter_types, + traits::{Everything, NeverEnsureOrigin, OnFinalize, OnInitialize}, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; -use parity_scale_codec::Compact; +use frame_system::{EnsureRoot, EnsureSignedBy}; +#[cfg(feature = "parachain")] +use orml_asset_registry::AssetMetadata; use sp_arithmetic::per_things::Percent; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, ConstU32, IdentityLookup}, + traits::{BlakeTwo256, IdentityLookup}, DispatchError, DispatchResult, }; use std::cell::RefCell; use zeitgeist_primitives::{ constants::mock::{ - AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AssetsAccountDeposit, - AssetsApprovalDeposit, AssetsDeposit, AssetsMetadataDepositBase, - AssetsMetadataDepositPerByte, AssetsStringLimit, AuthorizedPalletId, BlockHashCount, - BlocksPerYear, CloseEarlyBlockPeriod, CloseEarlyDisputeBond, + AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AuthorizedPalletId, + BlockHashCount, BlocksPerYear, CloseEarlyBlockPeriod, CloseEarlyDisputeBond, CloseEarlyProtectionBlockPeriod, CloseEarlyProtectionTimeFramePeriod, CloseEarlyRequestBond, CloseEarlyTimeFramePeriod, CorrectionPeriod, CourtPalletId, - DestroyAccountWeight, DestroyApprovalWeight, DestroyFinishWeight, ExistentialDeposit, - ExistentialDeposits, GdVotingPeriod, GetNativeCurrencyId, GlobalDisputeLockId, - GlobalDisputesPalletId, InflationPeriod, LiquidityMiningPalletId, LockId, MaxAppeals, - MaxApprovals, MaxCategories, MaxCourtParticipants, MaxCreatorFee, MaxDelegations, - MaxDisputeDuration, MaxDisputes, MaxEditReasonLen, MaxGlobalDisputeVotes, MaxGracePeriod, - MaxMarketLifetime, MaxOracleDuration, MaxOwners, MaxRejectReasonLen, MaxReserves, - MaxSelectedDraws, MaxYearlyInflation, MinCategories, MinDisputeDuration, MinJurorStake, - MinOracleDuration, MinOutcomeVoteAmount, MinimumPeriod, OutcomeBond, OutcomeFactor, - OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, SimpleDisputesPalletId, - TreasuryPalletId, VotePeriod, VotingOutcomeFee, BASE, CENT, MILLISECS_PER_BLOCK, + ExistentialDeposit, ExistentialDeposits, GdVotingPeriod, GetNativeCurrencyId, + GlobalDisputeLockId, GlobalDisputesPalletId, InflationPeriod, LiquidityMiningPalletId, + LockId, MaxAppeals, MaxApprovals, MaxCategories, MaxCourtParticipants, MaxCreatorFee, + MaxDelegations, MaxDisputeDuration, MaxDisputes, MaxEditReasonLen, MaxGlobalDisputeVotes, + MaxGracePeriod, MaxMarketLifetime, MaxOracleDuration, MaxOwners, MaxRejectReasonLen, + MaxReserves, MaxSelectedDraws, MaxYearlyInflation, MinCategories, MinDisputeDuration, + MinJurorStake, MinOracleDuration, MinOutcomeVoteAmount, MinimumPeriod, OutcomeBond, + OutcomeFactor, OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, + SimpleDisputesPalletId, TreasuryPalletId, VotePeriod, VotingOutcomeFee, BASE, CENT, + MILLISECS_PER_BLOCK, }, - traits::{DeployPoolApi, MarketTransitionApi}, + traits::DeployPoolApi, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetClass, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, - Hash, Index, MarketAsset, MarketId, Moment, ResultWithWeightInfo, UncheckedExtrinsicTest, + AccountIdTest, Amount, Asset, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, + CurrencyId, Hash, Index, MarketId, Moment, SerdeWrapper, UncheckedExtrinsicTest, }, }; -#[cfg(feature = "parachain")] -use {orml_asset_registry::AssetMetadata, zeitgeist_primitives::types::XcmAsset}; - -pub(super) const ON_PROPOSAL_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x00]; -pub(super) const ON_ACTIVATION_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x01]; -pub(super) const ON_CLOSURE_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x02]; -pub(super) const ON_REPORT_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x03]; -pub(super) const ON_DISPUTE_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x04]; -pub(super) const ON_RESOLUTION_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x05]; - pub const ALICE: AccountIdTest = 0; pub const BOB: AccountIdTest = 1; pub const CHARLIE: AccountIdTest = 2; @@ -108,36 +90,6 @@ pub struct DeployPoolArgs { swap_fee: Balance, } -// It just writes true to specific memory locations depending on the hook that's invoked. -pub struct StateTransitionMock; - -impl MarketTransitionApi for StateTransitionMock { - fn on_proposal(_market_id: &MarketId) -> ResultWithWeightInfo { - put(&ON_PROPOSAL_STORAGE, &true); - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_activation(_market_id: &MarketId) -> ResultWithWeightInfo { - put(&ON_ACTIVATION_STORAGE, &true); - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_closure(_market_id: &MarketId) -> ResultWithWeightInfo { - put(&ON_CLOSURE_STORAGE, &true); - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_report(_market_id: &MarketId) -> ResultWithWeightInfo { - put(&ON_REPORT_STORAGE, &true); - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_dispute(_market_id: &MarketId) -> ResultWithWeightInfo { - put(&ON_DISPUTE_STORAGE, &true); - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } - fn on_resolution(_market_id: &MarketId) -> ResultWithWeightInfo { - put(&ON_RESOLUTION_STORAGE, &true); - ResultWithWeightInfo::new(Ok(()), Weight::zero()) - } -} - thread_local! { pub static DEPLOY_POOL_CALL_DATA: RefCell> = const { RefCell::new(vec![]) }; pub static DEPLOY_POOL_RETURN_VALUE: RefCell = const { RefCell::new(Ok(())) }; @@ -212,10 +164,6 @@ parameter_types! { pub const DisputeBond: Balance = 109 * CENT; } -type CustomAssetsInstance = pallet_assets::Instance1; -type CampaignAssetsInstance = pallet_assets::Instance2; -type MarketAssetsInstance = pallet_assets::Instance3; - construct_runtime!( pub enum Runtime where @@ -223,15 +171,11 @@ construct_runtime!( NodeBlock = BlockTest, UncheckedExtrinsic = UncheckedExtrinsicTest, { - AssetRouter: zrml_asset_router::{Pallet}, Authorized: zrml_authorized::{Event, Pallet, Storage}, Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, Court: zrml_court::{Event, Pallet, Storage}, AssetManager: orml_currencies::{Call, Pallet, Storage}, LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, MarketCommons: zrml_market_commons::{Pallet, Storage}, PredictionMarkets: prediction_markets::{Event, Pallet, Storage}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage}, @@ -248,9 +192,6 @@ impl crate::Config for Runtime { type AdvisoryBond = AdvisoryBond; type AdvisoryBondSlashPercentage = AdvisoryBondSlashPercentage; type ApproveOrigin = EnsureSignedBy; - type AssetCreator = AssetRouter; - type AssetDestroyer = AssetRouter; - type AssetManager = AssetManager; #[cfg(feature = "parachain")] type AssetRegistry = MockRegistry; type Authorized = Authorized; @@ -279,7 +220,6 @@ impl crate::Config for Runtime { type MinCategories = MinCategories; type MaxEditReasonLen = MaxEditReasonLen; type MaxRejectReasonLen = MaxRejectReasonLen; - type OnStateTransition = (StateTransitionMock,); type OracleBond = OracleBond; type OutsiderBond = OutsiderBond; type PalletId = PmPalletId; @@ -288,6 +228,7 @@ impl crate::Config for Runtime { type RejectOrigin = EnsureSignedBy; type RequestEditOrigin = EnsureSignedBy; type ResolveOrigin = EnsureSignedBy; + type AssetManager = AssetManager; type SimpleDisputes = SimpleDisputes; type Slash = Treasury; type ValidityBond = ValidityBond; @@ -323,7 +264,7 @@ impl frame_system::Config for Runtime { impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = AssetRouter; + type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type WeightInfo = (); } @@ -331,7 +272,7 @@ impl orml_currencies::Config for Runtime { impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Currencies; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = Everything; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -345,7 +286,7 @@ impl orml_tokens::Config for Runtime { #[cfg(feature = "parachain")] crate::orml_asset_registry::impl_mock_registry! { MockRegistry, - XcmAsset, + CurrencyId, Balance, zeitgeist_primitives::types::CustomMetadata } @@ -375,122 +316,6 @@ ord_parameter_types! { pub const AuthorizedDisputeResolutionUser: AccountIdTest = ALICE; } -pallet_assets::runtime_benchmarks_enabled! { - pub struct AssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for AssetsBenchmarkHelper - where - AssetIdParameter: From, - { - fn create_asset_id_parameter(id: u32) -> AssetIdParameter { - (id as u128).into() - } - } -} - -pallet_assets::runtime_benchmarks_enabled! { - use zeitgeist_primitives::types::CategoryIndex; - - pub struct MarketAssetsBenchmarkHelper; - - impl pallet_assets::BenchmarkHelper - for MarketAssetsBenchmarkHelper - { - fn create_asset_id_parameter(id: u32) -> MarketAsset { - MarketAsset::CategoricalOutcome(0, id as CategoryIndex) - } - } -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CampaignAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = CustomAsset; - type AssetIdParameter = Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = AssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = AssetsApprovalDeposit; - type AssetAccountDeposit = AssetsAccountDeposit; - type AssetDeposit = AssetsDeposit; - type AssetId = MarketAsset; - type AssetIdParameter = MarketAsset; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = MarketAssetsBenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type Destroyer = AssetRouter; - type MetadataDepositBase = AssetsMetadataDepositBase; - type MetadataDepositPerByte = AssetsMetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<50>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = (); -} - -impl zrml_asset_router::Config for Runtime { - type AssetType = Assets; - type Balance = Balance; - type CurrencyType = Currencies; - type Currencies = Tokens; - type CampaignAssetType = CampaignAsset; - type CampaignAssets = CampaignAssets; - type CustomAssetType = CustomAsset; - type CustomAssets = CustomAssets; - type DestroyAccountWeight = DestroyAccountWeight; - type DestroyApprovalWeight = DestroyApprovalWeight; - type DestroyFinishWeight = DestroyFinishWeight; - type MarketAssetType = MarketAsset; - type MarketAssets = MarketAssets; -} - impl zrml_authorized::Config for Runtime { type AuthorizedDisputeResolutionOrigin = EnsureSignedBy; @@ -621,42 +446,29 @@ impl ExtBuilder { // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); - pallet_assets::GenesisConfig:: { - assets: vec![(CampaignAssetClass(100), ALICE, true, 1)], - metadata: vec![], - accounts: self - .balances - .iter() - .map(|(account, balance)| (CampaignAssetClass(100), *account, *balance)) - .collect(), - } - .assimilate_storage(&mut t) - .unwrap(); - pallet_balances::GenesisConfig:: { balances: self.balances } .assimilate_storage(&mut t) .unwrap(); - + #[cfg(feature = "parachain")] + use frame_support::traits::GenesisBuild; #[cfg(feature = "parachain")] orml_tokens::GenesisConfig:: { balances: (0..69) - .map(|idx| (idx, Currencies::ForeignAsset(100), INITIAL_BALANCE)) + .map(|idx| (idx, CurrencyId::ForeignAsset(100), INITIAL_BALANCE)) .collect(), } .assimilate_storage(&mut t) .unwrap(); - #[cfg(feature = "parachain")] let custom_metadata = zeitgeist_primitives::types::CustomMetadata { allow_as_base_asset: true, ..Default::default() }; - #[cfg(feature = "parachain")] orml_asset_registry_mock::GenesisConfig { metadata: vec![ ( - XcmAsset::ForeignAsset(100), + CurrencyId::ForeignAsset(100), AssetMetadata { decimals: 18, name: "ACALA USD".as_bytes().to_vec(), @@ -667,7 +479,7 @@ impl ExtBuilder { }, ), ( - XcmAsset::ForeignAsset(420), + CurrencyId::ForeignAsset(420), AssetMetadata { decimals: 18, name: "FANCY_TOKEN".as_bytes().to_vec(), @@ -699,7 +511,6 @@ pub fn run_to_block(n: BlockNumber) { PredictionMarkets::on_initialize(System::block_number()); Court::on_initialize(System::block_number()); Balances::on_initialize(System::block_number()); - AssetRouter::on_idle(System::block_number(), Weight::MAX); } } @@ -716,8 +527,8 @@ pub fn set_timestamp_for_on_initialize(time: Moment) { sp_api::mock_impl_runtime_apis! { impl zrml_prediction_markets_runtime_api::PredictionMarketsApi, MarketId, Hash> for Runtime { - fn market_outcome_share_id(_: MarketId, _: u16) -> Assets { - Assets::PoolShare(1) + fn market_outcome_share_id(_: MarketId, _: u16) -> Asset { + Asset::PoolShare(SerdeWrapper(1)) } } } diff --git a/zrml/prediction-markets/src/tests/admin_move_market_to_closed.rs b/zrml/prediction-markets/src/tests/admin_move_market_to_closed.rs index 90896a335..5417f1e6a 100644 --- a/zrml/prediction-markets/src/tests/admin_move_market_to_closed.rs +++ b/zrml/prediction-markets/src/tests/admin_move_market_to_closed.rs @@ -28,7 +28,7 @@ fn admin_move_market_to_closed_successfully_closes_market_and_sets_end_blocknumb let now = frame_system::Pallet::::block_number(); let end = 42; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, now..end, ScoringRule::AmmCdaHybrid, @@ -59,7 +59,7 @@ fn admin_move_market_to_closed_successfully_closes_market_and_sets_end_timestamp let end = start + 42u64 * (MILLISECS_PER_BLOCK as u64); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(start..end), @@ -114,7 +114,7 @@ fn admin_move_market_to_closed_fails_if_market_does_not_exist() { fn admin_move_market_to_closed_fails_if_market_is_not_active(market_status: MarketStatus) { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, ScoringRule::AmmCdaHybrid, @@ -140,7 +140,7 @@ fn admin_move_market_to_closed_correctly_clears_auto_close_blocks() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Block(22..66), @@ -153,7 +153,7 @@ fn admin_move_market_to_closed_correctly_clears_auto_close_blocks() { )); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Block(33..66), diff --git a/zrml/prediction-markets/src/tests/admin_move_market_to_resolved.rs b/zrml/prediction-markets/src/tests/admin_move_market_to_resolved.rs index 9835169eb..6a6f9759e 100644 --- a/zrml/prediction-markets/src/tests/admin_move_market_to_resolved.rs +++ b/zrml/prediction-markets/src/tests/admin_move_market_to_resolved.rs @@ -24,7 +24,7 @@ use zeitgeist_primitives::types::OutcomeReport; #[test] fn admin_move_market_to_resolved_resolves_reported_market() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let end = 33; simple_create_categorical_market( base_asset, @@ -83,21 +83,18 @@ fn admin_move_market_to_resolved_resolves_reported_market() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn admin_move_market_to_resolved_resolves_disputed_market() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let end = 33; simple_create_categorical_market( base_asset, @@ -159,11 +156,11 @@ fn admin_move_market_to_resolved_resolves_disputed_market() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -175,7 +172,7 @@ fn admin_move_market_to_resolved_fails_if_market_is_not_reported_or_disputed( ) { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..33, ScoringRule::AmmCdaHybrid, diff --git a/zrml/prediction-markets/src/tests/approve_market.rs b/zrml/prediction-markets/src/tests/approve_market.rs index 6eabd8566..6405e59db 100644 --- a/zrml/prediction-markets/src/tests/approve_market.rs +++ b/zrml/prediction-markets/src/tests/approve_market.rs @@ -30,7 +30,7 @@ use sp_runtime::DispatchError; fn fails_if_market_status_is_not_proposed(market_status: MarketStatus) { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -54,7 +54,7 @@ fn fails_if_market_status_is_not_proposed(market_status: MarketStatus) { fn it_allows_advisory_origin_to_approve_markets() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -84,7 +84,7 @@ fn market_with_edit_request_cannot_be_approved() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -113,7 +113,7 @@ fn market_with_edit_request_cannot_be_approved() { #[test] fn approve_market_correctly_unreserves_advisory_bond() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), @@ -141,31 +141,10 @@ fn approve_market_correctly_unreserves_advisory_bond() { assert!(market.bonds.creation.unwrap().is_settled); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); - }); -} - -#[test] -fn does_trigger_market_transition_api() { - ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - simple_create_categorical_market( - BaseAsset::Ztg, - MarketCreation::Advised, - 1..2, - ScoringRule::AmmCdaHybrid, - ); - assert_ok!(PredictionMarkets::approve_market( - RuntimeOrigin::signed(ApproveOrigin::get()), - 0 - )); - assert!(StateTransitionMock::on_activation_triggered()); + test(Asset::ForeignAsset(100)); }); } diff --git a/zrml/prediction-markets/src/tests/buy_complete_set.rs b/zrml/prediction-markets/src/tests/buy_complete_set.rs index 68b551cd1..71f51caa0 100644 --- a/zrml/prediction-markets/src/tests/buy_complete_set.rs +++ b/zrml/prediction-markets/src/tests/buy_complete_set.rs @@ -21,7 +21,7 @@ use test_case::test_case; #[test] fn buy_complete_set_works() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { simple_create_categorical_market( base_asset, MarketCreation::Permissionless, @@ -42,27 +42,24 @@ fn buy_complete_set_works() { let assets = market.outcome_assets(); for asset in assets.iter() { - let bal = AssetManager::free_balance((*asset).into(), &who); + let bal = Tokens::free_balance(*asset, &who); assert_eq!(bal, amount); } - let bal = AssetManager::free_balance(base_asset.into(), &who); + let bal = AssetManager::free_balance(base_asset, &who); assert_eq!(bal, 1_000 * BASE - amount); let market_account = PredictionMarkets::market_account(market_id); - let market_bal = AssetManager::free_balance(base_asset.into(), &market_account); + let market_bal = AssetManager::free_balance(base_asset, &market_account); assert_eq!(market_bal, amount); System::assert_last_event(Event::BoughtCompleteSet(market_id, amount, who).into()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -70,7 +67,7 @@ fn buy_complete_set_works() { fn buy_complete_fails_on_zero_amount() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, ScoringRule::AmmCdaHybrid, @@ -84,7 +81,7 @@ fn buy_complete_fails_on_zero_amount() { #[test] fn buy_complete_set_fails_on_insufficient_balance() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { simple_create_categorical_market( base_asset, MarketCreation::Permissionless, @@ -97,14 +94,11 @@ fn buy_complete_set_fails_on_insufficient_balance() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -116,7 +110,7 @@ fn buy_complete_set_fails_on_insufficient_balance() { fn buy_complete_set_fails_if_market_is_not_active(status: MarketStatus) { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, ScoringRule::AmmCdaHybrid, @@ -137,7 +131,7 @@ fn buy_complete_set_fails_if_market_is_not_active(status: MarketStatus) { fn buy_complete_set_fails_if_market_has_wrong_scoring_rule(scoring_rule: ScoringRule) { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, scoring_rule, diff --git a/zrml/prediction-markets/src/tests/close_market.rs b/zrml/prediction-markets/src/tests/close_trusted_market.rs similarity index 91% rename from zrml/prediction-markets/src/tests/close_market.rs rename to zrml/prediction-markets/src/tests/close_trusted_market.rs index 2fc116d0a..bdd5537b8 100644 --- a/zrml/prediction-markets/src/tests/close_market.rs +++ b/zrml/prediction-markets/src/tests/close_trusted_market.rs @@ -30,7 +30,7 @@ fn close_trusted_market_works() { let market_creator = ALICE; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(market_creator), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -80,7 +80,7 @@ fn fails_if_caller_is_not_market_creator() { let market_creator = ALICE; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(market_creator), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -110,7 +110,7 @@ fn close_trusted_market_fails_if_not_trusted() { let market_creator = ALICE; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(market_creator), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -156,7 +156,7 @@ fn close_trusted_market_fails_if_invalid_market_state(status: MarketStatus) { let market_creator = ALICE; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(market_creator), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -197,18 +197,3 @@ fn fails_if_market_is_not_found() { ); }); } - -#[test] -fn does_trigger_market_transition_api_permissionless() { - ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - simple_create_categorical_market( - BaseAsset::Ztg, - MarketCreation::Permissionless, - 1..2, - ScoringRule::AmmCdaHybrid, - ); - assert_ok!(PredictionMarkets::close_market(&0)); - assert!(StateTransitionMock::on_closure_triggered()); - }); -} diff --git a/zrml/prediction-markets/src/tests/create_market.rs b/zrml/prediction-markets/src/tests/create_market.rs index bb2baf79d..2dd3c407c 100644 --- a/zrml/prediction-markets/src/tests/create_market.rs +++ b/zrml/prediction-markets/src/tests/create_market.rs @@ -44,7 +44,7 @@ fn fails_if_user_cannot_afford_bonds_advised( assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(creator), - BaseAsset::Ztg, + Asset::Ztg, ::MaxCreatorFee::get(), BOB, MarketPeriod::Block(123..456), @@ -67,7 +67,7 @@ fn fails_on_fee_too_high() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, ::MaxCreatorFee::get() + one_billionth, BOB, MarketPeriod::Block(123..456), @@ -93,7 +93,7 @@ fn fails_on_invalid_multihash() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, ::MaxCreatorFee::get(), BOB, MarketPeriod::Block(123..456), @@ -116,7 +116,7 @@ fn create_scalar_market_fails_on_invalid_range(range: RangeInclusive) { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -143,7 +143,7 @@ fn create_market_fails_on_min_dispute_period() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -170,7 +170,7 @@ fn create_market_fails_on_min_oracle_duration() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -197,7 +197,7 @@ fn create_market_fails_on_max_dispute_period() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -224,7 +224,7 @@ fn create_market_fails_on_max_grace_period() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -251,7 +251,7 @@ fn create_market_fails_on_max_oracle_duration() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -283,7 +283,7 @@ fn create_market_with_foreign_assets() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::ForeignAsset(420), + Asset::ForeignAsset(420), Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -300,7 +300,7 @@ fn create_market_with_foreign_assets() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::ForeignAsset(50), + Asset::ForeignAsset(50), Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -316,7 +316,7 @@ fn create_market_with_foreign_assets() { // As per Mock asset_registry genesis ForeignAsset(100) has allow_as_base_asset set to true. assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::ForeignAsset(100), + Asset::ForeignAsset(100), Perbill::zero(), BOB, MarketPeriod::Block(123..456), @@ -328,7 +328,7 @@ fn create_market_with_foreign_assets() { ScoringRule::AmmCdaHybrid, )); let market = MarketCommons::market(&0).unwrap(); - assert_eq!(market.base_asset, BaseAsset::ForeignAsset(100)); + assert_eq!(market.base_asset, Asset::ForeignAsset(100)); }); } @@ -338,7 +338,7 @@ fn it_does_not_create_market_with_too_few_categories() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..100), @@ -360,7 +360,7 @@ fn it_does_not_create_market_with_too_many_categories() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..100), @@ -389,7 +389,7 @@ fn create_categorical_market_fails_if_market_period_is_invalid( assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, period, @@ -413,7 +413,7 @@ fn create_categorical_market_fails_if_end_is_not_far_enough_ahead() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end_block), @@ -431,7 +431,7 @@ fn create_categorical_market_fails_if_end_is_not_far_enough_ahead() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..end_time), @@ -460,7 +460,7 @@ fn create_market_succeeds_if_market_duration_is_maximal_in_blocks() { ); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(start..end), @@ -488,7 +488,7 @@ fn create_market_suceeds_if_market_duration_is_maximal_in_moments() { ); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(start..end), @@ -516,7 +516,7 @@ fn create_market_fails_if_market_duration_is_too_long_in_blocks() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(start..end), @@ -547,7 +547,7 @@ fn create_market_fails_if_market_duration_is_too_long_in_moments() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(start..end), @@ -611,7 +611,7 @@ fn create_market_sets_the_correct_market_parameters_and_reserves_the_correct_amo let creator_fee = Perbill::from_parts(1); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(creator), - BaseAsset::Ztg, + Asset::Ztg, creator_fee, oracle, period.clone(), @@ -646,7 +646,7 @@ fn create_market_fails_on_trusted_market_with_non_zero_dispute_period() { assert_noop!( PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(1..2), @@ -670,7 +670,7 @@ fn create_market_fails_on_trusted_market_with_non_zero_dispute_period() { fn create_categorical_market_deposits_the_correct_event() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 1..2, ScoringRule::AmmCdaHybrid, @@ -686,7 +686,7 @@ fn create_categorical_market_deposits_the_correct_event() { fn create_scalar_market_deposits_the_correct_event() { ExtBuilder::default().build().execute_with(|| { simple_create_scalar_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 1..2, ScoringRule::AmmCdaHybrid, @@ -697,31 +697,3 @@ fn create_scalar_market_deposits_the_correct_event() { System::assert_last_event(Event::MarketCreated(0, market_account, market).into()); }); } - -#[test] -fn does_trigger_market_transition_api() { - ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - simple_create_categorical_market( - BaseAsset::Ztg, - MarketCreation::Advised, - 1..2, - ScoringRule::AmmCdaHybrid, - ); - assert!(StateTransitionMock::on_proposal_triggered()); - }); -} - -#[test] -fn does_trigger_market_transition_api_permissionless() { - ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - simple_create_categorical_market( - BaseAsset::Ztg, - MarketCreation::Permissionless, - 1..2, - ScoringRule::AmmCdaHybrid, - ); - assert!(StateTransitionMock::on_activation_triggered()); - }); -} diff --git a/zrml/prediction-markets/src/tests/create_market_and_deploy_pool.rs b/zrml/prediction-markets/src/tests/create_market_and_deploy_pool.rs index a87cb2dc5..82087b6e2 100644 --- a/zrml/prediction-markets/src/tests/create_market_and_deploy_pool.rs +++ b/zrml/prediction-markets/src/tests/create_market_and_deploy_pool.rs @@ -45,7 +45,7 @@ fn create_market_and_deploy_pool_works() { let market_id = 0; assert_ok!(PredictionMarkets::create_market_and_deploy_pool( RuntimeOrigin::signed(creator), - BaseAsset::Ztg, + Asset::Ztg, creator_fee, oracle, period.clone(), diff --git a/zrml/prediction-markets/src/tests/dispute.rs b/zrml/prediction-markets/src/tests/dispute.rs index b762eb548..20627b9c4 100644 --- a/zrml/prediction-markets/src/tests/dispute.rs +++ b/zrml/prediction-markets/src/tests/dispute.rs @@ -31,7 +31,7 @@ fn it_allows_to_dispute_the_outcome_of_a_market() { ExtBuilder::default().build().execute_with(|| { let end = 2; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -76,7 +76,7 @@ fn dispute_fails_disputed_already() { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -117,7 +117,7 @@ fn dispute_fails_if_market_not_reported() { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -152,7 +152,7 @@ fn dispute_reserves_dispute_bond() { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -198,7 +198,7 @@ fn dispute_updates_market() { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -245,7 +245,7 @@ fn dispute_emits_event() { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -287,7 +287,7 @@ fn dispute_fails_unless_reported_or_disputed_market(status: MarketStatus) { ExtBuilder::default().build().execute_with(|| { // Creates a permissionless market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, ScoringRule::AmmCdaHybrid, @@ -304,34 +304,3 @@ fn dispute_fails_unless_reported_or_disputed_market(status: MarketStatus) { ); }); } - -#[test] -fn does_trigger_market_transition_api() { - ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - let end = 2; - simple_create_categorical_market( - BaseAsset::Ztg, - MarketCreation::Permissionless, - 0..end, - ScoringRule::AmmCdaHybrid, - ); - - // Run to the end of the trading phase. - let market = MarketCommons::market(&0).unwrap(); - let grace_period = end + market.deadlines.grace_period; - run_to_block(grace_period + 1); - - assert_ok!(PredictionMarkets::report( - RuntimeOrigin::signed(BOB), - 0, - OutcomeReport::Categorical(1) - )); - - let dispute_at = grace_period + 2; - run_to_block(dispute_at); - - assert_ok!(PredictionMarkets::dispute(RuntimeOrigin::signed(CHARLIE), 0)); - assert!(StateTransitionMock::on_dispute_triggered()); - }); -} diff --git a/zrml/prediction-markets/src/tests/dispute_early_close.rs b/zrml/prediction-markets/src/tests/dispute_early_close.rs index d5f75802f..9043c44e9 100644 --- a/zrml/prediction-markets/src/tests/dispute_early_close.rs +++ b/zrml/prediction-markets/src/tests/dispute_early_close.rs @@ -30,7 +30,7 @@ fn dispute_early_close_emits_event() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -55,7 +55,7 @@ fn dispute_early_close_from_market_creator_works() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -129,7 +129,7 @@ fn dispute_early_close_fails_if_scheduled_as_sudo() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -162,7 +162,7 @@ fn dispute_early_close_fails_if_already_disputed() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -200,7 +200,7 @@ fn dispute_early_close_fails_if_already_rejected() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -243,7 +243,7 @@ fn settles_early_close_bonds_with_resolution_in_state_disputed() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -306,7 +306,7 @@ fn settles_early_close_bonds_with_resolution_in_state_scheduled_as_market_creato let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -354,7 +354,7 @@ fn schedule_early_close_disputed_sudo_schedule_and_settle_bonds() { let old_period = MarketPeriod::Block(0..end); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, old_period.clone(), diff --git a/zrml/prediction-markets/src/tests/edit_market.rs b/zrml/prediction-markets/src/tests/edit_market.rs index a1d5d3e93..553289ab7 100644 --- a/zrml/prediction-markets/src/tests/edit_market.rs +++ b/zrml/prediction-markets/src/tests/edit_market.rs @@ -29,7 +29,7 @@ use crate::MarketIdsForEdit; fn only_creator_can_edit_market() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -54,7 +54,7 @@ fn only_creator_can_edit_market() { assert_noop!( PredictionMarkets::edit_market( RuntimeOrigin::signed(BOB), - BaseAsset::Ztg, + Asset::Ztg, 0, CHARLIE, MarketPeriod::Block(0..2), @@ -73,7 +73,7 @@ fn only_creator_can_edit_market() { fn edit_cycle_for_proposed_markets() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 2..4, ScoringRule::AmmCdaHybrid, @@ -97,7 +97,7 @@ fn edit_cycle_for_proposed_markets() { // After this edit its changed to ALICE assert_ok!(PredictionMarkets::edit_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, 0, CHARLIE, MarketPeriod::Block(2..4), @@ -122,7 +122,7 @@ fn edit_market_with_foreign_asset() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -148,7 +148,7 @@ fn edit_market_with_foreign_asset() { assert_noop!( PredictionMarkets::edit_market( RuntimeOrigin::signed(ALICE), - BaseAsset::ForeignAsset(50), + Asset::ForeignAsset(50), 0, CHARLIE, MarketPeriod::Block(0..2), @@ -164,7 +164,7 @@ fn edit_market_with_foreign_asset() { assert_noop!( PredictionMarkets::edit_market( RuntimeOrigin::signed(ALICE), - BaseAsset::ForeignAsset(420), + Asset::ForeignAsset(420), 0, CHARLIE, MarketPeriod::Block(0..2), @@ -179,7 +179,7 @@ fn edit_market_with_foreign_asset() { // As per Mock asset_registry genesis ForeignAsset(100) has allow_as_base_asset set to true. assert_ok!(PredictionMarkets::edit_market( RuntimeOrigin::signed(ALICE), - BaseAsset::ForeignAsset(100), + Asset::ForeignAsset(100), 0, CHARLIE, MarketPeriod::Block(0..2), @@ -190,6 +190,6 @@ fn edit_market_with_foreign_asset() { ScoringRule::AmmCdaHybrid )); let market = MarketCommons::market(&0).unwrap(); - assert_eq!(market.base_asset, BaseAsset::ForeignAsset(100)); + assert_eq!(market.base_asset, Asset::ForeignAsset(100)); }); } diff --git a/zrml/prediction-markets/src/tests/integration.rs b/zrml/prediction-markets/src/tests/integration.rs index 4ea7749ff..48e1a0db3 100644 --- a/zrml/prediction-markets/src/tests/integration.rs +++ b/zrml/prediction-markets/src/tests/integration.rs @@ -33,7 +33,7 @@ use zrml_global_disputes::{ #[test] fn it_appeals_a_court_market_to_global_dispute() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let mut free_before = BTreeMap::new(); let jurors = 1000..(1000 + ::MaxSelectedDraws::get() as u128); @@ -128,14 +128,11 @@ fn it_appeals_a_court_market_to_global_dispute() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -145,7 +142,7 @@ fn the_entire_market_lifecycle_works_with_timestamps() { // Creates a permissionless market. assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..100_000_000), @@ -182,7 +179,7 @@ fn the_entire_market_lifecycle_works_with_timestamps() { #[test] fn full_scalar_market_lifecycle() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), base_asset, @@ -208,9 +205,10 @@ fn full_scalar_market_lifecycle() { let assets = market.outcome_assets(); assert_eq!(assets.len(), 2); for asset in assets.iter() { - let bal = AssetManager::free_balance((*asset).into(), &CHARLIE); + let bal = Tokens::free_balance(*asset, &CHARLIE); assert_eq!(bal, 100 * BASE); } + let market = MarketCommons::market(&0).unwrap(); set_timestamp_for_on_initialize(100_000_000); let report_at = 2; @@ -250,7 +248,7 @@ fn full_scalar_market_lifecycle() { assert_eq!(disputes.len(), 0); // give EVE some shares - assert_ok!(AssetManager::transfer( + assert_ok!(Tokens::transfer( RuntimeOrigin::signed(CHARLIE), EVE, Asset::ScalarOutcome(0, ScalarPosition::Short), @@ -258,19 +256,19 @@ fn full_scalar_market_lifecycle() { )); assert_eq!( - AssetManager::free_balance(Asset::ScalarOutcome(0, ScalarPosition::Short), &CHARLIE), + Tokens::free_balance(Asset::ScalarOutcome(0, ScalarPosition::Short), &CHARLIE), 50 * BASE ); assert_ok!(PredictionMarkets::redeem_shares(RuntimeOrigin::signed(CHARLIE), 0)); for asset in assets.iter() { - let bal = AssetManager::free_balance((*asset).into(), &CHARLIE); + let bal = Tokens::free_balance(*asset, &CHARLIE); assert_eq!(bal, 0); } // check payouts is right for each CHARLIE and EVE - let base_asset_bal_charlie = AssetManager::free_balance(base_asset.into(), &CHARLIE); - let base_asset_bal_eve = AssetManager::free_balance(base_asset.into(), &EVE); + let base_asset_bal_charlie = AssetManager::free_balance(base_asset, &CHARLIE); + let base_asset_bal_eve = AssetManager::free_balance(base_asset, &EVE); assert_eq!(base_asset_bal_charlie, 98750 * CENT); // 75 (LONG) + 12.5 (SHORT) + 900 (balance) assert_eq!(base_asset_bal_eve, 1000 * BASE); System::assert_has_event( @@ -295,7 +293,7 @@ fn full_scalar_market_lifecycle() { ); assert_ok!(PredictionMarkets::redeem_shares(RuntimeOrigin::signed(EVE), 0)); - let base_asset_bal_eve_after = AssetManager::free_balance(base_asset.into(), &EVE); + let base_asset_bal_eve_after = AssetManager::free_balance(base_asset, &EVE); assert_eq!(base_asset_bal_eve_after, 101250 * CENT); // 12.5 (SHORT) + 1000 (balance) System::assert_last_event( Event::TokensRedeemed( @@ -309,21 +307,18 @@ fn full_scalar_market_lifecycle() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn authorized_correctly_resolves_disputed_market() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), @@ -349,14 +344,14 @@ fn authorized_correctly_resolves_disputed_market() { OutcomeReport::Categorical(0) )); - let charlie_balance = AssetManager::free_balance(base_asset.into(), &CHARLIE); + let charlie_balance = AssetManager::free_balance(base_asset, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - CENT); let dispute_at = grace_period + 1 + 1; run_to_block(dispute_at); assert_ok!(PredictionMarkets::dispute(RuntimeOrigin::signed(CHARLIE), 0,)); - if base_asset == BaseAsset::Ztg { + if base_asset == Asset::Ztg { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!( charlie_balance, @@ -365,7 +360,7 @@ fn authorized_correctly_resolves_disputed_market() { } else { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - ::DisputeBond::get()); - let charlie_balance = AssetManager::free_balance(base_asset.into(), &CHARLIE); + let charlie_balance = AssetManager::free_balance(base_asset, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - CENT); } @@ -393,7 +388,7 @@ fn authorized_correctly_resolves_disputed_market() { ); assert_eq!(market_ids_1.len(), 1); - if base_asset == BaseAsset::Ztg { + if base_asset == Asset::Ztg { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!( charlie_balance, @@ -402,7 +397,7 @@ fn authorized_correctly_resolves_disputed_market() { } else { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - ::DisputeBond::get()); - let charlie_balance = AssetManager::free_balance(base_asset.into(), &CHARLIE); + let charlie_balance = AssetManager::free_balance(base_asset, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - CENT); } @@ -411,7 +406,7 @@ fn authorized_correctly_resolves_disputed_market() { let market_after = MarketCommons::market(&0).unwrap(); assert_eq!(market_after.status, MarketStatus::Disputed); - if base_asset == BaseAsset::Ztg { + if base_asset == Asset::Ztg { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!( charlie_balance, @@ -420,13 +415,13 @@ fn authorized_correctly_resolves_disputed_market() { } else { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - ::DisputeBond::get()); - let charlie_balance = AssetManager::free_balance(base_asset.into(), &CHARLIE); + let charlie_balance = AssetManager::free_balance(base_asset, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - CENT); } run_blocks(1); - if base_asset == BaseAsset::Ztg { + if base_asset == Asset::Ztg { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!( charlie_balance, @@ -435,7 +430,7 @@ fn authorized_correctly_resolves_disputed_market() { } else { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE + ::OracleBond::get()); - let charlie_balance = AssetManager::free_balance(base_asset.into(), &CHARLIE); + let charlie_balance = AssetManager::free_balance(base_asset, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE - CENT); } @@ -446,13 +441,13 @@ fn authorized_correctly_resolves_disputed_market() { assert_ok!(PredictionMarkets::redeem_shares(RuntimeOrigin::signed(CHARLIE), 0)); - if base_asset == BaseAsset::Ztg { + if base_asset == Asset::Ztg { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE + ::OracleBond::get()); } else { let charlie_balance = AssetManager::free_balance(Asset::Ztg, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE + ::OracleBond::get()); - let charlie_balance = AssetManager::free_balance(base_asset.into(), &CHARLIE); + let charlie_balance = AssetManager::free_balance(base_asset, &CHARLIE); assert_eq!(charlie_balance, 1_000 * BASE); } let charlie_reserved_2 = AssetManager::reserved_balance(Asset::Ztg, &CHARLIE); @@ -470,20 +465,17 @@ fn authorized_correctly_resolves_disputed_market() { assert!(market_after.bonds.oracle.unwrap().is_settled); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn it_resolves_a_disputed_court_market() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let juror_0 = 1000; let juror_1 = 1001; let juror_2 = 1002; @@ -709,18 +701,18 @@ fn it_resolves_a_disputed_court_market() { assert_eq!(free_juror_2_after, free_juror_2_before + juror_2_share * total_slashed); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn outsider_reports_wrong_outcome() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; @@ -795,13 +787,10 @@ fn outsider_reports_wrong_outcome() { assert_eq!(Balances::free_balance(DAVE), dave_balance_before + outcome_bond); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } diff --git a/zrml/prediction-markets/src/tests/manually_close_market.rs b/zrml/prediction-markets/src/tests/manually_close_market.rs index 8af1ee78c..b88cab214 100644 --- a/zrml/prediction-markets/src/tests/manually_close_market.rs +++ b/zrml/prediction-markets/src/tests/manually_close_market.rs @@ -36,7 +36,7 @@ fn manually_close_market_after_long_stall() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -49,7 +49,7 @@ fn manually_close_market_after_long_stall() { )); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -105,7 +105,7 @@ fn manually_close_market_fails_if_market_not_in_close_time_frame_list() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -146,7 +146,7 @@ fn manually_close_market_fails_if_not_allowed_for_block_based_markets() { let end = 5; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Block(0..end), diff --git a/zrml/prediction-markets/src/tests/mod.rs b/zrml/prediction-markets/src/tests/mod.rs index 662ff84f8..95d13c1a8 100644 --- a/zrml/prediction-markets/src/tests/mod.rs +++ b/zrml/prediction-markets/src/tests/mod.rs @@ -22,7 +22,7 @@ mod admin_move_market_to_closed; mod admin_move_market_to_resolved; mod approve_market; mod buy_complete_set; -mod close_market; +mod close_trusted_market; mod create_market; mod create_market_and_deploy_pool; mod dispute; @@ -42,19 +42,19 @@ mod schedule_early_close; mod sell_complete_set; mod start_global_dispute; -use crate::{mock::*, AccountIdOf, BalanceOf, Config, Error, Event, MarketIdsPerDisputeBlock}; -use core::ops::Range; -use frame_support::{ - assert_noop, assert_ok, storage::unhashed::get_or, traits::NamedReservableCurrency, +use crate::{ + mock::*, AccountIdOf, AssetOf, BalanceOf, Config, Error, Event, MarketIdsPerDisputeBlock, }; +use core::ops::Range; +use frame_support::{assert_noop, assert_ok, traits::NamedReservableCurrency}; use orml_traits::MultiCurrency; use sp_arithmetic::Perbill; use sp_runtime::traits::{BlakeTwo256, Hash, Zero}; use zeitgeist_primitives::{ constants::mock::{BASE, CENT}, types::{ - Asset, BaseAsset, Deadlines, MarketCreation, MarketDisputeMechanism, MarketId, - MarketPeriod, MarketStatus, MarketType, MultiHash, OutcomeReport, ScoringRule, + Asset, Deadlines, MarketCreation, MarketDisputeMechanism, MarketId, MarketPeriod, + MarketStatus, MarketType, MultiHash, OutcomeReport, ScoringRule, }, }; use zrml_court::types::VoteItem; @@ -62,35 +62,6 @@ use zrml_market_commons::MarketCommonsPalletApi; const SENTINEL_AMOUNT: u128 = BASE; -impl StateTransitionMock { - pub(super) fn on_proposal_triggered() -> bool { - get_or(&ON_PROPOSAL_STORAGE, false) - } - pub(super) fn on_activation_triggered() -> bool { - get_or(&ON_ACTIVATION_STORAGE, false) - } - pub(super) fn on_closure_triggered() -> bool { - get_or(&ON_CLOSURE_STORAGE, false) - } - pub(super) fn on_report_triggered() -> bool { - get_or(&ON_REPORT_STORAGE, false) - } - pub(super) fn on_dispute_triggered() -> bool { - get_or(&ON_DISPUTE_STORAGE, false) - } - pub(super) fn on_resolution_triggered() -> bool { - get_or(&ON_RESOLUTION_STORAGE, false) - } - pub(super) fn ensure_empty_state() { - assert!(!StateTransitionMock::on_proposal_triggered()); - assert!(!StateTransitionMock::on_activation_triggered()); - assert!(!StateTransitionMock::on_closure_triggered()); - assert!(!StateTransitionMock::on_report_triggered()); - assert!(!StateTransitionMock::on_dispute_triggered()); - assert!(!StateTransitionMock::on_resolution_triggered()); - } -} - fn get_deadlines() -> Deadlines<::BlockNumber> { Deadlines { grace_period: 1_u32.into(), @@ -107,7 +78,7 @@ fn gen_metadata(byte: u8) -> MultiHash { } fn simple_create_categorical_market( - base_asset: BaseAsset, + base_asset: AssetOf, creation: MarketCreation, period: Range, scoring_rule: ScoringRule, @@ -128,7 +99,7 @@ fn simple_create_categorical_market( } fn simple_create_scalar_market( - base_asset: BaseAsset, + base_asset: AssetOf, creation: MarketCreation, period: Range, scoring_rule: ScoringRule, diff --git a/zrml/prediction-markets/src/tests/on_initialize.rs b/zrml/prediction-markets/src/tests/on_initialize.rs index b8c5588c1..b78388fbf 100644 --- a/zrml/prediction-markets/src/tests/on_initialize.rs +++ b/zrml/prediction-markets/src/tests/on_initialize.rs @@ -31,7 +31,7 @@ fn on_initialize_skips_the_genesis_block() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), diff --git a/zrml/prediction-markets/src/tests/on_market_close.rs b/zrml/prediction-markets/src/tests/on_market_close.rs index 866797798..63054872c 100644 --- a/zrml/prediction-markets/src/tests/on_market_close.rs +++ b/zrml/prediction-markets/src/tests/on_market_close.rs @@ -24,7 +24,7 @@ use zeitgeist_primitives::constants::MILLISECS_PER_BLOCK; #[test] fn on_market_close_auto_rejects_expired_advised_market() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond and the OracleBond gets unreserved, when the advised market expires. assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); @@ -60,20 +60,17 @@ fn on_market_close_auto_rejects_expired_advised_market() { System::assert_has_event(Event::MarketExpired(market_id).into()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn on_market_close_auto_rejects_expired_advised_market_with_edit_request() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond and the OracleBond gets unreserved, when the advised market expires. assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); @@ -122,14 +119,11 @@ fn on_market_close_auto_rejects_expired_advised_market_with_edit_request() { System::assert_has_event(Event::MarketExpired(market_id).into()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -140,7 +134,7 @@ fn on_market_close_successfully_auto_closes_market_with_blocks() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Block(0..end), @@ -172,7 +166,7 @@ fn on_market_close_successfully_auto_closes_market_with_timestamps() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -212,7 +206,7 @@ fn on_market_close_successfully_auto_closes_multiple_markets_after_stall() { let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -225,7 +219,7 @@ fn on_market_close_successfully_auto_closes_multiple_markets_after_stall() { )); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -263,7 +257,7 @@ fn on_market_close_market_status_manager_exceeds_max_recovery_time_frames_after_ let category_count = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), @@ -276,7 +270,7 @@ fn on_market_close_market_status_manager_exceeds_max_recovery_time_frames_after_ )); assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), ALICE, MarketPeriod::Timestamp(0..end), diff --git a/zrml/prediction-markets/src/tests/on_resolution.rs b/zrml/prediction-markets/src/tests/on_resolution.rs index 08b965073..7e70a6730 100644 --- a/zrml/prediction-markets/src/tests/on_resolution.rs +++ b/zrml/prediction-markets/src/tests/on_resolution.rs @@ -27,7 +27,7 @@ fn it_correctly_resolves_a_market_that_was_reported_on() { ExtBuilder::default().build().execute_with(|| { let end = 2; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -58,21 +58,22 @@ fn it_correctly_resolves_a_market_that_was_reported_on() { // Check balance of winning outcome asset. let share_b = Asset::CategoricalOutcome(0, 1); - let share_b_total = AssetManager::total_issuance(share_b); + let share_b_total = Tokens::total_issuance(share_b); assert_eq!(share_b_total, CENT); - let share_b_bal = AssetManager::free_balance(share_b, &CHARLIE); + let share_b_bal = Tokens::free_balance(share_b, &CHARLIE); assert_eq!(share_b_bal, CENT); + // TODO(#792): Remove other assets. let share_a = Asset::CategoricalOutcome(0, 0); - let share_a_total = AssetManager::total_issuance(share_a); - assert_eq!(share_a_total, 0); - let share_a_bal = AssetManager::free_balance(share_a, &CHARLIE); - assert_eq!(share_a_bal, 0); + let share_a_total = Tokens::total_issuance(share_a); + assert_eq!(share_a_total, CENT); + let share_a_bal = Tokens::free_balance(share_a, &CHARLIE); + assert_eq!(share_a_bal, CENT); let share_c = Asset::CategoricalOutcome(0, 2); - let share_c_total = AssetManager::total_issuance(share_c); + let share_c_total = Tokens::total_issuance(share_c); assert_eq!(share_c_total, 0); - let share_c_bal = AssetManager::free_balance(share_c, &CHARLIE); + let share_c_bal = Tokens::free_balance(share_c, &CHARLIE); assert_eq!(share_c_bal, 0); assert!(market.bonds.creation.unwrap().is_settled); @@ -84,7 +85,7 @@ fn it_correctly_resolves_a_market_that_was_reported_on() { fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_market_on_oracle_report() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -121,14 +122,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_ma assert_eq!(Balances::free_balance(ALICE), alice_balance_before + OracleBond::get()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -136,7 +134,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_ma fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_market_on_outsider_report() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -173,14 +171,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_ma assert_eq!(Balances::free_balance(ALICE), alice_balance_before); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -189,7 +184,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark { // Oracle reports in time but incorrect report, so OracleBond gets slashed on resolution // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -227,14 +222,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark assert_eq!(Balances::free_balance(ALICE), alice_balance_before + ValidityBond::get()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -243,7 +235,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_ma { // Oracle reports in time but incorrect report, so OracleBond gets slashed on resolution // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -285,14 +277,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_approved_advised_ma assert_eq!(Balances::free_balance(ALICE), alice_balance_before); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -301,7 +290,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark { // Oracle reports in time and correct report, so OracleBond does not get slashed on resolution // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -348,14 +337,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -364,7 +350,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_advised_approved_ma { // Oracle reports in time and correct report, so OracleBond does not get slashed on resolution // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -412,14 +398,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_advised_approved_ma assert_eq!(Balances::free_balance(ALICE), alice_balance_before + OracleBond::get()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -428,7 +411,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark { // Oracle does not report in time, so OracleBond gets slashed on resolution // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -487,14 +470,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -503,7 +483,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_advised_approved_ma { // Oracle does not report in time, so OracleBond gets slashed on resolution // NOTE: Bonds are always in ZTG - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -565,14 +545,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_advised_approved_ma ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -582,7 +559,7 @@ fn trusted_market_complete_lifecycle() { let end = 3; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -629,7 +606,7 @@ fn trusted_market_complete_lifecycle() { fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_market_on_oracle_report() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -663,14 +640,11 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -678,7 +652,7 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_market_on_outsider_report() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { reserve_sentinel_amounts(); let end = 100; assert_ok!(PredictionMarkets::create_market( @@ -737,42 +711,10 @@ fn on_resolution_correctly_reserves_and_unreserves_bonds_for_permissionless_mark assert!(market.bonds.outsider.unwrap().is_settled); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); - }); -} - -#[test] -fn does_trigger_market_transition_api() { - ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - let end = 3; - assert_ok!(PredictionMarkets::create_market( - RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, - Perbill::zero(), - BOB, - MarketPeriod::Block(0..end), - Deadlines { - grace_period: 0, - oracle_duration: ::MinOracleDuration::get(), - dispute_duration: Zero::zero(), - }, - gen_metadata(0x99), - MarketCreation::Permissionless, - MarketType::Categorical(3), - None, - ScoringRule::AmmCdaHybrid, - )); - run_to_block(end); - let outcome = OutcomeReport::Categorical(1); - assert_ok!(PredictionMarkets::report(RuntimeOrigin::signed(BOB), 0, outcome.clone())); - assert!(StateTransitionMock::on_resolution_triggered()); + test(Asset::ForeignAsset(100)); }); } diff --git a/zrml/prediction-markets/src/tests/redeem_shares.rs b/zrml/prediction-markets/src/tests/redeem_shares.rs index c71921add..f95511119 100644 --- a/zrml/prediction-markets/src/tests/redeem_shares.rs +++ b/zrml/prediction-markets/src/tests/redeem_shares.rs @@ -27,7 +27,7 @@ use zeitgeist_primitives::types::{OutcomeReport, ScalarPosition}; #[test] fn it_allows_to_redeem_shares() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let end = 2; simple_create_categorical_market( base_asset, @@ -58,20 +58,17 @@ fn it_allows_to_redeem_shares() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test_case(ScoringRule::Parimutuel; "parimutuel")] fn redeem_shares_fails_if_invalid_resolution_mechanism(scoring_rule: ScoringRule) { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { let end = 2; simple_create_categorical_market( base_asset, @@ -91,57 +88,48 @@ fn redeem_shares_fails_if_invalid_resolution_mechanism(scoring_rule: ScoringRule ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn scalar_market_correctly_resolves_on_out_of_range_outcomes_below_threshold() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { scalar_market_correctly_resolves_common(base_asset, 50); - assert_eq!(AssetManager::free_balance(base_asset.into(), &CHARLIE), 900 * BASE); - assert_eq!(AssetManager::free_balance(base_asset.into(), &EVE), 1100 * BASE); + assert_eq!(AssetManager::free_balance(base_asset, &CHARLIE), 900 * BASE); + assert_eq!(AssetManager::free_balance(base_asset, &EVE), 1100 * BASE); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test] fn scalar_market_correctly_resolves_on_out_of_range_outcomes_above_threshold() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { scalar_market_correctly_resolves_common(base_asset, 250); - assert_eq!(AssetManager::free_balance(base_asset.into(), &CHARLIE), 1000 * BASE); - assert_eq!(AssetManager::free_balance(base_asset.into(), &EVE), 1000 * BASE); + assert_eq!(AssetManager::free_balance(base_asset, &CHARLIE), 1000 * BASE); + assert_eq!(AssetManager::free_balance(base_asset, &EVE), 1000 * BASE); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } // Common code of `scalar_market_correctly_resolves_*` -fn scalar_market_correctly_resolves_common(base_asset: BaseAsset, reported_value: u128) { +fn scalar_market_correctly_resolves_common(base_asset: AssetOf, reported_value: u128) { let end = 100; simple_create_scalar_market( base_asset, @@ -150,7 +138,7 @@ fn scalar_market_correctly_resolves_common(base_asset: BaseAsset, reported_value ScoringRule::AmmCdaHybrid, ); assert_ok!(PredictionMarkets::buy_complete_set(RuntimeOrigin::signed(CHARLIE), 0, 100 * BASE)); - assert_ok!(AssetManager::transfer( + assert_ok!(Tokens::transfer( RuntimeOrigin::signed(CHARLIE), EVE, Asset::ScalarOutcome(0, ScalarPosition::Short), @@ -179,15 +167,15 @@ fn scalar_market_correctly_resolves_common(base_asset: BaseAsset, reported_value // Check balances before redeeming (just to make sure that our tests are based on correct // assumptions)! - assert_eq!(AssetManager::free_balance(base_asset.into(), &CHARLIE), 900 * BASE); - assert_eq!(AssetManager::free_balance(base_asset.into(), &EVE), 1000 * BASE); + assert_eq!(AssetManager::free_balance(base_asset, &CHARLIE), 900 * BASE); + assert_eq!(AssetManager::free_balance(base_asset, &EVE), 1000 * BASE); assert_ok!(PredictionMarkets::redeem_shares(RuntimeOrigin::signed(CHARLIE), 0)); assert_ok!(PredictionMarkets::redeem_shares(RuntimeOrigin::signed(EVE), 0)); let market = &MarketCommons::market(&0).unwrap(); let assets = market.outcome_assets(); for asset in assets.iter() { - assert_eq!(AssetManager::free_balance((*asset).into(), &CHARLIE), 0); - assert_eq!(AssetManager::free_balance((*asset).into(), &EVE), 0); + assert_eq!(AssetManager::free_balance(*asset, &CHARLIE), 0); + assert_eq!(AssetManager::free_balance(*asset, &EVE), 0); } } diff --git a/zrml/prediction-markets/src/tests/reject_early_close.rs b/zrml/prediction-markets/src/tests/reject_early_close.rs index e4b0de19c..fc40098c6 100644 --- a/zrml/prediction-markets/src/tests/reject_early_close.rs +++ b/zrml/prediction-markets/src/tests/reject_early_close.rs @@ -29,7 +29,7 @@ fn reject_early_close_emits_event() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -58,7 +58,7 @@ fn reject_early_close_fails_if_state_is_scheduled_as_market_creator() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -89,7 +89,7 @@ fn reject_early_close_fails_if_state_is_rejected() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -126,7 +126,7 @@ fn reject_early_close_resets_to_old_market_period() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -170,7 +170,7 @@ fn reject_early_close_settles_bonds() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), diff --git a/zrml/prediction-markets/src/tests/reject_market.rs b/zrml/prediction-markets/src/tests/reject_market.rs index 3af2f2a74..462d794df 100644 --- a/zrml/prediction-markets/src/tests/reject_market.rs +++ b/zrml/prediction-markets/src/tests/reject_market.rs @@ -27,7 +27,7 @@ use crate::{MarketIdsForEdit, MarketIdsPerCloseBlock}; fn it_allows_the_advisory_origin_to_reject_markets() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 4..6, ScoringRule::AmmCdaHybrid, @@ -58,7 +58,7 @@ fn reject_errors_if_reject_reason_is_too_long() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -86,7 +86,7 @@ fn it_allows_the_advisory_origin_to_reject_markets_with_edit_request() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, @@ -122,7 +122,7 @@ fn it_allows_the_advisory_origin_to_reject_markets_with_edit_request() { #[test] fn reject_market_unreserves_oracle_bond_and_slashes_advisory_bond() { // NOTE: Bonds are always in ZTG, irrespective of base_asset. - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { simple_create_categorical_market( base_asset, MarketCreation::Advised, @@ -179,14 +179,11 @@ fn reject_market_unreserves_oracle_bond_and_slashes_advisory_bond() { assert_eq!(balance_treasury_after, slash_amount_advisory_bond); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -196,19 +193,19 @@ fn reject_market_clears_auto_close_blocks() { // can not be deployed on pending advised pools. ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 33..66, ScoringRule::AmmCdaHybrid, ); simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 22..66, ScoringRule::AmmCdaHybrid, ); simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 22..33, ScoringRule::AmmCdaHybrid, @@ -232,7 +229,7 @@ fn reject_market_fails_on_permissionless_market() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, ScoringRule::AmmCdaHybrid, @@ -255,7 +252,7 @@ fn reject_market_fails_on_approved_market() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, diff --git a/zrml/prediction-markets/src/tests/report.rs b/zrml/prediction-markets/src/tests/report.rs index 34f5e72d6..0cd5fe807 100644 --- a/zrml/prediction-markets/src/tests/report.rs +++ b/zrml/prediction-markets/src/tests/report.rs @@ -18,7 +18,6 @@ use super::*; -use test_case::test_case; use zeitgeist_primitives::{constants::MILLISECS_PER_BLOCK, types::OutcomeReport}; // TODO(#1239) MarketDoesNotExist @@ -33,7 +32,7 @@ fn it_allows_to_report_the_outcome_of_a_market() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -66,7 +65,7 @@ fn report_fails_before_grace_period_is_over() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -92,7 +91,7 @@ fn it_allows_only_oracle_to_report_the_outcome_of_a_market_during_oracle_duratio ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -134,7 +133,7 @@ fn it_allows_only_oracle_to_report_the_outcome_of_a_market_during_oracle_duratio ExtBuilder::default().build().execute_with(|| { assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..100_000_000), @@ -175,7 +174,7 @@ fn report_fails_on_mismatched_outcome_for_categorical_market() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -198,7 +197,7 @@ fn report_fails_on_out_of_range_outcome_for_categorical_market() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -221,7 +220,7 @@ fn report_fails_on_mismatched_outcome_for_scalar_market() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_scalar_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -244,7 +243,7 @@ fn it_allows_anyone_to_report_an_unreported_market() { ExtBuilder::default().build().execute_with(|| { let end = 2; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -282,7 +281,7 @@ fn report_fails_on_market_state_proposed() { ExtBuilder::default().build().execute_with(|| { assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..100_000_000), @@ -305,7 +304,7 @@ fn report_fails_on_market_state_closed_for_advised_market() { ExtBuilder::default().build().execute_with(|| { assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..100_000_000), @@ -328,7 +327,7 @@ fn report_fails_on_market_state_active() { ExtBuilder::default().build().execute_with(|| { assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..100_000_000), @@ -351,7 +350,7 @@ fn report_fails_on_market_state_resolved() { ExtBuilder::default().build().execute_with(|| { assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(0..100_000_000), @@ -373,38 +372,35 @@ fn report_fails_on_market_state_resolved() { }); } -#[test_case(Some(MarketDisputeMechanism::SimpleDisputes); "with_dispute_mechanism")] -#[test_case(None; "without_dispute_mechanism")] -fn does_trigger_market_transition_api(dispute_mechanism: Option) { +#[test] +fn report_fails_if_reporter_is_not_the_oracle() { ExtBuilder::default().build().execute_with(|| { - StateTransitionMock::ensure_empty_state(); - let mut deadlines = get_deadlines(); - - if dispute_mechanism.is_none() { - deadlines.dispute_duration = Zero::zero(); - } - assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, - MarketPeriod::Block(0..2), - deadlines, + MarketPeriod::Timestamp(0..100_000_000), + get_deadlines(), gen_metadata(2), MarketCreation::Permissionless, MarketType::Categorical(2), - dispute_mechanism, + Some(MarketDisputeMechanism::SimpleDisputes), ScoringRule::AmmCdaHybrid, )); - let market = MarketCommons::market(&0).unwrap(); - run_to_block(2 + market.deadlines.grace_period + market.deadlines.oracle_duration + 1); - assert_ok!(PredictionMarkets::report( - RuntimeOrigin::signed(BOB), - 0, - OutcomeReport::Categorical(1) - )); - assert!(StateTransitionMock::on_report_triggered()); + set_timestamp_for_on_initialize(100_000_000); + // Trigger hooks which close the market. + run_to_block(2); + let grace_period: u64 = market.deadlines.grace_period * MILLISECS_PER_BLOCK as u64; + set_timestamp_for_on_initialize(100_000_000 + grace_period + MILLISECS_PER_BLOCK as u64); + assert_noop!( + PredictionMarkets::report( + RuntimeOrigin::signed(CHARLIE), + 0, + OutcomeReport::Categorical(1) + ), + Error::::ReporterNotOracle, + ); }); } diff --git a/zrml/prediction-markets/src/tests/request_edit.rs b/zrml/prediction-markets/src/tests/request_edit.rs index 3736f06c9..fb09532a1 100644 --- a/zrml/prediction-markets/src/tests/request_edit.rs +++ b/zrml/prediction-markets/src/tests/request_edit.rs @@ -27,7 +27,7 @@ use sp_runtime::DispatchError; fn it_allows_request_edit_origin_to_request_edits_for_markets() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 2..4, ScoringRule::AmmCdaHybrid, @@ -68,7 +68,7 @@ fn request_edit_fails_on_bad_origin() { frame_system::Pallet::::set_block_number(1); // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 2..4, ScoringRule::AmmCdaHybrid, @@ -92,7 +92,7 @@ fn edit_request_fails_if_edit_reason_is_too_long() { ExtBuilder::default().build().execute_with(|| { // Creates an advised market. simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Advised, 0..2, ScoringRule::AmmCdaHybrid, diff --git a/zrml/prediction-markets/src/tests/schedule_early_close.rs b/zrml/prediction-markets/src/tests/schedule_early_close.rs index 3709df23e..2e3886235 100644 --- a/zrml/prediction-markets/src/tests/schedule_early_close.rs +++ b/zrml/prediction-markets/src/tests/schedule_early_close.rs @@ -36,7 +36,7 @@ fn schedule_early_close_emits_event() { ExtBuilder::default().build().execute_with(|| { let end = 100; simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..end, ScoringRule::AmmCdaHybrid, @@ -71,7 +71,7 @@ fn sudo_schedule_early_close_at_block_works() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -143,7 +143,7 @@ fn sudo_schedule_early_close_at_timeframe_works() { let end = start + (42 * MILLISECS_PER_BLOCK) as u64; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(start..end), @@ -213,7 +213,7 @@ fn schedule_early_close_block_fails_if_early_close_request_too_late() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), @@ -245,7 +245,7 @@ fn schedule_early_close_timestamp_fails_if_early_close_request_too_late() { let end = start + (42 * MILLISECS_PER_BLOCK) as u64; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Timestamp(start..end), @@ -274,7 +274,7 @@ fn schedule_early_close_as_market_creator_works() { let end = 100; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..end), diff --git a/zrml/prediction-markets/src/tests/sell_complete_set.rs b/zrml/prediction-markets/src/tests/sell_complete_set.rs index a2ed720b2..899b3f3c0 100644 --- a/zrml/prediction-markets/src/tests/sell_complete_set.rs +++ b/zrml/prediction-markets/src/tests/sell_complete_set.rs @@ -23,7 +23,7 @@ use test_case::test_case; #[test_case(ScoringRule::AmmCdaHybrid)] fn sell_complete_set_works(scoring_rule: ScoringRule) { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { simple_create_categorical_market( base_asset, MarketCreation::Permissionless, @@ -51,24 +51,21 @@ fn sell_complete_set_works(scoring_rule: ScoringRule) { let market = MarketCommons::market(&market_id).unwrap(); let assets = market.outcome_assets(); for asset in assets.iter() { - let bal = AssetManager::free_balance((*asset).into(), &who); + let bal = AssetManager::free_balance(*asset, &who); assert_eq!(bal, expected_amount); } - let bal = AssetManager::free_balance(base_asset.into(), &who); + let bal = AssetManager::free_balance(base_asset, &who); assert_eq!(bal, 1_000 * BASE - expected_amount); System::assert_last_event(Event::SoldCompleteSet(market_id, sell_amount, who).into()); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } @@ -76,7 +73,7 @@ fn sell_complete_set_works(scoring_rule: ScoringRule) { fn sell_complete_set_fails_on_zero_amount() { ExtBuilder::default().build().execute_with(|| { simple_create_categorical_market( - BaseAsset::Ztg, + Asset::Ztg, MarketCreation::Permissionless, 0..2, ScoringRule::AmmCdaHybrid, @@ -90,7 +87,7 @@ fn sell_complete_set_fails_on_zero_amount() { #[test] fn sell_complete_set_fails_on_insufficient_share_balance() { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { simple_create_categorical_market( base_asset, MarketCreation::Permissionless, @@ -112,20 +109,17 @@ fn sell_complete_set_fails_on_insufficient_share_balance() { ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } #[test_case(ScoringRule::Parimutuel; "parimutuel")] fn sell_complete_set_fails_if_market_has_wrong_scoring_rule(scoring_rule: ScoringRule) { - let test = |base_asset: BaseAsset| { + let test = |base_asset: AssetOf| { simple_create_categorical_market( base_asset, MarketCreation::Permissionless, @@ -138,13 +132,10 @@ fn sell_complete_set_fails_if_market_has_wrong_scoring_rule(scoring_rule: Scorin ); }; ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::CampaignAsset(100)); - }); - ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::Ztg); + test(Asset::Ztg); }); #[cfg(feature = "parachain")] ExtBuilder::default().build().execute_with(|| { - test(BaseAsset::ForeignAsset(100)); + test(Asset::ForeignAsset(100)); }); } diff --git a/zrml/prediction-markets/src/tests/start_global_dispute.rs b/zrml/prediction-markets/src/tests/start_global_dispute.rs index b87ed6ac8..2ed871296 100644 --- a/zrml/prediction-markets/src/tests/start_global_dispute.rs +++ b/zrml/prediction-markets/src/tests/start_global_dispute.rs @@ -33,7 +33,7 @@ fn start_global_dispute_fails_on_wrong_mdm() { let end = 2; assert_ok!(PredictionMarkets::create_market( RuntimeOrigin::signed(ALICE), - BaseAsset::Ztg, + Asset::Ztg, Perbill::zero(), BOB, MarketPeriod::Block(0..2), diff --git a/zrml/prediction-markets/src/weights.rs b/zrml/prediction-markets/src/weights.rs index 5ac4c5a91..fb9b4d4cc 100644 --- a/zrml/prediction-markets/src/weights.rs +++ b/zrml/prediction-markets/src/weights.rs @@ -238,10 +238,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:64 w:64) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: MarketAssets Account (r:64 w:64) - /// Proof: MarketAssets Account (max_values: None, max_size: Some(117), added: 2592, mode: MaxEncodedLen) /// The range of component `a` is `[2, 64]`. fn buy_complete_set(a: u32) -> Weight { // Proof Size summary in bytes: @@ -272,14 +268,14 @@ impl WeightInfoZeitgeist for WeightInfo { /// The range of component `m` is `[0, 63]`. fn create_market(m: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `316 + m * (16 ±0)` - // Estimated: `181063` - // Minimum execution time: 580_722 nanoseconds. - Weight::from_parts(746_949_580, 181063) - // Standard Error: 134_673 - .saturating_add(Weight::from_parts(95_879, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(68)) - .saturating_add(T::DbWeight::get().writes(68)) + // Measured: `240 + m * (16 ±0)` + // Estimated: `8263` + // Minimum execution time: 55_550 nanoseconds. + Weight::from_parts(74_259_340, 8263) + // Standard Error: 7_534 + .saturating_add(Weight::from_parts(63_015, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: PredictionMarkets MarketIdsForEdit (r:1 w:1) /// Proof: PredictionMarkets MarketIdsForEdit (max_values: None, max_size: Some(1050), added: 3525, mode: MaxEncodedLen) @@ -290,14 +286,12 @@ impl WeightInfoZeitgeist for WeightInfo { /// Storage: Timestamp Now (r:1 w:0) /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) /// The range of component `m` is `[0, 63]`. - fn edit_market(m: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `751 + m * (16 ±0)` - // Estimated: `10720` - // Minimum execution time: 56_321 nanoseconds. - Weight::from_parts(74_197_986, 10720) - // Standard Error: 12_078 - .saturating_add(Weight::from_parts(99_545, 0).saturating_mul(m.into())) + fn edit_market(_m: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `735 + m * (16 ±0)` + // Estimated: `10706` + // Minimum execution time: 53_490 nanoseconds. + Weight::from_parts(75_146_182, 10706) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -462,11 +456,6 @@ impl WeightInfoZeitgeist for WeightInfo { .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:1 w:1) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: MarketAssets Account (r:1 w:1) - /// Proof: MarketAssets Account (max_values: None, max_size: Some(117), added: 2592, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) /// Storage: AssetRouter DestroyAssets (r:1 w:1) @@ -485,11 +474,6 @@ impl WeightInfoZeitgeist for WeightInfo { .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: MarketCommons Markets (r:1 w:0) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:2) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: MarketAssets Account (r:2 w:2) - /// Proof: MarketAssets Account (max_values: None, max_size: Some(117), added: 2592, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) /// Storage: AssetRouter DestroyAssets (r:1 w:1) @@ -573,10 +557,6 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:1) /// Proof: System Account (max_values: None, max_size: Some(132), added: 2607, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:64 w:64) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) - /// Storage: MarketAssets Account (r:64 w:64) - /// Proof: MarketAssets Account (max_values: None, max_size: Some(117), added: 2592, mode: MaxEncodedLen) /// The range of component `a` is `[2, 64]`. fn sell_complete_set(a: u32) -> Weight { // Proof Size summary in bytes: @@ -650,14 +630,16 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: PredictionMarkets MarketIdsPerCloseTimeFrame (max_values: None, max_size: Some(1050), added: 3525, mode: MaxEncodedLen) /// The range of component `o` is `[0, 63]`. /// The range of component `n` is `[0, 63]`. - fn schedule_early_close_as_authority(o: u32, _n: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `763 + o * (16 ±0)` - // Estimated: `10720` - // Minimum execution time: 53_380 nanoseconds. - Weight::from_parts(69_829_159, 10720) - // Standard Error: 9_438 - .saturating_add(Weight::from_parts(58_622, 0).saturating_mul(o.into())) + fn schedule_early_close_as_authority(o: u32, n: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `747 + o * (16 ±0)` + // Estimated: `10706` + // Minimum execution time: 51_230 nanoseconds. + Weight::from_parts(61_363_456, 10706) + // Standard Error: 13_970 + .saturating_add(Weight::from_parts(50_244, 0).saturating_mul(o.into())) + // Standard Error: 13_970 + .saturating_add(Weight::from_parts(62_184, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -671,12 +653,16 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: PredictionMarkets MarketIdsPerCloseTimeFrame (max_values: None, max_size: Some(1050), added: 3525, mode: MaxEncodedLen) /// The range of component `o` is `[0, 63]`. /// The range of component `n` is `[0, 63]`. - fn schedule_early_close_after_dispute(_o: u32, _n: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `986 + o * (16 ±0)` - // Estimated: `14444` - // Minimum execution time: 98_240 nanoseconds. - Weight::from_parts(129_586_211, 14444) + fn schedule_early_close_after_dispute(o: u32, n: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `970 + o * (16 ±0)` + // Estimated: `14430` + // Minimum execution time: 96_271 nanoseconds. + Weight::from_parts(119_475_237, 14430) + // Standard Error: 22_292 + .saturating_add(Weight::from_parts(90_541, 0).saturating_mul(o.into())) + // Standard Error: 22_292 + .saturating_add(Weight::from_parts(12_780, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -692,14 +678,14 @@ impl WeightInfoZeitgeist for WeightInfo { /// The range of component `n` is `[0, 63]`. fn schedule_early_close_as_market_creator(o: u32, n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `824 + o * (16 ±0)` - // Estimated: `14444` - // Minimum execution time: 75_620 nanoseconds. - Weight::from_parts(92_020_605, 14444) - // Standard Error: 13_677 - .saturating_add(Weight::from_parts(115_579, 0).saturating_mul(o.into())) - // Standard Error: 13_677 - .saturating_add(Weight::from_parts(28_959, 0).saturating_mul(n.into())) + // Measured: `808 + o * (16 ±0)` + // Estimated: `14430` + // Minimum execution time: 74_650 nanoseconds. + Weight::from_parts(92_510_070, 14430) + // Standard Error: 11_870 + .saturating_add(Weight::from_parts(29_343, 0).saturating_mul(o.into())) + // Standard Error: 11_870 + .saturating_add(Weight::from_parts(37_672, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -713,14 +699,16 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: PredictionMarkets MarketIdsPerCloseTimeFrame (max_values: None, max_size: Some(1050), added: 3525, mode: MaxEncodedLen) /// The range of component `o` is `[0, 63]`. /// The range of component `n` is `[0, 63]`. - fn dispute_early_close(_o: u32, n: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `940 + o * (16 ±0) + n * (16 ±0)` - // Estimated: `14444` - // Minimum execution time: 72_551 nanoseconds. - Weight::from_parts(96_247_822, 14444) - // Standard Error: 11_213 - .saturating_add(Weight::from_parts(22_013, 0).saturating_mul(n.into())) + fn dispute_early_close(o: u32, n: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `924 + o * (16 ±0) + n * (16 ±0)` + // Estimated: `14430` + // Minimum execution time: 71_610 nanoseconds. + Weight::from_parts(86_696_361, 14430) + // Standard Error: 13_050 + .saturating_add(Weight::from_parts(59_792, 0).saturating_mul(o.into())) + // Standard Error: 13_050 + .saturating_add(Weight::from_parts(64_792, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -732,12 +720,16 @@ impl WeightInfoZeitgeist for WeightInfo { /// Proof: PredictionMarkets MarketIdsPerCloseTimeFrame (max_values: None, max_size: Some(1050), added: 3525, mode: MaxEncodedLen) /// The range of component `o` is `[0, 63]`. /// The range of component `n` is `[0, 63]`. - fn reject_early_close_after_authority(_o: u32, _n: u32) -> Weight { - // Proof Size summary in bytes: - // Measured: `830 + o * (16 ±0) + n * (16 ±0)` - // Estimated: `10720` - // Minimum execution time: 57_031 nanoseconds. - Weight::from_parts(75_086_876, 10720) + fn reject_early_close_after_authority(o: u32, n: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `814 + o * (16 ±0) + n * (16 ±0)` + // Estimated: `10706` + // Minimum execution time: 55_950 nanoseconds. + Weight::from_parts(70_714_615, 10706) + // Standard Error: 14_905 + .saturating_add(Weight::from_parts(63_828, 0).saturating_mul(o.into())) + // Standard Error: 14_905 + .saturating_add(Weight::from_parts(40_198, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -805,7 +797,6 @@ impl WeightInfoZeitgeist for WeightInfo { .saturating_add(Weight::from_parts(0, 7884).saturating_mul(n.into())) } /// Storage: MarketCommons Markets (r:1 w:1) - /// Proof: MarketCommons Markets (max_values: None, max_size: Some(692), added: 3167, mode: MaxEncodedLen) /// Storage: Timestamp Now (r:1 w:0) /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) /// Storage: PredictionMarkets MarketIdsPerCloseTimeFrame (r:1 w:1) diff --git a/zrml/simple-disputes/src/lib.rs b/zrml/simple-disputes/src/lib.rs index ba02d764b..2a3401e5c 100644 --- a/zrml/simple-disputes/src/lib.rs +++ b/zrml/simple-disputes/src/lib.rs @@ -33,7 +33,7 @@ pub use simple_disputes_pallet_api::SimpleDisputesPalletApi; use zeitgeist_primitives::{ traits::{DisputeApi, DisputeMaxWeightApi, DisputeResolutionApi}, types::{ - BaseAsset, GlobalDisputeItem, Market, MarketDispute, MarketDisputeMechanism, MarketStatus, + GlobalDisputeItem, Market, MarketDispute, MarketDisputeMechanism, MarketStatus, OutcomeReport, Report, ResultWithWeightInfo, }, }; @@ -115,7 +115,6 @@ mod pallet { BalanceOf, ::BlockNumber, MomentOf, - BaseAsset, MarketIdOf, >; pub(crate) type DisputesOf = BoundedVec< @@ -554,11 +553,11 @@ where { use frame_support::traits::Get; use sp_runtime::{traits::AccountIdConversion, SaturatedConversion}; - use zeitgeist_primitives::types::{MarketBonds, ScoringRule}; + use zeitgeist_primitives::types::{Asset, MarketBonds, ScoringRule}; zeitgeist_primitives::types::Market { market_id: Default::default(), - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: zeitgeist_primitives::types::MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: T::PalletId::get().into_account_truncating(), diff --git a/zrml/simple-disputes/src/mock.rs b/zrml/simple-disputes/src/mock.rs index b74e497f0..4d1d40cdb 100644 --- a/zrml/simple-disputes/src/mock.rs +++ b/zrml/simple-disputes/src/mock.rs @@ -30,13 +30,13 @@ use sp_runtime::{ }; use zeitgeist_primitives::{ constants::mock::{ - BlockHashCount, ExistentialDepositsAssets, GetNativeCurrencyId, MaxDisputes, MaxReserves, + BlockHashCount, ExistentialDeposits, GetNativeCurrencyId, MaxDisputes, MaxReserves, MinimumPeriod, OutcomeBond, OutcomeFactor, SimpleDisputesPalletId, BASE, }, traits::{DisputeResolutionApi, MarketOfDisputeResolutionApi}, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, Hash, - Index, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, CurrencyId, + Hash, Index, MarketId, Moment, UncheckedExtrinsicTest, }, }; @@ -165,10 +165,10 @@ impl orml_currencies::Config for Runtime { impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Assets; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = Everything; type RuntimeEvent = (); - type ExistentialDeposits = ExistentialDepositsAssets; + type ExistentialDeposits = ExistentialDeposits; type MaxLocks = (); type MaxReserves = MaxReserves; type CurrencyHooks = (); diff --git a/zrml/simple-disputes/src/tests.rs b/zrml/simple-disputes/src/tests.rs index d8d51098c..fe0b7cfe0 100644 --- a/zrml/simple-disputes/src/tests.rs +++ b/zrml/simple-disputes/src/tests.rs @@ -27,14 +27,14 @@ use zeitgeist_primitives::{ constants::mock::{OutcomeBond, OutcomeFactor}, traits::DisputeApi, types::{ - BaseAsset, Deadlines, Market, MarketBonds, MarketCreation, MarketDispute, + Asset, Deadlines, Market, MarketBonds, MarketCreation, MarketDispute, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, OutcomeReport, ScoringRule, }, }; const DEFAULT_MARKET: MarketOf = Market { market_id: 0, - base_asset: BaseAsset::Ztg, + base_asset: Asset::Ztg, creation: MarketCreation::Permissionless, creator_fee: sp_runtime::Perbill::zero(), creator: 0, diff --git a/zrml/swaps/Cargo.toml b/zrml/swaps/Cargo.toml index 2437f503c..a999bf4e6 100644 --- a/zrml/swaps/Cargo.toml +++ b/zrml/swaps/Cargo.toml @@ -2,7 +2,6 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } -orml-tokens = { workspace = true } orml-traits = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } @@ -15,6 +14,7 @@ zeitgeist-primitives = { workspace = true } env_logger = { workspace = true, optional = true } orml-currencies = { workspace = true, optional = true } +orml-tokens = { workspace = true, optional = true } pallet-balances = { workspace = true, optional = true } pallet-timestamp = { workspace = true, optional = true } sp-api = { workspace = true, optional = true } @@ -32,6 +32,7 @@ zrml-swaps = { workspace = true, features = ["mock"] } default = ["std"] mock = [ "orml-currencies/default", + "orml-tokens/default", "pallet-balances/default", "pallet-timestamp/default", "sp-api/default", @@ -51,7 +52,6 @@ std = [ "frame-benchmarking?/std", "frame-support/std", "frame-system/std", - "orml-tokens/default", "orml-traits/std", "parity-scale-codec/std", "sp-runtime/std", diff --git a/zrml/swaps/fuzz/create_pool.rs b/zrml/swaps/fuzz/create_pool.rs index 932212420..4e7470e87 100644 --- a/zrml/swaps/fuzz/create_pool.rs +++ b/zrml/swaps/fuzz/create_pool.rs @@ -18,14 +18,13 @@ #![no_main] +mod utils; + use libfuzzer_sys::fuzz_target; +use utils::{construct_asset, PoolCreationData}; use zeitgeist_primitives::traits::Swaps as SwapsTrait; - use zrml_swaps::mock::{ExtBuilder, Swaps}; -mod utils; -use utils::{construct_asset, PoolCreationData}; - fuzz_target!(|data: PoolCreationData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { diff --git a/zrml/swaps/fuzz/pool_exit.rs b/zrml/swaps/fuzz/pool_exit.rs index 7f595412b..0645a4750 100644 --- a/zrml/swaps/fuzz/pool_exit.rs +++ b/zrml/swaps/fuzz/pool_exit.rs @@ -1,4 +1,4 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. @@ -18,22 +18,20 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{ExtBuilder, RuntimeOrigin, Swaps}; - mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; use utils::{construct_asset, GeneralPoolData}; -use zeitgeist_primitives::types::Asset; -use zrml_swaps::mock::AssetManager; +use zeitgeist_primitives::types::{Asset, SerdeWrapper}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: GeneralPoolData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, data.pool_creation.amount, @@ -42,7 +40,11 @@ fuzz_target!(|data: GeneralPoolData| { let pool_creator = data.pool_creation.origin; let pool_id = data.pool_creation.create_pool(); // to exit a pool, origin also needs to have the pool tokens of the pool that they're exiting - let _ = AssetManager::deposit(Asset::PoolShare(pool_id), &pool_creator, data.pool_amount); + let _ = Currencies::deposit( + Asset::PoolShare(SerdeWrapper(pool_id)), + &pool_creator, + data.pool_amount, + ); let _ = Swaps::pool_exit( RuntimeOrigin::signed(data.origin), pool_id, diff --git a/zrml/swaps/fuzz/pool_exit_with_exact_asset_amount.rs b/zrml/swaps/fuzz/pool_exit_with_exact_asset_amount.rs index 11f3c60f9..e86ed4dec 100644 --- a/zrml/swaps/fuzz/pool_exit_with_exact_asset_amount.rs +++ b/zrml/swaps/fuzz/pool_exit_with_exact_asset_amount.rs @@ -1,4 +1,4 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. @@ -18,23 +18,20 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{ExtBuilder, RuntimeOrigin, Swaps}; - mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; use utils::{construct_asset, ExactAssetAmountData}; -use zrml_swaps::mock::AssetManager; - -use zeitgeist_primitives::types::Asset; +use zeitgeist_primitives::types::{Asset, SerdeWrapper}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: ExactAssetAmountData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, data.pool_creation.amount, @@ -44,7 +41,11 @@ fuzz_target!(|data: ExactAssetAmountData| { let pool_creator = data.pool_creation.origin; let pool_id = data.pool_creation.create_pool(); // to exit a pool, origin also needs to have the pool tokens of the pool that they're exiting - let _ = AssetManager::deposit(Asset::PoolShare(pool_id), &pool_creator, data.pool_amount); + let _ = Currencies::deposit( + Asset::PoolShare(SerdeWrapper(pool_id)), + &pool_creator, + data.pool_amount, + ); let _ = Swaps::pool_exit_with_exact_asset_amount( RuntimeOrigin::signed(data.origin), pool_id, diff --git a/zrml/swaps/fuzz/pool_exit_with_exact_pool_amount.rs b/zrml/swaps/fuzz/pool_exit_with_exact_pool_amount.rs index 072fd3a42..2fd939c78 100644 --- a/zrml/swaps/fuzz/pool_exit_with_exact_pool_amount.rs +++ b/zrml/swaps/fuzz/pool_exit_with_exact_pool_amount.rs @@ -1,4 +1,4 @@ -// Copyright 2023-2024 Forecasting Technologies LTD. +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. @@ -18,22 +18,20 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{ExtBuilder, RuntimeOrigin, Swaps}; - mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; use utils::{construct_asset, ExactAmountData}; -use zeitgeist_primitives::types::Asset; -use zrml_swaps::mock::AssetManager; +use zeitgeist_primitives::types::{Asset, SerdeWrapper}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: ExactAmountData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, data.pool_creation.amount, @@ -43,7 +41,11 @@ fuzz_target!(|data: ExactAmountData| { let pool_creator = data.pool_creation.origin; let pool_id = data.pool_creation.create_pool(); // to exit a pool, origin also needs to have the pool tokens of the pool that they're exiting - let _ = AssetManager::deposit(Asset::PoolShare(pool_id), &pool_creator, data.pool_amount); + let _ = Currencies::deposit( + Asset::PoolShare(SerdeWrapper(pool_id)), + &pool_creator, + data.pool_amount, + ); let _ = Swaps::pool_exit_with_exact_pool_amount( RuntimeOrigin::signed(data.origin), pool_id, diff --git a/zrml/swaps/fuzz/pool_join.rs b/zrml/swaps/fuzz/pool_join.rs index 76a1bf87c..27023affa 100644 --- a/zrml/swaps/fuzz/pool_join.rs +++ b/zrml/swaps/fuzz/pool_join.rs @@ -17,22 +17,19 @@ #![no_main] +mod utils; + use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; - -use utils::GeneralPoolData; -use zrml_swaps::mock::{ExtBuilder, RuntimeOrigin, Swaps}; -mod utils; -use utils::construct_asset; -use zrml_swaps::mock::AssetManager; +use utils::{construct_asset, GeneralPoolData}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: GeneralPoolData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, data.pool_creation.amount, diff --git a/zrml/swaps/fuzz/pool_join_with_exact_asset_amount.rs b/zrml/swaps/fuzz/pool_join_with_exact_asset_amount.rs index 91f1808d6..677b5a5a6 100644 --- a/zrml/swaps/fuzz/pool_join_with_exact_asset_amount.rs +++ b/zrml/swaps/fuzz/pool_join_with_exact_asset_amount.rs @@ -17,22 +17,19 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{ExtBuilder, RuntimeOrigin, Swaps}; - -use utils::ExactAssetAmountData; mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; -use utils::construct_asset; -use zrml_swaps::mock::AssetManager; +use utils::{construct_asset, ExactAssetAmountData}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: ExactAssetAmountData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, // In order to successfully join the pool, data.asset_amount more tokens needed diff --git a/zrml/swaps/fuzz/pool_join_with_exact_pool_amount.rs b/zrml/swaps/fuzz/pool_join_with_exact_pool_amount.rs index f480592dd..a1574b749 100644 --- a/zrml/swaps/fuzz/pool_join_with_exact_pool_amount.rs +++ b/zrml/swaps/fuzz/pool_join_with_exact_pool_amount.rs @@ -17,22 +17,19 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{ExtBuilder, RuntimeOrigin, Swaps}; - -use utils::ExactAmountData; mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; -use utils::construct_asset; -use zrml_swaps::mock::AssetManager; +use utils::{construct_asset, ExactAmountData}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: ExactAmountData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, // In order to successfully join the pool, data.asset_amount more tokens needed diff --git a/zrml/swaps/fuzz/swap_exact_amount_in.rs b/zrml/swaps/fuzz/swap_exact_amount_in.rs index 4aba80d2f..60a594cc4 100644 --- a/zrml/swaps/fuzz/swap_exact_amount_in.rs +++ b/zrml/swaps/fuzz/swap_exact_amount_in.rs @@ -17,32 +17,27 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{AssetManager, ExtBuilder, RuntimeOrigin, Swaps}; - -use utils::SwapExactAmountInData; mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; -use utils::construct_asset; +use utils::{construct_asset, SwapExactAmountInData}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: SwapExactAmountInData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, data.pool_creation.amount, ); } let pool_id = data.pool_creation.create_pool(); - let _ = AssetManager::deposit( - construct_asset(data.asset_in), - &data.origin, - data.asset_amount_in, - ); + let _ = + Currencies::deposit(construct_asset(data.asset_in), &data.origin, data.asset_amount_in); let _ = Swaps::swap_exact_amount_in( RuntimeOrigin::signed(data.origin), pool_id, diff --git a/zrml/swaps/fuzz/swap_exact_amount_out.rs b/zrml/swaps/fuzz/swap_exact_amount_out.rs index 93eab4325..05ca45474 100644 --- a/zrml/swaps/fuzz/swap_exact_amount_out.rs +++ b/zrml/swaps/fuzz/swap_exact_amount_out.rs @@ -17,20 +17,19 @@ #![no_main] -use libfuzzer_sys::fuzz_target; -use zrml_swaps::mock::{AssetManager, ExtBuilder, RuntimeOrigin, Swaps}; - mod utils; + +use libfuzzer_sys::fuzz_target; use orml_traits::currency::MultiCurrency; use utils::{construct_asset, SwapExactAmountOutData}; +use zrml_swaps::mock::{Currencies, ExtBuilder, RuntimeOrigin, Swaps}; fuzz_target!(|data: SwapExactAmountOutData| { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { // ensure that the account origin has a sufficient balance - // use orml_traits::MultiCurrency; required for this for a in &data.pool_creation.assets { - let _ = AssetManager::deposit( + let _ = Currencies::deposit( construct_asset(*a), &data.pool_creation.origin, data.pool_creation.amount, @@ -39,7 +38,7 @@ fuzz_target!(|data: SwapExactAmountOutData| { let pool_id = data.pool_creation.create_pool(); if let Some(amount) = data.asset_amount_in { - let _ = AssetManager::deposit(construct_asset(data.asset_in), &data.origin, amount); + let _ = Currencies::deposit(construct_asset(data.asset_in), &data.origin, amount); } let _ = Swaps::swap_exact_amount_out( diff --git a/zrml/swaps/fuzz/utils.rs b/zrml/swaps/fuzz/utils.rs index c3e1084f9..eaf3f17fe 100644 --- a/zrml/swaps/fuzz/utils.rs +++ b/zrml/swaps/fuzz/utils.rs @@ -29,7 +29,7 @@ use zeitgeist_primitives::{ MaxAssets, MaxSwapFee, MaxTotalWeight, MaxWeight, MinAssets, MinWeight, BASE, CENT, }, traits::Swaps as SwapsTrait, - types::{Asset, PoolId, ScalarPosition}, + types::{Asset, PoolId, ScalarPosition, SerdeWrapper}, }; use zrml_swaps::mock::Swaps; @@ -43,7 +43,7 @@ pub fn construct_asset(seed: (u8, u128, u16)) -> Asset { if seed1 % 2 == 0 { ScalarPosition::Long } else { ScalarPosition::Short }; Asset::ScalarOutcome(seed0, scalar_position) } - 2 => Asset::PoolShare(seed0), + 2 => Asset::PoolShare(SerdeWrapper(seed0)), _ => Asset::Ztg, } } diff --git a/zrml/swaps/rpc/src/lib.rs b/zrml/swaps/rpc/src/lib.rs index 5591fb2f9..4cad2388f 100644 --- a/zrml/swaps/rpc/src/lib.rs +++ b/zrml/swaps/rpc/src/lib.rs @@ -27,14 +27,14 @@ use jsonrpsee::{ proc_macros::rpc, types::error::{CallError, ErrorObject}, }; -use parity_scale_codec::{Codec, HasCompact, MaxEncodedLen}; +use parity_scale_codec::{Codec, MaxEncodedLen}; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, MaybeDisplay, MaybeFromStr, NumberFor}, }; -use zeitgeist_primitives::types::Asset; +use zeitgeist_primitives::types::{Asset, SerdeWrapper}; pub use zrml_swaps_runtime_api::SwapsApi as SwapsRuntimeApi; @@ -42,7 +42,7 @@ pub use zrml_swaps_runtime_api::SwapsApi as SwapsRuntimeApi; pub trait SwapsApi where Balance: FromStr + Display + parity_scale_codec::MaxEncodedLen, - MarketId: FromStr + Display + HasCompact + MaxEncodedLen + Ord, + MarketId: FromStr + Display + parity_scale_codec::MaxEncodedLen + Ord, PoolId: FromStr + Display, BlockNumber: Ord + parity_scale_codec::MaxEncodedLen + Display + FromStr, { @@ -51,7 +51,7 @@ where &self, pool_id: PoolId, at: Option, - ) -> RpcResult>; + ) -> RpcResult>>; #[method(name = "swaps_poolAccountId", aliases = ["swaps_poolAccountIdAt"])] async fn pool_account_id(&self, pool_id: PoolId, at: Option) @@ -65,7 +65,7 @@ where asset_out: Asset, with_fees: bool, at: Option, - ) -> RpcResult; + ) -> RpcResult>; #[method(name = "swaps_getSpotPrices")] async fn get_spot_prices( @@ -75,7 +75,7 @@ where asset_out: Asset, with_fees: bool, blocks: Vec, - ) -> RpcResult>; + ) -> RpcResult>>; } /// A struct that implements the [`SwapsApi`]. @@ -116,22 +116,14 @@ where C::Api: SwapsRuntimeApi, PoolId: Clone + Codec + MaybeDisplay + MaybeFromStr + Send + 'static, AccountId: Clone + Display + Codec + Send + 'static, - Balance: Codec + HasCompact + MaybeDisplay + MaybeFromStr + MaxEncodedLen + Send + 'static, - MarketId: Clone - + Codec - + HasCompact - + MaybeDisplay - + MaybeFromStr - + MaxEncodedLen - + Ord - + Send - + 'static, + Balance: Codec + MaybeDisplay + MaybeFromStr + MaxEncodedLen + Send + 'static, + MarketId: Clone + Codec + MaybeDisplay + MaybeFromStr + MaxEncodedLen + Ord + Send + 'static, { async fn pool_shares_id( &self, pool_id: PoolId, at: Option<::Hash>, - ) -> RpcResult> { + ) -> RpcResult>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| //if the block hash is not supplied assume the best block @@ -175,7 +167,7 @@ where asset_out: Asset, with_fees: bool, at: Option<::Hash>, - ) -> RpcResult { + ) -> RpcResult> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); let res = @@ -196,7 +188,7 @@ where asset_out: Asset, with_fees: bool, blocks: Vec>, - ) -> RpcResult> { + ) -> RpcResult>> { let api = self.client.runtime_api(); blocks .into_iter() diff --git a/zrml/swaps/runtime-api/src/lib.rs b/zrml/swaps/runtime-api/src/lib.rs index 2045560a2..b76ca8038 100644 --- a/zrml/swaps/runtime-api/src/lib.rs +++ b/zrml/swaps/runtime-api/src/lib.rs @@ -19,24 +19,26 @@ #![doc = include_str!("../README.md")] #![cfg_attr(not(feature = "std"), no_std)] -use parity_scale_codec::{Codec, HasCompact, MaxEncodedLen}; +use parity_scale_codec::{Codec, MaxEncodedLen}; use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; -use zeitgeist_primitives::types::Asset; +use zeitgeist_primitives::types::{Asset, SerdeWrapper}; sp_api::decl_runtime_apis! { pub trait SwapsApi where PoolId: Codec, AccountId: Codec, - Balance: Codec + MaybeDisplay + MaybeFromStr + HasCompact + MaxEncodedLen, - MarketId: Codec + HasCompact + MaxEncodedLen, + Balance: Codec + MaybeDisplay + MaybeFromStr + MaxEncodedLen, + MarketId: Codec + MaxEncodedLen, { - fn pool_shares_id(pool_id: PoolId) -> Asset; + fn pool_shares_id(pool_id: PoolId) -> Asset>; + fn pool_account_id(pool_id: &PoolId) -> AccountId; + fn get_spot_price( pool_id: &PoolId, asset_in: &Asset, asset_out: &Asset, with_fees: bool, - ) -> Balance; + ) -> SerdeWrapper; } } diff --git a/zrml/swaps/src/benchmarks.rs b/zrml/swaps/src/benchmarks.rs index c7442491a..55f125067 100644 --- a/zrml/swaps/src/benchmarks.rs +++ b/zrml/swaps/src/benchmarks.rs @@ -61,7 +61,7 @@ where for i in 0..asset_count { let asset = T::Asset::create_asset_id(i as u128); assets.push(asset); - T::AssetManager::deposit(asset, owner, asset_amount).unwrap() + T::MultiCurrency::deposit(asset, owner, asset_amount).unwrap() } (assets, asset_amount) } @@ -181,7 +181,7 @@ benchmarks! { true, ); let asset_in = assets[0]; - T::AssetManager::deposit(asset_in, &caller, u64::MAX.saturated_into()).unwrap(); + T::MultiCurrency::deposit(asset_in, &caller, u64::MAX.saturated_into()).unwrap(); let asset_out = assets[asset_count as usize - 1]; let min_asset_amount_out: Option> = Some(0u128.saturated_into()); let max_price = Some(u128::MAX.saturated_into()); @@ -217,7 +217,7 @@ benchmarks! { true, ); let asset_in = assets[0]; - T::AssetManager::deposit(asset_in, &caller, u64::MAX.saturated_into()).unwrap(); + T::MultiCurrency::deposit(asset_in, &caller, u64::MAX.saturated_into()).unwrap(); let asset_out = assets[asset_count as usize - 1]; let max_asset_amount_in: Option> = Some(u128::MAX.saturated_into()); let max_price = Some(u128::MAX.saturated_into()); diff --git a/zrml/swaps/src/lib.rs b/zrml/swaps/src/lib.rs index 17e2e0132..af2880d61 100644 --- a/zrml/swaps/src/lib.rs +++ b/zrml/swaps/src/lib.rs @@ -81,7 +81,7 @@ mod pallet { fixed::FixedMul, }, traits::{PoolSharesId, Swaps}, - types::PoolId, + types::{PoolId, SerdeWrapper}, }; /// The current storage version. @@ -89,9 +89,9 @@ mod pallet { pub(crate) type AccountIdOf = ::AccountId; pub(crate) type AssetOf = - <::AssetManager as MultiCurrency>>::CurrencyId; + <::MultiCurrency as MultiCurrency>>::CurrencyId; pub(crate) type BalanceOf = - <::AssetManager as MultiCurrency>>::Balance; + <::MultiCurrency as MultiCurrency>>::Balance; pub(crate) type PoolOf = Pool, BalanceOf>; const MIN_BALANCE: u128 = CENT; @@ -359,8 +359,6 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config { - type AssetManager: MultiCurrency; - type Asset: Parameter + Member + Copy @@ -368,7 +366,9 @@ mod pallet { + MaybeSerializeDeserialize + Ord + TypeInfo - + PoolSharesId; + + PoolSharesId>; + + type MultiCurrency: MultiCurrency; type RuntimeEvent: From> + IsType<::RuntimeEvent>; @@ -602,13 +602,13 @@ mod pallet { // If transferring to `who` triggers the existential deposit, burn the tokens // instead. let new_balance = - T::AssetManager::free_balance(asset, &who).checked_add_res(&amount)?; - if new_balance >= T::AssetManager::minimum_balance(asset) { + T::MultiCurrency::free_balance(asset, &who).checked_add_res(&amount)?; + if new_balance >= T::MultiCurrency::minimum_balance(asset) { ensure!(amount >= amount_bound, Error::::LimitOut); - T::AssetManager::transfer(asset, &pool_account_id, &who, amount)?; + T::MultiCurrency::transfer(asset, &pool_account_id, &who, amount)?; } else { ensure!(amount_bound.is_zero(), Error::::LimitOut); - T::AssetManager::withdraw(asset, &pool_account_id, amount)?; + T::MultiCurrency::withdraw(asset, &pool_account_id, amount)?; } Ok(()) }, @@ -696,7 +696,7 @@ mod pallet { pool: &pool, transfer_asset: |amount, amount_bound, asset| { ensure!(amount <= amount_bound, Error::::LimitIn); - T::AssetManager::transfer(asset, &who, &pool_account_id, amount)?; + T::MultiCurrency::transfer(asset, &who, &pool_account_id, amount)?; Ok(()) }, transfer_pool: || Self::mint_pool_shares(pool_id, &who, pool_amount), @@ -860,15 +860,15 @@ mod pallet { let pool = Pallet::::pool_by_id(pool_id)?; let pool_account_id = Pallet::::pool_account_id(&pool_id); ensure!( - T::AssetManager::free_balance(asset_in, &who) >= asset_amount_in, + T::MultiCurrency::free_balance(asset_in, &who) >= asset_amount_in, Error::::InsufficientBalance ); let params = SwapExactAmountParams { // TODO(#1215): This probably doesn't need to be a closure. asset_amounts: || { - let balance_out = T::AssetManager::free_balance(asset_out, &pool_account_id); - let balance_in = T::AssetManager::free_balance(asset_in, &pool_account_id); + let balance_out = T::MultiCurrency::free_balance(asset_out, &pool_account_id); + let balance_in = T::MultiCurrency::free_balance(asset_in, &pool_account_id); ensure!( asset_amount_in <= balance_in.bmul(MAX_IN_RATIO.saturated_into())?, Error::::MaxInRatio @@ -922,13 +922,13 @@ mod pallet { let params = SwapExactAmountParams { asset_amounts: || { - let balance_out = T::AssetManager::free_balance(asset_out, &pool_account_id); + let balance_out = T::MultiCurrency::free_balance(asset_out, &pool_account_id); ensure!( asset_amount_out <= balance_out.bmul(MAX_OUT_RATIO.saturated_into())?, Error::::MaxOutRatio, ); - let balance_in = T::AssetManager::free_balance(asset_in, &pool_account_id); + let balance_in = T::MultiCurrency::free_balance(asset_in, &pool_account_id); let asset_amount_in: BalanceOf = crate::math::calc_in_given_out( balance_in.saturated_into(), Self::pool_weight_rslt(&pool, &asset_in)?.saturated_into(), @@ -969,8 +969,8 @@ mod pallet { ensure!(pool.assets.binary_search(asset_in).is_ok(), Error::::AssetNotInPool); ensure!(pool.assets.binary_search(asset_out).is_ok(), Error::::AssetNotInPool); let pool_account = Self::pool_account_id(pool_id); - let balance_in = T::AssetManager::free_balance(*asset_in, &pool_account); - let balance_out = T::AssetManager::free_balance(*asset_out, &pool_account); + let balance_in = T::MultiCurrency::free_balance(*asset_in, &pool_account); + let balance_out = T::MultiCurrency::free_balance(*asset_out, &pool_account); let in_weight = Self::pool_weight_rslt(&pool, asset_in)?; let out_weight = Self::pool_weight_rslt(&pool, asset_out)?; @@ -993,7 +993,7 @@ mod pallet { /// The minimum allowed balance of `asset` in a liquidity pool. pub(crate) fn min_balance(asset: AssetOf) -> BalanceOf { - T::AssetManager::minimum_balance(asset).max(MIN_BALANCE.saturated_into()) + T::MultiCurrency::minimum_balance(asset).max(MIN_BALANCE.saturated_into()) } /// Returns the minimum allowed balance allowed for a pool with id `pool_id` containing @@ -1023,7 +1023,7 @@ mod pallet { return Ok(()); } let pool_shares_id = Self::pool_shares_id(pool_id); - let total_issuance = T::AssetManager::total_issuance(pool_shares_id); + let total_issuance = T::MultiCurrency::total_issuance(pool_shares_id); let max_withdraw = total_issuance.saturating_sub(Self::min_balance(pool_shares_id).saturated_into()); ensure!(amount <= max_withdraw, Error::::PoolDrain); @@ -1041,7 +1041,7 @@ mod pallet { return Ok(()); } let pool_account = Self::pool_account_id(&pool_id); - let balance = T::AssetManager::free_balance(asset, &pool_account); + let balance = T::MultiCurrency::free_balance(asset, &pool_account); let max_withdraw = balance.saturating_sub(Self::min_balance(asset).saturated_into()); ensure!(amount <= max_withdraw, Error::::PoolDrain); Ok(()) @@ -1054,9 +1054,9 @@ mod pallet { ) -> DispatchResult { let shares_id = Self::pool_shares_id(pool_id); // Check that the account has at least as many free shares as we wish to burn! - T::AssetManager::ensure_can_withdraw(shares_id, from, amount) + T::MultiCurrency::ensure_can_withdraw(shares_id, from, amount) .map_err(|_| Error::::InsufficientBalance)?; - T::AssetManager::withdraw(shares_id, from, amount)?; + T::MultiCurrency::withdraw(shares_id, from, amount)?; Ok(()) } @@ -1088,11 +1088,11 @@ mod pallet { amount: BalanceOf, ) -> DispatchResult { let shares_id = Self::pool_shares_id(pool_id); - T::AssetManager::deposit(shares_id, to, amount) + T::MultiCurrency::deposit(shares_id, to, amount) } pub(crate) fn pool_shares_id(pool_id: PoolId) -> AssetOf { - T::Asset::pool_shares_id(pool_id) + T::Asset::pool_shares_id(SerdeWrapper(pool_id)) } pub fn pool_by_id(pool_id: PoolId) -> Result, DispatchError> @@ -1186,17 +1186,17 @@ mod pallet { Self::check_provided_values_len_must_equal_assets_len(&assets, &weights)?; for (asset, weight) in assets.iter().copied().zip(weights) { - let free_balance = T::AssetManager::free_balance(asset, &who); + let free_balance = T::MultiCurrency::free_balance(asset, &who); ensure!(free_balance >= amount, Error::::InsufficientBalance); ensure!(weight >= T::MinWeight::get(), Error::::BelowMinimumWeight); ensure!(weight <= T::MaxWeight::get(), Error::::AboveMaximumWeight); map.insert(asset, weight); total_weight = total_weight.checked_add_res(&weight)?; - T::AssetManager::transfer(asset, &who, &pool_account, amount)?; + T::MultiCurrency::transfer(asset, &who, &pool_account, amount)?; } ensure!(total_weight <= T::MaxTotalWeight::get(), Error::::MaxTotalWeight); - T::AssetManager::deposit(pool_shares_id, &who, amount)?; + T::MultiCurrency::deposit(pool_shares_id, &who, amount)?; let pool = Pool { assets: sorted_assets @@ -1239,8 +1239,8 @@ mod pallet { let pool_account = Self::pool_account_id(&pool_id); let asset_len = pool.assets.len() as u32; for asset in pool.assets.into_iter() { - let amount = T::AssetManager::free_balance(asset, &pool_account); - T::AssetManager::withdraw(asset, &pool_account, amount)?; + let amount = T::MultiCurrency::free_balance(asset, &pool_account); + T::MultiCurrency::withdraw(asset, &pool_account, amount)?; } // NOTE: Currently we don't clean up accounts with pool_share_id. // TODO(#792): Remove pool_share_id asset for accounts! It may require storage migration. diff --git a/zrml/swaps/src/mock.rs b/zrml/swaps/src/mock.rs index de0c3fa27..324d4b7da 100644 --- a/zrml/swaps/src/mock.rs +++ b/zrml/swaps/src/mock.rs @@ -45,8 +45,8 @@ use zeitgeist_primitives::{ BASE, }, types::{ - AccountIdTest, Amount, Asset, Assets, Balance, BasicCurrencyAdapter, BlockNumber, - BlockTest, Hash, Index, MarketId, Moment, PoolId, UncheckedExtrinsicTest, + AccountIdTest, Amount, Asset, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, + CurrencyId, Hash, Index, MarketId, Moment, PoolId, SerdeWrapper, UncheckedExtrinsicTest, }, }; @@ -92,10 +92,9 @@ construct_runtime!( } ); -pub type AssetManager = Currencies; - impl crate::Config for Runtime { type Asset = Asset; + type MultiCurrency = Currencies; type RuntimeEvent = RuntimeEvent; type ExitFee = ExitFeeMock; type MaxAssets = MaxAssets; @@ -105,7 +104,6 @@ impl crate::Config for Runtime { type MinAssets = MinAssets; type MinWeight = MinWeight; type PalletId = SwapsPalletId; - type AssetManager = AssetManager; type WeightInfo = zrml_swaps::weights::WeightInfo; } @@ -144,7 +142,7 @@ impl orml_currencies::Config for Runtime { } parameter_type_with_key! { - pub ExistentialDeposits: |currency_id: Assets| -> Balance { + pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { &BASE_ASSET => ExistentialDeposit::get(), Asset::Ztg => ExistentialDeposit::get(), @@ -181,7 +179,7 @@ where impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; - type CurrencyId = Assets; + type CurrencyId = CurrencyId; type DustRemovalWhitelist = DustRemovalWhitelist; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; @@ -254,16 +252,16 @@ sp_api::mock_impl_runtime_apis! { asset_in: &Asset, asset_out: &Asset, with_fees: bool, - ) -> Balance { - Swaps::get_spot_price(pool_id, asset_in, asset_out, with_fees).ok().unwrap_or(0) + ) -> SerdeWrapper { + SerdeWrapper(Swaps::get_spot_price(pool_id, asset_in, asset_out, with_fees).ok().unwrap_or(0)) } fn pool_account_id(pool_id: &PoolId) -> AccountIdTest { Swaps::pool_account_id(pool_id) } - fn pool_shares_id(pool_id: PoolId) -> Asset { - Asset::PoolShare(pool_id) + fn pool_shares_id(pool_id: PoolId) -> Asset> { + Asset::PoolShare(SerdeWrapper(pool_id)) } } } diff --git a/zrml/swaps/src/utils.rs b/zrml/swaps/src/utils.rs index 7e746b808..041f8fc37 100644 --- a/zrml/swaps/src/utils.rs +++ b/zrml/swaps/src/utils.rs @@ -53,17 +53,17 @@ where ensure!(p.pool.bound(&p.asset), Error::::AssetNotInPool); let pool_account = Pallet::::pool_account_id(&p.pool_id); - let asset_balance = T::AssetManager::free_balance(p.asset, &pool_account); + let asset_balance = T::MultiCurrency::free_balance(p.asset, &pool_account); (p.ensure_balance)(asset_balance)?; let pool_shares_id = Pallet::::pool_shares_id(p.pool_id); - let total_issuance = T::AssetManager::total_issuance(pool_shares_id); + let total_issuance = T::MultiCurrency::total_issuance(pool_shares_id); let asset_amount = (p.asset_amount)(asset_balance, total_issuance)?; let pool_amount = (p.pool_amount)(asset_balance, total_issuance)?; Pallet::::burn_pool_shares(p.pool_id, &p.who, pool_amount)?; - T::AssetManager::transfer(p.asset, &pool_account, &p.who, asset_amount)?; + T::MultiCurrency::transfer(p.asset, &pool_account, &p.who, asset_amount)?; (p.event)(PoolAssetEvent { asset: p.asset, @@ -89,16 +89,16 @@ where Pallet::::ensure_pool_is_active(p.pool)?; let pool_shares_id = Pallet::::pool_shares_id(p.pool_id); let pool_account_id = Pallet::::pool_account_id(&p.pool_id); - let total_issuance = T::AssetManager::total_issuance(pool_shares_id); + let total_issuance = T::MultiCurrency::total_issuance(pool_shares_id); ensure!(p.pool.bound(&p.asset), Error::::AssetNotInPool); - let asset_balance = T::AssetManager::free_balance(p.asset, p.pool_account_id); + let asset_balance = T::MultiCurrency::free_balance(p.asset, p.pool_account_id); let asset_amount = (p.asset_amount)(asset_balance, total_issuance)?; let pool_amount = (p.pool_amount)(asset_balance, total_issuance)?; Pallet::::mint_pool_shares(p.pool_id, &p.who, pool_amount)?; - T::AssetManager::transfer(p.asset, &p.who, &pool_account_id, asset_amount)?; + T::MultiCurrency::transfer(p.asset, &p.who, &pool_account_id, asset_amount)?; (p.event)(PoolAssetEvent { asset: p.asset, @@ -121,7 +121,7 @@ where T: Config, { let pool_shares_id = Pallet::::pool_shares_id(p.pool_id); - let total_issuance = T::AssetManager::total_issuance(pool_shares_id); + let total_issuance = T::MultiCurrency::total_issuance(pool_shares_id); let ratio = p.pool_amount.bdiv(total_issuance)?; Pallet::::check_provided_values_len_must_equal_assets_len(&p.pool.assets, &p.asset_bounds)?; @@ -130,7 +130,7 @@ where let mut transferred = Vec::with_capacity(p.asset_bounds.len()); for (asset, amount_bound) in p.pool.assets.iter().cloned().zip(p.asset_bounds.iter().cloned()) { - let balance = T::AssetManager::free_balance(asset, p.pool_account_id); + let balance = T::MultiCurrency::free_balance(asset, p.pool_account_id); // Dusting may result in zero balances in the pool; just ignore these. if balance.is_zero() { continue; @@ -183,8 +183,8 @@ where let [asset_amount_in, asset_amount_out] = (p.asset_amounts)()?; - T::AssetManager::transfer(p.asset_in, &p.who, p.pool_account_id, asset_amount_in)?; - T::AssetManager::transfer(p.asset_out, p.pool_account_id, &p.who, asset_amount_out)?; + T::MultiCurrency::transfer(p.asset_in, &p.who, p.pool_account_id, asset_amount_in)?; + T::MultiCurrency::transfer(p.asset_out, p.pool_account_id, &p.who, asset_amount_out)?; let spot_price_after = Pallet::::get_spot_price(&p.pool_id, &p.asset_in, &p.asset_out, true)?; diff --git a/zrml/swaps/src/weights.rs b/zrml/swaps/src/weights.rs index 4e923b1d0..554d3505d 100644 --- a/zrml/swaps/src/weights.rs +++ b/zrml/swaps/src/weights.rs @@ -67,8 +67,6 @@ pub struct WeightInfo(PhantomData); impl WeightInfoZeitgeist for WeightInfo { /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:66 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:131 w:131) @@ -92,8 +90,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:3 w:3) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) @@ -111,8 +107,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:3 w:3) @@ -130,8 +124,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:66 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:131 w:131) @@ -153,8 +145,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:3 w:3) @@ -170,8 +160,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:1 w:1) /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(43), added: 2518, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:3 w:3) @@ -187,8 +175,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:4 w:4) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:0) @@ -204,8 +190,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:0) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:2 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:4 w:4) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: System Account (r:1 w:0) @@ -249,8 +233,6 @@ impl WeightInfoZeitgeist for WeightInfo { } /// Storage: Swaps Pools (r:1 w:1) /// Proof: Swaps Pools (max_values: None, max_size: Some(3579), added: 6054, mode: MaxEncodedLen) - /// Storage: MarketAssets Asset (r:65 w:0) - /// Proof: MarketAssets Asset (max_values: None, max_size: Some(225), added: 2700, mode: MaxEncodedLen) /// Storage: Tokens Accounts (r:65 w:65) /// Proof: Tokens Accounts (max_values: None, max_size: Some(123), added: 2598, mode: MaxEncodedLen) /// Storage: Tokens TotalIssuance (r:65 w:65)