diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 4b8025012..86f3665e4 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -8,6 +8,8 @@ members = [ "currencies", "gradually-update", "oracle", + "oracle/rpc", + "oracle/rpc/runtime-api", "tokens", "traits", "utilities", @@ -16,26 +18,73 @@ members = [ "nft", "xtokens", "xcm-support", + "unknown-tokens", + "build-script-utils", "weight-meter", ] resolver = "2" -[patch.crates-io] -frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-scheduler = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-treasury = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-api = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-application-crypto = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-arithmetic = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-inherents = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-runtime-interface = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-trie = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-version = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } +[patch.'https://github.com/paritytech/substrate'] +frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +frame-support = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +frame-system = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-session = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-api = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-core = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-io = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-std = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-trie = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-version = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-staking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-storage = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-executor = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-session = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } + +[patch.'https://github.com/paritytech/cumulus'] +cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } +cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } +parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } +cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } + +[patch.'https://github.com/paritytech/polkadot'] +xcm = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } diff --git a/Makefile b/Makefile index afee442fd..0583cd27d 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,6 @@ check-tests: githooks test: githooks ./scripts/run.sh test - cargo test --manifest-path nft/Cargo.toml -p orml-nft --features disable-tokens-by-owner GITHOOKS_SRC = $(wildcard githooks/*) GITHOOKS_DEST = $(patsubst githooks/%, $(GITHOOK)/%, $(GITHOOKS_SRC)) @@ -47,5 +46,4 @@ dev-check-tests: Cargo.toml cargo check --tests --all dev-test: Cargo.toml - cargo test --all - cargo test --manifest-path nft/Cargo.toml -p orml-nft --features disable-tokens-by-owner + cargo test --all --features runtime-benchmarks diff --git a/README.md b/README.md index 7cc205fcc..852832c49 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,11 @@ The Open Runtime Module Library (ORML) is a community maintained collection of S - Provides scheduled balance locking mechanism, in a *graded vesting* way. - [orml-gradually-update](./gradually-update) - Provides way to adjust numeric parameter gradually over a period of time. +- [orml-xtokens](./xtokens) + - Provides way to do cross-chain assets transfer. + - [Step-by-Step guide](https://github.com/open-web3-stack/open-runtime-module-library/wiki/xtokens) to make XCM cross-chain fungible asset transfer available on your parachain +- [orml-xcm-support](./xcm-support) + - Provides traits, types, and implementations to support XCM integration. ## Example @@ -48,7 +53,7 @@ ORML use `Cargo.dev.toml` to avoid workspace conflicts with project cargo config - change the command to `make dev-check` etc which does the copy. (For the full list of `make` commands, check `Makefile`) # Web3 Foundation Grant Project -ORML is part of the bigger `Open-Web3-Stack` initiative, that is currently under a General Grant from Web3 Foundation. See Application details [here](https://github.com/open-web3-stack/General-Grants-Program/blob/master/grants/speculative/open_web3_stack.md). The 1st milestone has been delivered. +ORML is part of the bigger `Open-Web3-Stack` initiative, that is currently under a General Grant from Web3 Foundation. See Application details [here](https://github.com/open-web3-stack/General-Grants-Program/blob/master/grants/speculative/open_web3_stack.md). The 1st milestone has been delivered. # Projects using ORML - [If you intend or are using ORML, please add your project here](https://github.com/open-web3-stack/open-runtime-module-library/edit/master/README.md) @@ -61,6 +66,10 @@ _In alphabetical order_ - [ChainX](https://github.com/chainx-org/ChainX) - [HydraDX](https://github.com/galacticcouncil/hack.HydraDX-node) - [Laminar Chain](https://github.com/laminar-protocol/laminar-chain) +- [Listen](https://github.com/listenofficial) +- [Minterest](https://github.com/minterest-finance/minterest-chain-node) - [Plasm Network](https://github.com/PlasmNetwork) - [Setheum Network](https://github.com/Setheum-Labs/Setheum) - [Valiu Liquidity Network](https://github.com/valibre-org/vln-node) +- [Zeitgeist](https://github.com/zeitgeistpm/zeitgeist) + diff --git a/auction/Cargo.toml b/auction/Cargo.toml index 5c568933b..64d024a3d 100644 --- a/auction/Cargo.toml +++ b/auction/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/auction/src/default_weight.rs b/auction/src/default_weight.rs index 84a711aa7..26e552fef 100644 --- a/auction/src/default_weight.rs +++ b/auction/src/default_weight.rs @@ -12,16 +12,6 @@ impl crate::WeightInfo for () { .saturating_add(DbWeight::get().reads(12 as Weight)) .saturating_add(DbWeight::get().writes(12 as Weight)) } - fn bid_surplus_auction() -> Weight { - (257_830_000 as Weight) - .saturating_add(DbWeight::get().reads(6 as Weight)) - .saturating_add(DbWeight::get().writes(5 as Weight)) - } - fn bid_debit_auction() -> Weight { - (287_271_000 as Weight) - .saturating_add(DbWeight::get().reads(7 as Weight)) - .saturating_add(DbWeight::get().writes(8 as Weight)) - } fn on_finalize(c: u32) -> Weight { (50_992_000 as Weight) .saturating_add((171_653_000 as Weight).saturating_mul(c as Weight)) diff --git a/auction/src/lib.rs b/auction/src/lib.rs index 115861bbf..53b40f31c 100644 --- a/auction/src/lib.rs +++ b/auction/src/lib.rs @@ -33,8 +33,6 @@ pub mod module { pub trait WeightInfo { fn bid_collateral_auction() -> Weight; - fn bid_surplus_auction() -> Weight; - fn bid_debit_auction() -> Weight; fn on_finalize(c: u32) -> Weight; } @@ -131,7 +129,7 @@ pub mod module { Auctions::::try_mutate_exists(id, |auction| -> DispatchResult { let mut auction = auction.as_mut().ok_or(Error::::AuctionNotExist)?; - let block_number = >::block_number(); + let block_number = >::block_number(); // make sure auction is started ensure!(block_number >= auction.start, Error::::AuctionNotStarted); diff --git a/auction/src/mock.rs b/auction/src/mock.rs index ab409e6f0..718c25164 100644 --- a/auction/src/mock.rs +++ b/auction/src/mock.rs @@ -42,6 +42,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } pub struct Handler; @@ -86,8 +87,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - AuctionModule: auction::{Module, Storage, Call, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + AuctionModule: auction::{Pallet, Storage, Call, Event}, } ); diff --git a/authority/Cargo.toml b/authority/Cargo.toml index 5d7a393f4..ecd262d0d 100644 --- a/authority/Cargo.toml +++ b/authority/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -38,4 +38,6 @@ std = [ "orml-traits/std", ] runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", ] diff --git a/authority/src/lib.rs b/authority/src/lib.rs index 01d45f920..6481a2c01 100644 --- a/authority/src/lib.rs +++ b/authority/src/lib.rs @@ -244,7 +244,7 @@ pub mod module { *id = id.checked_add(1).ok_or(Error::::Overflow)?; Ok(current_id) })?; - let now = frame_system::Module::::block_number(); + let now = frame_system::Pallet::::block_number(); let delay = match when { DispatchTime::At(x) => x.checked_sub(&now).ok_or(Error::::Overflow)?, DispatchTime::After(x) => x, @@ -283,7 +283,7 @@ pub mod module { task_id: ScheduleTaskIndex, when: DispatchTime, ) -> DispatchResultWithPostInfo { - let now = frame_system::Module::::block_number(); + let now = frame_system::Pallet::::block_number(); let new_delay = match when { DispatchTime::At(x) => x.checked_sub(&now).ok_or(Error::::Overflow)?, DispatchTime::After(x) => x, @@ -317,7 +317,7 @@ pub mod module { ) .map_err(|_| Error::::FailedToDelay)?; - let now = frame_system::Module::::block_number(); + let now = frame_system::Pallet::::block_number(); let dispatch_at = now.saturating_add(additional_delay); Self::deposit_event(Event::Delayed(initial_origin, task_id, dispatch_at)); diff --git a/authority/src/mock.rs b/authority/src/mock.rs index a3f6fa02d..593710bc6 100644 --- a/authority/src/mock.rs +++ b/authority/src/mock.rs @@ -51,6 +51,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } parameter_types! { @@ -162,9 +163,9 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Module, Call, Config, Event}, - Authority: authority::{Module, Call, Origin, Event}, - Scheduler: pallet_scheduler::{Module, Call, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Event}, + Authority: authority::{Pallet, Call, Origin, Event}, + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event}, } ); diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index e2ae5e252..5727669c6 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } paste = "0.1.16" codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 71c6af4e7..0755894cd 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -844,8 +844,8 @@ macro_rules! impl_benchmark { >::instance(&selected_benchmark, c, verify)?; // Set the block number to at least 1 so events are deposited. - if $crate::Zero::is_zero(&frame_system::Module::<$runtime>::block_number()) { - frame_system::Module::<$runtime>::set_block_number(1u32.into()); + if $crate::Zero::is_zero(&frame_system::Pallet::<$runtime>::block_number()) { + frame_system::Pallet::<$runtime>::set_block_number(1u32.into()); } // Commit the externalities to the database, flushing the DB cache. @@ -864,12 +864,21 @@ macro_rules! impl_benchmark { "Start Benchmark: {:?}", c ); + let start_pov = $crate::benchmarking::proof_size(); let start_extrinsic = $crate::benchmarking::current_time(); closure_to_benchmark()?; let finish_extrinsic = $crate::benchmarking::current_time(); - let elapsed_extrinsic = finish_extrinsic - start_extrinsic; + let end_pov = $crate::benchmarking::proof_size(); + + // Calculate the diff caused by the benchmark. + let elapsed_extrinsic = finish_extrinsic.saturating_sub(start_extrinsic); + let diff_pov = match (start_pov, end_pov) { + (Some(start), Some(end)) => end.saturating_sub(start), + _ => Default::default(), + }; + // Commit the changes to get proper write count $crate::benchmarking::commit_db(); frame_support::log::trace!( @@ -896,6 +905,7 @@ macro_rules! impl_benchmark { repeat_reads: read_write_count.1, writes: read_write_count.2, repeat_writes: read_write_count.3, + proof_size: diff_pov, }); } @@ -990,8 +1000,8 @@ macro_rules! impl_benchmark_test { >::instance(&selected_benchmark, &c, true)?; // Set the block number to at least 1 so events are deposited. - if $crate::Zero::is_zero(&frame_system::Module::<$runtime>::block_number()) { - frame_system::Module::<$runtime>::set_block_number(1u32.into()); + if $crate::Zero::is_zero(&frame_system::Pallet::<$runtime>::block_number()) { + frame_system::Pallet::<$runtime>::set_block_number(1u32.into()); } // Run execution + verification diff --git a/benchmarking/src/tests.rs b/benchmarking/src/tests.rs index 2c015f329..333a776cb 100644 --- a/benchmarking/src/tests.rs +++ b/benchmarking/src/tests.rs @@ -76,6 +76,7 @@ impl frame_system::Config for Test { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } impl tests::test::Config for Test { @@ -97,8 +98,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Pallet: test::{Module, Call, Storage, Config}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Pallet: test::{Pallet, Call, Storage, Config}, } ); diff --git a/build-script-utils/Cargo.toml b/build-script-utils/Cargo.toml new file mode 100644 index 000000000..c5d311634 --- /dev/null +++ b/build-script-utils/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "orml-build-script-utils" +description = "Crate with utility functions for `build.rs` scripts." +repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/build-script-utils" +license = "Apache-2.0" +version = "0.4.1-dev" +authors = ["Parity Technologies ", "Laminar Developers "] +edition = "2018" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +platforms = "1.1" diff --git a/build-script-utils/README.md b/build-script-utils/README.md new file mode 100644 index 000000000..1c184f673 --- /dev/null +++ b/build-script-utils/README.md @@ -0,0 +1,3 @@ +Crate with utility functions for `build.rs` scripts. + +License: Apache-2.0 \ No newline at end of file diff --git a/build-script-utils/src/lib.rs b/build-script-utils/src/lib.rs new file mode 100644 index 000000000..6d3177d51 --- /dev/null +++ b/build-script-utils/src/lib.rs @@ -0,0 +1,5 @@ +//! Crate with utility functions for `build.rs` scripts. + +mod version; + +pub use version::*; diff --git a/build-script-utils/src/version.rs b/build-script-utils/src/version.rs new file mode 100644 index 000000000..599f0d617 --- /dev/null +++ b/build-script-utils/src/version.rs @@ -0,0 +1,55 @@ +use platforms::*; +use std::process::Command; + +/// Generate the `cargo:` key output +pub fn generate_cargo_keys() { + println!( + "cargo:rustc-env=SUBSTRATE_CLI_IMPL_VERSION={}", + get_version(get_commit()) + ) +} + +fn get_platform() -> String { + let env_dash = if TARGET_ENV.is_some() { "-" } else { "" }; + + format!( + "{}-{}{}{}", + TARGET_ARCH.as_str(), + TARGET_OS.as_str(), + env_dash, + TARGET_ENV.map(|x| x.as_str()).unwrap_or(""), + ) +} + +fn get_version(impl_commit: String) -> String { + let commit_dash = if impl_commit.is_empty() { "" } else { "-" }; + + format!( + "{}{}{}-{}", + std::env::var("CARGO_PKG_VERSION").unwrap_or_default(), + commit_dash, + impl_commit, + get_platform(), + ) +} + +fn get_commit() -> String { + let commit = std::env::var("GIT_COMMIT").unwrap_or_default(); + if !commit.is_empty() { + return commit; + } + + let output = Command::new("git").args(&["rev-parse", "--short", "HEAD"]).output(); + + match output { + Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().into(), + Ok(o) => { + println!("cargo:warning=Git command failed with status: {}", o.status); + "unknown".into() + } + Err(err) => { + println!("cargo:warning=Failed to execute git command: {}", err); + "unknown".into() + } + } +} diff --git a/currencies/Cargo.toml b/currencies/Cargo.toml index a7029ed79..a58fd4cf8 100644 --- a/currencies/Cargo.toml +++ b/currencies/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/currencies/src/mock.rs b/currencies/src/mock.rs index 621876964..ef82359e4 100644 --- a/currencies/src/mock.rs +++ b/currencies/src/mock.rs @@ -3,13 +3,13 @@ #![cfg(test)] use super::*; -use frame_support::{construct_runtime, parameter_types}; +use frame_support::{construct_runtime, parameter_types, PalletId}; use orml_traits::parameter_type_with_key; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{AccountIdConversion, IdentityLookup}, - AccountId32, ModuleId, + AccountId32, }; use crate as currencies; @@ -42,6 +42,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } type CurrencyId = u32; @@ -56,7 +57,7 @@ impl pallet_balances::Config for Runtime { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = frame_system::Pallet; type MaxLocks = (); type WeightInfo = (); } @@ -68,7 +69,7 @@ parameter_type_with_key! { } parameter_types! { - pub DustAccount: AccountId = ModuleId(*b"orml/dst").into_account(); + pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); } impl orml_tokens::Config for Runtime { @@ -107,10 +108,10 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Currencies: currencies::{Module, Call, Event}, - Tokens: orml_tokens::{Module, Storage, Event, Config}, - PalletBalances: pallet_balances::{Module, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Currencies: currencies::{Pallet, Call, Event}, + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + PalletBalances: pallet_balances::{Pallet, Call, Storage, Config, Event}, } ); diff --git a/gradually-update/Cargo.toml b/gradually-update/Cargo.toml index 6df11cae4..1bde0d610 100644 --- a/gradually-update/Cargo.toml +++ b/gradually-update/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/gradually-update/src/mock.rs b/gradually-update/src/mock.rs index 981492564..410cb935d 100644 --- a/gradually-update/src/mock.rs +++ b/gradually-update/src/mock.rs @@ -39,6 +39,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } parameter_types! { @@ -61,9 +62,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - GraduallyUpdateModule: gradually_update::{Module, Storage, Call, Event}, - + System: frame_system::{Pallet, Call, Storage, Config, Event}, + GraduallyUpdateModule: gradually_update::{Pallet, Storage, Call, Event}, } ); diff --git a/nft/Cargo.toml b/nft/Cargo.toml index 1870aa65e..35f1b3cee 100644 --- a/nft/Cargo.toml +++ b/nft/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -32,4 +32,3 @@ std = [ "frame-support/std", "frame-system/std", ] -disable-tokens-by-owner = [] diff --git a/nft/src/lib.rs b/nft/src/lib.rs index 706a76000..19110231b 100644 --- a/nft/src/lib.rs +++ b/nft/src/lib.rs @@ -136,9 +136,6 @@ pub mod module { StorageDoubleMap<_, Twox64Concat, T::ClassId, Twox64Concat, T::TokenId, TokenInfoOf>; /// Token existence check by owner and class ID. - // TODO: pallet macro doesn't support conditional compiling. Always having `TokensByOwner` storage doesn't hurt but - // it could be removed once conditional compiling supported. - // #[cfg(not(feature = "disable-tokens-by-owner"))] #[pallet::storage] #[pallet::getter(fn tokens_by_owner)] pub type TokensByOwner = @@ -216,11 +213,8 @@ impl Pallet { info.owner = to.clone(); - #[cfg(not(feature = "disable-tokens-by-owner"))] - { - TokensByOwner::::remove(from, token); - TokensByOwner::::insert(to, token, ()); - } + TokensByOwner::::remove(from, token); + TokensByOwner::::insert(to, token, ()); Ok(()) }) @@ -252,7 +246,6 @@ impl Pallet { data, }; Tokens::::insert(class_id, token_id, token_info); - #[cfg(not(feature = "disable-tokens-by-owner"))] TokensByOwner::::insert(owner, (class_id, token_id), ()); Ok(token_id) @@ -274,7 +267,6 @@ impl Pallet { Ok(()) })?; - #[cfg(not(feature = "disable-tokens-by-owner"))] TokensByOwner::::remove(owner, token); Ok(()) @@ -295,10 +287,6 @@ impl Pallet { } pub fn is_owner(account: &T::AccountId, token: (T::ClassId, T::TokenId)) -> bool { - #[cfg(feature = "disable-tokens-by-owner")] - return Tokens::::get(token.0, token.1).map_or(false, |token| token.owner == *account); - - #[cfg(not(feature = "disable-tokens-by-owner"))] TokensByOwner::::contains_key(account, token) } } diff --git a/nft/src/mock.rs b/nft/src/mock.rs index a8d1dae2a..915f67561 100644 --- a/nft/src/mock.rs +++ b/nft/src/mock.rs @@ -40,6 +40,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } impl Config for Runtime { @@ -58,8 +59,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - NonFungibleTokenModule: nft::{Module, Storage, Config}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + NonFungibleTokenModule: nft::{Pallet, Storage, Config}, } ); diff --git a/oracle/Cargo.toml b/oracle/Cargo.toml index 8bd2e9df9..54e7bde93 100644 --- a/oracle/Cargo.toml +++ b/oracle/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/oracle/rpc/Cargo.toml b/oracle/rpc/Cargo.toml index 9ab71dbee..d64349197 100644 --- a/oracle/rpc/Cargo.toml +++ b/oracle/rpc/Cargo.toml @@ -3,6 +3,8 @@ name = "orml-oracle-rpc" version = "0.4.1-dev" authors = ["Laminar Developers "] edition = "2018" +license = "Apache-2.0" +description = "RPC module for orml-oracle." [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0" } @@ -13,6 +15,6 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } -orml-oracle-rpc-runtime-api = { path = "runtime-api" } +orml-oracle-rpc-runtime-api = { path = "runtime-api", version = "0.4.1-dev" } funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 diff --git a/oracle/rpc/runtime-api/Cargo.toml b/oracle/rpc/runtime-api/Cargo.toml index 3003f32f8..19edb53a2 100644 --- a/oracle/rpc/runtime-api/Cargo.toml +++ b/oracle/rpc/runtime-api/Cargo.toml @@ -3,6 +3,8 @@ name = "orml-oracle-rpc-runtime-api" version = "0.4.1-dev" authors = ["Laminar Developers "] edition = "2018" +license = "Apache-2.0" +description = "Runtime API module for orml-oracle-rpc." [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } diff --git a/oracle/src/lib.rs b/oracle/src/lib.rs index 4292be64f..0716ff3b9 100644 --- a/oracle/src/lib.rs +++ b/oracle/src/lib.rs @@ -139,10 +139,6 @@ pub mod module { #[pallet::getter(fn members)] pub type Members, I: 'static = ()> = StorageValue<_, OrderedSet, ValueQuery>; - #[pallet::storage] - #[pallet::getter(fn nonces)] - pub type Nonces, I: 'static = ()> = StorageMap<_, Twox64Concat, T::AccountId, u32>; - #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub members: OrderedSet, diff --git a/oracle/src/mock.rs b/oracle/src/mock.rs index b0173ac2b..569dcdc6a 100644 --- a/oracle/src/mock.rs +++ b/oracle/src/mock.rs @@ -45,6 +45,7 @@ impl frame_system::Config for Test { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } thread_local! { @@ -92,8 +93,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - ModuleOracle: oracle::{Module, Storage, Call, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + ModuleOracle: oracle::{Pallet, Storage, Call, Config, Event}, } ); diff --git a/rewards/Cargo.toml b/rewards/Cargo.toml index fb7c747f6..674018a63 100644 --- a/rewards/Cargo.toml +++ b/rewards/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/rewards/src/default_weight.rs b/rewards/src/default_weight.rs deleted file mode 100644 index a2be6a5dc..000000000 --- a/rewards/src/default_weight.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0 - -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight}; - -impl crate::WeightInfo for () { - fn on_initialize(c: u32) -> Weight { - (33_360_000 as Weight) - .saturating_add((23_139_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(DbWeight::get().reads(2 as Weight)) - .saturating_add(DbWeight::get().reads((1 as Weight).saturating_mul(c as Weight))) - } -} diff --git a/rewards/src/lib.rs b/rewards/src/lib.rs index 057c7e3d1..55be0d164 100644 --- a/rewards/src/lib.rs +++ b/rewards/src/lib.rs @@ -1,7 +1,6 @@ #![allow(clippy::unused_unit)] #![cfg_attr(not(feature = "std"), no_std)] -mod default_weight; mod mock; mod tests; @@ -37,10 +36,6 @@ pub use module::*; pub mod module { use super::*; - pub trait WeightInfo { - fn on_initialize(c: u32) -> Weight; - } - #[pallet::config] pub trait Config: frame_system::Config { /// The share type of pool. @@ -64,19 +59,10 @@ pub mod module { + FixedPointOperand; /// The reward pool ID type. - type PoolId: Parameter + Member + Copy + FullCodec; + type PoolId: Parameter + Member + Clone + FullCodec; /// The `RewardHandler` - type Handler: RewardHandler< - Self::AccountId, - Self::BlockNumber, - Share = Self::Share, - Balance = Self::Balance, - PoolId = Self::PoolId, - >; - - /// Weight information for extrinsics in this module. - type WeightInfo: WeightInfo; + type Handler: RewardHandler; } /// Stores reward pool info. @@ -95,27 +81,22 @@ pub mod module { pub struct Pallet(PhantomData); #[pallet::hooks] - impl Hooks for Pallet { - fn on_initialize(now: T::BlockNumber) -> Weight { - let mut count = 0; - T::Handler::accumulate_reward(now, |pool, reward_to_accumulate| { - if !reward_to_accumulate.is_zero() { - count += 1; - Pools::::mutate(pool, |pool_info| { - pool_info.total_rewards = pool_info.total_rewards.saturating_add(reward_to_accumulate) - }); - } - }); - T::WeightInfo::on_initialize(count) - } - } + impl Hooks for Pallet {} #[pallet::call] impl Pallet {} } impl Pallet { - pub fn add_share(who: &T::AccountId, pool: T::PoolId, add_amount: T::Share) { + pub fn accumulate_reward(pool: &T::PoolId, reward_increment: T::Balance) { + if !reward_increment.is_zero() { + Pools::::mutate(pool, |pool_info| { + pool_info.total_rewards = pool_info.total_rewards.saturating_add(reward_increment) + }); + } + } + + pub fn add_share(who: &T::AccountId, pool: &T::PoolId, add_amount: T::Share) { if add_amount.is_zero() { return; } @@ -135,7 +116,7 @@ impl Pallet { }); } - pub fn remove_share(who: &T::AccountId, pool: T::PoolId, remove_amount: T::Share) { + pub fn remove_share(who: &T::AccountId, pool: &T::PoolId, remove_amount: T::Share) { if remove_amount.is_zero() { return; } @@ -167,7 +148,7 @@ impl Pallet { }); } - pub fn set_share(who: &T::AccountId, pool: T::PoolId, new_share: T::Share) { + pub fn set_share(who: &T::AccountId, pool: &T::PoolId, new_share: T::Share) { let (share, _) = Self::share_and_withdrawn_reward(pool, who); if new_share > share { @@ -177,7 +158,7 @@ impl Pallet { } } - pub fn claim_rewards(who: &T::AccountId, pool: T::PoolId) { + pub fn claim_rewards(who: &T::AccountId, pool: &T::PoolId) { ShareAndWithdrawnReward::::mutate(pool, who, |(share, withdrawn_rewards)| { if share.is_zero() { return; diff --git a/rewards/src/mock.rs b/rewards/src/mock.rs index 5838f30bc..2a34337b3 100644 --- a/rewards/src/mock.rs +++ b/rewards/src/mock.rs @@ -16,14 +16,11 @@ pub type Balance = u64; pub type Share = u64; pub type PoolId = u32; pub type BlockNumber = u64; -pub type CurrencyId = u32; pub const ALICE: AccountId = 1; pub const BOB: AccountId = 2; pub const CAROL: AccountId = 3; pub const DOT_POOL: PoolId = 1; -pub const BTC_POOL: PoolId = 2; -pub const XBTC_POOL: PoolId = 3; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -52,6 +49,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } thread_local! { @@ -59,41 +57,17 @@ thread_local! { } pub struct Handler; -impl RewardHandler for Handler { - type Share = Share; +impl RewardHandler for Handler { type Balance = Balance; type PoolId = PoolId; - type CurrencyId = CurrencyId; - - fn accumulate_reward( - now: BlockNumber, - mut callback: impl FnMut(Self::PoolId, Self::Balance), - ) -> Vec<(Self::CurrencyId, Self::Balance)> { - if now % 2 == 0 { - let mut total_accumulated_rewards = 0; - let valid_pool_ids = vec![DOT_POOL, BTC_POOL]; - - for (pool, _) in Pools::::iter() { - if valid_pool_ids.contains(&pool) { - let rewards: Balance = 100; - callback(pool, rewards); - total_accumulated_rewards += rewards; - } - } - - vec![(1, total_accumulated_rewards)] - } else { - vec![] - } - } - fn payout(who: &AccountId, pool: Self::PoolId, amount: Self::Balance) { + fn payout(who: &AccountId, pool: &Self::PoolId, amount: Self::Balance) { RECEIVED_PAYOUT.with(|v| { let mut old_map = v.borrow().clone(); - if let Some(before) = old_map.get_mut(&(pool, *who)) { + if let Some(before) = old_map.get_mut(&(*pool, *who)) { *before += amount; } else { - old_map.insert((pool, *who), amount); + old_map.insert((*pool, *who), amount); }; *v.borrow_mut() = old_map; @@ -106,7 +80,6 @@ impl Config for Runtime { type Balance = Balance; type PoolId = PoolId; type Handler = Handler; - type WeightInfo = (); } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -118,8 +91,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - RewardsModule: rewards::{Module, Storage, Call}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + RewardsModule: rewards::{Pallet, Storage, Call}, } ); diff --git a/rewards/src/tests.rs b/rewards/src/tests.rs index b3d8b9d30..cc2380db8 100644 --- a/rewards/src/tests.rs +++ b/rewards/src/tests.rs @@ -18,7 +18,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, ALICE), (0, 0)); - RewardsModule::add_share(&ALICE, DOT_POOL, 0); + RewardsModule::add_share(&ALICE, &DOT_POOL, 0); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -29,7 +29,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, ALICE), (0, 0)); - RewardsModule::add_share(&ALICE, DOT_POOL, 100); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -54,7 +54,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, BOB), (0, 0)); - RewardsModule::add_share(&BOB, DOT_POOL, 50); + RewardsModule::add_share(&BOB, &DOT_POOL, 50); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -65,7 +65,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, BOB), (50, 2500)); - RewardsModule::add_share(&ALICE, DOT_POOL, 150); + RewardsModule::add_share(&ALICE, &DOT_POOL, 150); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -81,12 +81,12 @@ fn add_share_should_work() { #[test] fn claim_rewards_should_work() { ExtBuilder::default().build().execute_with(|| { - RewardsModule::add_share(&ALICE, DOT_POOL, 100); - RewardsModule::add_share(&BOB, DOT_POOL, 100); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); + RewardsModule::add_share(&BOB, &DOT_POOL, 100); Pools::::mutate(DOT_POOL, |pool_info| { pool_info.total_rewards += 5000; }); - RewardsModule::add_share(&CAROL, DOT_POOL, 200); + RewardsModule::add_share(&CAROL, &DOT_POOL, 200); assert_eq!( RewardsModule::pools(DOT_POOL), @@ -112,7 +112,7 @@ fn claim_rewards_should_work() { 0 ); - RewardsModule::claim_rewards(&ALICE, DOT_POOL); + RewardsModule::claim_rewards(&ALICE, &DOT_POOL); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -127,7 +127,7 @@ fn claim_rewards_should_work() { 2500 ); - RewardsModule::claim_rewards(&CAROL, DOT_POOL); + RewardsModule::claim_rewards(&CAROL, &DOT_POOL); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -142,7 +142,7 @@ fn claim_rewards_should_work() { 0 ); - RewardsModule::claim_rewards(&BOB, DOT_POOL); + RewardsModule::claim_rewards(&BOB, &DOT_POOL); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -162,8 +162,8 @@ fn claim_rewards_should_work() { #[test] fn remove_share_should_work() { ExtBuilder::default().build().execute_with(|| { - RewardsModule::add_share(&ALICE, DOT_POOL, 100); - RewardsModule::add_share(&BOB, DOT_POOL, 100); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); + RewardsModule::add_share(&BOB, &DOT_POOL, 100); Pools::::mutate(DOT_POOL, |pool_info| { pool_info.total_rewards += 10000; }); @@ -188,7 +188,7 @@ fn remove_share_should_work() { ); // remove amount is zero, do not claim interest - RewardsModule::remove_share(&ALICE, DOT_POOL, 0); + RewardsModule::remove_share(&ALICE, &DOT_POOL, 0); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -203,7 +203,7 @@ fn remove_share_should_work() { 0 ); - RewardsModule::remove_share(&BOB, DOT_POOL, 50); + RewardsModule::remove_share(&BOB, &DOT_POOL, 50); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -218,7 +218,7 @@ fn remove_share_should_work() { 5000 ); - RewardsModule::remove_share(&ALICE, DOT_POOL, 101); + RewardsModule::remove_share(&ALICE, &DOT_POOL, 101); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -248,7 +248,7 @@ fn set_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, ALICE), (0, 0)); - RewardsModule::set_share(&ALICE, DOT_POOL, 100); + RewardsModule::set_share(&ALICE, &DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -271,7 +271,7 @@ fn set_share_should_work() { } ); - RewardsModule::set_share(&ALICE, DOT_POOL, 500); + RewardsModule::set_share(&ALICE, &DOT_POOL, 500); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -286,7 +286,7 @@ fn set_share_should_work() { 0 ); - RewardsModule::set_share(&ALICE, DOT_POOL, 100); + RewardsModule::set_share(&ALICE, &DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -304,43 +304,18 @@ fn set_share_should_work() { } #[test] -fn on_initialize_should_work() { +fn accumulate_reward_should_work() { ExtBuilder::default().build().execute_with(|| { - Pools::::mutate(DOT_POOL, |pool_info| { - pool_info.total_rewards += 100; - }); - Pools::::mutate(BTC_POOL, |pool_info| { - pool_info.total_rewards += 200; - }); - Pools::::mutate(XBTC_POOL, |pool_info| { - pool_info.total_rewards += 300; - }); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { total_shares: 0, - total_rewards: 100, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(BTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 200, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(XBTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, + total_rewards: 0, total_withdrawn_rewards: 0, } ); - RewardsModule::on_initialize(1); + RewardsModule::accumulate_reward(&DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -349,47 +324,5 @@ fn on_initialize_should_work() { total_withdrawn_rewards: 0, } ); - assert_eq!( - RewardsModule::pools(BTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 200, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(XBTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, - total_withdrawn_rewards: 0, - } - ); - - RewardsModule::on_initialize(2); - assert_eq!( - RewardsModule::pools(DOT_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 200, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(BTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(XBTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, - total_withdrawn_rewards: 0, - } - ); }); } diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 641eb41b2..735420dd3 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -35,3 +35,7 @@ std = [ "frame-system/std", "orml-traits/std", ] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] diff --git a/tokens/src/imbalances.rs b/tokens/src/imbalances.rs index 76faac858..084a3b9a5 100644 --- a/tokens/src/imbalances.rs +++ b/tokens/src/imbalances.rs @@ -1,7 +1,7 @@ // wrapping these imbalances in a private module is necessary to ensure absolute // privacy of the inner member. use crate::{Config, TotalIssuance}; -use frame_support::traits::{Get, Imbalance, TryDrop}; +use frame_support::traits::{Get, Imbalance, SameOrOther, TryDrop}; use sp_runtime::traits::{Saturating, Zero}; use sp_std::{marker, mem, result}; @@ -21,6 +21,12 @@ impl> PositiveImbalance> Default for PositiveImbalance { + fn default() -> Self { + Self::zero() + } +} + /// Opaque, move-only struct with private fields that serves as a token /// denoting that funds have been destroyed without any equal and opposite /// accounting. @@ -37,6 +43,12 @@ impl> NegativeImbalance> Default for NegativeImbalance { + fn default() -> Self { + Self::zero() + } +} + impl> TryDrop for PositiveImbalance { fn try_drop(self) -> result::Result<(), Self> { self.drop_zero() @@ -73,14 +85,18 @@ impl> Imbalance for Pos self.0 = self.0.saturating_add(other.0); mem::forget(other); } - fn offset(self, other: Self::Opposite) -> result::Result { + // allow to make the impl same with `pallet-balances` + #[allow(clippy::comparison_chain)] + fn offset(self, other: Self::Opposite) -> SameOrOther { let (a, b) = (self.0, other.0); mem::forget((self, other)); - if a >= b { - Ok(Self::new(a - b)) + if a > b { + SameOrOther::Same(Self::new(a - b)) + } else if b > a { + SameOrOther::Other(NegativeImbalance::new(b - a)) } else { - Err(NegativeImbalance::new(b - a)) + SameOrOther::None } } fn peek(&self) -> T::Balance { @@ -124,14 +140,18 @@ impl> Imbalance for Neg self.0 = self.0.saturating_add(other.0); mem::forget(other); } - fn offset(self, other: Self::Opposite) -> result::Result { + // allow to make the impl same with `pallet-balances` + #[allow(clippy::comparison_chain)] + fn offset(self, other: Self::Opposite) -> SameOrOther { let (a, b) = (self.0, other.0); mem::forget((self, other)); - if a >= b { - Ok(Self::new(a - b)) + if a > b { + SameOrOther::Same(Self::new(a - b)) + } else if b > a { + SameOrOther::Other(PositiveImbalance::new(b - a)) } else { - Err(PositiveImbalance::new(b - a)) + SameOrOther::None } } fn peek(&self) -> T::Balance { diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index 717698ff4..6c1202fca 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -47,7 +47,7 @@ use frame_support::{ LockableCurrency as PalletLockableCurrency, ReservableCurrency as PalletReservableCurrency, SignedImbalance, WithdrawReasons, }, - transactional, + transactional, PalletId, }; use frame_system::{ensure_signed, pallet_prelude::*}; use orml_traits::{ @@ -61,7 +61,7 @@ use sp_runtime::{ AccountIdConversion, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Member, Saturating, StaticLookup, Zero, }, - DispatchError, DispatchResult, ModuleId, RuntimeDebug, + DispatchError, DispatchResult, RuntimeDebug, }; use sp_std::{ convert::{Infallible, TryFrom, TryInto}, @@ -348,7 +348,7 @@ pub mod module { impl Pallet { /// Check whether account_id is a module account pub(crate) fn is_module_account_id(account_id: &T::AccountId) -> bool { - ModuleId::try_from_account(account_id).is_some() + PalletId::try_from_account(account_id).is_some() } pub(crate) fn try_mutate_account( @@ -381,10 +381,10 @@ impl Pallet { // If existed before, decrease account provider. // Ignore the result, because if it failed means that these’s remain consumers, // and the account storage in frame_system shouldn't be repeaded. - let _ = frame_system::Module::::dec_providers(who); + let _ = frame_system::Pallet::::dec_providers(who); } else if !existed && exists { // if new, increase account provider - frame_system::Module::::inc_providers(who); + frame_system::Pallet::::inc_providers(who); } if let Some(dust_amount) = handle_dust { @@ -446,13 +446,13 @@ impl Pallet { >::remove(who, currency_id); if existed { // decrease account ref count when destruct lock - frame_system::Module::::dec_consumers(who); + frame_system::Pallet::::dec_consumers(who); } } else { >::insert(who, currency_id, locks); if !existed { // increase account ref count when initialize lock - if frame_system::Module::::inc_consumers(who).is_err() { + if frame_system::Pallet::::inc_consumers(who).is_err() { // No providers for the locks. This is impossible under normal circumstances // since the funds that are under the lock will themselves be stored in the // account and therefore will need a reference. diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index a46a04667..c83901dae 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -54,6 +54,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } thread_local! { @@ -75,7 +76,7 @@ impl Contains for TenToFourteen { fn add(new: &AccountId) { TEN_TO_FOURTEEN.with(|v| { let mut members = v.borrow_mut(); - members.push(*new); + members.push(new.clone()); members.sort(); }) } @@ -95,12 +96,12 @@ parameter_types! { pub const ProposalBondMinimum: u64 = 1; pub const SpendPeriod: u64 = 2; pub const Burn: Permill = Permill::from_percent(50); - pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry"); + pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const GetTokenId: CurrencyId = DOT; } impl pallet_treasury::Config for Runtime { - type ModuleId = TreasuryModuleId; + type PalletId = TreasuryPalletId; type Currency = CurrencyAdapter; type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; @@ -164,7 +165,7 @@ impl ChangeMembers for TestChangeMembers { } parameter_types! { - pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect"; + pub const ElectionsPhragmenPalletId: LockIdentifier = *b"phrelect"; pub const CandidacyBond: u64 = 3; pub const VotingBond: u64 = 2; pub const DesiredMembers: u32 = 2; @@ -175,7 +176,7 @@ parameter_types! { } impl pallet_elections_phragmen::Config for Runtime { - type ModuleId = ElectionsPhragmenModuleId; + type PalletId = ElectionsPhragmenPalletId; type Event = Event; type Currency = CurrencyAdapter; type CurrencyToVote = SaturatingCurrencyToVote; @@ -203,7 +204,7 @@ parameter_type_with_key! { } parameter_types! { - pub DustAccount: AccountId = ModuleId(*b"orml/dst").into_account(); + pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); } impl Config for Runtime { @@ -226,10 +227,10 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Tokens: tokens::{Module, Storage, Event, Config}, - Treasury: pallet_treasury::{Module, Call, Storage, Config, Event}, - ElectionsPhragmen: pallet_elections_phragmen::{Module, Call, Storage, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Tokens: tokens::{Pallet, Storage, Event, Config}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + ElectionsPhragmen: pallet_elections_phragmen::{Pallet, Call, Storage, Event}, } ); diff --git a/traits/Cargo.toml b/traits/Cargo.toml index e99c0d48b..2c92c0f16 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -8,15 +8,16 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } num-traits = { version = "0.2.14", default-features = false } -impl-trait-for-tuples = "0.1.3" +impl-trait-for-tuples = "0.2.1" frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } +xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 @@ -31,4 +32,5 @@ std = [ "num-traits/std", "frame-support/std", "orml-utilities/std", + "xcm/std", ] diff --git a/traits/src/lib.rs b/traits/src/lib.rs index d8dfbab39..a8962dbcf 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -1,7 +1,8 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; -use sp_runtime::RuntimeDebug; +use impl_trait_for_tuples::impl_for_tuples; +use sp_runtime::{DispatchResult, RuntimeDebug}; use sp_std::{ cmp::{Eq, PartialEq}, prelude::Vec, @@ -27,6 +28,7 @@ pub mod auction; pub mod currency; pub mod data_provider; pub mod get_by_key; +pub mod location; pub mod nft; pub mod price; pub mod rewards; @@ -64,11 +66,23 @@ pub struct TimestampedValue { pub timestamp: Moment, } -#[impl_trait_for_tuples::impl_for_tuples(30)] +#[impl_for_tuples(30)] pub trait Happened { fn happened(t: &T); } +pub trait Handler { + fn handle(t: &T) -> DispatchResult; +} + +#[impl_for_tuples(30)] +impl Handler for Tuple { + fn handle(t: &T) -> DispatchResult { + for_tuples!( #( Tuple::handle(t); )* ); + Ok(()) + } +} + pub trait Contains { fn contains(t: &T) -> bool; } diff --git a/traits/src/location.rs b/traits/src/location.rs new file mode 100644 index 000000000..a0b9bdd0b --- /dev/null +++ b/traits/src/location.rs @@ -0,0 +1,123 @@ +use xcm::v0::{ + Junction::{self, *}, + MultiAsset, MultiLocation, +}; + +pub trait Parse { + /// Returns the "chain" location part. It could be parent, sibling + /// parachain, or child parachain. + fn chain_part(&self) -> Option; + /// Returns "non-chain" location part. + fn non_chain_part(&self) -> Option; +} + +fn is_chain_junction(junction: Option<&Junction>) -> bool { + matches!(junction, Some(Parent) | Some(Parachain { id: _ })) +} + +impl Parse for MultiLocation { + fn chain_part(&self) -> Option { + match (self.first(), self.at(1)) { + (Some(Parent), Some(Parachain { id })) => Some((Parent, Parachain { id: *id }).into()), + (Some(Parent), _) => Some(Parent.into()), + (Some(Parachain { id }), _) => Some(Parachain { id: *id }.into()), + _ => None, + } + } + + fn non_chain_part(&self) -> Option { + let mut location = self.clone(); + while is_chain_junction(location.first()) { + let _ = location.take_first(); + } + + if location != MultiLocation::Null { + Some(location) + } else { + None + } + } +} + +pub trait Reserve { + /// Returns assets reserve location. + fn reserve(&self) -> Option; +} + +impl Reserve for MultiAsset { + fn reserve(&self) -> Option { + if let MultiAsset::ConcreteFungible { id, .. } = self { + id.chain_part() + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PARACHAIN: Junction = Parachain { id: 1 }; + const GENERAL_INDEX: Junction = GeneralIndex { id: 1 }; + + fn concrete_fungible(id: MultiLocation) -> MultiAsset { + MultiAsset::ConcreteFungible { id, amount: 1 } + } + + #[test] + fn parent_as_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X2(Parent, GENERAL_INDEX)).reserve(), + Some(Parent.into()) + ); + } + + #[test] + fn sibling_parachain_as_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X3(Parent, PARACHAIN, GENERAL_INDEX)).reserve(), + Some((Parent, PARACHAIN).into()) + ); + } + + #[test] + fn child_parachain_as_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X2(PARACHAIN, GENERAL_INDEX)).reserve(), + Some(PARACHAIN.into()) + ); + } + + #[test] + fn no_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X1(GeneralKey("DOT".into()))).reserve(), + None + ); + } + + #[test] + fn non_chain_part_works() { + assert_eq!(MultiLocation::X1(Parent).non_chain_part(), None); + assert_eq!(MultiLocation::X2(Parent, PARACHAIN).non_chain_part(), None); + assert_eq!(MultiLocation::X1(PARACHAIN).non_chain_part(), None); + + assert_eq!( + MultiLocation::X2(Parent, GENERAL_INDEX).non_chain_part(), + Some(GENERAL_INDEX.into()) + ); + assert_eq!( + MultiLocation::X3(Parent, GENERAL_INDEX, GENERAL_INDEX).non_chain_part(), + Some((GENERAL_INDEX, GENERAL_INDEX).into()) + ); + assert_eq!( + MultiLocation::X3(Parent, PARACHAIN, GENERAL_INDEX).non_chain_part(), + Some(GENERAL_INDEX.into()) + ); + assert_eq!( + MultiLocation::X2(PARACHAIN, GENERAL_INDEX).non_chain_part(), + Some(GENERAL_INDEX.into()) + ); + } +} diff --git a/traits/src/rewards.rs b/traits/src/rewards.rs index e53b905a6..ebf21f4b8 100644 --- a/traits/src/rewards.rs +++ b/traits/src/rewards.rs @@ -1,27 +1,15 @@ use codec::FullCodec; use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize}; -use sp_std::{fmt::Debug, vec::Vec}; +use sp_std::fmt::Debug; /// Hooks to manage reward pool -pub trait RewardHandler { - /// The share type of pool - type Share: AtLeast32BitUnsigned + Default + Copy + MaybeSerializeDeserialize + Debug; - +pub trait RewardHandler { /// The reward balance type type Balance: AtLeast32BitUnsigned + Default + Copy + MaybeSerializeDeserialize + Debug; /// The reward pool ID type - type PoolId: Copy + FullCodec; - - /// The currency type - type CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug; - - /// Accumulate rewards - fn accumulate_reward( - now: BlockNumber, - callback: impl FnMut(Self::PoolId, Self::Balance), - ) -> Vec<(Self::CurrencyId, Self::Balance)>; + type PoolId: FullCodec; /// Payout the reward to `who` - fn payout(who: &AccountId, pool: Self::PoolId, amount: Self::Balance); + fn payout(who: &AccountId, pool: &Self::PoolId, amount: Self::Balance); } diff --git a/unknown-tokens/Cargo.toml b/unknown-tokens/Cargo.toml new file mode 100644 index 000000000..3518ee05d --- /dev/null +++ b/unknown-tokens/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "orml-unknown-tokens" +description = "Unknown tokens module that implements `UnknownAsset` trait." +repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/unknown-tokens" +license = "Apache-2.0" +version = "0.4.1-dev" +authors = ["Acala Developers"] +edition = "2018" + +[dependencies] +serde = { version = "1.0.124", optional = true } +codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } + +xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } + +orml-xcm-support = { path = "../xcm-support", default-features = false } + +[dev-dependencies] +sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "xcm/std", + "orml-xcm-support/std", +] diff --git a/unknown-tokens/src/lib.rs b/unknown-tokens/src/lib.rs new file mode 100644 index 000000000..e048ba370 --- /dev/null +++ b/unknown-tokens/src/lib.rs @@ -0,0 +1,115 @@ +#![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::unused_unit)] + +use frame_support::pallet_prelude::*; +use sp_std::vec::Vec; +use xcm::v0::{MultiAsset, MultiLocation}; + +use orml_xcm_support::UnknownAsset; + +pub use module::*; + +mod mock; +mod tests; + +#[frame_support::pallet] +pub mod module { + use super::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type Event: From + IsType<::Event>; + } + + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + pub enum Event { + /// Deposit success. [asset, to] + Deposited(MultiAsset, MultiLocation), + /// Withdraw success. [asset, from] + Withdrawn(MultiAsset, MultiLocation), + } + + #[pallet::error] + pub enum Error { + /// The balance is too low. + BalanceTooLow, + /// The operation will cause balance to overflow. + BalanceOverflow, + /// Unhandled asset. + UnhandledAsset, + } + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::hooks] + impl Hooks for Pallet {} + + /// Concrete fungible balances under a given location and a concrete + /// fungible id. + /// + /// double_map: who, asset_id => u128 + #[pallet::storage] + #[pallet::getter(fn concrete_fungible_balances)] + pub(crate) type ConcreteFungibleBalances = + StorageDoubleMap<_, Blake2_128Concat, MultiLocation, Blake2_128Concat, MultiLocation, u128, ValueQuery>; + + /// Abstract fungible balances under a given location and a abstract + /// fungible id. + /// + /// double_map: who, asset_id => u128 + #[pallet::storage] + #[pallet::getter(fn abstract_fungible_balances)] + pub(crate) type AbstractFungibleBalances = + StorageDoubleMap<_, Blake2_128Concat, MultiLocation, Blake2_128Concat, Vec, u128, ValueQuery>; + + #[pallet::call] + impl Pallet {} +} + +impl UnknownAsset for Pallet { + fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult { + match asset { + MultiAsset::ConcreteFungible { id, amount } => { + ConcreteFungibleBalances::::try_mutate(to, id, |b| -> DispatchResult { + *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; + Ok(()) + }) + } + MultiAsset::AbstractFungible { id, amount } => { + AbstractFungibleBalances::::try_mutate(to, id, |b| -> DispatchResult { + *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; + Ok(()) + }) + } + _ => Err(Error::::UnhandledAsset.into()), + }?; + + Self::deposit_event(Event::Deposited(asset.clone(), to.clone())); + + Ok(()) + } + + fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult { + match asset { + MultiAsset::ConcreteFungible { id, amount } => { + ConcreteFungibleBalances::::try_mutate(from, id, |b| -> DispatchResult { + *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; + Ok(()) + }) + } + MultiAsset::AbstractFungible { id, amount } => { + AbstractFungibleBalances::::try_mutate(from, id, |b| -> DispatchResult { + *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; + Ok(()) + }) + } + _ => Err(Error::::UnhandledAsset.into()), + }?; + + Self::deposit_event(Event::Withdrawn(asset.clone(), from.clone())); + + Ok(()) + } +} diff --git a/unknown-tokens/src/mock.rs b/unknown-tokens/src/mock.rs new file mode 100644 index 000000000..b8e297a15 --- /dev/null +++ b/unknown-tokens/src/mock.rs @@ -0,0 +1,74 @@ +//! Mocks for the unknown pallet. + +#![cfg(test)] + +use super::*; +use crate as unknown_tokens; + +use frame_support::{construct_runtime, parameter_types}; +use sp_core::H256; +use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; + +pub type AccountId = AccountId32; + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +impl frame_system::Config for Runtime { + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); +} + +impl Config for Runtime { + type Event = Event; +} + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + UnknownTokens: unknown_tokens::{Pallet, Storage, Event}, + } +); + +pub struct ExtBuilder; + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } +} diff --git a/unknown-tokens/src/tests.rs b/unknown-tokens/src/tests.rs new file mode 100644 index 000000000..cc5c60686 --- /dev/null +++ b/unknown-tokens/src/tests.rs @@ -0,0 +1,144 @@ +//! Unit tests for unknown tokens pallet. + +#![cfg(test)] + +use super::*; +use mock::{Event, *}; + +use frame_support::{assert_err, assert_ok}; +use xcm::v0::Junction; + +const MOCK_RECIPIENT: MultiLocation = MultiLocation::X1(Junction::Parent); +const MOCK_CONCRETE_FUNGIBLE_ID: MultiLocation = MultiLocation::X1(Junction::Parent); + +fn mock_abstract_fungible_id() -> Vec { + vec![1] +} + +fn concrete_fungible(amount: u128) -> MultiAsset { + MultiAsset::ConcreteFungible { + id: MOCK_CONCRETE_FUNGIBLE_ID, + amount, + } +} + +fn abstract_fungible(amount: u128) -> MultiAsset { + MultiAsset::AbstractFungible { + id: mock_abstract_fungible_id(), + amount, + } +} + +#[test] +fn deposit_concrete_fungible_asset_works() { + ExtBuilder.build().execute_with(|| { + let asset = concrete_fungible(3); + assert_ok!(UnknownTokens::deposit(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::concrete_fungible_balances(&MOCK_RECIPIENT, &MOCK_CONCRETE_FUNGIBLE_ID), + 3 + ); + + let deposited_event = Event::unknown_tokens(crate::Event::Deposited(asset, MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == deposited_event)); + + // overflow case + let max_asset = concrete_fungible(u128::max_value()); + assert_err!( + UnknownTokens::deposit(&max_asset, &MOCK_RECIPIENT), + Error::::BalanceOverflow + ); + }); +} + +#[test] +fn deposit_abstract_fungible_asset() { + ExtBuilder.build().execute_with(|| { + let asset = abstract_fungible(3); + assert_ok!(UnknownTokens::deposit(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id()), + 3 + ); + + let deposited_event = Event::unknown_tokens(crate::Event::Deposited(asset, MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == deposited_event)); + + // overflow case + let max_asset = abstract_fungible(u128::max_value()); + assert_err!( + UnknownTokens::deposit(&max_asset, &MOCK_RECIPIENT), + Error::::BalanceOverflow + ); + assert_eq!( + UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id()), + 3 + ); + }); +} + +#[test] +fn deposit_unhandled_asset_should_fail() { + ExtBuilder.build().execute_with(|| { + assert_err!( + UnknownTokens::deposit(&MultiAsset::All, &MOCK_RECIPIENT), + Error::::UnhandledAsset + ); + }); +} + +#[test] +fn withdraw_concrete_fungible_asset_works() { + ExtBuilder.build().execute_with(|| { + ConcreteFungibleBalances::::insert(&MOCK_RECIPIENT, &MOCK_CONCRETE_FUNGIBLE_ID, 3); + + let asset = concrete_fungible(3); + assert_ok!(UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::concrete_fungible_balances(&MOCK_RECIPIENT, &MOCK_CONCRETE_FUNGIBLE_ID), + 0 + ); + + let withdrawn_event = Event::unknown_tokens(crate::Event::Withdrawn(asset.clone(), MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == withdrawn_event)); + + // balance too low case + assert_err!( + UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), + Error::::BalanceTooLow + ); + }); +} + +#[test] +fn withdraw_abstract_fungible_asset_works() { + ExtBuilder.build().execute_with(|| { + AbstractFungibleBalances::::insert(&MOCK_RECIPIENT, &mock_abstract_fungible_id(), 3); + + let asset = abstract_fungible(3); + assert_ok!(UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id()), + 0 + ); + + let withdrawn_event = Event::unknown_tokens(crate::Event::Withdrawn(asset.clone(), MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == withdrawn_event)); + + // balance too low case + assert_err!( + UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), + Error::::BalanceTooLow + ); + }); +} + +#[test] +fn withdraw_unhandled_asset_should_fail() { + ExtBuilder.build().execute_with(|| { + assert_err!( + UnknownTokens::withdraw(&MultiAsset::All, &MOCK_RECIPIENT), + Error::::UnhandledAsset + ); + }); +} diff --git a/utilities/Cargo.toml b/utilities/Cargo.toml index 955ebc0ec..4b505a7a6 100644 --- a/utilities/Cargo.toml +++ b/utilities/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -18,7 +18,7 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 [dev-dependencies] -serde_json = "1.0.53" +serde_json = "1.0.64" frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } [features] diff --git a/vesting/Cargo.toml b/vesting/Cargo.toml index bb4cdc717..064519e91 100644 --- a/vesting/Cargo.toml +++ b/vesting/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -34,3 +34,7 @@ std = [ "frame-support/std", "frame-system/std", ] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] diff --git a/vesting/src/lib.rs b/vesting/src/lib.rs index b314dfb0b..b913d0516 100644 --- a/vesting/src/lib.rs +++ b/vesting/src/lib.rs @@ -277,7 +277,7 @@ impl Pallet { /// Returns locked balance based on current block number. fn locked_balance(who: &T::AccountId) -> BalanceOf { - let now = >::block_number(); + let now = >::block_number(); >::mutate_exists(who, |maybe_schedules| { let total = if let Some(schedules) = maybe_schedules.as_mut() { let mut total: BalanceOf = Zero::zero(); diff --git a/vesting/src/mock.rs b/vesting/src/mock.rs index 7274ef9c7..e3b250191 100644 --- a/vesting/src/mock.rs +++ b/vesting/src/mock.rs @@ -38,6 +38,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } type Balance = u64; @@ -52,7 +53,7 @@ impl pallet_balances::Config for Runtime { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = frame_system::Pallet; type MaxLocks = (); type WeightInfo = (); } @@ -92,9 +93,9 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Vesting: vesting::{Module, Storage, Call, Event, Config}, - PalletBalances: pallet_balances::{Module, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Vesting: vesting::{Pallet, Storage, Call, Event, Config}, + PalletBalances: pallet_balances::{Pallet, Call, Storage, Config, Event}, } ); diff --git a/xcm-support/Cargo.toml b/xcm-support/Cargo.toml index 045d9898c..d6b1ae783 100644 --- a/xcm-support/Cargo.toml +++ b/xcm-support/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "orml-xcm-support" -description = "Crosschain token transfer" +description = "Supporting module for XCM integration." repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xcm-support" license = "Apache-2.0" version = "0.4.1-dev" diff --git a/xcm-support/README.md b/xcm-support/README.md new file mode 100644 index 000000000..11fa712a6 --- /dev/null +++ b/xcm-support/README.md @@ -0,0 +1,6 @@ +# XCM Support Module. + +## Overview + +The XCM support module provides supporting traits, types and implementations, +to support cross-chain message(XCM) integration with ORML modules. diff --git a/xcm-support/src/currency_adapter.rs b/xcm-support/src/currency_adapter.rs new file mode 100644 index 000000000..8a9b820bf --- /dev/null +++ b/xcm-support/src/currency_adapter.rs @@ -0,0 +1,108 @@ +use codec::FullCodec; +use sp_runtime::traits::{Convert, MaybeSerializeDeserialize, SaturatedConversion}; +use sp_std::{ + cmp::{Eq, PartialEq}, + fmt::Debug, + marker::PhantomData, + prelude::*, + result, +}; + +use xcm::v0::{Error as XcmError, MultiAsset, MultiLocation, Result}; +use xcm_executor::traits::{LocationConversion, MatchesFungible, TransactAsset}; + +use crate::UnknownAsset as UnknownAssetT; + +/// Asset transaction errors. +enum Error { + /// Failed to match fungible. + FailedToMatchFungible, + /// `MultiLocation` to `AccountId` Conversion failed. + AccountIdConversionFailed, + /// `CurrencyId` conversion failed. + CurrencyIdConversionFailed, +} + +impl From for XcmError { + fn from(e: Error) -> Self { + match e { + Error::FailedToMatchFungible => XcmError::FailedToTransactAsset("FailedToMatchFungible"), + Error::AccountIdConversionFailed => XcmError::FailedToTransactAsset("AccountIdConversionFailed"), + Error::CurrencyIdConversionFailed => XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), + } + } +} + +/// The `TransactAsset` implementation, to handle `MultiAsset` deposit/withdraw. +/// +/// If the asset is known, deposit/withdraw will be handled by `MultiCurrency`, +/// else by `UnknownAsset` if unknown. +pub struct MultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Matcher, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, +>( + PhantomData<( + MultiCurrency, + UnknownAsset, + Matcher, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, + )>, +); + +impl< + MultiCurrency: orml_traits::MultiCurrency, + UnknownAsset: UnknownAssetT, + Matcher: MatchesFungible, + AccountId: sp_std::fmt::Debug, + AccountIdConvert: LocationConversion, + CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, + CurrencyIdConvert: Convert>, + > TransactAsset + for MultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Matcher, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, + > +{ + fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { + match ( + AccountIdConvert::from_location(location), + CurrencyIdConvert::convert(asset.clone()), + Matcher::matches_fungible(&asset), + ) { + // known asset + (Some(who), Some(currency_id), Some(amount)) => { + MultiCurrency::deposit(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) + } + // unknown asset + _ => UnknownAsset::deposit(asset, location).map_err(|e| XcmError::FailedToTransactAsset(e.into())), + } + } + + fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> result::Result { + UnknownAsset::withdraw(asset, location).or_else(|_| { + let who = AccountIdConvert::from_location(location) + .ok_or_else(|| XcmError::from(Error::AccountIdConversionFailed))?; + let currency_id = CurrencyIdConvert::convert(asset.clone()) + .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; + let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) + .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? + .saturated_into(); + MultiCurrency::withdraw(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) + })?; + + Ok(asset.clone()) + } +} diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index a5d55ed10..039af0295 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -1,142 +1,82 @@ +//! # XCM Support Module. +//! +//! ## Overview +//! +//! The XCM support module provides supporting traits, types and +//! implementations, to support cross-chain message(XCM) integration with ORML +//! modules. + #![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::unused_unit)] -use codec::FullCodec; -use sp_runtime::traits::{CheckedConversion, Convert, MaybeSerializeDeserialize, SaturatedConversion}; -use sp_std::{ - cmp::{Eq, PartialEq}, - collections::btree_set::BTreeSet, - convert::{TryFrom, TryInto}, - fmt::Debug, - marker::PhantomData, - prelude::*, - result, -}; +use frame_support::dispatch::{DispatchError, DispatchResult}; +use sp_runtime::traits::{CheckedConversion, Convert}; +use sp_std::{convert::TryFrom, marker::PhantomData, prelude::*}; -use xcm::v0::{Error, Junction, MultiAsset, MultiLocation, Result}; -use xcm_executor::traits::{FilterAssetLocation, LocationConversion, MatchesFungible, NativeAsset, TransactAsset}; +use xcm::v0::{MultiAsset, MultiLocation, Xcm}; +use xcm_executor::traits::{FilterAssetLocation, MatchesFungible}; -use frame_support::{log, traits::Get}; +use orml_traits::location::Reserve; -pub trait CurrencyIdConversion { - fn from_asset(asset: &MultiAsset) -> Option; -} +pub use currency_adapter::MultiCurrencyAdapter; -pub struct MultiCurrencyAdapter( - PhantomData<( - MultiCurrency, - Matcher, - AccountIdConverter, - AccountId, - CurrencyIdConverter, - CurrencyId, - )>, -); +mod currency_adapter; -impl< - MultiCurrency: orml_traits::MultiCurrency, - Matcher: MatchesFungible, - AccountIdConverter: LocationConversion, - AccountId: sp_std::fmt::Debug, - CurrencyIdConverter: CurrencyIdConversion, - CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, - > TransactAsset - for MultiCurrencyAdapter -{ - fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { - log::info!("------------------------------------------------"); - log::info!(">>> trying deposit. asset: {:?}, location: {:?}", asset, location); - let who = AccountIdConverter::from_location(location).ok_or(())?; - log::info!("who: {:?}", who); - let currency_id = CurrencyIdConverter::from_asset(asset).ok_or(())?; - log::info!("currency_id: {:?}", currency_id); - let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset).ok_or(())?.saturated_into(); - log::info!("amount: {:?}", amount); - MultiCurrency::deposit(currency_id, &who, amount).map_err(|_| ())?; - log::info!(">>> success deposit."); - log::info!("------------------------------------------------"); - Ok(()) - } +mod tests; - fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> result::Result { - log::info!("------------------------------------------------"); - log::info!(">>> trying withdraw. asset: {:?}, location: {:?}", asset, location); - let who = AccountIdConverter::from_location(location).ok_or(())?; - log::info!("who: {:?}", who); - let currency_id = CurrencyIdConverter::from_asset(asset).ok_or(())?; - log::info!("currency_id: {:?}", currency_id); - let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset).ok_or(())?.saturated_into(); - log::info!("amount: {:?}", amount); - MultiCurrency::withdraw(currency_id, &who, amount).map_err(|_| ())?; - log::info!(">>> success withdraw."); - log::info!("------------------------------------------------"); - Ok(asset.clone()) - } +/// The XCM handler to execute XCM locally. +pub trait XcmHandler { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult; } -pub struct IsConcreteWithGeneralKey( - PhantomData<(CurrencyId, FromRelayChainBalance)>, -); -impl MatchesFungible - for IsConcreteWithGeneralKey +/// A `MatchesFungible` implementation. It matches concrete fungible assets +/// whose `id` could be converted into `CurrencyId`. +pub struct IsNativeConcrete(PhantomData<(CurrencyId, CurrencyIdConvert)>); +impl MatchesFungible for IsNativeConcrete where - CurrencyId: TryFrom>, - B: TryFrom, - FromRelayChainBalance: Convert, + CurrencyIdConvert: Convert>, + Amount: TryFrom, { - fn matches_fungible(a: &MultiAsset) -> Option { + fn matches_fungible(a: &MultiAsset) -> Option { if let MultiAsset::ConcreteFungible { id, amount } = a { - if id == &MultiLocation::X1(Junction::Parent) { - // Convert relay chain decimals to local chain - let local_amount = FromRelayChainBalance::convert(*amount); - return CheckedConversion::checked_from(local_amount); - } - if let Some(Junction::GeneralKey(key)) = id.last() { - if TryInto::::try_into(key.clone()).is_ok() { - return CheckedConversion::checked_from(*amount); - } + if CurrencyIdConvert::convert(id.clone()).is_some() { + return CheckedConversion::checked_from(*amount); } } None } } -pub struct NativePalletAssetOr(PhantomData); -impl, MultiLocation)>>> FilterAssetLocation for NativePalletAssetOr { +/// A `FilterAssetLocation` implementation. Filters multi native assets whose +/// reserve is same with `origin`. +pub struct MultiNativeAsset; +impl FilterAssetLocation for MultiNativeAsset { fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { - if NativeAsset::filter_asset_location(asset, origin) { - return true; - } - - // native orml-tokens with a general key - if let MultiAsset::ConcreteFungible { ref id, .. } = asset { - if let Some(Junction::GeneralKey(key)) = id.last() { - return Pairs::get().contains(&(key.clone(), origin.clone())); + if let Some(ref reserve) = asset.reserve() { + if reserve == origin { + return true; } } - false } } -pub struct CurrencyIdConverter( - PhantomData, - PhantomData, -); -impl CurrencyIdConversion - for CurrencyIdConverter -where - CurrencyId: TryFrom>, - RelayChainCurrencyId: Get, -{ - fn from_asset(asset: &MultiAsset) -> Option { - if let MultiAsset::ConcreteFungible { id: location, .. } = asset { - if location == &MultiLocation::X1(Junction::Parent) { - return Some(RelayChainCurrencyId::get()); - } - if let Some(Junction::GeneralKey(key)) = location.last() { - return CurrencyId::try_from(key.clone()).ok(); - } - } - None +/// Handlers unknown asset deposit and withdraw. +pub trait UnknownAsset { + /// Deposit unknown asset. + fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult; + + /// Withdraw unknown asset. + fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult; +} + +const NO_UNKNOWN_ASSET_IMPL: &str = "NoUnknownAssetImpl"; + +impl UnknownAsset for () { + fn deposit(_asset: &MultiAsset, _to: &MultiLocation) -> DispatchResult { + Err(DispatchError::Other(NO_UNKNOWN_ASSET_IMPL)) + } + fn withdraw(_asset: &MultiAsset, _from: &MultiLocation) -> DispatchResult { + Err(DispatchError::Other(NO_UNKNOWN_ASSET_IMPL)) } } diff --git a/xcm-support/src/tests.rs b/xcm-support/src/tests.rs new file mode 100644 index 000000000..c83b5021b --- /dev/null +++ b/xcm-support/src/tests.rs @@ -0,0 +1,109 @@ +//! Unit tests for xcm-support implementations. + +#![cfg(test)] + +use super::*; + +use xcm::v0::{Junction::*, MultiAsset::ConcreteFungible, MultiLocation::*}; + +#[derive(Debug, PartialEq, Eq)] +pub enum TestCurrencyId { + TokenA, + TokenB, + RelayChainToken, +} + +pub struct CurrencyIdConvert; +impl Convert> for CurrencyIdConvert { + fn convert(l: MultiLocation) -> Option { + use TestCurrencyId::*; + let token_a: Vec = "TokenA".into(); + let token_b: Vec = "TokenB".into(); + match l { + X1(Parent) => Some(RelayChainToken), + X3(Parent, Parachain { id: 1 }, GeneralKey(k)) if k == token_a => Some(TokenA), + X3(Parent, Parachain { id: 2 }, GeneralKey(k)) if k == token_b => Some(TokenB), + _ => None, + } + } +} + +type MatchesCurrencyId = IsNativeConcrete; + +#[test] +fn is_native_concrete_matches_native_currencies() { + assert_eq!( + MatchesCurrencyId::matches_fungible(&ConcreteFungible { + id: X1(Parent), + amount: 100 + }), + Some(100), + ); + assert_eq!( + MatchesCurrencyId::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenA".into())), + amount: 100 + }), + Some(100), + ); + assert_eq!( + MatchesCurrencyId::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 2 }, GeneralKey("TokenB".into())), + amount: 100 + }), + Some(100), + ); +} + +#[test] +fn is_native_concrete_does_not_matches_non_native_currencies() { + assert!( + >::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 2 }, GeneralKey("TokenC".into())), + amount: 100 + }) + .is_none() + ); + assert!( + >::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenB".into())), + amount: 100 + }) + .is_none() + ); + assert!( + >::matches_fungible(&ConcreteFungible { + id: X1(GeneralKey("TokenB".into())), + amount: 100 + }) + .is_none() + ); +} + +#[test] +fn multi_native_asset() { + assert!(MultiNativeAsset::filter_asset_location( + &ConcreteFungible { + id: Parent.into(), + amount: 10, + }, + &Parent.into() + )); + assert!(MultiNativeAsset::filter_asset_location( + &ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenA".into())), + amount: 10, + }, + &X2(Parent, Parachain { id: 1 }), + )); + assert_eq!( + MultiNativeAsset::filter_asset_location( + &ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenA".into())), + amount: 10, + }, + &X1(Parent), + ), + false + ); +} diff --git a/xtokens/Cargo.toml b/xtokens/Cargo.toml index 5124431b1..6f45a4462 100644 --- a/xtokens/Cargo.toml +++ b/xtokens/Cargo.toml @@ -1,14 +1,14 @@ [package] name = "orml-xtokens" -description = "Crosschain token transfer" -repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/tokens" +description = "Cross-chain token transfer." +repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xtokens" license = "Apache-2.0" version = "0.4.1-dev" authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -20,12 +20,23 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "roco cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "rococo-v1", default-features = false } xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } -xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } + +orml-xcm-support = { path = "../xcm-support", default-features = false } +orml-traits = { path = "../traits", default-features = false} [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +xcm-simulator = { git = "https://github.com/shaunxw/xcm-simulator", branch = "master" } +cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech/cumulus", branch = "rococo-v1" } +parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "rococo-v1" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } +xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } + orml-tokens = { path = "../tokens", version = "0.4.1-dev" } +orml-traits = { path = "../traits", version = "0.4.1-dev" } [features] default = ["std"] @@ -39,4 +50,6 @@ std = [ "frame-system/std", "cumulus-primitives-core/std", "xcm/std", + "orml-xcm-support/std", + "orml-traits/std", ] diff --git a/xtokens/README.md b/xtokens/README.md new file mode 100644 index 000000000..4e12469b1 --- /dev/null +++ b/xtokens/README.md @@ -0,0 +1,31 @@ +# Xtokens Module + +## Overview + +The xtokens module provides cross-chain token transfer functionality, by cross-consensus +messages(XCM). + +The xtokens module provides functions for +- Token transfer from parachains to relay chain. +- Token transfer between parachains, including relay chain tokens like DOT, + KSM, and parachain tokens like ACA, aUSD. + +## Notes + +#### Integration tests + +Integration tests could be done manually after integrating xtokens into runtime. To cover the full features, set up at least 4 relay chain validators and 3 collators of different parachains, and use dispatchable calls to include all these scenarios: + +- Transfer relay chain tokens to relay chain. +- Transfer tokens issued by parachain A, from parachain A to parachain B. + - Sending the tx from parachain A. + - Set the destination as Parachain B. + - Set the currency ID as parachain A token. +- Transfer tokens issued by parachain B, from parachain A to parachain B. + - Sending the tx from parachain A. + - Set the destination as Parachain B. + - Set the currency ID as parachain B token. +- Transfer tokens issued by parachain C, from parachain A to parachain B. + - Sending the tx from parachain A. + - Set the destination as Parachain B. + - Set the currency ID as parachain C token. diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index e045c3529..7df979629 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -1,60 +1,59 @@ +//! # Xtokens Module +//! +//! ## Overview +//! +//! The xtokens module provides cross-chain token transfer functionality, by +//! cross-consensus messages(XCM). +//! +//! The xtokens module provides functions for +//! - Token transfer from parachains to relay chain. +//! - Token transfer between parachains, including relay chain tokens like DOT, +//! KSM, and parachain tokens like ACA, aUSD. +//! +//! ## Interface +//! +//! ### Dispatchable functions +//! +//! - `transfer`: Transfer local assets with given `CurrencyId` and `Amount`. +//! - `transfer_multiasset`: Transfer `MultiAsset` assets. + #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::from_over_into)] #![allow(clippy::unused_unit)] +#![allow(clippy::large_enum_variant)] -pub use module::*; +use frame_support::{pallet_prelude::*, traits::Get, transactional, Parameter}; +use frame_system::{ensure_signed, pallet_prelude::*}; +use sp_runtime::{ + traits::{AtLeast32BitUnsigned, Convert, MaybeSerializeDeserialize, Member, Zero}, + DispatchError, +}; +use sp_std::prelude::*; -#[frame_support::pallet] -pub mod module { - use codec::{Decode, Encode}; - use frame_support::{pallet_prelude::*, traits::Get, transactional, Parameter}; - use frame_system::{ensure_signed, pallet_prelude::*}; - use sp_runtime::{ - traits::{AtLeast32BitUnsigned, Convert, MaybeSerializeDeserialize, Member}, - RuntimeDebug, - }; - use sp_std::prelude::*; - - use cumulus_primitives_core::{relay_chain::Balance as RelayChainBalance, ParaId}; - use xcm::v0::{Error as XcmError, ExecuteXcm, Junction, MultiAsset, MultiLocation, NetworkId, Order, Xcm}; - use xcm_executor::traits::LocationConversion; - - #[derive(Encode, Decode, Eq, PartialEq, Clone, Copy, RuntimeDebug)] - /// Identity of chain. - pub enum ChainId { - /// The relay chain. - RelayChain, - /// A parachain. - ParaChain(ParaId), - } +use xcm::v0::{ + Junction::*, + MultiAsset, MultiLocation, Order, + Order::*, + Xcm::{self, *}, +}; - #[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug)] - /// Identity of cross chain currency. - pub struct XCurrencyId { - /// The reserve chain of the currency. For instance, the reserve chain - /// of DOT is Polkadot. - pub chain_id: ChainId, - /// The identity of the currency. - pub currency_id: Vec, - } +use orml_traits::location::{Parse, Reserve}; +use orml_xcm_support::XcmHandler; - #[cfg(test)] - impl XCurrencyId { - pub fn new(chain_id: ChainId, currency_id: Vec) -> Self { - XCurrencyId { chain_id, currency_id } - } - } +mod mock; +mod tests; - impl Into for XCurrencyId { - fn into(self) -> MultiLocation { - MultiLocation::X1(Junction::GeneralKey(self.currency_id)) - } - } +pub use module::*; + +#[frame_support::pallet] +pub mod module { + use super::*; #[pallet::config] pub trait Config: frame_system::Config { type Event: From> + IsType<::Event>; + /// The balance type. type Balance: Parameter + Member + AtLeast32BitUnsigned @@ -63,51 +62,43 @@ pub mod module { + MaybeSerializeDeserialize + Into; - /// Convertor `Balance` to `RelayChainBalance`. - type ToRelayChainBalance: Convert; + /// Currency Id. + type CurrencyId: Parameter + Member + Clone; - type AccountId32Convert: Convert; + /// Convert `T::CurrencyIn` to `MultiLocation`. + type CurrencyIdConvert: Convert>; - type RelayChainNetworkId: Get; - - /// Parachain ID. - type ParaId: Get; + /// Convert `Self::Account` to `AccountId32` + type AccountId32Convert: Convert; - type AccountIdConverter: LocationConversion; + /// Self chain location. + #[pallet::constant] + type SelfLocation: Get; - type XcmExecutor: ExecuteXcm; + /// Xcm handler to execute XCM. + type XcmHandler: XcmHandler; } #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId", T::CurrencyId = "CurrencyId", T::Balance = "Balance")] pub enum Event { - /// Transferred to relay chain. \[src, dest, amount\] - TransferredToRelayChain(T::AccountId, T::AccountId, T::Balance), - - /// Transfer to relay chain failed. \[src, dest, amount, error\] - TransferToRelayChainFailed(T::AccountId, T::AccountId, T::Balance, XcmError), - - /// Transferred to parachain. \[x_currency_id, src, para_id, dest, - /// dest_network, amount\] - TransferredToParachain(XCurrencyId, T::AccountId, ParaId, T::AccountId, NetworkId, T::Balance), - - /// Transfer to parachain failed. \[x_currency_id, src, para_id, dest, - /// dest_network, amount, error\] - TransferToParachainFailed( - XCurrencyId, - T::AccountId, - ParaId, - T::AccountId, - NetworkId, - T::Balance, - XcmError, - ), + /// Transferred. \[sender, currency_id, amount, dest\] + Transferred(T::AccountId, T::CurrencyId, T::Balance, MultiLocation), + /// Transferred `MultiAsset`. \[sender, asset, dest\] + TransferredMultiAsset(T::AccountId, MultiAsset, MultiLocation), } #[pallet::error] pub enum Error { - /// Bad location. - BadLocation, + /// Asset has no reserve location. + AssetHasNoReserve, + /// Not cross-chain transfer. + NotCrossChainTransfer, + /// Invalid transfer destination. + InvalidDest, + /// Currency is not cross-chain transferable. + NotCrossChainTransferableCurrency, } #[pallet::hooks] @@ -118,220 +109,158 @@ pub mod module { #[pallet::call] impl Pallet { - /// Transfer relay chain tokens to relay chain. - #[pallet::weight(10)] + /// Transfer native currencies. #[transactional] - pub fn transfer_to_relay_chain( + #[pallet::weight(1000)] + pub fn transfer( origin: OriginFor, - dest: T::AccountId, + currency_id: T::CurrencyId, amount: T::Balance, + dest: MultiLocation, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - let xcm = Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: MultiLocation::X1(Junction::Parent), - amount: T::ToRelayChainBalance::convert(amount), - }], - effects: vec![Order::InitiateReserveWithdraw { - assets: vec![MultiAsset::All], - reserve: MultiLocation::X1(Junction::Parent), - effects: vec![Order::DepositAsset { - assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: T::RelayChainNetworkId::get(), - id: T::AccountId32Convert::convert(dest.clone()), - }), - }], - }], - }; - - let xcm_origin = - T::AccountIdConverter::try_into_location(who.clone()).map_err(|_| Error::::BadLocation)?; - // TODO: revert state on xcm execution failure. - match T::XcmExecutor::execute_xcm(xcm_origin, xcm) { - Ok(_) => Self::deposit_event(Event::::TransferredToRelayChain(who, dest, amount)), - Err(err) => Self::deposit_event(Event::::TransferToRelayChainFailed(who, dest, amount, err)), + if amount == Zero::zero() { + return Ok(().into()); } + let id: MultiLocation = T::CurrencyIdConvert::convert(currency_id.clone()) + .ok_or(Error::::NotCrossChainTransferableCurrency)?; + let asset = MultiAsset::ConcreteFungible { + id, + amount: amount.into(), + }; + Self::do_transfer_multiasset(who.clone(), asset, dest.clone())?; + Self::deposit_event(Event::::Transferred(who, currency_id, amount, dest)); Ok(().into()) } - /// Transfer tokens to parachain. - #[pallet::weight(10)] + /// Transfer `MultiAsset`. #[transactional] - pub fn transfer_to_parachain( + #[pallet::weight(1000)] + pub fn transfer_multiasset( origin: OriginFor, - x_currency_id: XCurrencyId, - para_id: ParaId, - dest: T::AccountId, - dest_network: NetworkId, - amount: T::Balance, + asset: MultiAsset, + dest: MultiLocation, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - if para_id == T::ParaId::get() { + if Self::is_zero_amount(&asset) { return Ok(().into()); } - let xcm = match x_currency_id.chain_id { - ChainId::RelayChain => { - Self::transfer_relay_chain_tokens_to_parachain(para_id, &dest, dest_network.clone(), amount) - } - ChainId::ParaChain(reserve_chain) => { - if T::ParaId::get() == reserve_chain { - Self::transfer_owned_tokens_to_parachain( - x_currency_id.clone(), - para_id, - &dest, - dest_network.clone(), - amount, - ) - } else { - Self::transfer_non_owned_tokens_to_parachain( - reserve_chain, - x_currency_id.clone(), - para_id, - &dest, - dest_network.clone(), - amount, - ) - } - } + Self::do_transfer_multiasset(who.clone(), asset.clone(), dest.clone())?; + Self::deposit_event(Event::::TransferredMultiAsset(who, asset, dest)); + Ok(().into()) + } + } + + impl Pallet { + /// Transfer `MultiAsset` without depositing event. + fn do_transfer_multiasset( + who: T::AccountId, + asset: MultiAsset, + dest: MultiLocation, + ) -> DispatchResultWithPostInfo { + let (dest, recipient) = Self::ensure_valid_dest(dest)?; + + let self_location = T::SelfLocation::get(); + ensure!(dest != self_location, Error::::NotCrossChainTransfer); + + let reserve = asset.reserve().ok_or(Error::::AssetHasNoReserve)?; + let xcm = if reserve == self_location { + Self::transfer_self_reserve_asset(asset, dest, recipient) + } else if reserve == dest { + Self::transfer_to_reserve(asset, dest, recipient) + } else { + Self::transfer_to_non_reserve(asset, reserve, dest, recipient) }; - let xcm_origin = - T::AccountIdConverter::try_into_location(who.clone()).map_err(|_| Error::::BadLocation)?; - // TODO: revert state on xcm execution failure. - match T::XcmExecutor::execute_xcm(xcm_origin, xcm) { - Ok(_) => Self::deposit_event(Event::::TransferredToParachain( - x_currency_id, - who, - para_id, - dest, - dest_network, - amount, - )), - Err(err) => Self::deposit_event(Event::::TransferToParachainFailed( - x_currency_id, - who, - para_id, - dest, - dest_network, - amount, - err, - )), - } + T::XcmHandler::execute_xcm(who, xcm)?; Ok(().into()) } - } - impl Pallet { - fn transfer_relay_chain_tokens_to_parachain( - para_id: ParaId, - dest: &T::AccountId, - dest_network: NetworkId, - amount: T::Balance, - ) -> Xcm { - Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: MultiLocation::X1(Junction::Parent), - amount: T::ToRelayChainBalance::convert(amount), + fn transfer_self_reserve_asset(asset: MultiAsset, dest: MultiLocation, recipient: MultiLocation) -> Xcm { + WithdrawAsset { + assets: vec![asset], + effects: vec![DepositReserveAsset { + assets: vec![MultiAsset::All], + dest, + effects: Self::deposit_asset(recipient), }], - effects: vec![Order::InitiateReserveWithdraw { + } + } + + fn transfer_to_reserve(asset: MultiAsset, reserve: MultiLocation, recipient: MultiLocation) -> Xcm { + WithdrawAsset { + assets: vec![asset], + effects: vec![InitiateReserveWithdraw { assets: vec![MultiAsset::All], - reserve: MultiLocation::X1(Junction::Parent), - effects: vec![Order::DepositReserveAsset { - assets: vec![MultiAsset::All], - // `dest` is children parachain(of parent). - dest: MultiLocation::X1(Junction::Parachain { id: para_id.into() }), - effects: vec![Order::DepositAsset { - assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: dest_network, - id: T::AccountId32Convert::convert(dest.clone()), - }), - }], - }], + reserve, + effects: Self::deposit_asset(recipient), }], } } - /// Transfer parachain tokens "owned" by self parachain to another - /// parachain. - /// - /// NOTE - `para_id` must not be self parachain. - fn transfer_owned_tokens_to_parachain( - x_currency_id: XCurrencyId, - para_id: ParaId, - dest: &T::AccountId, - dest_network: NetworkId, - amount: T::Balance, + fn transfer_to_non_reserve( + asset: MultiAsset, + reserve: MultiLocation, + dest: MultiLocation, + recipient: MultiLocation, ) -> Xcm { - Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: x_currency_id.into(), - amount: amount.into(), - }], - effects: vec![Order::DepositReserveAsset { + let mut reanchored_dest = dest.clone(); + if reserve == Parent.into() { + if let MultiLocation::X2(Parent, Parachain { id }) = dest { + reanchored_dest = Parachain { id }.into(); + } + } + + WithdrawAsset { + assets: vec![asset], + effects: vec![InitiateReserveWithdraw { assets: vec![MultiAsset::All], - dest: MultiLocation::X2(Junction::Parent, Junction::Parachain { id: para_id.into() }), - effects: vec![Order::DepositAsset { + reserve, + effects: vec![DepositReserveAsset { assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: dest_network, - id: T::AccountId32Convert::convert(dest.clone()), - }), + dest: reanchored_dest, + effects: Self::deposit_asset(recipient), }], }], } } - /// Transfer parachain tokens not "owned" by self chain to another - /// parachain. - fn transfer_non_owned_tokens_to_parachain( - reserve_chain: ParaId, - x_currency_id: XCurrencyId, - para_id: ParaId, - dest: &T::AccountId, - dest_network: NetworkId, - amount: T::Balance, - ) -> Xcm { - let deposit_to_dest = Order::DepositAsset { + fn deposit_asset(recipient: MultiLocation) -> Vec { + vec![DepositAsset { assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: dest_network, - id: T::AccountId32Convert::convert(dest.clone()), - }), - }; - // If transfer to reserve chain, deposit to `dest` on reserve chain, - // else deposit reserve asset. - let reserve_chain_order = if para_id == reserve_chain { - deposit_to_dest - } else { - Order::DepositReserveAsset { - assets: vec![MultiAsset::All], - dest: MultiLocation::X2(Junction::Parent, Junction::Parachain { id: para_id.into() }), - effects: vec![deposit_to_dest], + dest: recipient, + }] + } + + fn is_zero_amount(asset: &MultiAsset) -> bool { + if let MultiAsset::ConcreteFungible { id: _, amount } = asset { + if *amount == Zero::zero() { + return true; } - }; + } - Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: x_currency_id.into(), - amount: amount.into(), - }], - effects: vec![Order::InitiateReserveWithdraw { - assets: vec![MultiAsset::All], - reserve: MultiLocation::X2( - Junction::Parent, - Junction::Parachain { - id: reserve_chain.into(), - }, - ), - effects: vec![reserve_chain_order], - }], + if let MultiAsset::AbstractFungible { id: _, amount } = asset { + if *amount == Zero::zero() { + return true; + } + } + + false + } + + /// Ensure has the `dest` has chain part and recipient part. + fn ensure_valid_dest( + dest: MultiLocation, + ) -> sp_std::result::Result<(MultiLocation, MultiLocation), DispatchError> { + if let (Some(dest), Some(recipient)) = (dest.chain_part(), dest.non_chain_part()) { + Ok((dest, recipient)) + } else { + Err(Error::::InvalidDest.into()) } } } diff --git a/xtokens/src/mock.rs b/xtokens/src/mock.rs new file mode 100644 index 000000000..463aa3a03 --- /dev/null +++ b/xtokens/src/mock.rs @@ -0,0 +1,470 @@ +#![cfg(test)] + +use super::*; +use crate as orml_xtokens; + +use frame_support::parameter_types; +use orml_traits::parameter_type_with_key; +use orml_xcm_support::{IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, XcmHandler as XcmHandlerT}; +use polkadot_parachain::primitives::Sibling; +use serde::{Deserialize, Serialize}; +use sp_io::TestExternalities; +use sp_runtime::AccountId32; +use xcm::v0::{Junction, MultiLocation::*, NetworkId}; +use xcm_builder::{ + AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation, +}; +use xcm_executor::Config as XcmConfigT; +use xcm_simulator::{decl_test_network, decl_test_parachain, prelude::*}; + +pub const ALICE: AccountId32 = AccountId32::new([0u8; 32]); +pub const BOB: AccountId32 = AccountId32::new([1u8; 32]); + +#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub enum CurrencyId { + /// Relay chain token. + R, + /// Parachain A token. + A, + /// Parachain B token. + B, +} + +pub struct CurrencyIdConvert; +impl Convert> for CurrencyIdConvert { + fn convert(id: CurrencyId) -> Option { + match id { + CurrencyId::R => Some(Junction::Parent.into()), + CurrencyId::A => Some( + ( + Junction::Parent, + Junction::Parachain { id: 1 }, + Junction::GeneralKey("A".into()), + ) + .into(), + ), + CurrencyId::B => Some( + ( + Junction::Parent, + Junction::Parachain { id: 2 }, + Junction::GeneralKey("B".into()), + ) + .into(), + ), + } + } +} +impl Convert> for CurrencyIdConvert { + fn convert(l: MultiLocation) -> Option { + let a: Vec = "A".into(); + let b: Vec = "B".into(); + match l { + X1(Parent) => Some(CurrencyId::R), + X3(Junction::Parent, Junction::Parachain { id: 1 }, Junction::GeneralKey(k)) if k == a => { + Some(CurrencyId::A) + } + X3(Junction::Parent, Junction::Parachain { id: 2 }, Junction::GeneralKey(k)) if k == b => { + Some(CurrencyId::B) + } + _ => None, + } + } +} +impl Convert> for CurrencyIdConvert { + fn convert(a: MultiAsset) -> Option { + if let MultiAsset::ConcreteFungible { id, amount: _ } = a { + Self::convert(id) + } else { + None + } + } +} + +pub type Balance = u128; +pub type Amount = i128; + +decl_test_parachain! { + pub struct ParaA { + new_ext = parachain_ext::(1), + para_id = 1, + } + pub mod para_a { + test_network = super::TestNetwork, + xcm_config = { + use super::*; + + parameter_types! { + pub ParaANetwork: NetworkId = NetworkId::Any; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm_handler::Origin::Relay.into(); + pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain { + id: ParachainInfo::get().into(), + }); + pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R; + } + + pub type LocationConverter = ( + ParentIsDefault, + SiblingParachainConvertsVia, + AccountId32Aliases, + ); + + pub type LocalAssetTransactor = MultiCurrencyAdapter< + Tokens, + (), + IsNativeConcrete, + AccountId, + LocationConverter, + CurrencyId, + CurrencyIdConvert, + >; + + pub type LocalOriginConverter = ( + SovereignSignedViaLocation, + RelayChainAsNative, + SiblingParachainAsNative, + SignedAccountId32AsNative, + ); + + pub struct XcmConfig; + impl XcmConfigT for XcmConfig { + type Call = Call; + type XcmSender = XcmHandler; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + } + }, + extra_config = { + parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance { + Default::default() + }; + } + + impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = super::CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + } + + pub struct HandleXcm; + impl XcmHandlerT for HandleXcm { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult { + XcmHandler::execute_xcm(origin, xcm) + } + } + + pub struct AccountId32Convert; + impl Convert for AccountId32Convert { + fn convert(account_id: AccountId) -> [u8; 32] { + account_id.into() + } + } + + parameter_types! { + pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into(); + } + + impl orml_xtokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = CurrencyIdConvert; + type AccountId32Convert = AccountId32Convert; + type SelfLocation = SelfLocation; + type XcmHandler = HandleXcm; + } + }, + extra_modules = { + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event}, + }, + } +} + +decl_test_parachain! { + pub struct ParaB { + new_ext = parachain_ext::(2), + para_id = 2, + } + pub mod para_c { + test_network = super::TestNetwork, + xcm_config = { + use super::*; + + parameter_types! { + pub ParaANetwork: NetworkId = NetworkId::Any; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm_handler::Origin::Relay.into(); + pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain { + id: ParachainInfo::get().into(), + }); + pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R; + } + + pub type LocationConverter = ( + ParentIsDefault, + SiblingParachainConvertsVia, + AccountId32Aliases, + ); + + pub type LocalAssetTransactor = MultiCurrencyAdapter< + Tokens, + (), + IsNativeConcrete, + AccountId, + LocationConverter, + CurrencyId, + CurrencyIdConvert, + >; + + pub type LocalOriginConverter = ( + SovereignSignedViaLocation, + RelayChainAsNative, + SiblingParachainAsNative, + SignedAccountId32AsNative, + ); + + pub struct XcmConfig; + impl XcmConfigT for XcmConfig { + type Call = Call; + type XcmSender = XcmHandler; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + } + }, + extra_config = { + parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance { + Default::default() + }; + } + + impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = super::CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + } + + pub struct HandleXcm; + impl XcmHandlerT for HandleXcm { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult { + XcmHandler::execute_xcm(origin, xcm) + } + } + + pub struct AccountId32Convert; + impl Convert for AccountId32Convert { + fn convert(account_id: AccountId) -> [u8; 32] { + account_id.into() + } + } + + parameter_types! { + pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into(); + } + + impl orml_xtokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = CurrencyIdConvert; + type AccountId32Convert = AccountId32Convert; + type SelfLocation = SelfLocation; + type XcmHandler = HandleXcm; + } + }, + extra_modules = { + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event}, + }, + } +} + +decl_test_parachain! { + pub struct ParaC { + new_ext = parachain_ext::(3), + para_id = 3, + } + pub mod para_b { + test_network = super::TestNetwork, + xcm_config = { + use super::*; + + parameter_types! { + pub ParaANetwork: NetworkId = NetworkId::Any; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm_handler::Origin::Relay.into(); + pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain { + id: ParachainInfo::get().into(), + }); + pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R; + } + + pub type LocationConverter = ( + ParentIsDefault, + SiblingParachainConvertsVia, + AccountId32Aliases, + ); + + pub type LocalAssetTransactor = MultiCurrencyAdapter< + Tokens, + (), + IsNativeConcrete, + AccountId, + LocationConverter, + CurrencyId, + CurrencyIdConvert, + >; + + pub type LocalOriginConverter = ( + SovereignSignedViaLocation, + RelayChainAsNative, + SiblingParachainAsNative, + SignedAccountId32AsNative, + ); + + pub struct XcmConfig; + impl XcmConfigT for XcmConfig { + type Call = Call; + type XcmSender = XcmHandler; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + } + }, + extra_config = { + parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance { + Default::default() + }; + } + + impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = super::CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + } + + pub struct HandleXcm; + impl XcmHandlerT for HandleXcm { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult { + XcmHandler::execute_xcm(origin, xcm) + } + } + + pub struct AccountId32Convert; + impl Convert for AccountId32Convert { + fn convert(account_id: AccountId) -> [u8; 32] { + account_id.into() + } + } + + parameter_types! { + pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into(); + } + + impl orml_xtokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = CurrencyIdConvert; + type AccountId32Convert = AccountId32Convert; + type SelfLocation = SelfLocation; + type XcmHandler = HandleXcm; + } + }, + extra_modules = { + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event}, + }, + } +} + +decl_test_network! { + pub struct TestNetwork { + relay_chain = default, + parachains = vec![ + (1, ParaA), + (2, ParaB), + (3, ParaC), + ], + } +} + +pub type ParaAXtokens = orml_xtokens::Pallet; +pub type ParaATokens = orml_tokens::Pallet; +pub type ParaBTokens = orml_tokens::Pallet; +pub type ParaCTokens = orml_tokens::Pallet; + +pub type RelayBalances = pallet_balances::Pallet; + +pub struct ParaExtBuilder; + +impl Default for ParaExtBuilder { + fn default() -> Self { + ParaExtBuilder + } +} + +impl ParaExtBuilder { + pub fn build< + Runtime: frame_system::Config + orml_tokens::Config, + >( + self, + para_id: u32, + ) -> TestExternalities + where + ::BlockNumber: From, + { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + parachain_info::GenesisConfig { + parachain_id: para_id.into(), + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + endowed_accounts: vec![(ALICE, CurrencyId::R, 100)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = TestExternalities::new(t); + ext.execute_with(|| frame_system::Pallet::::set_block_number(1.into())); + ext + } +} + +pub fn parachain_ext< + Runtime: frame_system::Config + orml_tokens::Config, +>( + para_id: u32, +) -> TestExternalities +where + ::BlockNumber: From, +{ + ParaExtBuilder::default().build::(para_id) +} diff --git a/xtokens/src/tests.rs b/xtokens/src/tests.rs new file mode 100644 index 000000000..a90ca0b32 --- /dev/null +++ b/xtokens/src/tests.rs @@ -0,0 +1,290 @@ +#![cfg(test)] + +use super::*; +use cumulus_primitives_core::ParaId; +use frame_support::{assert_noop, assert_ok, traits::Currency}; +use mock::*; +use orml_traits::MultiCurrency; +use polkadot_parachain::primitives::{AccountIdConversion, Sibling}; +use sp_runtime::AccountId32; +use xcm::v0::{Junction, NetworkId}; +use xcm_simulator::TestExt; + +fn para_a_account() -> AccountId32 { + ParaId::from(1).into_account() +} + +fn para_b_account() -> AccountId32 { + ParaId::from(2).into_account() +} + +fn sibling_a_account() -> AccountId32 { + use sp_runtime::traits::AccountIdConversion; + Sibling::from(1).into_account() +} + +fn sibling_b_account() -> AccountId32 { + use sp_runtime::traits::AccountIdConversion; + Sibling::from(2).into_account() +} + +fn sibling_c_account() -> AccountId32 { + use sp_runtime::traits::AccountIdConversion; + Sibling::from(3).into_account() +} + +#[test] +fn send_relay_chain_asset_to_relay_chain() { + TestNetwork::reset(); + + MockRelay::execute_with(|| { + let _ = RelayBalances::deposit_creating(¶_a_account(), 100); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::R, + 30, + ( + Parent, + Junction::AccountId32 { + network: NetworkId::Polkadot, + id: BOB.into(), + }, + ) + .into(), + )); + assert_eq!(ParaATokens::free_balance(CurrencyId::R, &ALICE), 70); + }); + + MockRelay::execute_with(|| { + assert_eq!(RelayBalances::free_balance(¶_a_account()), 70); + assert_eq!(RelayBalances::free_balance(&BOB), 30); + }); +} + +#[test] +fn send_relay_chain_asset_to_sibling() { + TestNetwork::reset(); + + MockRelay::execute_with(|| { + let _ = RelayBalances::deposit_creating(¶_a_account(), 100); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::R, + 30, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + assert_eq!(ParaATokens::free_balance(CurrencyId::R, &ALICE), 70); + }); + + MockRelay::execute_with(|| { + assert_eq!(RelayBalances::free_balance(¶_a_account()), 70); + assert_eq!(RelayBalances::free_balance(¶_b_account()), 30); + }); + + ParaB::execute_with(|| { + assert_eq!(ParaBTokens::free_balance(CurrencyId::R, &BOB), 30); + }); +} + +#[test] +fn send_sibling_asset_to_reserve_sibling() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_ok!(ParaATokens::deposit(CurrencyId::B, &ALICE, 100)); + }); + + ParaB::execute_with(|| { + assert_ok!(ParaBTokens::deposit(CurrencyId::B, &sibling_a_account(), 100)); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::B, + 30, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + + assert_eq!(ParaATokens::free_balance(CurrencyId::B, &ALICE), 70); + }); + + ParaB::execute_with(|| { + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &sibling_a_account()), 70); + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &BOB), 30); + }); +} + +#[test] +fn send_sibling_asset_to_non_reserve_sibling() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_ok!(ParaATokens::deposit(CurrencyId::B, &ALICE, 100)); + }); + + ParaB::execute_with(|| { + assert_ok!(ParaBTokens::deposit(CurrencyId::B, &sibling_a_account(), 100)); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::B, + 30, + ( + Parent, + Parachain { id: 3 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + assert_eq!(ParaATokens::free_balance(CurrencyId::B, &ALICE), 70); + }); + + // check reserve accounts + ParaB::execute_with(|| { + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &sibling_a_account()), 70); + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &sibling_c_account()), 30); + }); + + ParaC::execute_with(|| { + assert_eq!(ParaCTokens::free_balance(CurrencyId::B, &BOB), 30); + }); +} + +#[test] +fn send_self_parachain_asset_to_sibling() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_ok!(ParaATokens::deposit(CurrencyId::A, &ALICE, 100)); + + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::A, + 30, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + + assert_eq!(ParaATokens::free_balance(CurrencyId::A, &ALICE), 70); + assert_eq!(ParaATokens::free_balance(CurrencyId::A, &sibling_b_account()), 30); + }); + + ParaB::execute_with(|| { + para_b::System::events().iter().for_each(|r| { + println!(">>> {:?}", r.event); + }); + assert_eq!(ParaBTokens::free_balance(CurrencyId::A, &BOB), 30); + }); +} + +#[test] +fn transfer_no_reserve_assets_fails() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_noop!( + ParaAXtokens::transfer_multiasset( + Some(ALICE).into(), + MultiAsset::ConcreteFungible { + id: GeneralKey("B".into()).into(), + amount: 1 + }, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into() + } + ) + .into() + ), + Error::::AssetHasNoReserve + ); + }); +} + +#[test] +fn transfer_to_self_chain_fails() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_noop!( + ParaAXtokens::transfer_multiasset( + Some(ALICE).into(), + MultiAsset::ConcreteFungible { + id: (Parent, Parachain { id: 1 }, GeneralKey("A".into())).into(), + amount: 1 + }, + ( + Parent, + Parachain { id: 1 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into() + } + ) + .into() + ), + Error::::NotCrossChainTransfer + ); + }); +} + +#[test] +fn transfer_to_invalid_dest_fails() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_noop!( + ParaAXtokens::transfer_multiasset( + Some(ALICE).into(), + MultiAsset::ConcreteFungible { + id: (Parent, Parachain { id: 1 }, GeneralKey("A".into())).into(), + amount: 1 + }, + (Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into() + }) + .into() + ), + Error::::InvalidDest + ); + }); +}