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
--- a/pallets/balances-adapter/src/erc.rs
+++ b/pallets/balances-adapter/src/erc.rs
@@ -38,14 +38,14 @@
 
 #[solidity_interface(name = ERC20, events(ERC20Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x942e8b22)]
 impl<T: Config> NativeFungibleHandle<T> {
-	fn allowance(&self, owner: Address, spender: Address) -> Result<U256> {
+	fn allowance(&self, _owner: Address, _spender: Address) -> Result<U256> {
 		Ok(U256::zero())
 	}
 
 	// #[weight(<SelfWeightOf<T>>::approve())]
-	fn approve(&mut self, caller: Caller, spender: Address, amount: U256) -> Result<bool> {
+	fn approve(&mut self, _caller: Caller, _spender: Address, _amount: U256) -> Result<bool> {
 		// self.consume_store_reads(1)?;
-		Err("Approve not supported now".into())
+		Err("Approve not supported".into())
 	}
 
 	fn balance_of(&self, owner: Address) -> Result<U256> {
@@ -106,7 +106,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		if from != to {
+		if from != caller {
 			return Err("no permission".into());
 		}
 		// let budget = self
@@ -171,7 +171,7 @@
 		let to = to.into_sub_cross_account::<T>()?;
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		if from != to {
+		if from != caller {
 			return Err("no permission".into());
 		}
 
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
15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
1616
17import {IKeyringPair} from '@polkadot/types/types';17import {IKeyringPair} from '@polkadot/types/types';
18import {itEth, usingEthPlaygrounds} from './util';18import {expect, itEth, usingEthPlaygrounds} from './util';
1919
20describe('NativeFungible: Plain calls', () => {20describe('NativeFungible: ERC20 calls', () => {
21 let donor: IKeyringPair;21 let donor: IKeyringPair;
22 let alice: IKeyringPair;
23 let owner: IKeyringPair;
2422
25 before(async function() {23 before(async function() {
26 await usingEthPlaygrounds(async (helper, privateKey) => {24 await usingEthPlaygrounds(async (helper, privateKey) => {
27 donor = await privateKey({url: import.meta.url});25 donor = await privateKey({url: import.meta.url});
28 [alice, owner] = await helper.arrange.createAccounts([30n, 20n], donor);26 // [alice] = await helper.arrange.createAccounts([30n], donor);
29 });27 });
30 });28 });
3129
32 itEth.skip('Can perform approve()', async ({helper}) => {30 itEth('approve()', async ({helper}) => {
33 const owner = await helper.eth.createAccountWithBalance(donor);31 const owner = await helper.eth.createAccountWithBalance(donor);
34 const spender = helper.eth.createAccount();32 const spender = helper.eth.createAccount();
35 const collection = await helper.ft.mintCollection(alice);
36 await collection.mint(alice, 200n, {Ethereum: owner});
37
38 const collectionAddress = helper.ethAddress.fromCollectionId(0);33 const collectionAddress = helper.ethAddress.fromCollectionId(0);
39 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);34 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
4035
41 await contract.methods.approve(spender, 100).send({from: owner});36 await expect(contract.methods.approve(spender, 100).call({from: owner})).to.be.rejectedWith('Approve not supported');
42 });37 });
38
39 itEth('balanceOf()', async ({helper}) => {
40 const owner = await helper.eth.createAccountWithBalance(donor, 123n);
41 const collectionAddress = helper.ethAddress.fromCollectionId(0);
42 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
43
44 const balance = await contract.methods.balanceOf(owner).call({from: owner});
45 expect(balance).to.be.eq('123000000000000000000');
46 });
47
48 itEth('decimals()', async ({helper}) => {
49 const owner = await helper.eth.createAccountWithBalance(donor);
50 const collectionAddress = helper.ethAddress.fromCollectionId(0);
51 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
52
53 const decimals = await contract.methods.decimals().call({from: owner});
54 expect(decimals).to.be.eq('18');
55 });
56
57 itEth('name()', async ({helper}) => {
58 const owner = await helper.eth.createAccountWithBalance(donor);
59 const collectionAddress = helper.ethAddress.fromCollectionId(0);
60 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
61
62 const name = await contract.methods.name().call({from: owner});
63 expect(name).to.be.eq('opal');
64 });
65
66 itEth('symbol()', async ({helper}) => {
67 const owner = await helper.eth.createAccountWithBalance(donor);
68 const collectionAddress = helper.ethAddress.fromCollectionId(0);
69 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
70
71 const name = await contract.methods.symbol().call({from: owner});
72 expect(name).to.be.eq('OPL');
73 });
74
75 itEth('totalSupply()', async ({helper}) => {
76 const owner = await helper.eth.createAccountWithBalance(donor);
77 const collectionAddress = helper.ethAddress.fromCollectionId(0);
78 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
79
80 const totalSupplyEth = BigInt(await contract.methods.totalSupply().call({from: owner}));
81 const totalSupplySub = await helper.balance.getTotalIssuance();
82 expect(totalSupplyEth).to.be.eq(totalSupplySub);
83 });
84
85 itEth('transfer()', async ({helper}) => {
86 const owner = await helper.eth.createAccountWithBalance(donor);
87 const receiver = await helper.eth.createAccountWithBalance(donor);
88 const collectionAddress = helper.ethAddress.fromCollectionId(0);
89 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
90
91 const balanceOwnerBefore = await helper.balance.getEthereum(owner);
92 const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
93
94 await contract.methods.transfer(receiver, 50).send({from: owner});
95
96 const balanceOwnerAfter = await helper.balance.getEthereum(owner);
97 const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
98
99 expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
100 expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
101 });
102
103 itEth('transferFrom()', async ({helper}) => {
104 const owner = await helper.eth.createAccountWithBalance(donor);
105 const receiver = await helper.eth.createAccountWithBalance(donor);
106 const collectionAddress = helper.ethAddress.fromCollectionId(0);
107 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
108
109 const balanceOwnerBefore = await helper.balance.getEthereum(owner);
110 const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
111
112 await contract.methods.transferFrom(owner, receiver, 50).send({from: owner});
113
114 const balanceOwnerAfter = await helper.balance.getEthereum(owner);
115 const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
116
117 expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
118 expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
119
120 await expect(contract.methods.transferFrom(receiver, receiver, 50).call({from: owner})).to.be.rejectedWith('no permission');
121 });
43});122});
123
124describe('NativeFungible: ERC20UniqueExtensions calls', () => {
125 let donor: IKeyringPair;
126
127 before(async function() {
128 await usingEthPlaygrounds(async (helper, privateKey) => {
129 donor = await privateKey({url: import.meta.url});
130 // [alice] = await helper.arrange.createAccounts([30n], donor);
131 });
132 });
133
134 itEth('transferCross()', async ({helper}) => {
135 const owner = await helper.eth.createAccountWithBalance(donor);
136 const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
137 const collectionAddress = helper.ethAddress.fromCollectionId(0);
138 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
139
140 const balanceOwnerBefore = await helper.balance.getEthereum(owner);
141 const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
142
143 await contract.methods.transferCross(receiver, 50).send({from: owner});
144
145 const balanceOwnerAfter = await helper.balance.getEthereum(owner);
146 const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
147
148 expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
149 expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
150 });
151
152 itEth('transferFromCross()', async ({helper}) => {
153 const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);
154 const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
155 const collectionAddress = helper.ethAddress.fromCollectionId(0);
156 const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner.eth);
157
158 const balanceOwnerBefore = await helper.balance.getEthereum(owner.eth);
159 const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
160
161 await contract.methods.transferFromCross(owner, receiver, 50).send({from: owner.eth});
162
163 const balanceOwnerAfter = await helper.balance.getEthereum(owner.eth);
164 const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
165
166 expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
167 expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
168
169 await expect(contract.methods.transferFromCross(receiver, receiver, 50).call({from: owner.eth})).to.be.rejectedWith('no permission');
170 });
171});
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