difftreelog
refactor combine sponsorship fields
in: master
5 files changed
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -193,8 +193,7 @@
mint_mode: false,
offchain_schema: vec![],
schema_version: SchemaVersion::default(),
- sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
- sponsor_confirmed: true,
+ sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),
const_on_chain_schema: vec![],
variable_on_chain_schema: vec![],
limits: CollectionLimits::default()
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -123,6 +123,42 @@
pub fraction: u128,
}
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum SponsorshipState<AccountId> {
+ /// The fees are applied to the transaction sender
+ Disabled,
+ Unconfirmed(AccountId),
+ /// Transactions are sponsored by specified account
+ Confirmed(AccountId),
+}
+
+impl<AccountId> SponsorshipState<AccountId> {
+ fn sponsor(&self) -> Option<&AccountId> {
+ match self {
+ Self::Confirmed(sponsor) => Some(sponsor),
+ _ => None,
+ }
+ }
+
+ fn pending_sponsor(&self) -> Option<&AccountId> {
+ match self {
+ Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
+ _ => None,
+ }
+ }
+
+ fn confirmed(&self) -> bool {
+ matches!(self, Self::Confirmed(_))
+ }
+}
+
+impl<T> Default for SponsorshipState<T> {
+ fn default() -> Self {
+ Self::Disabled
+ }
+}
+
#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct CollectionType<AccountId> {
@@ -136,8 +172,7 @@
pub mint_mode: bool,
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
- pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
- pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.
+ pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
@@ -665,8 +700,7 @@
token_prefix: token_prefix,
offchain_schema: Vec::new(),
schema_version: SchemaVersion::ImageURL,
- sponsor: T::AccountId::default(),
- sponsor_confirmed: false,
+ sponsorship: SponsorshipState::Disabled,
variable_on_chain_schema: Vec::new(),
const_on_chain_schema: Vec::new(),
limits,
@@ -922,8 +956,7 @@
let mut target_collection = <Collection<T>>::get(collection_id);
ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
- target_collection.sponsor = new_sponsor;
- target_collection.sponsor_confirmed = false;
+ target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
<Collection<T>>::insert(collection_id, target_collection);
Ok(())
@@ -943,9 +976,12 @@
ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);
let mut target_collection = <Collection<T>>::get(collection_id);
- ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);
+ ensure!(
+ target_collection.sponsorship.pending_sponsor() == Some(&sender),
+ Error::<T>::ConfirmUnsetSponsorFail
+ );
- target_collection.sponsor_confirmed = true;
+ target_collection.sponsorship = SponsorshipState::Confirmed(sender);
<Collection<T>>::insert(collection_id, target_collection);
Ok(())
@@ -969,8 +1005,7 @@
let mut target_collection = <Collection<T>>::get(collection_id);
ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
- target_collection.sponsor = T::AccountId::default();
- target_collection.sponsor_confirmed = false;
+ target_collection.sponsorship = SponsorshipState::Disabled;
<Collection<T>>::insert(collection_id, target_collection);
Ok(())
@@ -2485,7 +2520,9 @@
// sponsor timeout
let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
- let limit = <Collection<T>>::get(collection_id).limits.sponsor_transfer_timeout;
+ 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));
@@ -2499,11 +2536,12 @@
}
// check free create limit
- if (<Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)) &&
- (<Collection<T>>::get(collection_id).sponsor_confirmed) &&
+ if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&
(sponsored)
{
- <Collection<T>>::get(collection_id).sponsor
+ collection.sponsorship.sponsor()
+ .cloned()
+ .unwrap_or_default()
} else {
T::AccountId::default()
}
@@ -2511,7 +2549,7 @@
Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {
let mut sponsor_transfer = false;
- if <Collection<T>>::get(collection_id).sponsor_confirmed {
+ if <Collection<T>>::get(collection_id).sponsorship.confirmed() {
let collection_limits = <Collection<T>>::get(collection_id).limits;
let collection_mode = <Collection<T>>::get(collection_id).mode;
@@ -2598,7 +2636,9 @@
if !sponsor_transfer {
T::AccountId::default()
} else {
- <Collection<T>>::get(collection_id).sponsor
+ <Collection<T>>::get(collection_id).sponsorship.sponsor()
+ .cloned()
+ .unwrap_or_default()
}
}
runtime_types.jsondiffbeforeafterboth--- a/runtime_types.json
+++ b/runtime_types.json
@@ -31,6 +31,13 @@
"ConstData": "Vec<u8>",
"VariableData": "Vec<u8>"
},
+ "SponsorshipState": {
+ "_enum": {
+ "Disabled": null,
+ "Unconfirmed": "AccountId",
+ "Confirmed": "AccountId"
+ }
+ },
"CollectionType": {
"Owner": "AccountId",
"Mode": "CollectionMode",
@@ -42,8 +49,7 @@
"MintMode": "bool",
"OffchainSchema": "Vec<u8>",
"SchemaVersion": "SchemaVersion",
- "Sponsor": "AccountId",
- "SponsorConfirmed": "bool",
+ "Sponsorship": "SponsorshipState",
"Limits": "CollectionLimits",
"VariableOnChainSchema": "Vec<u8>",
"ConstOnChainSchema": "Vec<u8>"
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -26,6 +26,7 @@
"testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
"testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
+ "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
"testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
tests/src/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39 recipient: string;40}4142interface TransferResult {43 success: boolean;44 collectionId: number;45 itemId: number;46 sender: string;47 recipient: string;48 value: bigint;49}5051interface IReFungibleOwner {52 Fraction: BN;53 Owner: number[];54}5556interface ITokenDataType {57 Owner: number[];58 ConstData: number[];59 VariableData: number[];60}6162interface IFungibleTokenDataType {63 Value: BN;64}6566export interface IReFungibleTokenDataType {67 Owner: IReFungibleOwner[];68 ConstData: number[];69 VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73 const result: GenericResult = {74 success: false,75 };76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method === 'ExtrinsicSuccess') {79 result.success = true;80 }81 });82 return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86 let success = false;87 let collectionId: number = 0;88 events.forEach(({ phase, event: { data, method, section } }) => {89 // console.log(` ${phase}: ${section}.${method}:: ${data}`);90 if (method == 'ExtrinsicSuccess') {91 success = true;92 } else if ((section == 'nft') && (method == 'Created')) {93 collectionId = parseInt(data[0].toString());94 }95 });96 const result: CreateCollectionResult = {97 success,98 collectionId,99 };100 return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104 let success = false;105 let collectionId: number = 0;106 let itemId: number = 0;107 let recipient: string = '';108 events.forEach(({ phase, event: { data, method, section } }) => {109 // console.log(` ${phase}: ${section}.${method}:: ${data}`);110 if (method == 'ExtrinsicSuccess') {111 success = true;112 } else if ((section == 'nft') && (method == 'ItemCreated')) {113 collectionId = parseInt(data[0].toString());114 itemId = parseInt(data[1].toString());115 recipient = data[2].toString();116 }117 });118 const result: CreateItemResult = {119 success,120 collectionId,121 itemId,122 recipient,123 };124 return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128 const result: TransferResult = {129 success: false,130 collectionId: 0,131 itemId: 0,132 sender: '',133 recipient: '',134 value: 0n,135 };136137 events.forEach(({event: {data, method, section}}) => {138 if (method === 'ExtrinsicSuccess') {139 result.success = true;140 } else if (section === 'nft' && method === 'Transfer') {141 result.collectionId = +data[0].toString();142 result.itemId = +data[1].toString();143 result.sender = data[2].toString();144 result.recipient = data[3].toString();145 result.value = BigInt(data[4].toString());146 }147 });148149 return result;150}151152interface Invalid {153 type: 'Invalid';154}155156interface Nft {157 type: 'NFT';158}159160interface Fungible {161 type: 'Fungible';162 decimalPoints: number;163}164165interface ReFungible {166 type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172 mode: CollectionMode,173 name: string,174 description: string,175 tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179 description: 'description',180 mode: { type: 'NFT' },181 name: 'name',182 tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188 let collectionId: number = 0;189 await usingApi(async (api) => {190 // Get number of collections before the transaction191 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193 // Run the CreateCollection transaction194 const alicePrivateKey = privateKey('//Alice');195196 let modeprm = {};197 if (mode.type === 'NFT') {198 modeprm = {nft: null};199 } else if (mode.type === 'Fungible') {200 modeprm = {fungible: mode.decimalPoints};201 } else if (mode.type === 'ReFungible') {202 modeprm = {refungible: null};203 } else if (mode.type === 'Invalid') {204 modeprm = {invalid: null};205 }206207 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208 const events = await submitTransactionAsync(alicePrivateKey, tx);209 const result = getCreateCollectionResult(events);210211 // Get number of collections after the transaction212 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214 // Get the collection215 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();216217 // What to expect218 // tslint:disable-next-line:no-unused-expression219 expect(result.success).to.be.true;220 expect(result.collectionId).to.be.equal(BcollectionCount);221 // tslint:disable-next-line:no-unused-expression222 expect(collection).to.be.not.null;223 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224 expect(collection.Owner).to.be.equal(alicesPublicKey);225 expect(utf16ToStr(collection.Name)).to.be.equal(name);226 expect(utf16ToStr(collection.Description)).to.be.equal(description);227 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229 collectionId = result.collectionId;230 });231232 return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238 let modeprm = {};239 if (mode.type === 'NFT') {240 modeprm = {nft: null};241 } else if (mode.type === 'Fungible') {242 modeprm = {fungible: mode.decimalPoints};243 } else if (mode.type === 'ReFungible') {244 modeprm = {refungible: null};245 } else if (mode.type === 'Invalid') {246 modeprm = {invalid: null};247 }248249 await usingApi(async (api) => {250 // Get number of collections before the transaction251 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253 // Run the CreateCollection transaction254 const alicePrivateKey = privateKey('//Alice');255 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257 const result = getCreateCollectionResult(events);258259 // Get number of collections after the transaction260 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262 // What to expect263 // tslint:disable-next-line:no-unused-expression264 expect(result.success).to.be.false;265 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266 });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270 let bal = new BigNumber(0);271 let unused;272 do {273 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274 const keyring = new Keyring({ type: 'sr25519' });275 unused = keyring.addFromUri(`//${randomSeed}`);276 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277 } while (bal.toFixed() != '0');278 return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282 return await usingApi(async (api) => {283 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284 return BigInt(bn.toString());285 });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294 const newCollection: number = totalNumber + 1;295 return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299 let success: boolean = false;300 events.forEach(({ phase, event: { data, method, section } }) => {301 // console.log(` ${phase}: ${section}.${method}:: ${data}`);302 if (method == 'ExtrinsicSuccess') {303 success = true;304 }305 });306 return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310 await usingApi(async (api) => {311 // Run the DestroyCollection transaction312 const alicePrivateKey = privateKey(senderSeed);313 const tx = api.tx.nft.destroyCollection(collectionId);314 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315 });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319 await usingApi(async (api) => {320 // Run the DestroyCollection transaction321 const alicePrivateKey = privateKey(senderSeed);322 const tx = api.tx.nft.destroyCollection(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getDestroyResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result).to.be.true;331 expect(collection).to.be.not.null;332 expect(collection.Owner).to.be.equal(nullPublicKey);333 });334}335336export async function queryCollectionLimits(collectionId: number) {337 return await usingApi(async (api) => {338 return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;339 });340}341342export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {343 await usingApi(async (api) => {344 const oldLimits = await queryCollectionLimits(collectionId);345 const newLimits = { ...oldLimits as any, ...limits };346 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);347 const events = await submitTransactionAsync(sender, tx);348 const result = getGenericResult(events);349350 expect(result.success).to.be.true;351 });352}353354export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {355 await usingApi(async (api) => {356 const oldLimits = await queryCollectionLimits(collectionId);357 const newLimits = { ...oldLimits as any, ...limits };358 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);359 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;360 const result = getGenericResult(events);361362 expect(result.success).to.be.false;363 });364}365366export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {367 await usingApi(async (api) => {368369 // Run the transaction370 const alicePrivateKey = privateKey('//Alice');371 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);372 const events = await submitTransactionAsync(alicePrivateKey, tx);373 const result = getGenericResult(events);374375 // Get the collection376 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();377378 // What to expect379 expect(result.success).to.be.true;380 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());381 expect(collection.SponsorConfirmed).to.be.false;382 });383}384385export async function removeCollectionSponsorExpectSuccess(collectionId: number) {386 await usingApi(async (api) => {387388 // Run the transaction389 const alicePrivateKey = privateKey('//Alice');390 const tx = api.tx.nft.removeCollectionSponsor(collectionId);391 const events = await submitTransactionAsync(alicePrivateKey, tx);392 const result = getGenericResult(events);393394 // Get the collection395 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();396397 // What to expect398 expect(result.success).to.be.true;399 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });400 });401}402403export async function removeCollectionSponsorExpectFailure(collectionId: number) {404 await usingApi(async (api) => {405406 // Run the transaction407 const alicePrivateKey = privateKey('//Alice');408 const tx = api.tx.nft.removeCollectionSponsor(collectionId);409 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;410 });411}412413export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {414 await usingApi(async (api) => {415416 // Run the transaction417 const alicePrivateKey = privateKey(senderSeed);418 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);419 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;420 });421}422423export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {424 await usingApi(async (api) => {425426 // Run the transaction427 const sender = privateKey(senderSeed);428 const tx = api.tx.nft.confirmSponsorship(collectionId);429 const events = await submitTransactionAsync(sender, tx);430 const result = getGenericResult(events);431432 // Get the collection433 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();434435 // What to expect436 expect(result.success).to.be.true;437 expect(collection.Sponsor).to.be.equal(sender.address);438 expect(collection.SponsorConfirmed).to.be.true;439 });440}441442443export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {444 await usingApi(async (api) => {445446 // Run the transaction447 const sender = privateKey(senderSeed);448 const tx = api.tx.nft.confirmSponsorship(collectionId);449 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;450 });451}452453export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {454 await usingApi(async (api) => {455 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);456 const events = await submitTransactionAsync(sender, tx);457 const result = getGenericResult(events);458459 expect(result.success).to.be.true;460 });461}462463export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {464 await usingApi(async (api) => {465 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);466 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;467 const result = getGenericResult(events);468469 expect(result.success).to.be.false;470 });471}472473export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {474 await usingApi(async (api) => {475 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);476 const events = await submitTransactionAsync(sender, tx);477 const result = getGenericResult(events);478479 expect(result.success).to.be.true;480 });481}482483export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {484 await usingApi(async (api) => {485 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);486 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;487 const result = getGenericResult(events);488489 expect(result.success).to.be.false;490 });491}492493export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {494 await usingApi(async (api) => {495 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);496 const events = await submitTransactionAsync(sender, tx);497 const result = getGenericResult(events);498499 expect(result.success).to.be.true;500 });501}502503export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {504 let whitelisted: boolean = false;505 await usingApi(async (api) => {506 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;507 });508 return whitelisted;509}510511export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {512 await usingApi(async (api) => {513 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);514 const events = await submitTransactionAsync(sender, tx);515 const result = getGenericResult(events);516517 expect(result.success).to.be.true;518 });519}520521export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {522 await usingApi(async (api) => {523 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);524 const events = await submitTransactionAsync(sender, tx);525 const result = getGenericResult(events);526527 expect(result.success).to.be.true;528 });529}530531export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {532 await usingApi(async (api) => {533 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);534 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;535 const result = getGenericResult(events);536537 expect(result.success).to.be.false;538 });539}540541export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {542 await usingApi(async (api) => {543 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));544 const events = await submitTransactionAsync(sender, tx);545 const result = getGenericResult(events);546547 expect(result.success).to.be.true;548 });549}550551export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {552 await usingApi(async (api) => {553 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));554 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;555 });556}557558export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {559 await usingApi(async (api) => {560 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {569 await usingApi(async (api) => {570 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));571 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;572 });573}574575export interface CreateFungibleData {576 readonly Value: bigint;577}578579export interface CreateReFungibleData { }580export interface CreateNftData { }581582export type CreateItemData = {583 NFT: CreateNftData;584} | {585 Fungible: CreateFungibleData;586} | {587 ReFungible: CreateReFungibleData;588};589590export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);593 const events = await submitTransactionAsync(owner, tx);594 const result = getGenericResult(events);595 // Get the item596 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();597 // What to expect598 // tslint:disable-next-line:no-unused-expression599 expect(result.success).to.be.true;600 // tslint:disable-next-line:no-unused-expression601 expect(item).to.be.not.null;602 expect(item.Owner).to.be.equal(nullPublicKey);603 });604}605606export async function607approveExpectSuccess(collectionId: number,608 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {609 await usingApi(async (api: ApiPromise) => {610 const allowanceBefore =611 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;612 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);613 const events = await submitTransactionAsync(owner, approveNftTx);614 const result = getCreateItemResult(events);615 // tslint:disable-next-line:no-unused-expression616 expect(result.success).to.be.true;617 const allowanceAfter =618 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;619 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());620 });621}622623export async function624transferFromExpectSuccess(collectionId: number,625 tokenId: number,626 accountApproved: IKeyringPair,627 accountFrom: IKeyringPair,628 accountTo: IKeyringPair,629 value: number | bigint = 1,630 type: string = 'NFT') {631 await usingApi(async (api: ApiPromise) => {632 let balanceBefore = new BN(0);633 if (type === 'Fungible') {634 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;635 }636 const transferFromTx = await api.tx.nft.transferFrom(637 accountFrom.address, accountTo.address, collectionId, tokenId, value);638 const events = await submitTransactionAsync(accountApproved, transferFromTx);639 const result = getCreateItemResult(events);640 // tslint:disable-next-line:no-unused-expression641 expect(result.success).to.be.true;642 if (type === 'NFT') {643 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;644 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);645 }646 if (type === 'Fungible') {647 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;648 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());649 }650 if (type === 'ReFungible') {651 const nftItemData =652 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;653 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);654 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);655 }656 });657}658659export async function660transferFromExpectFail(collectionId: number,661 tokenId: number,662 accountApproved: IKeyringPair,663 accountFrom: IKeyringPair,664 accountTo: IKeyringPair,665 value: number | bigint = 1) {666 await usingApi(async (api: ApiPromise) => {667 const transferFromTx = await api.tx.nft.transferFrom(668 accountFrom.address, accountTo.address, collectionId, tokenId, value);669 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;670 const result = getCreateCollectionResult(events);671 // tslint:disable-next-line:no-unused-expression672 expect(result.success).to.be.false;673 });674}675676export async function677transferExpectSuccess(collectionId: number,678 tokenId: number,679 sender: IKeyringPair,680 recipient: IKeyringPair,681 value: number | bigint = 1,682 type: string = 'NFT') {683 await usingApi(async (api: ApiPromise) => {684 let balanceBefore = new BN(0);685 if (type === 'Fungible') {686 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;687 }688 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);689 const events = await submitTransactionAsync(sender, transferTx);690 const result = getTransferResult(events);691 // tslint:disable-next-line:no-unused-expression692 expect(result.success).to.be.true;693 expect(result.collectionId).to.be.equal(collectionId);694 expect(result.itemId).to.be.equal(tokenId);695 expect(result.sender).to.be.equal(sender.address);696 expect(result.recipient).to.be.equal(recipient.address);697 expect(result.value.toString()).to.be.equal(value.toString());698 if (type === 'NFT') {699 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;700 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);701 }702 if (type === 'Fungible') {703 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;704 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());705 }706 if (type === 'ReFungible') {707 const nftItemData =708 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;709 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);710 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);711 }712 });713}714715export async function716transferExpectFail(collectionId: number,717 tokenId: number,718 sender: IKeyringPair,719 recipient: IKeyringPair,720 value: number | bigint = 1,721 type: string = 'NFT') {722 await usingApi(async (api: ApiPromise) => {723 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);724 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;725 if (events && Array.isArray(events)) {726 const result = getCreateCollectionResult(events);727 // tslint:disable-next-line:no-unused-expression728 expect(result.success).to.be.false;729 }730 });731}732733export async function734approveExpectFail(collectionId: number,735 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {736 await usingApi(async (api: ApiPromise) => {737 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);738 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;739 const result = getCreateCollectionResult(events);740 // tslint:disable-next-line:no-unused-expression741 expect(result.success).to.be.false;742 });743}744745export async function getFungibleBalance(746 collectionId: number,747 owner: string,748) {749 return await usingApi(async (api) => {750 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};751 return BigInt(response.Value);752 });753}754755export async function createFungibleItemExpectSuccess(756 sender: IKeyringPair,757 collectionId: number,758 data: CreateFungibleData,759 owner: string = sender.address,760) {761 return await usingApi(async (api) => {762 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });763764 const events = await submitTransactionAsync(sender, tx);765 const result = getCreateItemResult(events);766767 expect(result.success).to.be.true;768 return result.itemId;769 });770}771772export async function createItemExpectSuccess(773 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {774 let newItemId: number = 0;775 await usingApi(async (api) => {776 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);777 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();778 const AItemBalance = new BigNumber(Aitem.Value);779780 if (owner === '') {781 owner = sender.address;782 }783784 let tx;785 if (createMode === 'Fungible') {786 const createData = {fungible: {value: 10}};787 tx = api.tx.nft.createItem(collectionId, owner, createData);788 } else if (createMode === 'ReFungible') {789 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};790 tx = api.tx.nft.createItem(collectionId, owner, createData);791 } else {792 tx = api.tx.nft.createItem(collectionId, owner, createMode);793 }794 const events = await submitTransactionAsync(sender, tx);795 const result = getCreateItemResult(events);796797 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);798 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();799 const BItemBalance = new BigNumber(Bitem.Value);800801 // What to expect802 // tslint:disable-next-line:no-unused-expression803 expect(result.success).to.be.true;804 if (createMode === 'Fungible') {805 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);806 } else {807 expect(BItemCount).to.be.equal(AItemCount + 1);808 }809 expect(collectionId).to.be.equal(result.collectionId);810 expect(BItemCount).to.be.equal(result.itemId);811 expect(owner).to.be.equal(result.recipient);812 newItemId = result.itemId;813 });814 return newItemId;815}816817export async function createItemExpectFailure(818 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {819 await usingApi(async (api) => {820 const tx = api.tx.nft.createItem(collectionId, owner, createMode);821 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;822 const result = getCreateItemResult(events);823824 expect(result.success).to.be.false;825 });826}827828export async function setPublicAccessModeExpectSuccess(829 sender: IKeyringPair, collectionId: number,830 accessMode: 'Normal' | 'WhiteList',831) {832 await usingApi(async (api) => {833834 // Run the transaction835 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);836 const events = await submitTransactionAsync(sender, tx);837 const result = getGenericResult(events);838839 // Get the collection840 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();841842 // What to expect843 // tslint:disable-next-line:no-unused-expression844 expect(result.success).to.be.true;845 expect(collection.Access).to.be.equal(accessMode);846 });847}848849export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {850 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');851}852853export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {854 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');855}856857export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {858 await usingApi(async (api) => {859860 // Run the transaction861 const tx = api.tx.nft.setMintPermission(collectionId, enabled);862 const events = await submitTransactionAsync(sender, tx);863 const result = getGenericResult(events);864865 // Get the collection866 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();867868 // What to expect869 // tslint:disable-next-line:no-unused-expression870 expect(result.success).to.be.true;871 expect(collection.MintMode).to.be.equal(enabled);872 });873}874875export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {876 await setMintPermissionExpectSuccess(sender, collectionId, true);877}878879export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {880 await usingApi(async (api) => {881 // Run the transaction882 const tx = api.tx.nft.setMintPermission(collectionId, enabled);883 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;884 const result = getCreateCollectionResult(events);885 // tslint:disable-next-line:no-unused-expression886 expect(result.success).to.be.false;887 });888}889890export async function isWhitelisted(collectionId: number, address: string) {891 let whitelisted: boolean = false;892 await usingApi(async (api) => {893 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;894 });895 return whitelisted;896}897898export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {899 await usingApi(async (api) => {900901 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();902903 // Run the transaction904 const tx = api.tx.nft.addToWhiteList(collectionId, address);905 const events = await submitTransactionAsync(sender, tx);906 const result = getGenericResult(events);907908 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();909910 // What to expect911 // tslint:disable-next-line:no-unused-expression912 expect(result.success).to.be.true;913 // tslint:disable-next-line: no-unused-expression914 expect(whiteListedBefore).to.be.false;915 // tslint:disable-next-line: no-unused-expression916 expect(whiteListedAfter).to.be.true;917 });918}919920export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {921 await usingApi(async (api) => {922 // Run the transaction923 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);924 const events = await submitTransactionAsync(sender, tx);925 const result = getGenericResult(events);926927 // What to expect928 // tslint:disable-next-line:no-unused-expression929 expect(result.success).to.be.true;930 });931}932933export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {934 await usingApi(async (api) => {935 // Run the transaction936 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);937 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;938 const result = getGenericResult(events);939940 // What to expect941 // tslint:disable-next-line:no-unused-expression942 expect(result.success).to.be.false;943 });944}945946export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)947 : Promise<ICollectionInterface | null> => {948 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;949};950951export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {952 // set global object - collectionsCount953 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();954};955956export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {957 return await usingApi(async (api) => {958 return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;959 });960}