git.delta.rocks / unique-network / refs/commits / 82643c5daa1a

difftreelog

feat add tests

Trubnikov Sergey2023-04-25parent: #f0ad1b0.patch.diff
in: master

12 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -267,7 +267,7 @@
 pub fn development_config() -> DefaultChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
-	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
 	properties.insert(
 		"ss58Format".into(),
 		default_runtime::SS58Prefix::get().into(),
@@ -341,7 +341,7 @@
 pub fn local_testnet_config() -> DefaultChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
-	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
 	properties.insert(
 		"ss58Format".into(),
 		default_runtime::SS58Prefix::get().into(),
modifiedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
before · pallets/balances-adapter/src/erc.rs
1use crate::{Config, NativeFungibleHandle};2use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};3use frame_support::traits::{Currency, ExistenceRequirement};4use pallet_common::{5	erc::{CommonEvmHandler, CrossAccountId, PrecompileHandle, PrecompileResult},6	eth::CrossAddress,7};8use pallet_evm_coder_substrate::{9	call, dispatch_to_evm,10	execution::{PreDispatch, Result},11	frontier_contract, WithRecorder, SubstrateRecorder,12};13use sp_core::{U256, Get};14use sp_std::vec::Vec;1516frontier_contract! {17	macro_rules! NativeFungibleHandle_result {...}18	impl<T: Config> Contract for NativeFungibleHandle<T> {...}19}2021#[derive(ToLog)]22pub enum ERC20Events {23	Transfer {24		#[indexed]25		from: Address,26		#[indexed]27		to: Address,28		value: U256,29	},30	Approval {31		#[indexed]32		owner: Address,33		#[indexed]34		spender: Address,35		value: U256,36	},37}3839#[solidity_interface(name = ERC20, events(ERC20Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x942e8b22)]40impl<T: Config> NativeFungibleHandle<T> {41	fn allowance(&self, owner: Address, spender: Address) -> Result<U256> {42		Ok(U256::zero())43	}4445	// #[weight(<SelfWeightOf<T>>::approve())]46	fn approve(&mut self, caller: Caller, spender: Address, amount: U256) -> Result<bool> {47		// self.consume_store_reads(1)?;48		Err("Approve not supported now".into())49	}5051	fn balance_of(&self, owner: Address) -> Result<U256> {52		// self.consume_store_reads(1)?;53		let owner = T::CrossAccountId::from_eth(owner);54		let balance = <T as Config>::Currency::free_balance(owner.as_sub());55		Ok(balance.into())56	}5758	fn decimals(&self) -> Result<u8> {59		Ok(T::Decimals::get())60	}6162	fn name(&self) -> Result<String> {63		Ok(T::Name::get())64	}6566	fn symbol(&self) -> Result<String> {67		Ok(T::Symbol::get())68	}6970	fn total_supply(&self) -> Result<U256> {71		// self.consume_store_reads(1)?;72		let total = <T as Config>::Currency::total_issuance();73		Ok(total.into())74	}7576	// #[weight(<SelfWeightOf<T>>::transfer())]77	fn transfer(&mut self, caller: Caller, to: Address, amount: U256) -> Result<bool> {78		let caller = T::CrossAccountId::from_eth(caller);79		let to = T::CrossAccountId::from_eth(to);80		let amount = amount.try_into().map_err(|_| "amount overflow")?;81		// let budget = self82		// 	.recorder83		// 	.weight_calls_budget(<StructureWeight<T>>::find_parent());8485		// <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;86		<T as Config>::Currency::transfer(87			caller.as_sub(),88			to.as_sub(),89			amount,90			ExistenceRequirement::KeepAlive,91		)92		.map_err(dispatch_to_evm::<T>)?;93		Ok(true)94	}9596	// #[weight(<SelfWeightOf<T>>::transfer_from())]97	fn transfer_from(98		&mut self,99		caller: Caller,100		from: Address,101		to: Address,102		amount: U256,103	) -> Result<bool> {104		let caller = T::CrossAccountId::from_eth(caller);105		let from = T::CrossAccountId::from_eth(from);106		let to = T::CrossAccountId::from_eth(to);107		let amount = amount.try_into().map_err(|_| "amount overflow")?;108109		if from != to {110			return Err("no permission".into());111		}112		// let budget = self113		// 	.recorder114		// 	.weight_calls_budget(<StructureWeight<T>>::find_parent());115116		// <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)117		// 	.map_err(dispatch_to_evm::<T>)?;118		<T as Config>::Currency::transfer(119			caller.as_sub(),120			to.as_sub(),121			amount,122			ExistenceRequirement::KeepAlive,123		)124		.map_err(dispatch_to_evm::<T>)?;125		Ok(true)126	}127}128129#[solidity_interface(name = ERC20UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]130impl<T: Config> NativeFungibleHandle<T>131where132	T::AccountId: From<[u8; 32]>,133{134	fn balance_of_cross(&self, owner: CrossAddress) -> Result<U256> {135		// self.consume_store_reads(1)?;136		let owner = owner.into_sub_cross_account::<T>()?;137		let balance = <T as Config>::Currency::free_balance(owner.as_sub());138		Ok(balance.into())139	}140141	// #[weight(<SelfWeightOf<T>>::transfer())]142	fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {143		let caller = T::CrossAccountId::from_eth(caller);144		let to = to.into_sub_cross_account::<T>()?;145		let amount = amount.try_into().map_err(|_| "amount overflow")?;146		// let budget = self147		// 	.recorder148		// 	.weight_calls_budget(<StructureWeight<T>>::find_parent());149150		// <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;151		<T as Config>::Currency::transfer(152			caller.as_sub(),153			to.as_sub(),154			amount,155			ExistenceRequirement::KeepAlive,156		)157		.map_err(dispatch_to_evm::<T>)?;158		Ok(true)159	}160161	// #[weight(<SelfWeightOf<T>>::transfer_from())]162	fn transfer_from_cross(163		&mut self,164		caller: Caller,165		from: CrossAddress,166		to: CrossAddress,167		amount: U256,168	) -> Result<bool> {169		let caller = T::CrossAccountId::from_eth(caller);170		let from = from.into_sub_cross_account::<T>()?;171		let to = to.into_sub_cross_account::<T>()?;172		let amount = amount.try_into().map_err(|_| "amount overflow")?;173174		if from != to {175			return Err("no permission".into());176		}177178		// let budget = self179		// 	.recorder180		// 	.weight_calls_budget(<StructureWeight<T>>::find_parent());181182		// <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)183		// 	.map_err(dispatch_to_evm::<T>)?;184		<T as Config>::Currency::transfer(185			caller.as_sub(),186			to.as_sub(),187			amount,188			ExistenceRequirement::KeepAlive,189		)190		.map_err(dispatch_to_evm::<T>)?;191		Ok(true)192	}193}194195#[solidity_interface(196	name = UniqueNativeFungible,197	is(ERC20, ERC20UniqueExtensions),198	enum(derive(PreDispatch))199)]200impl<T: Config> NativeFungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}201202generate_stubgen!(gen_impl, UniqueNativeFungibleCall<()>, true);203generate_stubgen!(gen_iface, UniqueNativeFungibleCall<()>, false);204205impl<T: Config> CommonEvmHandler for NativeFungibleHandle<T>206where207	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,208{209	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNativeFungible.raw");210211	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {212		call::<T, UniqueNativeFungibleCall<T>, _, _>(handle, self)213	}214}
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -83,7 +83,7 @@
 	///
 	/// * `sender` - The owner of the collection.
 	/// * `handle` - Collection handle.
-	fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
+	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult;
 
 	/// Get a specialized collection from the handle.
 	///
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -1296,10 +1296,7 @@
 			sender: T::CrossAccountId,
 			collection_id: CollectionId,
 		) -> DispatchResult {
-			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_internal()?;
-
-			T::CollectionDispatch::destroy(sender, collection)?;
+			T::CollectionDispatch::destroy(sender, collection_id)?;
 
 			// TODO: basket cleanup should be moved elsewhere
 			// Maybe runtime dispatch.rs should perform it?
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -24,7 +24,8 @@
 		weights::CommonWeights,
 		RelayChainBlockNumberProvider,
 	},
-	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, Balances,
+	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
+	Balances,
 };
 use frame_support::traits::{ConstU32, ConstU64, Currency};
 use up_common::{
@@ -53,7 +54,7 @@
 
 parameter_types! {
 	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;
-	pub const Decimals: u8 = 32;
+	pub const Decimals: u8 = DECIMALS;
 	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account_truncating();
 	pub Name: String = RUNTIME_NAME.to_string();
 	pub Symbol: String = TOKEN_SYMBOL.to_string();
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -99,7 +99,10 @@
 		Ok(id)
 	}
 
-	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {
+	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {
+		let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+		collection.check_is_internal()?;
+
 		match collection.mode {
 			CollectionMode::ReFungible => {
 				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -45,6 +45,7 @@
 
 pub const RUNTIME_NAME: &str = "opal";
 pub const TOKEN_SYMBOL: &str = "OPL";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -48,6 +48,7 @@
 #[cfg(not(feature = "become-sapphire"))]
 pub const RUNTIME_NAME: &str = "quartz";
 pub const TOKEN_SYMBOL: &str = "QTZ";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -45,6 +45,7 @@
 
 pub const RUNTIME_NAME: &str = "unique";
 pub const TOKEN_SYMBOL: &str = "UNQ";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedtests/src/eth/nativeFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nativeFungible.test.ts
+++ b/tests/src/eth/nativeFungible.test.ts
@@ -15,29 +15,157 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {itEth, usingEthPlaygrounds} from './util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
 
-describe('NativeFungible: Plain calls', () => {
+describe('NativeFungible: ERC20 calls', () => {
   let donor: IKeyringPair;
-  let alice: IKeyringPair;
-  let owner: IKeyringPair;
 
   before(async function() {
     await usingEthPlaygrounds(async (helper, privateKey) => {
       donor = await privateKey({url: import.meta.url});
-      [alice, owner] = await helper.arrange.createAccounts([30n, 20n], donor);
+      // [alice] = await helper.arrange.createAccounts([30n], donor);
     });
   });
 
-  itEth.skip('Can perform approve()', async ({helper}) => {
+  itEth('approve()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const spender = helper.eth.createAccount();
-    const collection = await helper.ft.mintCollection(alice);
-    await collection.mint(alice, 200n, {Ethereum: owner});
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    await expect(contract.methods.approve(spender, 100).call({from: owner})).to.be.rejectedWith('Approve not supported');
+  });
+
+  itEth('balanceOf()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor, 123n);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balance = await contract.methods.balanceOf(owner).call({from: owner});
+    expect(balance).to.be.eq('123000000000000000000');
+  });
+
+  itEth('decimals()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const decimals = await contract.methods.decimals().call({from: owner});
+    expect(decimals).to.be.eq('18');
+  });
+
+  itEth('name()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const name = await contract.methods.name().call({from: owner});
+    expect(name).to.be.eq('opal');
+  });
+
+  itEth('symbol()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const name = await contract.methods.symbol().call({from: owner});
+    expect(name).to.be.eq('OPL');
+  });
+
+  itEth('totalSupply()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const totalSupplyEth = BigInt(await contract.methods.totalSupply().call({from: owner}));
+    const totalSupplySub = await helper.balance.getTotalIssuance();
+    expect(totalSupplyEth).to.be.eq(totalSupplySub);
+  });
+
+  itEth('transfer()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
+
+    await contract.methods.transfer(receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+  });
 
+  itEth('transferFrom()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
     const collectionAddress = helper.ethAddress.fromCollectionId(0);
     const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    await contract.methods.approve(spender, 100).send({from: owner});
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
+
+    await contract.methods.transferFrom(owner, receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+
+    await expect(contract.methods.transferFrom(receiver, receiver, 50).call({from: owner})).to.be.rejectedWith('no permission');
+  });
+});
+
+describe('NativeFungible: ERC20UniqueExtensions calls', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({url: import.meta.url});
+      // [alice] = await helper.arrange.createAccounts([30n], donor);
+    });
+  });
+
+  itEth('transferCross()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
+
+    await contract.methods.transferCross(receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+  });
+
+  itEth('transferFromCross()', async ({helper}) => {
+    const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner.eth);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner.eth);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
+
+    await contract.methods.transferFromCross(owner, receiver, 50).send({from: owner.eth});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner.eth);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+
+    await expect(contract.methods.transferFromCross(receiver, receiver, 50).call({from: owner.eth})).to.be.rejectedWith('no permission');
   });
 });
\ No newline at end of file
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -142,7 +142,7 @@
 
   async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {
     let abi;
-    if (address === '0x17C4e6453cC49aaAAEaCA894E6d9683e00000000' && mode === 'ft') {
+    if (address === '0x17C4e6453cC49aaAAEaCA894E6d9683e00000000') {
       abi = nativeFungibleAbi;
     } else {
       abi ={
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2400,7 +2400,16 @@
     return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};
   }
 
-  async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {
+  /**
+   * Get total issuance
+   * @returns
+   */
+  async getTotalIssuance(): Promise<bigint> {
+    const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));
+    return total.toBigInt();
+  }
+
+  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {
     const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();
     return locks.map((lock: any) => { return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}; });
   }
@@ -2488,6 +2497,14 @@
   }
 
   /**
+   * Get total issuance
+   * @returns
+   */
+  getTotalIssuance(): Promise<bigint> {
+    return this.subBalanceGroup.getTotalIssuance();
+  }
+
+  /**
    * Get locked balances
    * @param address substrate address
    * @returns locked balances with reason via api.query.balances.locks