git.delta.rocks / unique-network / refs/commits / d82d09e3c952

difftreelog

fix(refungible-pallet) fixed wrong amount in ItemCreated event

Grigoriy Simonov2022-08-04parent: #3203150.patch.diff
in: master

4 files changed

modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -393,14 +393,7 @@
 			})
 			.ok_or(ArithmeticError::Overflow)?;
 
-		let mut balances = data;
-		for (k, v) in balances.iter_mut() {
-			*v = <Balance<T>>::get((collection.id, &k))
-				.checked_add(*v)
-				.ok_or(ArithmeticError::Overflow)?;
-		}
-
-		for (to, _) in balances.iter() {
+		for (to, _) in data.iter() {
 			<PalletStructure<T>>::check_nesting(
 				sender.clone(),
 				to,
@@ -413,8 +406,11 @@
 		// =========
 
 		<TotalSupply<T>>::insert(collection.id, total_supply);
-		for (user, amount) in balances {
-			<Balance<T>>::insert((collection.id, &user), amount);
+		for (user, amount) in data {
+			let updated_balance = <Balance<T>>::get((collection.id, &user))
+				.checked_add(amount)
+				.ok_or(ArithmeticError::Overflow)?;
+			<Balance<T>>::insert((collection.id, &user), updated_balance);
 			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(
 				&user,
 				collection.id,
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -560,10 +560,7 @@
 		<Pallet<T>>::create_item(
 			self,
 			&caller,
-			CreateItemData::<T> {
-				users,
-				properties,
-			},
+			CreateItemData::<T> { users, properties },
 			&budget,
 		)
 		.map_err(dispatch_to_evm::<T>)?;
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
before · tests/src/createItem.test.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {default as usingApi} from './substrate/substrate-api';18import chai from 'chai';19import {IKeyringPair} from '@polkadot/types/types';20import {21  createCollectionExpectSuccess,22  createItemExpectSuccess,23  addCollectionAdminExpectSuccess,24  createCollectionWithPropsExpectSuccess,25  createItemWithPropsExpectSuccess,26  createItemWithPropsExpectFailure,27  createCollection,28  transferExpectSuccess,29} from './util/helpers';3031const expect = chai.expect;32let alice: IKeyringPair;33let bob: IKeyringPair;3435describe('integration test: ext. ():', () => {36  before(async () => {37    await usingApi(async (api, privateKeyWrapper) => {38      alice = privateKeyWrapper('//Alice');39      bob = privateKeyWrapper('//Bob');40    });41  });4243  it('Create new item in NFT collection', async () => {44    const createMode = 'NFT';45    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});46    await createItemExpectSuccess(alice, newCollectionID, createMode);47  });48  it('Create new item in Fungible collection', async () => {49    const createMode = 'Fungible';50    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});51    await createItemExpectSuccess(alice, newCollectionID, createMode);52  });53  it('Create new item in ReFungible collection', async () => {54    const createMode = 'ReFungible';55    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});56    await createItemExpectSuccess(alice, newCollectionID, createMode);57  });58  it('Create new item in NFT collection with collection admin permissions', async () => {59    const createMode = 'NFT';60    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});61    await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);62    await createItemExpectSuccess(bob, newCollectionID, createMode);63  });64  it('Create new item in Fungible collection with collection admin permissions', async () => {65    const createMode = 'Fungible';66    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});67    await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);68    await createItemExpectSuccess(bob, newCollectionID, createMode);69  });70  it('Create new item in ReFungible collection with collection admin permissions', async () => {71    const createMode = 'ReFungible';72    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});73    await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);74    await createItemExpectSuccess(bob, newCollectionID, createMode);75  });7677  it('Set property Admin', async () => {78    const createMode = 'NFT';79    const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode}, 80      propPerm:   [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});81    82    await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'k', value: 't2'}]);83  });8485  it('Set property AdminConst', async () => {86    const createMode = 'NFT';87    const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode}, 88      propPerm:   [{key: 'key1', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]});89    90    await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);91  });9293  it('Set property itemOwnerOrAdmin', async () => {94    const createMode = 'NFT';95    const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},96      propPerm:   [{key: 'key1', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]});97    98    await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);99  });100101  it('Check total pieces of Fungible token', async () => {102    await usingApi(async api => {103      const createMode = 'Fungible';104      const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});105      const amountPieces = 10n;106      const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);107      {108        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);109        expect(totalPieces.isSome).to.be.true;110        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);111      }112113      await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);114      {115        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);116        expect(totalPieces.isSome).to.be.true;117        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);118      }119120      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;121      expect(totalPieces.toBigInt()).to.be.eq(amountPieces);122    });123  });124125  it('Check total pieces of NFT token', async () => {126    await usingApi(async api => {127      const createMode = 'NFT';128      const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});129      const amountPieces = 1n;130      const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);131      {132        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);133        expect(totalPieces.isSome).to.be.true;134        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);135      }136137      await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);138      {139        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);140        expect(totalPieces.isSome).to.be.true;141        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);142      }143144      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;145      expect(totalPieces.toBigInt()).to.be.eq(amountPieces);146    });147  });148149  it('Check total pieces of ReFungible token', async () => {150    await usingApi(async api => {151      const createMode = 'ReFungible';152      const createCollectionResult = await createCollection(api, alice, {mode: {type: createMode}});153      const collectionId  = createCollectionResult.collectionId;154      const amountPieces = 100n;155      const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);156      {157        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);158        expect(totalPieces.isSome).to.be.true;159        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);160      }161162      await transferExpectSuccess(collectionId, tokenId, bob, alice, 60n, createMode);163      {164        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);165        expect(totalPieces.isSome).to.be.true;166        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);167      }168169      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;170      expect(totalPieces.toBigInt()).to.be.eq(amountPieces);171    });172  });173});174175describe('Negative integration test: ext. createItem():', () => {176  before(async () => {177    await usingApi(async (api, privateKeyWrapper) => {178      alice = privateKeyWrapper('//Alice');179      bob = privateKeyWrapper('//Bob');180    });181  });182183  it('Regular user cannot create new item in NFT collection', async () => {184    const createMode = 'NFT';185    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});186    await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;187  });188  it('Regular user cannot create new item in Fungible collection', async () => {189    const createMode = 'Fungible';190    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});191    await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;192  });193  it('Regular user cannot create new item in ReFungible collection', async () => {194    const createMode = 'ReFungible';195    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});196    await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;197  });198199  it('No editing rights', async () => {200    await usingApi(async () => {201      const createMode = 'NFT';202      const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode}, 203        propPerm:   [{key: 'key1', permission: {mutable: false, collectionAdmin: false, tokenOwner: false}}]});204      await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);205206      await createItemWithPropsExpectFailure(bob, newCollectionID, 'NFT', [{key: 'key1', value: 'v'}]);207    });208  });209210  it('User doesnt have editing rights', async () => {211    await usingApi(async () => {212      const newCollectionID = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]});213      await createItemWithPropsExpectFailure(bob, newCollectionID, 'NFT', [{key: 'key1', value: 'v'}]);214    });215  });216217  it('Adding property without access rights', async () => {218    await usingApi(async () => {219      const newCollectionID = await createCollectionWithPropsExpectSuccess();220      await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);221222      await createItemWithPropsExpectFailure(bob, newCollectionID, 'NFT', [{key: 'k', value: 'v'}]);223    });224  });225226  it('Adding more than 64 prps', async () => {227    await usingApi(async () => {228      const prps = [];229230      for (let i = 0; i < 65; i++) {231        prps.push({key: `key${i}`, value: `value${i}`});232      }233234      const newCollectionID = await createCollectionWithPropsExpectSuccess();235      236      await createItemWithPropsExpectFailure(alice, newCollectionID, 'NFT', prps);237    });238  });239240  it('Trying to add bigger property than allowed', async () => {241    await usingApi(async () => {242      const newCollectionID = await createCollectionWithPropsExpectSuccess();243      244      await createItemWithPropsExpectFailure(alice, newCollectionID, 'NFT', [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]);245    });246  });247248  it('Check total pieces for invalid Fungible token', async () => {249    await usingApi(async api => {250      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});251      const collectionId  = createCollectionResult.collectionId;252      const invalidTokenId = 1000_000;253      254      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;255      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.toBigInt()).to.be.eq(0n);256    });257  });258259  it('Check total pieces for invalid NFT token', async () => {260    await usingApi(async api => {261      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'NFT'}});262      const collectionId  = createCollectionResult.collectionId;263      const invalidTokenId = 1000_000;264      265      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;266      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.toBigInt()).to.be.eq(0n);267    });268  });269270  it('Check total pieces for invalid Refungible token', async () => {271    await usingApi(async api => {272      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});273      const collectionId  = createCollectionResult.collectionId;274      const invalidTokenId = 1000_000;275      276      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;277      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.toBigInt()).to.be.eq(0n);278    });279  });280});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -248,22 +248,23 @@
 }
 
 export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
-  const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [
-    parseInt(data[0].toString(), 10),
-    parseInt(data[1].toString(), 10),
-    normalizeAccountId(data[2].toJSON() as any),
-  ]);
-
-  if (genericResult.data == null) genericResult.data = [0, 0];
-
-  const result: CreateItemResult = {
-    success: genericResult.success,
-    collectionId: genericResult.data[0],
-    itemId: genericResult.data[1],
-    recipient: genericResult.data![2],
-  };
+  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
   
-  return result;
+  if (genericResult.data == null) 
+    return {
+      success: genericResult.success,
+      collectionId: 0,
+      itemId: 0,
+      amount: 0,
+    };
+  else 
+    return {
+      success: genericResult.success,
+      collectionId: genericResult.data[0] as number,
+      itemId: genericResult.data[1] as number,
+      recipient: normalizeAccountId(genericResult.data![2] as any),
+      amount: genericResult.data[3] as number,
+    };
 }
 
 export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
@@ -1699,3 +1700,14 @@
 
   return result.success;
 }
+
+export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
+  let i: any = it;
+  if (opts.only) i = i.only;
+  else if (opts.skip) i = i.skip;
+  i(name, async () => {
+    await usingApi(async (api, privateKeyWrapper) => {
+      await cb({api, privateKeyWrapper});
+    });
+  });
+}