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

difftreelog

Merge pull request #133 from usetech-llc/feature/NFTPAR-196_sponsor_setVariableMetadata

Greg Zaitsev2021-03-22parents: #e72e7a9 #ff8c59d.patch.diff
in: master
Feature/nftpar 196 sponsor set variable metadata

3 files changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -174,7 +174,7 @@
     pub mint_mode: bool,
     pub offchain_schema: Vec<u8>,
     pub schema_version: SchemaVersion,
-    pub sponsorship: SponsorshipState<AccountId>,
+    pub sponsorship: SponsorshipState<T::AccountId>,
     pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 
     pub variable_on_chain_schema: Vec<u8>, //
     pub const_on_chain_schema: Vec<u8>, //
@@ -1853,8 +1853,6 @@
     }
 
     fn create_item_no_validation(collection: &CollectionHandle<T>, owner: T::AccountId, data: CreateItemData) -> DispatchResult {
-        let collection_id = collection.id;
-
         match data
         {
             CreateItemData::NFT(data) => {
@@ -2622,10 +2620,7 @@
                 // sponsor timeout
                 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
 
-                let collection = <Collection<T>>::get(collection_id);
-
                 let limit = collection.limits.sponsor_transfer_timeout;
-                let mut sponsored = true;
                 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {
                     let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));
                     let limit_time = last_tx_block + limit.into();
@@ -2636,9 +2631,7 @@
                 <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);
 
                 // check free create limit
-                if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&
-                   (sponsored)
-                {
+                if collection.limits.sponsored_data_size >= (_properties.len() as u32) {
                     collection.sponsorship.sponsor()
                         .cloned()
                 } else {
@@ -2747,7 +2740,7 @@
                 let collection = <CollectionById<T>>::get(collection_id)?;
 
                 if
-                    collection.sponsor_confirmed &&
+                    collection.sponsorship.confirmed() &&
                     // Can't sponsor fungible collection, this tx will be rejected
                     // as invalid
                     !matches!(collection.mode, CollectionMode::Fungible(_)) &&
@@ -2769,7 +2762,7 @@
                 if !sponsor_metadata_changes {
                     None
                 } else {
-                    Some(collection.sponsor)
+                    collection.sponsorship.sponsor().cloned()
                 }
             }
 
modifiedtests/src/rpc.load.tsdiffbeforeafterboth
before · tests/src/rpc.load.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { expect, assert } from "chai";7import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { IKeyringPair } from "@polkadot/types/types";9import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";10import { ApiPromise, Keyring } from "@polkadot/api";11import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";12import { BigNumber } from 'bignumber.js';13import { findUnusedAddress } from './util/helpers'14import fs from "fs";15import privateKey from "./substrate/privateKey";1617const value = 0;18const gasLimit = 500000n * 1000000n;19const endowment = `1000000000000000`;202122function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {23  return new Promise<Blueprint>(async (resolve, reject) => {24    const unsub = await code25      .createBlueprint()26      .signAndSend(alice, (result) => {27        if (result.status.isInBlock || result.status.isFinalized) {28          // here we have an additional field in the result, containing the blueprint29          resolve(result.blueprint);30          unsub();31        }32      })33  });34}3536function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {37  return new Promise<any>(async (resolve, reject) => {38    const unsub = await blueprint.tx39    .new(endowment, gasLimit)40    .signAndSend(alice, (result) => {41      if (result.status.isInBlock || result.status.isFinalized) {42        unsub();43        resolve(result);44      }45    });    46  });47}4849async function prepareDeployer(api: ApiPromise) {50  // Find unused address51  const deployer = await findUnusedAddress(api);5253  // Transfer balance to it54  const keyring = new Keyring({ type: 'sr25519' });55  const alice = keyring.addFromUri(`//Alice`);56  let amount = new BigNumber(endowment);57  amount = amount.plus(1e15);58  const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());59  await submitTransactionAsync(alice, tx);6061  return deployer;62}6364async function deployLoadTester(api: ApiPromise): Promise<[Contract, IKeyringPair]> {65  const metadata = JSON.parse(fs.readFileSync('./src/load_test_sc/metadata.json').toString('utf-8'));66  const abi = new Abi(metadata);6768  const deployer = await prepareDeployer(api);6970  const wasm = fs.readFileSync('./src/load_test_sc/loadtester.wasm');7172  const code = new CodePromise(api, abi, wasm);7374  const blueprint = await deployBlueprint(deployer, code);75  const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7677  return [contract, deployer];78}7980async function getScData(contract: Contract, deployer: IKeyringPair) {81  const result = await contract.query.get(deployer.address, value, gasLimit);8283  if(!result.result.isSuccess) {84    throw `Failed to get value`;85  }86  return result.result.asSuccess.data;87}888990describe('RPC Tests', () => {91  it('Simple RPC Load Test', async () => {92    await usingApi(async api => {93      let count = 0;94      let hrTime = process.hrtime();95      let microsec1 = hrTime[0] * 1000000 + hrTime[1] / 1000;96      let rate = 0;97      const checkPoint = 1000;98      while (true) {99        await api.rpc.system.chain();100        count++;101        process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s            \r`);102    103        if (count % checkPoint == 0) {104          hrTime = process.hrtime();105          let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;106          rate = 1000000*checkPoint/(microsec2 - microsec1);107          microsec1 = microsec2;108        }109      }110    });111  });112113  it.only('Smart Contract RPC Load Test', async () => {114    await usingApi(async api => {115116      // Deploy smart contract117      const [contract, deployer] = await deployLoadTester(api);118119      // Fill smart contract up with data120      const bob = privateKey("//Bob");121      const tx = contract.tx.bloat(value, gasLimit, 200);122      await submitTransactionAsync(bob, tx);123124      // Run load test125      let count = 0;126      let hrTime = process.hrtime();127      let microsec1 = hrTime[0] * 1000000 + hrTime[1] / 1000;128      let rate = 0;129      const checkPoint = 10;130      while (true) {131        await getScData(contract, deployer);132        count++;133        process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s            \r`);134    135        if (count % checkPoint == 0) {136          hrTime = process.hrtime();137          let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;138          rate = 1000000*checkPoint/(microsec2 - microsec1);139          microsec1 = microsec2;140        }141      }142    });143  });144145});
after · tests/src/rpc.load.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { expect, assert } from "chai";7import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { IKeyringPair } from "@polkadot/types/types";9import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";10import { ApiPromise, Keyring } from "@polkadot/api";11import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";12import { BigNumber } from 'bignumber.js';13import { findUnusedAddress } from './util/helpers'14import fs from "fs";15import privateKey from "./substrate/privateKey";1617const value = 0;18const gasLimit = 500000n * 1000000n;19const endowment = `1000000000000000`;202122function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {23  return new Promise<Blueprint>(async (resolve, reject) => {24    const unsub = await code25      .createBlueprint()26      .signAndSend(alice, (result) => {27        if (result.status.isInBlock || result.status.isFinalized) {28          // here we have an additional field in the result, containing the blueprint29          resolve(result.blueprint);30          unsub();31        }32      })33  });34}3536function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {37  return new Promise<any>(async (resolve, reject) => {38    const unsub = await blueprint.tx39    .new(endowment, gasLimit)40    .signAndSend(alice, (result) => {41      if (result.status.isInBlock || result.status.isFinalized) {42        unsub();43        resolve(result);44      }45    });    46  });47}4849async function prepareDeployer(api: ApiPromise) {50  // Find unused address51  const deployer = await findUnusedAddress(api);5253  // Transfer balance to it54  const keyring = new Keyring({ type: 'sr25519' });55  const alice = keyring.addFromUri(`//Alice`);56  let amount = new BigNumber(endowment);57  amount = amount.plus(1e15);58  const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());59  await submitTransactionAsync(alice, tx);6061  return deployer;62}6364async function deployLoadTester(api: ApiPromise): Promise<[Contract, IKeyringPair]> {65  const metadata = JSON.parse(fs.readFileSync('./src/load_test_sc/metadata.json').toString('utf-8'));66  const abi = new Abi(metadata);6768  const deployer = await prepareDeployer(api);6970  const wasm = fs.readFileSync('./src/load_test_sc/loadtester.wasm');7172  const code = new CodePromise(api, abi, wasm);7374  const blueprint = await deployBlueprint(deployer, code);75  const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7677  return [contract, deployer];78}7980async function getScData(contract: Contract, deployer: IKeyringPair) {81  const result = await contract.query.get(deployer.address, value, gasLimit);8283  if(!result.result.isSuccess) {84    throw `Failed to get value`;85  }86  return result.result.asSuccess.data;87}888990describe('RPC Tests', () => {91  it('Simple RPC Load Test', async () => {92    await usingApi(async api => {93      let count = 0;94      let hrTime = process.hrtime();95      let microsec1 = hrTime[0] * 1000000 + hrTime[1] / 1000;96      let rate = 0;97      const checkPoint = 1000;98      while (true) {99        await api.rpc.system.chain();100        count++;101        process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s            \r`);102    103        if (count % checkPoint == 0) {104          hrTime = process.hrtime();105          let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;106          rate = 1000000*checkPoint/(microsec2 - microsec1);107          microsec1 = microsec2;108        }109      }110    });111  });112113  it('Smart Contract RPC Load Test', async () => {114    await usingApi(async api => {115116      // Deploy smart contract117      const [contract, deployer] = await deployLoadTester(api);118119      // Fill smart contract up with data120      const bob = privateKey("//Bob");121      const tx = contract.tx.bloat(value, gasLimit, 200);122      await submitTransactionAsync(bob, tx);123124      // Run load test125      let count = 0;126      let hrTime = process.hrtime();127      let microsec1 = hrTime[0] * 1000000 + hrTime[1] / 1000;128      let rate = 0;129      const checkPoint = 10;130      while (true) {131        await getScData(contract, deployer);132        count++;133        process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s            \r`);134    135        if (count % checkPoint == 0) {136          hrTime = process.hrtime();137          let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;138          rate = 1000000*checkPoint/(microsec2 - microsec1);139          microsec1 = microsec2;140        }141      }142    });143  });144145});
modifiedtests/src/setVariableMetadataSponsoringRateLimit.test.tsdiffbeforeafterboth
--- a/tests/src/setVariableMetadataSponsoringRateLimit.test.ts
+++ b/tests/src/setVariableMetadataSponsoringRateLimit.test.ts
@@ -68,7 +68,7 @@
     await setVariableMetaDataExpectFailure(userWithNoBalance, collectionId, itemId, [1, 2]);
   });
 
-  it.only('Default value of rate limit does not sponsor setting variable metadata', async () => {
+  it('Default value of rate limit does not sponsor setting variable metadata', async () => {
     const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, alice.address);
     await confirmSponsorshipExpectSuccess(collectionId);