From bfc8c656b4144b265548982c073d7b97dafe6301 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Thu, 2 Jun 2022 17:35:31 +0530 Subject: [PATCH 01/14] add: skeleton pallet --- pallets/test-token-provider/Cargo.toml | 50 ++++++++++++++++++++++++++ pallets/test-token-provider/src/lib.rs | 24 +++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 pallets/test-token-provider/Cargo.toml create mode 100644 pallets/test-token-provider/src/lib.rs diff --git a/pallets/test-token-provider/Cargo.toml b/pallets/test-token-provider/Cargo.toml new file mode 100644 index 000000000..c8b489bce --- /dev/null +++ b/pallets/test-token-provider/Cargo.toml @@ -0,0 +1,50 @@ +[package] +authors = ['Polkadex Authors'] +description = 'FRAME pallet for migrating ERC20 PDEX to Native PDEX' +edition = '2021' +homepage = 'https://polkadex.trade' +name = 'test-token-provider' +version = '1.1.0' + +[package.metadata.docs.rs] +targets = ['x86_64-unknown-linux-gnu'] + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } +scale-info = { version = "2.0.1", default-features = false, features = ["derive"] } + +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false, optional = true } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } + +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } + +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } + +[dev-dependencies] +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19"} + +[features] +default = ['std'] +std = [ + 'codec/std', + 'scale-info/std', + 'frame-support/std', + 'frame-system/std', + 'sp-runtime/std', + 'pallet-balances/std', + 'pallet-sudo/std', +] +runtime-benchmarks = [ + "frame-benchmarking", + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + 'sp-runtime/runtime-benchmarks', + 'pallet-balances/runtime-benchmarks', + # 'sp-io/std', +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs new file mode 100644 index 000000000..72051301a --- /dev/null +++ b/pallets/test-token-provider/src/lib.rs @@ -0,0 +1,24 @@ +#[frame_support::pallet] +pub mod pallet { + use codec::{Decode, Encode, MaxEncodedLen}; + use frame_support::{ + pallet_prelude::*, + traits::{fungible::Mutate, Currency, Get, LockableCurrency, WithdrawReasons}, + }; + use frame_system::pallet_prelude::*; + use scale_info::TypeInfo; + use sp_runtime::{ + traits::{BlockNumberProvider, Saturating, Zero}, + SaturatedConversion, + }; + + #[pallet::config] + pub trait Config: frame_system::Config { + + } + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(PhantomData); + +} \ No newline at end of file From 4bd6326663bfb6ecce65ccafcea866899e5ccf0f Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Thu, 2 Jun 2022 18:06:37 +0530 Subject: [PATCH 02/14] fix: add AssetManager and skeleton extrinsic --- pallets/test-token-provider/src/lib.rs | 80 ++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 72051301a..10e65296e 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -3,22 +3,94 @@ pub mod pallet { use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ pallet_prelude::*, - traits::{fungible::Mutate, Currency, Get, LockableCurrency, WithdrawReasons}, + traits::{ + tokens::fungibles::{Create, Inspect, Mutate}, + Currency, Get, LockableCurrency, WithdrawReasons, + }, }; use frame_system::pallet_prelude::*; use scale_info::TypeInfo; use sp_runtime::{ - traits::{BlockNumberProvider, Saturating, Zero}, + traits::{AtLeast32BitUnsigned, BlockNumberProvider, Saturating, Zero}, SaturatedConversion, }; + // use frame_support::traits::tokens::nonfungibles::Create; #[pallet::config] pub trait Config: frame_system::Config { - + /// The overarching event type. + type Event: From> + IsType<::Event>; + /// Responsible for minting tokens + type AssetManager: Create<::AccountId> + + Mutate<::AccountId, Balance = u128, AssetId = u128> + + Inspect<::AccountId>; + /// Balance Type + type Balance: Parameter + + Member + + AtLeast32BitUnsigned + + Default + + Copy + + MaybeSerializeDeserialize; } #[pallet::pallet] #[pallet::without_storage_info] pub struct Pallet(PhantomData); -} \ No newline at end of file + #[pallet::error] + pub enum Error { + SignerNotFound, + OffenderNotFound, + BoundOverflow, + } + + #[pallet::validate_unsigned] + impl frame_support::unsigned::ValidateUnsigned for Pallet { + type Call = Call; + + fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { + let rng: u64 = 20; + + ValidTransaction::with_tag_prefix("thea-proc") + .priority(rng) + .and_provides([&(rng.to_be())]) + .longevity(3) + .propagate(true) + .build() + } + } + + #[pallet::call] + impl Pallet { + #[pallet::weight((10_000, DispatchClass::Normal))] + pub fn credit_account_with_tokens_unsigned( + origin: OriginFor, + account: T::AccountId, + ) -> dispatch::DispatchResult { + // Code here to mint tokens + Ok(()) + } + } + + /* #[pallet::storage] + #[pallet::getter(fn keygen_messages)] + /// sender, KeygenRound => Messages + pub(super) type KeygenMessages = StorageDoubleMap< + _, + Blake2_128Concat, + PartyIndex, + Blake2_128Concat, + KeygenRound, + TheaPayload< + T::TheaId, + KeygenRound, + thea_primitives::MsgLimit, + thea_primitives::MsgVecLimit, + >, + ValueQuery, + */ + + #[pallet::event] + #[pallet::generate_deposit(pub (super) fn deposit_event)] + pub enum Event {} +} From aaba9010d6592502a944518fe6aecdc6dbef456c Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Thu, 2 Jun 2022 19:24:39 +0530 Subject: [PATCH 03/14] add: demo minting function --- pallets/test-token-provider/src/lib.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 10e65296e..4c28c1977 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -62,13 +62,19 @@ pub mod pallet { #[pallet::call] impl Pallet { - #[pallet::weight((10_000, DispatchClass::Normal))] + #[pallet::weight((10_000, DispatchClass::Operational))] pub fn credit_account_with_tokens_unsigned( origin: OriginFor, account: T::AccountId, - ) -> dispatch::DispatchResult { + ) -> DispatchResultWithPostInfo { + // Will this fail? + T::AssetManager::mint_into( + 12, + &account, + 100, + )?; // Code here to mint tokens - Ok(()) + Ok(().into()) } } From a3ed9f9307b6006f8abb154d1fca39e8660d6073 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Thu, 2 Jun 2022 22:56:50 +0530 Subject: [PATCH 04/14] add: mock runtime environment with dependencies --- pallets/test-token-provider/Cargo.toml | 4 + pallets/test-token-provider/src/lib.rs | 6 +- pallets/test-token-provider/src/mock.rs | 151 ++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 pallets/test-token-provider/src/mock.rs diff --git a/pallets/test-token-provider/Cargo.toml b/pallets/test-token-provider/Cargo.toml index c8b489bce..e51d96763 100644 --- a/pallets/test-token-provider/Cargo.toml +++ b/pallets/test-token-provider/Cargo.toml @@ -27,6 +27,9 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkad [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19"} +pallet-assets = { default-features = false, branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate" } +polkadex-primitives = { git = "https://github.com/Polkadex-Substrate/polkadex-primitives.git", branch="polkadot-v0.9.19" , default-features = false } + [features] default = ['std'] @@ -38,6 +41,7 @@ std = [ 'sp-runtime/std', 'pallet-balances/std', 'pallet-sudo/std', + 'pallet-assets/std' ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 4c28c1977..dc54a005a 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -1,3 +1,7 @@ + +#[cfg(test)] +mod mock; + #[frame_support::pallet] pub mod pallet { use codec::{Decode, Encode, MaxEncodedLen}; @@ -62,7 +66,7 @@ pub mod pallet { #[pallet::call] impl Pallet { - #[pallet::weight((10_000, DispatchClass::Operational))] + #[pallet::weight((10_000, DispatchClass::Normal))] pub fn credit_account_with_tokens_unsigned( origin: OriginFor, account: T::AccountId, diff --git a/pallets/test-token-provider/src/mock.rs b/pallets/test-token-provider/src/mock.rs new file mode 100644 index 000000000..e0f60c05c --- /dev/null +++ b/pallets/test-token-provider/src/mock.rs @@ -0,0 +1,151 @@ +use super::*; +use crate as token; +use frame_support::{parameter_types, traits::{ConstU32, ConstU64}}; +use frame_system as system; +use system::{ + EnsureRoot +}; +use pallet_balances::AccountData; +use sp_runtime::{ + key_types::DUMMY, + testing::{Header, TestXt, UintAuthorityId}, + traits::{ + BlakeTwo256, ConvertInto, Extrinsic as ExtrinsicT, IdentityLookup, OpaqueKeys, Verify, + }, +}; +use sp_core::{ + offchain::{testing, OffchainWorkerExt, TransactionPoolExt}, + sr25519::Signature, + sr25519::Public, + H256, +}; +use polkadex_primitives::Balance; + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: system::{Pallet, Call, Config, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Event}, + Assets: pallet_assets::{Pallet, Call, Storage, Event}, + + } +); + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; +} + +// type AccountId = u64; + +impl system::Config for Test { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = Public; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +type Extrinsic = TestXt; + +impl system::offchain::SigningTypes for Test { + type Public = ::Signer; + type Signature = Signature; +} + +impl system::offchain::SendTransactionTypes for Test +where + Call: From, +{ + type OverarchingCall = Call; + type Extrinsic = Extrinsic; +} + +impl frame_system::offchain::CreateSignedTransaction for Test +where + Call: From, +{ + fn create_transaction>( + call: Call, + _public: ::Signer, + _account: Public, + nonce: u64, + ) -> Option<(Call, ::SignaturePayload)> { + Some((call, (nonce, ()))) + } +} + +parameter_types! { + pub const AssetDeposit: Balance = 100; + pub const ApprovalDeposit: Balance = 1; + pub const StringLimit: u32 = 50; + pub const MetadataDepositBase: Balance = 10; + pub const MetadataDepositPerByte: Balance = 1; +} + +impl pallet_assets::Config for Test { + type Event = Event; + type Balance = Balance; + type AssetId = u128; + type Currency = Balances; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = StringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = (); +} + +parameter_types! { + pub const ExistentialDeposit: Balance = 100; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Test { + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = frame_system::Pallet; + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type WeightInfo = (); +} + +pub fn new_test_ext() -> sp_io::TestExternalities { + let t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} \ No newline at end of file From 7f376d729da54ef63589cdafdfde544077c35ea9 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 01:46:26 +0530 Subject: [PATCH 05/14] add: small mvp with unit tests --- pallets/test-token-provider/Cargo.toml | 4 ++- pallets/test-token-provider/src/lib.rs | 20 +++++++++++++-- pallets/test-token-provider/src/mock.rs | 8 ++++++ pallets/test-token-provider/src/test.rs | 33 +++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 pallets/test-token-provider/src/test.rs diff --git a/pallets/test-token-provider/Cargo.toml b/pallets/test-token-provider/Cargo.toml index e51d96763..43e57114c 100644 --- a/pallets/test-token-provider/Cargo.toml +++ b/pallets/test-token-provider/Cargo.toml @@ -29,6 +29,8 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkad sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19"} pallet-assets = { default-features = false, branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate" } polkadex-primitives = { git = "https://github.com/Polkadex-Substrate/polkadex-primitives.git", branch="polkadot-v0.9.19" , default-features = false } +sp-keystore = {default-features = false, optional=false,branch = "polkadot-v0.9.19",git = 'https://github.com/paritytech/substrate' } +sp-application-crypto = {default-features = false, branch="polkadot-v0.9.19", git = 'https://github.com/paritytech/substrate'} [features] @@ -41,7 +43,7 @@ std = [ 'sp-runtime/std', 'pallet-balances/std', 'pallet-sudo/std', - 'pallet-assets/std' + 'pallet-assets/std', ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index dc54a005a..7827847a7 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -2,6 +2,11 @@ #[cfg(test)] mod mock; +#[cfg(test)] +mod test; + +pub use pallet::*; + #[frame_support::pallet] pub mod pallet { use codec::{Decode, Encode, MaxEncodedLen}; @@ -72,11 +77,20 @@ pub mod pallet { account: T::AccountId, ) -> DispatchResultWithPostInfo { // Will this fail? - T::AssetManager::mint_into( + if let Ok(()) = T::AssetManager::mint_into( 12, &account, 100, - )?; + ){ + + } else { + T::AssetManager::create( + 12, + account, + true, + 100, + )?; + } // Code here to mint tokens Ok(().into()) } @@ -103,4 +117,6 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event {} + + } diff --git a/pallets/test-token-provider/src/mock.rs b/pallets/test-token-provider/src/mock.rs index e0f60c05c..9012a42f3 100644 --- a/pallets/test-token-provider/src/mock.rs +++ b/pallets/test-token-provider/src/mock.rs @@ -33,6 +33,7 @@ frame_support::construct_runtime!( System: system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Event}, Assets: pallet_assets::{Pallet, Call, Storage, Event}, + Token: token::{Pallet, Call, Event}, } ); @@ -143,6 +144,13 @@ impl pallet_balances::Config for Test { type WeightInfo = (); } +impl token::Config for Test { + type Event = Event; + type AssetManager = Assets; + type Balance = Balance; +} + + pub fn new_test_ext() -> sp_io::TestExternalities { let t = system::GenesisConfig::default().build_storage::().unwrap(); let mut ext = sp_io::TestExternalities::new(t); diff --git a/pallets/test-token-provider/src/test.rs b/pallets/test-token-provider/src/test.rs new file mode 100644 index 000000000..4eeed06f5 --- /dev/null +++ b/pallets/test-token-provider/src/test.rs @@ -0,0 +1,33 @@ +use crate::mock::*; +use codec::Encode; +use frame_support::assert_ok; +// use sp_application_crypto::RuntimePublic; +use sp_core::sr25519::Signature; +use std::convert::TryInto; +use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStore}; +use crate::pallet::Pallet; + + +#[test] +fn test_minting_token(){ + const KEY_TYPE: sp_application_crypto::KeyTypeId = sp_application_crypto::KeyTypeId(*b"thea"); + const PHRASE: &str = + "news slush supreme milk chapter athlete soap sausage put clutch what kitten"; + let keystore = KeyStore::new(); + let account_id = SyncCryptoStore::sr25519_generate_new( + &keystore, + KEY_TYPE, + Some(&format!("{}/hunter1", PHRASE)), + ).unwrap(); + + let account_id_2 = SyncCryptoStore::sr25519_generate_new( + &keystore, + KEY_TYPE, + Some(&format!("{}/hunter2", PHRASE)), + ).unwrap(); + new_test_ext().execute_with(|| { + assert_ok!(Token::credit_account_with_tokens_unsigned(Origin::none(), account_id)); + assert_ok!(Token::credit_account_with_tokens_unsigned(Origin::none(), account_id_2)); + + }); +} \ No newline at end of file From a3f935dd8a74f0737448dbd09096ecd9fafd19ea Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 04:45:59 +0530 Subject: [PATCH 06/14] fix: integrate token provider with runtime --- pallets/test-token-provider/Cargo.toml | 4 +--- pallets/test-token-provider/src/lib.rs | 3 ++- runtime/Cargo.toml | 5 +++-- runtime/src/lib.rs | 7 +++++++ 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/pallets/test-token-provider/Cargo.toml b/pallets/test-token-provider/Cargo.toml index 43e57114c..df18b21f9 100644 --- a/pallets/test-token-provider/Cargo.toml +++ b/pallets/test-token-provider/Cargo.toml @@ -18,11 +18,9 @@ frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } -pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } [dev-dependencies] @@ -40,9 +38,9 @@ std = [ 'scale-info/std', 'frame-support/std', 'frame-system/std', + 'sp-io/std', 'sp-runtime/std', 'pallet-balances/std', - 'pallet-sudo/std', 'pallet-assets/std', ] runtime-benchmarks = [ diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 7827847a7..1fa50c97a 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -1,3 +1,4 @@ +#![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod mock; @@ -118,5 +119,5 @@ pub mod pallet { #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event {} - + } diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index 9efdf2ff7..866114d37 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -96,6 +96,7 @@ orml-vesting = { git = "https://github.com/Polkadex-Substrate/open-runtime-modul polkadex-primitives = { git = "https://github.com/Polkadex-Substrate/polkadex-primitives.git", branch = 'polkadot-v0.9.19', default-features = false } pdex-migration = { path = "../pallets/pdex-migration", default-features = false } polkadex-ido = { path = "../pallets/polkadex-ido", default-features = false } +test-token-provider = { path = "../pallets/test-token-provider", default-features = false } # Try Runtime frame-try-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.19", optional = true, default-features = false } @@ -169,7 +170,6 @@ std = [ "polkadex-primitives/std", "pdex-migration/std", 'polkadex-ido/std', - "frame-try-runtime/std", ] runtime-benchmarks = [ @@ -240,5 +240,6 @@ try-runtime = [ "pallet-democracy/try-runtime", "pallet-utility/try-runtime", "orml-vesting/try-runtime", - "pdex-migration/try-runtime" + "pdex-migration/try-runtime", + "test-token-provider/try-runtime" ] \ No newline at end of file diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 2967174e9..f7b465bac 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1135,6 +1135,12 @@ impl pallet_recovery::Config for Runtime { type RecoveryDeposit = RecoveryDeposit; } +impl test_token_provider::Config for Runtime { + type Event = Event; + type AssetManager = Assets; + type Balance = Balance; +} + parameter_types! { pub MinVestedTransfer: Balance = PDEX; pub const MaxVestingSchedules: u32 = 300; @@ -1269,6 +1275,7 @@ construct_runtime!( ChildBounties: pallet_child_bounties = 33, Assets: pallet_assets::{Pallet, Call, Storage, Event} = 34, PolkadexIdo: polkadex_ido::{Pallet, Call, Event, Storage} = 35, + Token: test_token_provider::{Pallet, Call, Event} = 36, } ); /// Digest item type. From 2a112161d4bcd10e05a5019eee2345966f23c62e Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 05:50:18 +0530 Subject: [PATCH 07/14] fix: validate_unsigned in token provider --- pallets/test-token-provider/src/lib.rs | 33 ++++++++++++++++++------- pallets/test-token-provider/src/mock.rs | 2 +- runtime/src/lib.rs | 2 +- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 1fa50c97a..9b915aadf 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -59,14 +59,19 @@ pub mod pallet { type Call = Call; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { - let rng: u64 = 20; - - ValidTransaction::with_tag_prefix("thea-proc") - .priority(rng) - .and_provides([&(rng.to_be())]) - .longevity(3) - .propagate(true) - .build() + // Need to create Block treshold + + match call { + Call::credit_account_with_tokens_unsigned {account} => { + ValidTransaction::with_tag_prefix("token-faucet") + .priority(1) + .and_provides([&b"request_token_faucet".to_vec()]) + .longevity(3) + .propagate(true) + .build() + }, + _ => InvalidTransaction::Call.into(), + } } } @@ -77,7 +82,7 @@ pub mod pallet { origin: OriginFor, account: T::AccountId, ) -> DispatchResultWithPostInfo { - // Will this fail? + let _ = ensure_none(origin)?; if let Ok(()) = T::AssetManager::mint_into( 12, &account, @@ -119,5 +124,15 @@ pub mod pallet { #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event {} + /* + ValidTransaction::with_tag_prefix("token-faucet") + .priority(UNSIGNED_TXS_PRIORITY) + .and_provides([&b"request_token_faucet".to_vec()]) + .longevity(3) + .propagate(true) + .build() + */ + + } diff --git a/pallets/test-token-provider/src/mock.rs b/pallets/test-token-provider/src/mock.rs index 9012a42f3..19e8ea9bc 100644 --- a/pallets/test-token-provider/src/mock.rs +++ b/pallets/test-token-provider/src/mock.rs @@ -33,7 +33,7 @@ frame_support::construct_runtime!( System: system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Event}, Assets: pallet_assets::{Pallet, Call, Storage, Event}, - Token: token::{Pallet, Call, Event}, + Token: token::{Pallet, Call, Event, ValidateUnsigned}, } ); diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index f7b465bac..34d943578 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1275,7 +1275,7 @@ construct_runtime!( ChildBounties: pallet_child_bounties = 33, Assets: pallet_assets::{Pallet, Call, Storage, Event} = 34, PolkadexIdo: polkadex_ido::{Pallet, Call, Event, Storage} = 35, - Token: test_token_provider::{Pallet, Call, Event} = 36, + Token: test_token_provider::{Pallet, Call, Event, ValidateUnsigned} = 36, } ); /// Digest item type. From 739adfc7e23b988be5a216bd34d61e061731ba95 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 06:05:02 +0530 Subject: [PATCH 08/14] fix: validation logic for minting tokens --- pallets/test-token-provider/src/lib.rs | 65 ++++++++++++-------------- 1 file changed, 30 insertions(+), 35 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 9b915aadf..ba7358f66 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -49,26 +49,38 @@ pub mod pallet { #[pallet::error] pub enum Error { - SignerNotFound, - OffenderNotFound, - BoundOverflow, + AccountAlreadyCredited, } + const BLOCK_THRESHOLD: u64 = (24 * 60 * 60) / 6; + #[pallet::validate_unsigned] impl frame_support::unsigned::ValidateUnsigned for Pallet { type Call = Call; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { // Need to create Block treshold - + let current_block_no: T::BlockNumber = >::block_number(); + let valid_tx = |account: &T::AccountId| { + let last_block_number: T::BlockNumber = >::get(account); + if (last_block_number == 0_u64.saturated_into()) || (current_block_no - last_block_number >= BLOCK_THRESHOLD.saturated_into()) + { + ValidTransaction::with_tag_prefix("token-faucet") + .priority(100) + .and_provides([&b"request_token_faucet".to_vec()]) + .longevity(3) + .propagate(true) + .build() + } else { + TransactionValidity::Err(TransactionValidityError::Invalid( + InvalidTransaction::ExhaustsResources, + )) + } + }; + match call { Call::credit_account_with_tokens_unsigned {account} => { - ValidTransaction::with_tag_prefix("token-faucet") - .priority(1) - .and_provides([&b"request_token_faucet".to_vec()]) - .longevity(3) - .propagate(true) - .build() + valid_tx(&account) }, _ => InvalidTransaction::Call.into(), } @@ -86,7 +98,7 @@ pub mod pallet { if let Ok(()) = T::AssetManager::mint_into( 12, &account, - 100, + 1, ){ } else { @@ -94,7 +106,7 @@ pub mod pallet { 12, account, true, - 100, + 1, )?; } // Code here to mint tokens @@ -102,37 +114,20 @@ pub mod pallet { } } - /* #[pallet::storage] - #[pallet::getter(fn keygen_messages)] - /// sender, KeygenRound => Messages - pub(super) type KeygenMessages = StorageDoubleMap< + #[pallet::storage] + #[pallet::getter(fn token_map)] + pub(super) type TokenFaucetMap = StorageMap< _, Blake2_128Concat, - PartyIndex, - Blake2_128Concat, - KeygenRound, - TheaPayload< - T::TheaId, - KeygenRound, - thea_primitives::MsgLimit, - thea_primitives::MsgVecLimit, - >, + T::AccountId, + T::BlockNumber, ValueQuery, - */ + >; #[pallet::event] #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event {} - /* - ValidTransaction::with_tag_prefix("token-faucet") - .priority(UNSIGNED_TXS_PRIORITY) - .and_provides([&b"request_token_faucet".to_vec()]) - .longevity(3) - .propagate(true) - .build() - */ - } From d9da9a290bec9baa31957a99ec35905a0d3f0567 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 16:27:15 +0530 Subject: [PATCH 09/14] fix: minting native token --- pallets/test-token-provider/Cargo.toml | 2 + pallets/test-token-provider/src/lib.rs | 51 ++++++++++++++++++++++--- pallets/test-token-provider/src/mock.rs | 9 +++++ runtime/src/lib.rs | 7 ++++ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/pallets/test-token-provider/Cargo.toml b/pallets/test-token-provider/Cargo.toml index df18b21f9..56163799f 100644 --- a/pallets/test-token-provider/Cargo.toml +++ b/pallets/test-token-provider/Cargo.toml @@ -23,6 +23,8 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0 sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +polkadex-primitives = { git = "https://github.com/Polkadex-Substrate/polkadex-primitives.git", branch="polkadot-v0.9.19" , default-features = false } + [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19"} pallet-assets = { default-features = false, branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate" } diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index ba7358f66..00ff4413c 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -12,20 +12,26 @@ pub use pallet::*; pub mod pallet { use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ + PalletId, pallet_prelude::*, traits::{ tokens::fungibles::{Create, Inspect, Mutate}, - Currency, Get, LockableCurrency, WithdrawReasons, + Currency, Get, LockableCurrency, WithdrawReasons, ReservableCurrency }, }; use frame_system::pallet_prelude::*; use scale_info::TypeInfo; use sp_runtime::{ - traits::{AtLeast32BitUnsigned, BlockNumberProvider, Saturating, Zero}, + traits::{AtLeast32BitUnsigned, BlockNumberProvider, Saturating, Zero, AccountIdConversion, Dispatchable, One, UniqueSaturatedInto}, SaturatedConversion, }; // use frame_support::traits::tokens::nonfungibles::Create; + const MODULE_ID: PalletId = PalletId(*b"phala/bg"); + + type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + #[pallet::config] pub trait Config: frame_system::Config { /// The overarching event type. @@ -41,6 +47,12 @@ pub mod pallet { + Default + Copy + MaybeSerializeDeserialize; + /// Asset Create/ Update Origin + type AssetCreateUpdateOrigin: EnsureOrigin<::Origin>; + /// Balances Pallet + type Currency: Currency + ReservableCurrency; + /// Default token amount to mint + type TokenAmount: Get>; } #[pallet::pallet] @@ -82,6 +94,14 @@ pub mod pallet { Call::credit_account_with_tokens_unsigned {account} => { valid_tx(&account) }, + Call::credit_account_with_native_tokens_unsigned {account} => { + ValidTransaction::with_tag_prefix("token-faucet") + .priority(100) + .and_provides([&b"request_token_faucet".to_vec()]) + .longevity(3) + .propagate(true) + .build() + }, _ => InvalidTransaction::Call.into(), } } @@ -98,20 +118,29 @@ pub mod pallet { if let Ok(()) = T::AssetManager::mint_into( 12, &account, - 1, + 100, ){ } else { T::AssetManager::create( 12, - account, + Self::account_id(), true, - 1, - )?; + BalanceOf::::one().unique_saturated_into(), + )?; } // Code here to mint tokens Ok(().into()) } + #[pallet::weight((10_000, DispatchClass::Normal))] + pub fn credit_account_with_native_tokens_unsigned(origin: OriginFor, account: T::AccountId) -> DispatchResultWithPostInfo { + let _ = ensure_none(origin)?; + TokenFaucetMap::::insert(&account,>::block_number()); + //Mint account with free tokens + T::Currency::deposit_creating(&account,T::TokenAmount::get()); + // Self::deposit_event(RawEvent::AccountCredited(account)); + Ok(().into()) + } } #[pallet::storage] @@ -128,6 +157,16 @@ pub mod pallet { #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event {} + impl Pallet { + // *** Utility methods *** + + /// Provides an AccountId for the pallet. + /// This is used both as an origin check and deposit/withdrawal account. + pub fn account_id() -> T::AccountId { + MODULE_ID.into_account() + } + } + } diff --git a/pallets/test-token-provider/src/mock.rs b/pallets/test-token-provider/src/mock.rs index 19e8ea9bc..e031b4ccd 100644 --- a/pallets/test-token-provider/src/mock.rs +++ b/pallets/test-token-provider/src/mock.rs @@ -144,10 +144,19 @@ impl pallet_balances::Config for Test { type WeightInfo = (); } +pub const PDEX: Balance = 1000_000_000_000; + +parameter_types! { + pub const TokenAmount: Balance = 100_000_u128 * PDEX; +} + impl token::Config for Test { type Event = Event; type AssetManager = Assets; type Balance = Balance; + type Currency = Balances; + type AssetCreateUpdateOrigin = frame_system::EnsureSigned; + type TokenAmount = TokenAmount; } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 34d943578..ed415f66a 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1135,10 +1135,17 @@ impl pallet_recovery::Config for Runtime { type RecoveryDeposit = RecoveryDeposit; } +parameter_types! { + pub const TokenAmount: Balance = 100_000_u128 * PDEX; +} + impl test_token_provider::Config for Runtime { type Event = Event; type AssetManager = Assets; type Balance = Balance; + type Currency = Balances; + type AssetCreateUpdateOrigin = EnsureRootOrHalfCouncil; + type TokenAmount = TokenAmount; } parameter_types! { From 2619321a99b5826d7a1e9108b7c95293945a32d3 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 16:29:29 +0530 Subject: [PATCH 10/14] refactor: update manifest --- pallets/test-token-provider/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/test-token-provider/Cargo.toml b/pallets/test-token-provider/Cargo.toml index 56163799f..dfd507d64 100644 --- a/pallets/test-token-provider/Cargo.toml +++ b/pallets/test-token-provider/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ['Polkadex Authors'] -description = 'FRAME pallet for migrating ERC20 PDEX to Native PDEX' +description = 'FRAME pallet for minting ERC20 and Native PDEX Tokens' edition = '2021' homepage = 'https://polkadex.trade' name = 'test-token-provider' From 9b29837a970bdff110e07d6712b2af6d35e2afbf Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 17:28:17 +0530 Subject: [PATCH 11/14] fix: asset_id for ether --- pallets/test-token-provider/src/lib.rs | 70 ++++++++++++++++++++------ 1 file changed, 54 insertions(+), 16 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 00ff4413c..89c9ce3f6 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -25,7 +25,6 @@ pub mod pallet { traits::{AtLeast32BitUnsigned, BlockNumberProvider, Saturating, Zero, AccountIdConversion, Dispatchable, One, UniqueSaturatedInto}, SaturatedConversion, }; - // use frame_support::traits::tokens::nonfungibles::Create; const MODULE_ID: PalletId = PalletId(*b"phala/bg"); @@ -89,18 +88,29 @@ pub mod pallet { )) } }; - - match call { - Call::credit_account_with_tokens_unsigned {account} => { - valid_tx(&account) - }, - Call::credit_account_with_native_tokens_unsigned {account} => { + let valid_native_tx = |account: &T::AccountId| { + let last_block_number: T::BlockNumber = >::get(account); + if (last_block_number == 0_u64.saturated_into()) || (current_block_no - last_block_number >= BLOCK_THRESHOLD.saturated_into()) + { ValidTransaction::with_tag_prefix("token-faucet") .priority(100) .and_provides([&b"request_token_faucet".to_vec()]) .longevity(3) .propagate(true) .build() + } else { + TransactionValidity::Err(TransactionValidityError::Invalid( + InvalidTransaction::ExhaustsResources, + )) + } + }; + + match call { + Call::credit_account_with_tokens_unsigned {account} => { + valid_tx(&account) + }, + Call::credit_account_with_native_tokens_unsigned {account} => { + valid_native_tx(&account) }, _ => InvalidTransaction::Call.into(), } @@ -115,30 +125,38 @@ pub mod pallet { account: T::AccountId, ) -> DispatchResultWithPostInfo { let _ = ensure_none(origin)?; - if let Ok(()) = T::AssetManager::mint_into( - 12, + if let Err(e) = T::AssetManager::mint_into( + Self::asset_id(), &account, 100, ){ - - } else { + // Handling Unknown Asset by creating the Asset T::AssetManager::create( - 12, + Self::asset_id(), Self::account_id(), true, BalanceOf::::one().unique_saturated_into(), )?; - } + // Minting Test Ether into the Account + T::AssetManager::mint_into( + Self::asset_id(), + &account, + 100, + )?; + } + TokenFaucetMap::::insert(&account,>::block_number()); + Self::deposit_event(Event::AccountCredited(account)); + // Code here to mint tokens Ok(().into()) } #[pallet::weight((10_000, DispatchClass::Normal))] pub fn credit_account_with_native_tokens_unsigned(origin: OriginFor, account: T::AccountId) -> DispatchResultWithPostInfo { let _ = ensure_none(origin)?; - TokenFaucetMap::::insert(&account,>::block_number()); + NativeTokenMap::::insert(&account,>::block_number()); //Mint account with free tokens T::Currency::deposit_creating(&account,T::TokenAmount::get()); - // Self::deposit_event(RawEvent::AccountCredited(account)); + Self::deposit_event(Event::AccountCredited(account)); Ok(().into()) } } @@ -153,9 +171,21 @@ pub mod pallet { ValueQuery, >; + #[pallet::storage] + #[pallet::getter(fn native_token_map)] + pub(super) type NativeTokenMap = StorageMap< + _, + Blake2_128Concat, + T::AccountId, + T::BlockNumber, + ValueQuery, + >; + #[pallet::event] #[pallet::generate_deposit(pub (super) fn deposit_event)] - pub enum Event {} + pub enum Event { + AccountCredited(T::AccountId) + } impl Pallet { // *** Utility methods *** @@ -165,6 +195,14 @@ pub mod pallet { pub fn account_id() -> T::AccountId { MODULE_ID.into_account() } + + /// Provides Ethers Asset Id for Test Ether + pub fn asset_id() -> u128 { + let ether_address: H160 = "0xF59ae934f6fe444afC309586cC60a84a0F89Aaee".parse().unwrap(); + let mut temp = [0u8; 16]; + temp.copy_from_slice(&token[0..16]); + u128::from_le_bytes(temp) + } } From db088ce3b234cc1c8d7e7d99a3b29e45fc2bb195 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 17:39:44 +0530 Subject: [PATCH 12/14] fix: build errors due to deps --- pallets/test-token-provider/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 89c9ce3f6..d83411e73 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -25,8 +25,9 @@ pub mod pallet { traits::{AtLeast32BitUnsigned, BlockNumberProvider, Saturating, Zero, AccountIdConversion, Dispatchable, One, UniqueSaturatedInto}, SaturatedConversion, }; + use sp_core::H160; - const MODULE_ID: PalletId = PalletId(*b"phala/bg"); + const MODULE_ID: PalletId = PalletId(*b"token/bg"); type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -200,7 +201,7 @@ pub mod pallet { pub fn asset_id() -> u128 { let ether_address: H160 = "0xF59ae934f6fe444afC309586cC60a84a0F89Aaee".parse().unwrap(); let mut temp = [0u8; 16]; - temp.copy_from_slice(&token[0..16]); + temp.copy_from_slice(ðer_address[0..16]); u128::from_le_bytes(temp) } } From b6c838446e479fa54ee380f0370342a53bb0fe46 Mon Sep 17 00:00:00 2001 From: felixfaisal Date: Fri, 3 Jun 2022 20:04:47 +0530 Subject: [PATCH 13/14] fix: hardcoded asset_id --- pallets/test-token-provider/src/lib.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index d83411e73..5e7b3ac43 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -7,6 +7,7 @@ mod mock; mod test; pub use pallet::*; +// use sp_core::H160; #[frame_support::pallet] pub mod pallet { @@ -25,7 +26,8 @@ pub mod pallet { traits::{AtLeast32BitUnsigned, BlockNumberProvider, Saturating, Zero, AccountIdConversion, Dispatchable, One, UniqueSaturatedInto}, SaturatedConversion, }; - use sp_core::H160; + pub use sp_core::H160; + // use core::str::FromStr; const MODULE_ID: PalletId = PalletId(*b"token/bg"); @@ -197,15 +199,11 @@ pub mod pallet { MODULE_ID.into_account() } - /// Provides Ethers Asset Id for Test Ether + /// Provides Ethers Asset Id for Test Ether pub fn asset_id() -> u128 { - let ether_address: H160 = "0xF59ae934f6fe444afC309586cC60a84a0F89Aaee".parse().unwrap(); - let mut temp = [0u8; 16]; - temp.copy_from_slice(ðer_address[0..16]); - u128::from_le_bytes(temp) + // Currently Hardcoding this value created from address "0xF59ae934f6fe444afC309586cC60a84a0F89Aaee" + 99237140875836081697465599727699073781 } } - - } From d684bb5e96c76e038746d36b1c77cabc4ed913a1 Mon Sep 17 00:00:00 2001 From: Faisal Ahmed Date: Thu, 9 Jun 2022 10:37:03 +0530 Subject: [PATCH 14/14] fix: provide accout to resolve priority issue --- pallets/test-token-provider/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pallets/test-token-provider/src/lib.rs b/pallets/test-token-provider/src/lib.rs index 5e7b3ac43..17e04c8d5 100644 --- a/pallets/test-token-provider/src/lib.rs +++ b/pallets/test-token-provider/src/lib.rs @@ -81,7 +81,7 @@ pub mod pallet { { ValidTransaction::with_tag_prefix("token-faucet") .priority(100) - .and_provides([&b"request_token_faucet".to_vec()]) + .and_provides([account]) .longevity(3) .propagate(true) .build() @@ -95,9 +95,9 @@ pub mod pallet { let last_block_number: T::BlockNumber = >::get(account); if (last_block_number == 0_u64.saturated_into()) || (current_block_no - last_block_number >= BLOCK_THRESHOLD.saturated_into()) { - ValidTransaction::with_tag_prefix("token-faucet") + ValidTransaction::with_tag_prefix("native-token") .priority(100) - .and_provides([&b"request_token_faucet".to_vec()]) + .and_provides([account]) .longevity(3) .propagate(true) .build()