difftreelog
test reformat code
in: master
48 files changed
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -109,7 +109,7 @@
const chainAdminLimit = (helper.getApi().consts.common.collectionAdminsLimit as any).toNumber();
expect(chainAdminLimit).to.be.equal(5);
- for (let i = 0; i < chainAdminLimit; i++) {
+ for(let i = 0; i < chainAdminLimit; i++) {
await collection.addAdmin(alice, {Substrate: accounts[i].address});
const adminListAfterAddAdmin = await collection.getAdmins();
expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: accounts[i].address});
tests/src/allowLists.test.tsdiffbeforeafterboth--- a/tests/src/allowLists.test.ts
+++ b/tests/src/allowLists.test.ts
@@ -315,7 +315,7 @@
await collection.setPermissions(alice, permissions);
await collection.addToAllowList(alice, {Substrate: bob.address});
- if (allowlistedMintingShouldFail)
+ if(allowlistedMintingShouldFail)
await expect(collection.mintToken(bob, {Substrate: bob.address})).to.be.rejectedWith(appropriateRejectionMessage);
else
await expect(collection.mintToken(bob, {Substrate: bob.address})).to.not.be.rejected;
@@ -338,7 +338,7 @@
await expect(collection.mintToken(bob, {Substrate: bob.address})).to.not.be.rejected;
});
- if (!allowlistedMintingShouldFail) allowlistedMintingTest();
+ if(!allowlistedMintingShouldFail) allowlistedMintingTest();
});
describe('Negative', () => {
@@ -349,12 +349,12 @@
.to.be.rejectedWith(appropriateRejectionMessage);
});
- if (allowlistedMintingShouldFail) allowlistedMintingTest();
+ if(allowlistedMintingShouldFail) allowlistedMintingTest();
});
});
};
- for (const permissions of permissionSet) {
+ for(const permissions of permissionSet) {
testPermissionSuite(permissions);
}
});
tests/src/benchmarks/mintFee/index.tsdiffbeforeafterboth--- a/tests/src/benchmarks/mintFee/index.ts
+++ b/tests/src/benchmarks/mintFee/index.ts
@@ -88,7 +88,7 @@
const result: IBenchmarkResultForProp[] = [];
const csvResult: IBenchmarkResultForProp[] = [];
- for (let i = 1; i <= 20; i++) {
+ for(let i = 1; i <= 20; i++) {
const benchResult = await benchMintWithProperties(helper, privateKey, contract, {
propertiesNumber: i,
}) as any;
@@ -254,7 +254,7 @@
'0',
);
- for (const val of PROPERTIES.slice(0, setup.propertiesNumber)) {
+ for(const val of PROPERTIES.slice(0, setup.propertiesNumber)) {
encodedCall = await evmContract.methods
.setProperty(subTokenId, val.key, Buffer.from(val.value))
.encodeABI();
tests/src/benchmarks/utils/common.tsdiffbeforeafterboth--- a/tests/src/benchmarks/utils/common.ts
+++ b/tests/src/benchmarks/utils/common.ts
@@ -77,11 +77,11 @@
Ethereum: helper.address.substrateToEth(donor.address),
});
- if (proxyContract) {
+ if(proxyContract) {
await collection.addToAllowList(donor, {Ethereum: proxyContract});
await collection.addAdmin(donor, {Ethereum: proxyContract});
}
- if (collection instanceof UniqueNFTCollection || collection instanceof UniqueRFTCollection)
+ if(collection instanceof UniqueNFTCollection || collection instanceof UniqueRFTCollection)
await collection.setTokenPropertyPermissions(donor, permissions);
return collection;
tests/src/benchmarks/utils/types.tsdiffbeforeafterboth--- a/tests/src/benchmarks/utils/types.ts
+++ b/tests/src/benchmarks/utils/types.ts
@@ -45,13 +45,13 @@
Object.keys(model).forEach(key => {
res[key] = {};
- if (model[key].fee && model[key].gas) {
+ if(model[key].fee && model[key].gas) {
res[key].ethFee = model[key].fee;
res[key].ethGas = model[key].gas;
}
- if (model[key].substrate)
+ if(model[key].substrate)
res[key].substrate = model[key].substrate;
- if (model[key].zeppelin) {
+ if(model[key].zeppelin) {
res[key].zeppelinFee = model[key].zeppelin?.fee;
res[key].zeppelinGas = model[key].zeppelin?.gas;
}
tests/src/calibrate.tsdiffbeforeafterboth--- a/tests/src/calibrate.ts
+++ b/tests/src/calibrate.ts
@@ -4,8 +4,8 @@
class Fract {
static ZERO = new Fract(0n);
constructor(public readonly a: bigint, public readonly b: bigint = 1n) {
- if (b === 0n) throw new Error('division by zero');
- if (b < 0n) throw new Error('missing normalization');
+ if(b === 0n) throw new Error('division by zero');
+ if(b < 0n) throw new Error('missing normalization');
}
mul(other: Fract) {
@@ -17,7 +17,7 @@
}
plus(other: Fract) {
- if (this.b === other.b) {
+ if(this.b === other.b) {
return new Fract(this.a + other.a, this.b);
}
return new Fract(this.a * other.b + other.a * this.b, this.b * other.b).optimize();
@@ -31,7 +31,7 @@
return new Fract(-this.a, this.b);
}
inv() {
- if (this.a < 0) {
+ if(this.a < 0) {
return new Fract(-this.b, -this.a);
} else {
return new Fract(this.b, this.a);
@@ -40,9 +40,9 @@
optimize() {
function gcd(x: bigint, y: bigint) {
- if (x < 0n)
+ if(x < 0n)
x = -x;
- if (y < 0n)
+ if(y < 0n)
y = -y;
while(y) {
const t = y;
@@ -75,17 +75,17 @@
}
sqrt() {
- if (this.a < 0n) {
+ if(this.a < 0n) {
throw new Error('square root of negative numbers is not supported');
}
- if (this.lt(new Fract(2n))) {
+ if(this.lt(new Fract(2n))) {
return this;
}
function newtonIteration(n: Fract, x0: Fract): Fract {
const x1 = rpn(n, x0, '/', x0, '+', new Fract(2n), '/');
- if (x0.eq(x1) || x0.eq(x1.minus(new Fract(1n)))) {
+ if(x0.eq(x1) || x0.eq(x1.minus(new Fract(1n)))) {
return x0;
}
return newtonIteration(n, x1);
@@ -98,46 +98,46 @@
type Op = Fract | '+' | '-' | '*' | '/' | 'dup' | Op[];
function rpn(...ops: (Op)[]) {
const stack: Fract[] = [];
- for (const op of ops) {
- if (op instanceof Fract) {
+ for(const op of ops) {
+ if(op instanceof Fract) {
stack.push(op);
- } else if (op === '+') {
- if (stack.length < 2)
+ } else if(op === '+') {
+ if(stack.length < 2)
throw new Error('stack underflow');
const b = stack.pop()!;
const a = stack.pop()!;
stack.push(a.plus(b));
- } else if (op === '*') {
- if (stack.length < 2)
+ } else if(op === '*') {
+ if(stack.length < 2)
throw new Error('stack underflow');
const b = stack.pop()!;
const a = stack.pop()!;
stack.push(a.mul(b));
- } else if (op === '-') {
- if (stack.length < 2)
+ } else if(op === '-') {
+ if(stack.length < 2)
throw new Error('stack underflow');
const b = stack.pop()!;
const a = stack.pop()!;
stack.push(a.minus(b));
- } else if (op === '/') {
- if (stack.length < 2)
+ } else if(op === '/') {
+ if(stack.length < 2)
throw new Error('stack underflow');
const b = stack.pop()!;
const a = stack.pop()!;
stack.push(a.div(b));
- } else if (op === 'dup') {
- if (stack.length < 1)
+ } else if(op === 'dup') {
+ if(stack.length < 1)
throw new Error('stack underflow');
const a = stack.pop()!;
stack.push(a);
stack.push(a);
- } else if (Array.isArray(op)) {
+ } else if(Array.isArray(op)) {
stack.push(rpn(...op));
} else {
throw new Error(`unknown operand: ${op}`);
}
}
- if (stack.length != 1)
+ if(stack.length != 1)
throw new Error('one element should be left on stack');
return stack[0]!;
}
@@ -148,7 +148,7 @@
let sumy = Fract.ZERO;
let sumx2 = Fract.ZERO;
const n = points.length;
- for (let i = 0; i < n; i++) {
+ for(let i = 0; i < n; i++) {
const p = points[i];
sumxy = rpn(p.x, p.y, '*', sumxy, '+');
sumx = sumx.plus(p.x);
@@ -200,7 +200,7 @@
const api = helper.getApi();
const base = (await api.query.configuration.weightToFeeCoefficientOverride() as any).toBigInt();
- for (let i = -5; i < 5; i++) {
+ for(let i = -5; i < 5; i++) {
await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(base + base / 1000n * BigInt(i))));
const coefficient = new Fract((await api.query.configuration.weightToFeeCoefficientOverride() as any).toBigInt());
@@ -256,7 +256,7 @@
const api = helper.getApi();
// const defaultCoeff = (api.consts.configuration.defaultMinGasPrice as any).toBigInt();
const base = (await api.query.configuration.minGasPriceOverride() as any).toBigInt();
- for (let i = -8; i < 8; i++) {
+ for(let i = -8; i < 8; i++) {
const gasPrice = base + base / 100000n * BigInt(i);
const gasPriceStr = '0x' + gasPrice.toString(16);
await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(gasPrice)));
@@ -303,14 +303,14 @@
const iterations = 3;
console.log('[Calibrate WeightToFee]');
- for (let i = 0; i < iterations; i++) {
+ for(let i = 0; i < iterations; i++) {
await calibrateWeightToFee(helper, privateKey);
}
console.log();
console.log('[Calibrate MinGasPrice]');
- for (let i = 0; i < iterations; i++) {
+ for(let i = 0; i < iterations; i++) {
await calibrateMinGasPrice(helper, privateKey);
}
});
tests/src/calibrateApply.tsdiffbeforeafterboth--- a/tests/src/calibrateApply.ts
+++ b/tests/src/calibrateApply.ts
@@ -22,7 +22,7 @@
weight2feeFound = true;
return p+formatNumber(weightToFeeCoefficientOverride)+s;
});
- if (!weight2feeFound) {
+ if(!weight2feeFound) {
throw new Error('failed to find weight2fee marker in source code');
}
@@ -31,7 +31,7 @@
minGasPriceFound = true;
return p+formatNumber(minGasPriceOverride)+s;
});
- if (!minGasPriceFound) {
+ if(!minGasPriceFound) {
throw new Error('failed to find mingasprice marker in source code');
}
tests/src/collator-selection/collatorSelection.seqtest.tsdiffbeforeafterboth--- a/tests/src/collator-selection/collatorSelection.seqtest.ts
+++ b/tests/src/collator-selection/collatorSelection.seqtest.ts
@@ -23,13 +23,13 @@
const alice = await privateKey('//Alice');
const bob = await privateKey('//Bob');
const invulnerables = await helper.collatorSelection.getInvulnerables();
- if (!invulnerables.includes(alice.address) || !invulnerables.includes(bob.address) || invulnerables.length != 2) {
+ if(!invulnerables.includes(alice.address) || !invulnerables.includes(bob.address) || invulnerables.length != 2) {
console.warn('Alice and Bob are not the invulnerables! Reinstating them back. '
+ 'Current invulnerables\' size: ' + invulnerables.length);
let nonce = await helper.chain.getNonce(alice.address);
// In case there are too many invulnerables already, remove some of them, leaving space for Alice and Bob.
- if (invulnerables.length + 2 >= helper.collatorSelection.maxCollators()) {
+ if(invulnerables.length + 2 >= helper.collatorSelection.maxCollators()) {
await Promise.all([
helper.getSudo().executeExtrinsic(superuser, 'api.tx.collatorSelection.removeInvulnerable', [invulnerables.pop()!], true, {nonce: nonce++}),
helper.getSudo().executeExtrinsic(superuser, 'api.tx.collatorSelection.removeInvulnerable', [invulnerables.pop()!], true, {nonce: nonce++}),
@@ -44,7 +44,7 @@
nonce = await helper.chain.getNonce(alice.address);
await Promise.all(invulnerables.map((invulnerable: any) => {
- if (invulnerable == alice.address || invulnerable == bob.address) return new Promise<void>(res => res());
+ if(invulnerable == alice.address || invulnerable == bob.address) return new Promise<void>(res => res());
return helper.getSudo().executeExtrinsic(superuser, 'api.tx.collatorSelection.removeInvulnerable', [invulnerable], true, {nonce: nonce++});
}));
}
@@ -58,7 +58,7 @@
let licenseBond = 0n;
before(async function() {
- if (!process.env.RUN_COLLATOR_TESTS) this.skip();
+ if(!process.env.RUN_COLLATOR_TESTS) this.skip();
await usingPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.CollatorSelection]);
@@ -82,7 +82,7 @@
await usingPlaygrounds(async (helper, privateKey) => {
// todo:collator see again if blocks start to be finalized in dev mode
// Skip the collator block production in dev mode, since the blocks are sealed automatically.
- if (await helper.arrange.isDevNode()) this.skip();
+ if(await helper.arrange.isDevNode()) this.skip();
alice = await privateKey('//Alice');
bob = await privateKey('//Bob');
@@ -95,7 +95,7 @@
.status.toLowerCase()).to.be.equal('success');
const invulnerables = await helper.collatorSelection.getInvulnerables();
- if (!invulnerables.includes(alice.address) || !invulnerables.includes(bob.address) || invulnerables.length != 2) {
+ if(!invulnerables.includes(alice.address) || !invulnerables.includes(bob.address) || invulnerables.length != 2) {
console.warn('Alice and Bob are not the invulnerables! Reinstating them back. '
+ 'Current invulnerables\' size: ' + invulnerables.length);
@@ -107,7 +107,7 @@
nonce = await helper.chain.getNonce(superuser.address);
await Promise.all(invulnerables.map((invulnerable: any) => {
- if (invulnerable == alice.address || invulnerable == bob.address) return new Promise((res) => res);
+ if(invulnerable == alice.address || invulnerable == bob.address) return new Promise((res) => res);
return helper.getSudo().executeExtrinsic(superuser, 'api.tx.collatorSelection.removeInvulnerable', [invulnerable], true, {nonce: nonce++});
}));
}
@@ -144,7 +144,7 @@
after(async () => {
await usingPlaygrounds(async (helper) => {
- if (await helper.arrange.isDevNode()) return;
+ if(await helper.arrange.isDevNode()) return;
let nonce = await helper.chain.getNonce(superuser.address);
await Promise.all([
@@ -452,10 +452,10 @@
});
after(async function() {
- if (!process.env.RUN_COLLATOR_TESTS) return;
+ if(!process.env.RUN_COLLATOR_TESTS) return;
await usingPlaygrounds(async (helper) => {
- if (helper.fetchMissingPalletNames([Pallets.CollatorSelection]).length != 0) return;
+ if(helper.fetchMissingPalletNames([Pallets.CollatorSelection]).length != 0) return;
await helper.getSudo().collatorSelection.setLicenseBond(superuser, previousLicenseBond);
tests/src/collator-selection/identity.seqtest.tsdiffbeforeafterboth--- a/tests/src/collator-selection/identity.seqtest.ts
+++ b/tests/src/collator-selection/identity.seqtest.ts
@@ -41,7 +41,7 @@
let superuser: IKeyringPair;
before(async function() {
- if (!process.env.RUN_COLLATOR_TESTS) this.skip();
+ if(!process.env.RUN_COLLATOR_TESTS) this.skip();
await usingPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.Identity]);
@@ -126,7 +126,7 @@
]);
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo] as any);
- for (let i = 0; i < supers.length; i++) {
+ for(let i = 0; i < supers.length; i++) {
// check deposit
expect(((await helper.getApi().query.identity.subsOf(supers[i].address)).toJSON() as any)[0]).to.be.equal(1000001 + i);
@@ -134,7 +134,7 @@
// check sub-identities as account ids
expect(subsAccounts).to.include.members(subs[i].map(x => x.address));
- for (let j = 0; j < subsAccounts.length; j++) {
+ for(let j = 0; j < subsAccounts.length; j++) {
// check sub-identities' names
expect((await getSubIdentityName(helper, subsAccounts[j]))[1]).to.be.deep.equal({Raw: `accounter #${j}`});
}
@@ -179,7 +179,7 @@
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo2] as any);
// make sure everything else is the same
- for (let i = 0; i < supers.length - 1; i++) {
+ for(let i = 0; i < supers.length - 1; i++) {
// check deposit
expect(((await helper.getApi().query.identity.subsOf(supers[i].address)).toJSON() as any)[0]).to.be.equal(1000001 + i);
@@ -187,7 +187,7 @@
// check sub-identities as account ids
expect(subsAccounts).to.include.members(subs[i].map(x => x.address));
- for (let j = 0; j < subsAccounts; j++) {
+ for(let j = 0; j < subsAccounts; j++) {
// check sub-identities' names
expect((await getSubIdentityName(helper, subsAccounts[j]))[1]).to.be.deep.equal({Raw: `accounter #${j}`});
}
@@ -200,7 +200,7 @@
// check sub-identities as account ids
expect(subsAccounts).to.include.members(subs[2].map(x => x.address));
- for (let j = 0; j < subsAccounts.length; j++) {
+ for(let j = 0; j < subsAccounts.length; j++) {
// check sub-identities' names
expect((await getSubIdentityName(helper, subsAccounts[j]))[1]).to.be.deep.equal({Raw: `discounter #${j}`});
}
@@ -233,7 +233,7 @@
// check deposit
expect((await helper.getApi().query.identity.subsOf(sup.address)).toHuman()).to.be.deep.equal(['0', []]);
- for (let j = 0; j < crowd.length; j++) {
+ for(let j = 0; j < crowd.length; j++) {
// check sub-identities' names
expect((await getSubIdentityName(helper, crowd[j].address))).to.be.null;
}
@@ -264,7 +264,7 @@
// check that sub-identities are deleted
expect((await helper.getApi().query.identity.subsOf(sup.address)).toHuman()).to.be.deep.equal(['0', []]);
- for (let j = 0; j < crowd.length; j++) {
+ for(let j = 0; j < crowd.length; j++) {
// check sub-identities' names
expect((await getSubIdentityName(helper, crowd[j].address))).to.be.null;
}
@@ -272,10 +272,10 @@
});
after(async function() {
- if (!process.env.RUN_COLLATOR_TESTS) return;
+ if(!process.env.RUN_COLLATOR_TESTS) return;
await usingPlaygrounds(async helper => {
- if (helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) return;
+ if(helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) return;
const identitiesToRemove: string[] = await getIdentityAccounts(helper);
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [identitiesToRemove]);
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -21,9 +21,9 @@
async function mintCollectionHelper(helper: UniqueHelper, signer: IKeyringPair, options: ICollectionCreationOptions, type?: 'nft' | 'fungible' | 'refungible') {
let collection;
- if (type === 'nft') {
+ if(type === 'nft') {
collection = await helper.nft.mintCollection(signer, options);
- } else if (type === 'fungible') {
+ } else if(type === 'fungible') {
collection = await helper.ft.mintCollection(signer, options, 0);
} else {
collection = await helper.rft.mintCollection(signer, options);
@@ -33,11 +33,11 @@
expect(data?.name).to.be.equal(options.name);
expect(data?.description).to.be.equal(options.description);
expect(data?.raw.tokenPrefix).to.be.equal(options.tokenPrefix);
- if (options.properties) {
+ if(options.properties) {
expect(data?.raw.properties).to.be.deep.equal(options.properties);
}
- if (options.tokenPropertyPermissions) {
+ if(options.tokenPropertyPermissions) {
expect(data?.raw.tokenPropertyPermissions).to.be.deep.equal(options.tokenPropertyPermissions);
}
@@ -136,7 +136,7 @@
itSub('(!negative test!) create collection with incorrect property limit (64 elements)', async ({helper}) => {
const props: IProperty[] = [];
- for (let i = 0; i < 65; i++) {
+ for(let i = 0; i < 65; i++) {
props.push({key: `key${i}`, value: `value${i}`});
}
const mintCollectionTx = () => helper.nft.mintCollection(alice, {name: 'name', description: 'descr', tokenPrefix: 'COL', properties: props});
@@ -146,7 +146,7 @@
itSub('(!negative test!) create collection with incorrect property limit (40 kb)', async ({helper}) => {
const props: IProperty[] = [];
- for (let i = 0; i < 32; i++) {
+ for(let i = 0; i < 32; i++) {
props.push({key: `key${i}`.repeat(80), value: `value${i}`.repeat(80)});
}
tests/src/createItem.test.tsdiffbeforeafterboth--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -23,9 +23,9 @@
let token;
const itemCountBefore = await helper.collection.getLastTokenId(collection.collectionId);
const itemBalanceBefore = (await helper.callRpc('api.rpc.unique.balance', [collection.collectionId, owner, 0])).toBigInt();
- if (type === 'nft') {
+ if(type === 'nft') {
token = await collection.mintToken(signer, owner, properties);
- } else if (type === 'fungible') {
+ } else if(type === 'fungible') {
await collection.mint(signer, 10n, owner);
} else {
token = await collection.mintToken(signer, 100n, owner, properties);
@@ -34,7 +34,7 @@
const itemCountAfter = await helper.collection.getLastTokenId(collection.collectionId);
const itemBalanceAfter = (await helper.callRpc('api.rpc.unique.balance', [collection.collectionId, owner, 0])).toBigInt();
- if (type === 'fungible') {
+ if(type === 'fungible') {
expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
} else {
expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
@@ -225,7 +225,7 @@
itSub('Adding more than 64 prps', async ({helper}) => {
const props: IProperty[] = [];
- for (let i = 0; i < 65; i++) {
+ for(let i = 0; i < 65; i++) {
props.push({key: `key${i}`, value: `value${i}`});
}
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -42,7 +42,7 @@
{properties: [{key: 'data', value: '3'}]},
];
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
expect(tokenData?.normalizedOwner.Substrate).to.be.deep.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
@@ -77,7 +77,7 @@
];
const tokens = await helper.rft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(BigInt(i + 1));
}
});
@@ -110,7 +110,7 @@
{properties: [{key: 'data', value: '3'}]},
];
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
expect(tokenData?.normalizedOwner.Substrate).to.be.deep.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
@@ -132,7 +132,7 @@
{properties: [{key: 'data', value: '3'}]},
];
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
expect(tokenData?.normalizedOwner.Substrate).to.be.deep.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
@@ -154,7 +154,7 @@
{properties: [{key: 'data', value: '3'}]},
];
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
expect(tokenData?.normalizedOwner.Substrate).to.be.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
@@ -358,7 +358,7 @@
});
const prps = [];
- for (let i = 0; i < 65; i++) {
+ for(let i = 0; i < 65; i++) {
prps.push({key: `key${i}`, value: `value${i}`});
}
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -49,7 +49,7 @@
];
const tokens = await collection.mintMultipleTokens(alice, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
expect(await token.getOwner()).to.be.deep.equal(args[i].owner);
}
});
@@ -87,7 +87,7 @@
];
const tokens = await collection.mintMultipleTokens(alice, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
expect(await token.getOwner()).to.be.deep.equal(args[i].owner);
expect(await token.getData()).to.not.be.empty;
}
@@ -126,7 +126,7 @@
];
const tokens = await collection.mintMultipleTokens(alice, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
expect(await token.getOwner()).to.be.deep.equal(args[i].owner);
expect(await token.getData()).to.not.be.empty;
}
@@ -165,7 +165,7 @@
];
const tokens = await collection.mintMultipleTokens(alice, args);
- for (const [i, token] of tokens.entries()) {
+ for(const [i, token] of tokens.entries()) {
expect(await token.getOwner()).to.be.deep.equal(args[i].owner);
expect(await token.getData()).to.not.be.empty;
}
@@ -383,7 +383,7 @@
const properties: IProperty[] = [];
- for (let i = 0; i < 65; i++) {
+ for(let i = 0; i < 65; i++) {
properties.push({key: `k${i}`, value: `v${i}`});
}
tests/src/creditFeesToTreasury.seqtest.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.seqtest.ts
+++ b/tests/src/creditFeesToTreasury.seqtest.ts
@@ -32,7 +32,7 @@
const blockInterval = api.consts.inflation.inflationBlockInterval.toNumber();
const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {
const currentBlock = head.number.toNumber();
- if (currentBlock % blockInterval < blockInterval - 10) {
+ if(currentBlock % blockInterval < blockInterval - 10) {
unsubscribe();
resolve();
} else {
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -130,7 +130,7 @@
await collectionEvm.methods.transfer(owner, 1).send({from: userEth});
await collectionEvm.methods.transferCross(userCrossSub, 2).send({from: userEth});
- if (testCase.mode === 'ft') {
+ if(testCase.mode === 'ft') {
expect(await helper.ft.getBalance(collectionId, {Ethereum: owner})).to.eq(1n);
expect(await helper.ft.getBalance(collectionId, {Substrate: userSub.address})).to.eq(2n);
} else {
@@ -188,14 +188,14 @@
// 1.1 plain ethereum or cross address:
await expect(collectionEvm.methods[addToAllowList](testCase.cross ? userCrossEth : userEth).call({from: notOwner})).to.be.rejectedWith('NoPermission');
// 1.2 cross-substrate address:
- if (testCase.cross)
+ if(testCase.cross)
await expect(collectionEvm.methods[addToAllowList](userCrossSub).call({from: notOwner})).to.be.rejectedWith('NoPermission');
// 2. owner can add to allow list:
// 2.1 plain ethereum or cross address:
await collectionEvm.methods[addToAllowList](testCase.cross ? userCrossEth : userEth).send({from: owner});
// 2.2 cross-substrate address:
- if (testCase.cross) {
+ if(testCase.cross) {
await collectionEvm.methods[addToAllowList](userCrossSub).send({from: owner});
expect(await helper.collection.allowed(collectionId, {Substrate: userSub.address})).to.be.true;
}
@@ -205,7 +205,7 @@
// 3.1 plain ethereum or cross address:
await expect(collectionEvm.methods[removeFromAllowList](testCase.cross ? userCrossEth : userEth).call({from: notOwner})).to.be.rejectedWith('NoPermission');
// 3.2 cross-substrate address:
- if (testCase.cross)
+ if(testCase.cross)
await expect(collectionEvm.methods[removeFromAllowList](userCrossSub).call({from: notOwner})).to.be.rejectedWith('NoPermission');
}));
});
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -447,7 +447,7 @@
let testContract: CompiledContract;
async function compileTestContract(helper: EthUniqueHelper) {
- if (!testContract) {
+ if(!testContract) {
testContract = await helper.ethContract.compile(
'TestContract',
`
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -30,7 +30,7 @@
});
function clearEvents(ethEvents: NormalizedEvent[] | null, subEvents: IEvent[]) {
- if (ethEvents !== null) {
+ if(ethEvents !== null) {
ethEvents.splice(0);
}
subEvents.splice(0);
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -58,8 +58,8 @@
// 3. Get balance depending on the test case:
let balance;
- if (testCase === 'ethereum') balance = await collection.getBalance({Ethereum: receiverEth});
- else if (testCase === 'substrate') balance = await collection.getBalance({Substrate: receiverSub.address});
+ if(testCase === 'ethereum') balance = await collection.getBalance({Ethereum: receiverEth});
+ else if(testCase === 'substrate') balance = await collection.getBalance({Substrate: receiverSub.address});
// 3.1 Check balance:
expect(balance).to.eq(100n);
});
@@ -79,7 +79,7 @@
[receivers[i], (i + 1) * 10]
))).send();
const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.value - b.returnValues.value);
- for (let i = 0; i < bulkSize; i++) {
+ for(let i = 0; i < bulkSize; i++) {
const event = events[i];
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
@@ -535,7 +535,7 @@
});
await collection.approveTokens(alice, {Ethereum: receiver}, 100n);
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Approval');
@@ -561,7 +561,7 @@
});
await collection.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n);
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
let event = events[0];
expect(event.event).to.be.equal('Transfer');
@@ -592,7 +592,7 @@
});
await collection.transfer(alice, {Ethereum:receiver}, 51n);
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Transfer');
tests/src/eth/migration.seqtest.tsdiffbeforeafterboth--- a/tests/src/eth/migration.seqtest.ts
+++ b/tests/src/eth/migration.seqtest.ts
@@ -121,7 +121,7 @@
], ADDRESS, {from: caller, gas: helper.eth.DEFAULT_GAS});
expect(await contract.methods.counterValue().call()).to.be.equal('10');
- for (let i = 1; i <= 4; i++) {
+ for(let i = 1; i <= 4; i++) {
expect(await contract.methods.get(i).call()).to.be.equal(i.toString());
}
});
@@ -196,7 +196,7 @@
await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txInsertEthLogs]);
}
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.address).to.be.equal(collectionAddress);
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -190,7 +190,7 @@
describe('Fungible', () => {
async function createFungibleCollection(helper: EthUniqueHelper, owner: string, mode: 'ft' | 'native ft') {
- if (mode === 'ft') {
+ if(mode === 'ft') {
const {collectionAddress} = await helper.eth.createFungibleCollection(owner, '', 18, '', '');
const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
await contract.methods.mint(owner, 100n).send({from: owner});
@@ -259,7 +259,7 @@
const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
- if (testCase.mode === 'ft') {
+ if(testCase.mode === 'ft') {
await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
} else {
await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.not.rejected;
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -39,7 +39,7 @@
const tokenId = result.events.Transfer.returnValues.tokenId;
expect(tokenId).to.be.equal('1');
- if (propertyKey && propertyValue) {
+ if(propertyKey && propertyValue) {
// Set URL or suffix
await contract.methods.setProperties(tokenId, [{key: propertyKey, value: Buffer.from(propertyValue)}]).send();
}
@@ -185,7 +185,7 @@
).send({from: caller});
const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.tokenId - b.returnValues.tokenId);
- for (let i = 0; i < bulkSize; i++) {
+ for(let i = 0; i < bulkSize; i++) {
const event = events[i];
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
@@ -669,7 +669,7 @@
expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');
- for (let i = 1; i < 10; i++) {
+ for(let i = 1; i < 10; i++) {
await collection.mintToken(minter, {Ethereum: owner.eth});
expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq(i.toString());
}
@@ -682,7 +682,7 @@
const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner.eth);
const {tokenId} = await collection.mintToken(minter, {Ethereum: owner.eth});
- for (let i = 1n; i < 10n; i++) {
+ for(let i = 1n; i < 10n; i++) {
const ownerCross = await collectionEvm.methods.ownerOfCross(tokenId).call({from: owner.eth});
expect(ownerCross.eth).to.be.eq(owner.eth);
expect(ownerCross.sub).to.be.eq(owner.sub);
@@ -805,7 +805,7 @@
});
const {tokenId} = await collection.mintToken(alice);
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Transfer');
@@ -828,7 +828,7 @@
});
await token.burn(alice);
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Transfer');
@@ -853,7 +853,7 @@
});
await token.approve(alice, {Ethereum: receiver});
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Approval');
@@ -881,7 +881,7 @@
await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.address).to.be.equal(collectionAddress);
@@ -906,7 +906,7 @@
await token.transfer(alice, {Ethereum: receiver});
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.address).to.be.equal(collectionAddress);
tests/src/eth/reFungible.test.tsdiffbeforeafterboth1// 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 {Pallets, requirePalletsOrSkip} from '../util';18import {expect, itEth, usingEthPlaygrounds} from './util';19import {IKeyringPair} from '@polkadot/types/types';20import {ITokenPropertyPermission} from '../util/playgrounds/types';2122describe('Refungible: Plain calls', () => {23 let donor: IKeyringPair;24 let minter: IKeyringPair;25 let bob: IKeyringPair;26 let charlie: IKeyringPair;2728 before(async function() {29 await usingEthPlaygrounds(async (helper, privateKey) => {30 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);3132 donor = await privateKey({url: import.meta.url});33 [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);34 });35 });3637 [38 'substrate' as const,39 'ethereum' as const,40 ].map(testCase => {41 itEth(`Can perform mintCross() for ${testCase} address`, async ({helper}) => {42 const collectionAdmin = await helper.eth.createAccountWithBalance(donor);4344 const receiverEth = helper.eth.createAccount();45 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);46 const receiverSub = bob;47 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);4849 const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));50 const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {51 tokenOwner: false,52 collectionAdmin: true,53 mutable: false}}));545556 const collection = await helper.rft.mintCollection(minter, {57 tokenPrefix: 'ethp',58 tokenPropertyPermissions: permissions,59 });60 await collection.addAdmin(minter, {Ethereum: collectionAdmin});6162 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);63 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', collectionAdmin, true);64 let expectedTokenId = await contract.methods.nextTokenId().call();65 let result = await contract.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, []).send();66 let tokenId = result.events.Transfer.returnValues.tokenId;67 expect(tokenId).to.be.equal(expectedTokenId);6869 let event = result.events.Transfer;70 expect(event.address).to.be.equal(collectionAddress);71 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');72 expect(event.returnValues.to).to.be.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(bob.address));73 expect(await contract.methods.properties(tokenId, []).call()).to.be.like([]);7475 expectedTokenId = await contract.methods.nextTokenId().call();76 result = await contract.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, properties).send();77 event = result.events.Transfer;78 expect(event.address).to.be.equal(collectionAddress);79 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');80 expect(event.returnValues.to).to.be.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(bob.address));81 expect(await contract.methods.properties(tokenId, []).call()).to.be.like([]);8283 tokenId = result.events.Transfer.returnValues.tokenId;8485 expect(tokenId).to.be.equal(expectedTokenId);8687 expect(await contract.methods.properties(tokenId, []).call()).to.be.like(properties88 .map(p => helper.ethProperty.property(p.key, p.value.toString())));8990 expect(await helper.nft.getTokenOwner(collection.collectionId, tokenId))91 .to.deep.eq(testCase === 'ethereum' ? {Ethereum: receiverEth.toLowerCase()} : {Substrate: receiverSub.address});92 });93 });9495 itEth.skip('Can perform mintBulk()', async ({helper}) => {96 const owner = await helper.eth.createAccountWithBalance(donor);97 const receiver = helper.eth.createAccount();98 const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');99 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);100101 {102 const nextTokenId = await contract.methods.nextTokenId().call();103 expect(nextTokenId).to.be.equal('1');104 const result = await contract.methods.mintBulkWithTokenURI(105 receiver,106 [107 [nextTokenId, 'Test URI 0'],108 [+nextTokenId + 1, 'Test URI 1'],109 [+nextTokenId + 2, 'Test URI 2'],110 ],111 ).send();112113 const events = result.events.Transfer;114 for (let i = 0; i < 2; i++) {115 const event = events[i];116 expect(event.address).to.equal(collectionAddress);117 expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');118 expect(event.returnValues.to).to.equal(receiver);119 expect(event.returnValues.tokenId).to.equal(String(+nextTokenId + i));120 }121122 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');123 expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');124 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');125 }126 });127128 itEth('Can perform setApprovalForAll()', async ({helper}) => {129 const owner = await helper.eth.createAccountWithBalance(donor);130 const operator = helper.eth.createAccount();131132 const collection = await helper.rft.mintCollection(minter, {});133134 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);135 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);136137 const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();138 expect(approvedBefore).to.be.equal(false);139140 {141 const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});142143 expect(result.events.ApprovalForAll).to.be.like({144 address: collectionAddress,145 event: 'ApprovalForAll',146 returnValues: {147 owner,148 operator,149 approved: true,150 },151 });152153 const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();154 expect(approvedAfter).to.be.equal(true);155 }156157 {158 const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});159160 expect(result.events.ApprovalForAll).to.be.like({161 address: collectionAddress,162 event: 'ApprovalForAll',163 returnValues: {164 owner,165 operator,166 approved: false,167 },168 });169170 const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();171 expect(approvedAfter).to.be.equal(false);172 }173 });174175 itEth('Can perform burn with ApprovalForAll', async ({helper}) => {176 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});177178 const owner = await helper.eth.createAccountWithBalance(donor);179 const operator = await helper.eth.createAccountWithBalance(donor);180181 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});182183 const address = helper.ethAddress.fromCollectionId(collection.collectionId);184 const contract = await helper.ethNativeContract.collection(address, 'rft');185186 {187 await contract.methods.setApprovalForAll(operator, true).send({from: owner});188 const ownerCross = helper.ethCrossAccount.fromAddress(owner);189 const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});190 const events = result.events.Transfer;191192 expect(events).to.be.like({193 address,194 event: 'Transfer',195 returnValues: {196 from: owner,197 to: '0x0000000000000000000000000000000000000000',198 tokenId: token.tokenId.toString(),199 },200 });201 }202 });203204 itEth('Can perform burn with approve and approvalForAll', async ({helper}) => {205 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});206207 const owner = await helper.eth.createAccountWithBalance(donor);208 const operator = await helper.eth.createAccountWithBalance(donor);209210 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});211212 const address = helper.ethAddress.fromCollectionId(collection.collectionId);213 const contract = await helper.ethNativeContract.collection(address, 'rft');214215 const rftToken = await helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner, true);216217 {218 await rftToken.methods.approve(operator, 15n).send({from: owner});219 await contract.methods.setApprovalForAll(operator, true).send({from: owner});220 await rftToken.methods.burnFrom(owner, 10n).send({from: operator});221 }222 {223 const allowance = await rftToken.methods.allowance(owner, operator).call();224 expect(+allowance).to.be.equal(5);225 }226 {227 const ownerCross = helper.ethCrossAccount.fromAddress(owner);228 const operatorCross = helper.ethCrossAccount.fromAddress(operator);229 const allowance = await rftToken.methods.allowanceCross(ownerCross, operatorCross).call();230 expect(+allowance).to.equal(5);231 }232 });233234 itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {235 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});236237 const owner = await helper.eth.createAccountWithBalance(donor);238 const operator = await helper.eth.createAccountWithBalance(donor);239 const receiver = charlie;240241 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});242243 const address = helper.ethAddress.fromCollectionId(collection.collectionId);244 const contract = await helper.ethNativeContract.collection(address, 'rft');245246 {247 await contract.methods.setApprovalForAll(operator, true).send({from: owner});248 const ownerCross = helper.ethCrossAccount.fromAddress(owner);249 const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);250 const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});251 const event = result.events.Transfer;252 expect(event).to.be.like({253 address: helper.ethAddress.fromCollectionId(collection.collectionId),254 event: 'Transfer',255 returnValues: {256 from: owner,257 to: helper.address.substrateToEth(receiver.address),258 tokenId: token.tokenId.toString(),259 },260 });261 }262263 expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);264 });265266 itEth('Can perform burn()', async ({helper}) => {267 const caller = await helper.eth.createAccountWithBalance(donor);268 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');269 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);270271 const result = await contract.methods.mint(caller).send();272 const tokenId = result.events.Transfer.returnValues.tokenId;273 {274 const result = await contract.methods.burn(tokenId).send();275 const event = result.events.Transfer;276 expect(event.address).to.equal(collectionAddress);277 expect(event.returnValues.from).to.equal(caller);278 expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');279 expect(event.returnValues.tokenId).to.equal(tokenId.toString());280 }281 });282283 itEth('Can perform transferFrom()', async ({helper}) => {284 const caller = await helper.eth.createAccountWithBalance(donor);285 const receiver = helper.eth.createAccount();286 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'TransferFromy', '6', '6');287 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);288289 const result = await contract.methods.mint(caller).send();290 const tokenId = result.events.Transfer.returnValues.tokenId;291292 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);293294 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, caller);295 await tokenContract.methods.repartition(15).send();296297 {298 const tokenEvents: any = [];299 tokenContract.events.allEvents((_: any, event: any) => {300 tokenEvents.push(event);301 });302 const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();303 if (tokenEvents.length == 0) await helper.wait.newBlocks(1);304305 let event = result.events.Transfer;306 expect(event.address).to.equal(collectionAddress);307 expect(event.returnValues.from).to.equal(caller);308 expect(event.returnValues.to).to.equal(receiver);309 expect(event.returnValues.tokenId).to.equal(tokenId.toString());310311 event = tokenEvents[0];312 expect(event.address).to.equal(tokenAddress);313 expect(event.returnValues.from).to.equal(caller);314 expect(event.returnValues.to).to.equal(receiver);315 expect(event.returnValues.value).to.equal('15');316 }317318 {319 const balance = await contract.methods.balanceOf(receiver).call();320 expect(+balance).to.equal(1);321 }322323 {324 const balance = await contract.methods.balanceOf(caller).call();325 expect(+balance).to.equal(0);326 }327 });328329 // Soft-deprecated330 itEth('Can perform burnFrom()', async ({helper}) => {331 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});332333 const owner = await helper.eth.createAccountWithBalance(donor);334 const spender = await helper.eth.createAccountWithBalance(donor);335336 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});337338 const address = helper.ethAddress.fromCollectionId(collection.collectionId);339 const contract = await helper.ethNativeContract.collection(address, 'rft', spender, true);340341 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);342 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, owner);343 await tokenContract.methods.repartition(15).send();344 await tokenContract.methods.approve(spender, 15).send();345346 {347 const result = await contract.methods.burnFrom(owner, token.tokenId).send();348 const event = result.events.Transfer;349 expect(event).to.be.like({350 address: helper.ethAddress.fromCollectionId(collection.collectionId),351 event: 'Transfer',352 returnValues: {353 from: owner,354 to: '0x0000000000000000000000000000000000000000',355 tokenId: token.tokenId.toString(),356 },357 });358 }359360 expect(await collection.getTokenBalance(token.tokenId, {Ethereum: owner})).to.be.eq(0n);361 });362363 itEth('Can perform burnFromCross()', async ({helper}) => {364 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});365366 const owner = bob;367 const spender = await helper.eth.createAccountWithBalance(donor);368369 const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});370371 const address = helper.ethAddress.fromCollectionId(collection.collectionId);372 const contract = await helper.ethNativeContract.collection(address, 'rft');373374 await token.repartition(owner, 15n);375 await token.approve(owner, {Ethereum: spender}, 15n);376377 {378 const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);379 const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender});380 const event = result.events.Transfer;381 expect(event).to.be.like({382 address: helper.ethAddress.fromCollectionId(collection.collectionId),383 event: 'Transfer',384 returnValues: {385 from: helper.address.substrateToEth(owner.address),386 to: '0x0000000000000000000000000000000000000000',387 tokenId: token.tokenId.toString(),388 },389 });390 }391392 expect(await collection.getTokenBalance(token.tokenId, {Substrate: owner.address})).to.be.eq(0n);393 });394395 itEth('Can perform transferFromCross()', async ({helper}) => {396 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});397398 const owner = bob;399 const spender = await helper.eth.createAccountWithBalance(donor);400 const receiver = charlie;401402 const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});403404 const address = helper.ethAddress.fromCollectionId(collection.collectionId);405 const contract = await helper.ethNativeContract.collection(address, 'rft');406407 await token.repartition(owner, 15n);408 await token.approve(owner, {Ethereum: spender}, 15n);409410 {411 const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);412 const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);413 const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender});414 const event = result.events.Transfer;415 expect(event).to.be.like({416 address: helper.ethAddress.fromCollectionId(collection.collectionId),417 event: 'Transfer',418 returnValues: {419 from: helper.address.substrateToEth(owner.address),420 to: helper.address.substrateToEth(receiver.address),421 tokenId: token.tokenId.toString(),422 },423 });424 }425426 expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);427 });428429 itEth('Can perform transfer()', async ({helper}) => {430 const caller = await helper.eth.createAccountWithBalance(donor);431 const receiver = helper.eth.createAccount();432 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry', '6', '6');433 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);434435 const result = await contract.methods.mint(caller).send();436 const tokenId = result.events.Transfer.returnValues.tokenId;437438 {439 const result = await contract.methods.transfer(receiver, tokenId).send();440441 const event = result.events.Transfer;442 expect(event.address).to.equal(collectionAddress);443 expect(event.returnValues.from).to.equal(caller);444 expect(event.returnValues.to).to.equal(receiver);445 expect(event.returnValues.tokenId).to.equal(tokenId.toString());446 }447448 {449 const balance = await contract.methods.balanceOf(caller).call();450 expect(+balance).to.equal(0);451 }452453 {454 const balance = await contract.methods.balanceOf(receiver).call();455 expect(+balance).to.equal(1);456 }457 });458459 itEth('Can perform transferCross()', async ({helper}) => {460 const sender = await helper.eth.createAccountWithBalance(donor);461 const receiverEth = await helper.eth.createAccountWithBalance(donor);462 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);463 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);464465 const collection = await helper.rft.mintCollection(minter, {});466 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);467 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', sender);468469 const token = await collection.mintToken(minter, 50n, {Ethereum: sender});470471 {472 // Can transferCross to ethereum address:473 const result = await collectionEvm.methods.transferCross(receiverCrossEth, token.tokenId).send({from: sender});474 // Check events:475 const event = result.events.Transfer;476 expect(event.address).to.equal(collectionAddress);477 expect(event.returnValues.from).to.equal(sender);478 expect(event.returnValues.to).to.equal(receiverEth);479 expect(event.returnValues.tokenId).to.equal(token.tokenId.toString());480 // Sender's balance decreased:481 const senderBalance = await collectionEvm.methods.balanceOf(sender).call();482 expect(+senderBalance).to.equal(0);483 expect(await token.getBalance({Ethereum: sender})).to.eq(0n);484 // Receiver's balance increased:485 const receiverBalance = await collectionEvm.methods.balanceOf(receiverEth).call();486 expect(+receiverBalance).to.equal(1);487 expect(await token.getBalance({Ethereum: receiverEth})).to.eq(50n);488 }489490 {491 // Can transferCross to substrate address:492 const substrateResult = await collectionEvm.methods.transferCross(receiverCrossSub, token.tokenId).send({from: receiverEth});493 // Check events:494 const event = substrateResult.events.Transfer;495 expect(event.address).to.be.equal(collectionAddress);496 expect(event.returnValues.from).to.be.equal(receiverEth);497 expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(minter.address));498 expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);499 // Sender's balance decreased:500 const senderBalance = await collectionEvm.methods.balanceOf(receiverEth).call();501 expect(+senderBalance).to.equal(0);502 expect(await token.getBalance({Ethereum: receiverEth})).to.eq(0n);503 // Receiver's balance increased:504 const receiverBalance = await helper.nft.getTokensByAddress(collection.collectionId, {Substrate: minter.address});505 expect(receiverBalance).to.contain(token.tokenId);506 expect(await token.getBalance({Substrate: minter.address})).to.eq(50n);507 }508 });509510 ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {511 const sender = await helper.eth.createAccountWithBalance(donor);512 const tokenOwner = await helper.eth.createAccountWithBalance(donor);513 const receiverSub = minter;514 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);515516 const collection = await helper.rft.mintCollection(minter, {});517 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);518 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', sender);519520 await collection.mintToken(minter, 50n, {Ethereum: sender});521 const nonSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});522523 // Cannot transferCross someone else's token:524 const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;525 await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;526 // Cannot transfer token if it does not exist:527 await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;528 }));529530 itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {531 const caller = await helper.eth.createAccountWithBalance(donor);532 const receiver = helper.eth.createAccount();533 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Partial-to-Full', '6', '6');534 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);535536 const result = await contract.methods.mint(caller).send();537 const tokenId = result.events.Transfer.returnValues.tokenId;538539 const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);540541 await tokenContract.methods.repartition(2).send();542 await tokenContract.methods.transfer(receiver, 1).send();543544 const events: any = [];545 contract.events.allEvents((_: any, event: any) => {546 events.push(event);547 });548549 await tokenContract.methods.transfer(receiver, 1).send();550 if (events.length == 0) await helper.wait.newBlocks(1);551 const event = events[0];552553 expect(event.address).to.equal(collectionAddress);554 expect(event.returnValues.from).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');555 expect(event.returnValues.to).to.equal(receiver);556 expect(event.returnValues.tokenId).to.equal(tokenId.toString());557 });558559 itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {560 const caller = await helper.eth.createAccountWithBalance(donor);561 const receiver = helper.eth.createAccount();562 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Full-to-Partial', '6', '6');563 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);564565 const result = await contract.methods.mint(caller).send();566 const tokenId = result.events.Transfer.returnValues.tokenId;567568 const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);569570 await tokenContract.methods.repartition(2).send();571572 const events: any = [];573 contract.events.allEvents((_: any, event: any) => {574 events.push(event);575 });576577 await tokenContract.methods.transfer(receiver, 1).send();578 if (events.length == 0) await helper.wait.newBlocks(1);579 const event = events[0];580581 expect(event.address).to.equal(collectionAddress);582 expect(event.returnValues.from).to.equal(caller);583 expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');584 expect(event.returnValues.tokenId).to.equal(tokenId.toString());585 });586587 itEth('Check balanceOfCross()', async ({helper}) => {588 const collection = await helper.rft.mintCollection(minter, {});589 const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);590 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);591 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner.eth);592593 expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');594595 for (let i = 1n; i < 10n; i++) {596 await collection.mintToken(minter, 100n, {Ethereum: owner.eth});597 expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq(i.toString());598 }599 });600601 itEth('Check ownerOfCross()', async ({helper}) => {602 const collection = await helper.rft.mintCollection(minter, {});603 let owner = await helper.ethCrossAccount.createAccountWithBalance(donor);604 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);605 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner.eth);606 const {tokenId} = await collection.mintToken(minter, 100n,{Ethereum: owner.eth});607608 for (let i = 1n; i < 10n; i++) {609 const ownerCross = await collectionEvm.methods.ownerOfCross(tokenId).call({from: owner.eth});610 expect(ownerCross.eth).to.be.eq(owner.eth);611 expect(ownerCross.sub).to.be.eq(owner.sub);612613 const newOwner = await helper.ethCrossAccount.createAccountWithBalance(donor);614 await collectionEvm.methods.transferCross(newOwner, tokenId).send({from: owner.eth});615 owner = newOwner;616 }617618 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);619 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, owner.eth, true);620 const newOwner = await helper.ethCrossAccount.createAccountWithBalance(donor);621 await tokenContract.methods.transferCross(newOwner, 50).send({from: owner.eth});622 const ownerCross = await collectionEvm.methods.ownerOfCross(tokenId).call({from: owner.eth});623 expect(ownerCross.eth.toUpperCase()).to.be.eq('0XFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');624 expect(ownerCross.sub).to.be.eq('0');625 });626});627628describe('RFT: Fees', () => {629 let donor: IKeyringPair;630631 before(async function() {632 await usingEthPlaygrounds(async (helper, privateKey) => {633 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);634635 donor = await privateKey({url: import.meta.url});636 });637 });638639 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {640 const caller = await helper.eth.createAccountWithBalance(donor);641 const receiver = helper.eth.createAccount();642 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer-From', '6', '6');643 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);644645 const result = await contract.methods.mint(caller).send();646 const tokenId = result.events.Transfer.returnValues.tokenId;647648 const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());649 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));650 expect(cost > 0n);651 });652653 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {654 const caller = await helper.eth.createAccountWithBalance(donor);655 const receiver = helper.eth.createAccount();656 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer', '6', '6');657 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);658659 const result = await contract.methods.mint(caller).send();660 const tokenId = result.events.Transfer.returnValues.tokenId;661662 const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());663 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));664 expect(cost > 0n);665 });666});667668describe('Common metadata', () => {669 let donor: IKeyringPair;670 let alice: IKeyringPair;671672 before(async function() {673 await usingEthPlaygrounds(async (helper, privateKey) => {674 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);675676 donor = await privateKey({url: import.meta.url});677 [alice] = await helper.arrange.createAccounts([1000n], donor);678 });679 });680681 itEth('Returns collection name', async ({helper}) => {682 // FIXME: should not have balance to use .call()683 const caller = await helper.eth.createAccountWithBalance(alice);684 const tokenPropertyPermissions = [{685 key: 'URI',686 permission: {687 mutable: true,688 collectionAdmin: true,689 tokenOwner: false,690 },691 }];692 const collection = await helper.rft.mintCollection(693 alice,694 {695 name: 'Leviathan',696 tokenPrefix: '11',697 properties: [{key: 'ERC721Metadata', value: '1'}],698 tokenPropertyPermissions,699 },700 );701702 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);703 const name = await contract.methods.name().call();704 expect(name).to.equal('Leviathan');705 });706707 itEth('Returns symbol name', async ({helper}) => {708 const caller = await helper.eth.createAccountWithBalance(donor);709 const tokenPropertyPermissions = [{710 key: 'URI',711 permission: {712 mutable: true,713 collectionAdmin: true,714 tokenOwner: false,715 },716 }];717 const {collectionId} = await helper.rft.mintCollection(718 alice,719 {720 name: 'Leviathan',721 tokenPrefix: '12',722 properties: [{key: 'ERC721Metadata', value: '1'}],723 tokenPropertyPermissions,724 },725 );726727 const contract = await helper.ethNativeContract.collectionById(collectionId, 'rft', caller);728 const symbol = await contract.methods.symbol().call();729 expect(symbol).to.equal('12');730 });731});732733describe('Negative tests', () => {734 let donor: IKeyringPair;735 let minter: IKeyringPair;736 let alice: IKeyringPair;737738 before(async function() {739 await usingEthPlaygrounds(async (helper, privateKey) => {740 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);741742 donor = await privateKey({url: import.meta.url});743 [minter, alice] = await helper.arrange.createAccounts([100n, 100n], donor);744 });745 });746747 itEth('[negative] Cant perform burn without approval', async ({helper}) => {748 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});749750 const owner = await helper.eth.createAccountWithBalance(donor);751 const spender = await helper.eth.createAccountWithBalance(donor);752753 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});754755 const address = helper.ethAddress.fromCollectionId(collection.collectionId);756 const contract = await helper.ethNativeContract.collection(address, 'rft');757758 const ownerCross = helper.ethCrossAccount.fromAddress(owner);759760 await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;761762 await contract.methods.setApprovalForAll(spender, true).send({from: owner});763 await contract.methods.setApprovalForAll(spender, false).send({from: owner});764765 await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;766 });767768 itEth('[negative] Cant perform transfer without approval', async ({helper}) => {769 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});770 const owner = await helper.eth.createAccountWithBalance(donor);771 const receiver = alice;772773 const spender = await helper.eth.createAccountWithBalance(donor);774775 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});776777 const address = helper.ethAddress.fromCollectionId(collection.collectionId);778 const contract = await helper.ethNativeContract.collection(address, 'rft');779780 const ownerCross = helper.ethCrossAccount.fromAddress(owner);781 const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);782783 await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;784785 await contract.methods.setApprovalForAll(spender, true).send({from: owner});786 await contract.methods.setApprovalForAll(spender, false).send({from: owner});787788 await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;789 });790});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 {Pallets, requirePalletsOrSkip} from '../util';18import {expect, itEth, usingEthPlaygrounds} from './util';19import {IKeyringPair} from '@polkadot/types/types';20import {ITokenPropertyPermission} from '../util/playgrounds/types';2122describe('Refungible: Plain calls', () => {23 let donor: IKeyringPair;24 let minter: IKeyringPair;25 let bob: IKeyringPair;26 let charlie: IKeyringPair;2728 before(async function() {29 await usingEthPlaygrounds(async (helper, privateKey) => {30 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);3132 donor = await privateKey({url: import.meta.url});33 [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);34 });35 });3637 [38 'substrate' as const,39 'ethereum' as const,40 ].map(testCase => {41 itEth(`Can perform mintCross() for ${testCase} address`, async ({helper}) => {42 const collectionAdmin = await helper.eth.createAccountWithBalance(donor);4344 const receiverEth = helper.eth.createAccount();45 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);46 const receiverSub = bob;47 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);4849 const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));50 const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {51 tokenOwner: false,52 collectionAdmin: true,53 mutable: false}}));545556 const collection = await helper.rft.mintCollection(minter, {57 tokenPrefix: 'ethp',58 tokenPropertyPermissions: permissions,59 });60 await collection.addAdmin(minter, {Ethereum: collectionAdmin});6162 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);63 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', collectionAdmin, true);64 let expectedTokenId = await contract.methods.nextTokenId().call();65 let result = await contract.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, []).send();66 let tokenId = result.events.Transfer.returnValues.tokenId;67 expect(tokenId).to.be.equal(expectedTokenId);6869 let event = result.events.Transfer;70 expect(event.address).to.be.equal(collectionAddress);71 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');72 expect(event.returnValues.to).to.be.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(bob.address));73 expect(await contract.methods.properties(tokenId, []).call()).to.be.like([]);7475 expectedTokenId = await contract.methods.nextTokenId().call();76 result = await contract.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, properties).send();77 event = result.events.Transfer;78 expect(event.address).to.be.equal(collectionAddress);79 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');80 expect(event.returnValues.to).to.be.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(bob.address));81 expect(await contract.methods.properties(tokenId, []).call()).to.be.like([]);8283 tokenId = result.events.Transfer.returnValues.tokenId;8485 expect(tokenId).to.be.equal(expectedTokenId);8687 expect(await contract.methods.properties(tokenId, []).call()).to.be.like(properties88 .map(p => helper.ethProperty.property(p.key, p.value.toString())));8990 expect(await helper.nft.getTokenOwner(collection.collectionId, tokenId))91 .to.deep.eq(testCase === 'ethereum' ? {Ethereum: receiverEth.toLowerCase()} : {Substrate: receiverSub.address});92 });93 });9495 itEth.skip('Can perform mintBulk()', async ({helper}) => {96 const owner = await helper.eth.createAccountWithBalance(donor);97 const receiver = helper.eth.createAccount();98 const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');99 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);100101 {102 const nextTokenId = await contract.methods.nextTokenId().call();103 expect(nextTokenId).to.be.equal('1');104 const result = await contract.methods.mintBulkWithTokenURI(105 receiver,106 [107 [nextTokenId, 'Test URI 0'],108 [+nextTokenId + 1, 'Test URI 1'],109 [+nextTokenId + 2, 'Test URI 2'],110 ],111 ).send();112113 const events = result.events.Transfer;114 for(let i = 0; i < 2; i++) {115 const event = events[i];116 expect(event.address).to.equal(collectionAddress);117 expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');118 expect(event.returnValues.to).to.equal(receiver);119 expect(event.returnValues.tokenId).to.equal(String(+nextTokenId + i));120 }121122 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');123 expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');124 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');125 }126 });127128 itEth('Can perform setApprovalForAll()', async ({helper}) => {129 const owner = await helper.eth.createAccountWithBalance(donor);130 const operator = helper.eth.createAccount();131132 const collection = await helper.rft.mintCollection(minter, {});133134 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);135 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);136137 const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();138 expect(approvedBefore).to.be.equal(false);139140 {141 const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});142143 expect(result.events.ApprovalForAll).to.be.like({144 address: collectionAddress,145 event: 'ApprovalForAll',146 returnValues: {147 owner,148 operator,149 approved: true,150 },151 });152153 const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();154 expect(approvedAfter).to.be.equal(true);155 }156157 {158 const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});159160 expect(result.events.ApprovalForAll).to.be.like({161 address: collectionAddress,162 event: 'ApprovalForAll',163 returnValues: {164 owner,165 operator,166 approved: false,167 },168 });169170 const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();171 expect(approvedAfter).to.be.equal(false);172 }173 });174175 itEth('Can perform burn with ApprovalForAll', async ({helper}) => {176 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});177178 const owner = await helper.eth.createAccountWithBalance(donor);179 const operator = await helper.eth.createAccountWithBalance(donor);180181 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});182183 const address = helper.ethAddress.fromCollectionId(collection.collectionId);184 const contract = await helper.ethNativeContract.collection(address, 'rft');185186 {187 await contract.methods.setApprovalForAll(operator, true).send({from: owner});188 const ownerCross = helper.ethCrossAccount.fromAddress(owner);189 const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});190 const events = result.events.Transfer;191192 expect(events).to.be.like({193 address,194 event: 'Transfer',195 returnValues: {196 from: owner,197 to: '0x0000000000000000000000000000000000000000',198 tokenId: token.tokenId.toString(),199 },200 });201 }202 });203204 itEth('Can perform burn with approve and approvalForAll', async ({helper}) => {205 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});206207 const owner = await helper.eth.createAccountWithBalance(donor);208 const operator = await helper.eth.createAccountWithBalance(donor);209210 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});211212 const address = helper.ethAddress.fromCollectionId(collection.collectionId);213 const contract = await helper.ethNativeContract.collection(address, 'rft');214215 const rftToken = await helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner, true);216217 {218 await rftToken.methods.approve(operator, 15n).send({from: owner});219 await contract.methods.setApprovalForAll(operator, true).send({from: owner});220 await rftToken.methods.burnFrom(owner, 10n).send({from: operator});221 }222 {223 const allowance = await rftToken.methods.allowance(owner, operator).call();224 expect(+allowance).to.be.equal(5);225 }226 {227 const ownerCross = helper.ethCrossAccount.fromAddress(owner);228 const operatorCross = helper.ethCrossAccount.fromAddress(operator);229 const allowance = await rftToken.methods.allowanceCross(ownerCross, operatorCross).call();230 expect(+allowance).to.equal(5);231 }232 });233234 itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {235 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});236237 const owner = await helper.eth.createAccountWithBalance(donor);238 const operator = await helper.eth.createAccountWithBalance(donor);239 const receiver = charlie;240241 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});242243 const address = helper.ethAddress.fromCollectionId(collection.collectionId);244 const contract = await helper.ethNativeContract.collection(address, 'rft');245246 {247 await contract.methods.setApprovalForAll(operator, true).send({from: owner});248 const ownerCross = helper.ethCrossAccount.fromAddress(owner);249 const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);250 const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});251 const event = result.events.Transfer;252 expect(event).to.be.like({253 address: helper.ethAddress.fromCollectionId(collection.collectionId),254 event: 'Transfer',255 returnValues: {256 from: owner,257 to: helper.address.substrateToEth(receiver.address),258 tokenId: token.tokenId.toString(),259 },260 });261 }262263 expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);264 });265266 itEth('Can perform burn()', async ({helper}) => {267 const caller = await helper.eth.createAccountWithBalance(donor);268 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');269 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);270271 const result = await contract.methods.mint(caller).send();272 const tokenId = result.events.Transfer.returnValues.tokenId;273 {274 const result = await contract.methods.burn(tokenId).send();275 const event = result.events.Transfer;276 expect(event.address).to.equal(collectionAddress);277 expect(event.returnValues.from).to.equal(caller);278 expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');279 expect(event.returnValues.tokenId).to.equal(tokenId.toString());280 }281 });282283 itEth('Can perform transferFrom()', async ({helper}) => {284 const caller = await helper.eth.createAccountWithBalance(donor);285 const receiver = helper.eth.createAccount();286 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'TransferFromy', '6', '6');287 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);288289 const result = await contract.methods.mint(caller).send();290 const tokenId = result.events.Transfer.returnValues.tokenId;291292 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);293294 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, caller);295 await tokenContract.methods.repartition(15).send();296297 {298 const tokenEvents: any = [];299 tokenContract.events.allEvents((_: any, event: any) => {300 tokenEvents.push(event);301 });302 const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();303 if(tokenEvents.length == 0) await helper.wait.newBlocks(1);304305 let event = result.events.Transfer;306 expect(event.address).to.equal(collectionAddress);307 expect(event.returnValues.from).to.equal(caller);308 expect(event.returnValues.to).to.equal(receiver);309 expect(event.returnValues.tokenId).to.equal(tokenId.toString());310311 event = tokenEvents[0];312 expect(event.address).to.equal(tokenAddress);313 expect(event.returnValues.from).to.equal(caller);314 expect(event.returnValues.to).to.equal(receiver);315 expect(event.returnValues.value).to.equal('15');316 }317318 {319 const balance = await contract.methods.balanceOf(receiver).call();320 expect(+balance).to.equal(1);321 }322323 {324 const balance = await contract.methods.balanceOf(caller).call();325 expect(+balance).to.equal(0);326 }327 });328329 // Soft-deprecated330 itEth('Can perform burnFrom()', async ({helper}) => {331 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});332333 const owner = await helper.eth.createAccountWithBalance(donor);334 const spender = await helper.eth.createAccountWithBalance(donor);335336 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});337338 const address = helper.ethAddress.fromCollectionId(collection.collectionId);339 const contract = await helper.ethNativeContract.collection(address, 'rft', spender, true);340341 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);342 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, owner);343 await tokenContract.methods.repartition(15).send();344 await tokenContract.methods.approve(spender, 15).send();345346 {347 const result = await contract.methods.burnFrom(owner, token.tokenId).send();348 const event = result.events.Transfer;349 expect(event).to.be.like({350 address: helper.ethAddress.fromCollectionId(collection.collectionId),351 event: 'Transfer',352 returnValues: {353 from: owner,354 to: '0x0000000000000000000000000000000000000000',355 tokenId: token.tokenId.toString(),356 },357 });358 }359360 expect(await collection.getTokenBalance(token.tokenId, {Ethereum: owner})).to.be.eq(0n);361 });362363 itEth('Can perform burnFromCross()', async ({helper}) => {364 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});365366 const owner = bob;367 const spender = await helper.eth.createAccountWithBalance(donor);368369 const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});370371 const address = helper.ethAddress.fromCollectionId(collection.collectionId);372 const contract = await helper.ethNativeContract.collection(address, 'rft');373374 await token.repartition(owner, 15n);375 await token.approve(owner, {Ethereum: spender}, 15n);376377 {378 const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);379 const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender});380 const event = result.events.Transfer;381 expect(event).to.be.like({382 address: helper.ethAddress.fromCollectionId(collection.collectionId),383 event: 'Transfer',384 returnValues: {385 from: helper.address.substrateToEth(owner.address),386 to: '0x0000000000000000000000000000000000000000',387 tokenId: token.tokenId.toString(),388 },389 });390 }391392 expect(await collection.getTokenBalance(token.tokenId, {Substrate: owner.address})).to.be.eq(0n);393 });394395 itEth('Can perform transferFromCross()', async ({helper}) => {396 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});397398 const owner = bob;399 const spender = await helper.eth.createAccountWithBalance(donor);400 const receiver = charlie;401402 const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});403404 const address = helper.ethAddress.fromCollectionId(collection.collectionId);405 const contract = await helper.ethNativeContract.collection(address, 'rft');406407 await token.repartition(owner, 15n);408 await token.approve(owner, {Ethereum: spender}, 15n);409410 {411 const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);412 const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);413 const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender});414 const event = result.events.Transfer;415 expect(event).to.be.like({416 address: helper.ethAddress.fromCollectionId(collection.collectionId),417 event: 'Transfer',418 returnValues: {419 from: helper.address.substrateToEth(owner.address),420 to: helper.address.substrateToEth(receiver.address),421 tokenId: token.tokenId.toString(),422 },423 });424 }425426 expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);427 });428429 itEth('Can perform transfer()', async ({helper}) => {430 const caller = await helper.eth.createAccountWithBalance(donor);431 const receiver = helper.eth.createAccount();432 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry', '6', '6');433 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);434435 const result = await contract.methods.mint(caller).send();436 const tokenId = result.events.Transfer.returnValues.tokenId;437438 {439 const result = await contract.methods.transfer(receiver, tokenId).send();440441 const event = result.events.Transfer;442 expect(event.address).to.equal(collectionAddress);443 expect(event.returnValues.from).to.equal(caller);444 expect(event.returnValues.to).to.equal(receiver);445 expect(event.returnValues.tokenId).to.equal(tokenId.toString());446 }447448 {449 const balance = await contract.methods.balanceOf(caller).call();450 expect(+balance).to.equal(0);451 }452453 {454 const balance = await contract.methods.balanceOf(receiver).call();455 expect(+balance).to.equal(1);456 }457 });458459 itEth('Can perform transferCross()', async ({helper}) => {460 const sender = await helper.eth.createAccountWithBalance(donor);461 const receiverEth = await helper.eth.createAccountWithBalance(donor);462 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);463 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);464465 const collection = await helper.rft.mintCollection(minter, {});466 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);467 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', sender);468469 const token = await collection.mintToken(minter, 50n, {Ethereum: sender});470471 {472 // Can transferCross to ethereum address:473 const result = await collectionEvm.methods.transferCross(receiverCrossEth, token.tokenId).send({from: sender});474 // Check events:475 const event = result.events.Transfer;476 expect(event.address).to.equal(collectionAddress);477 expect(event.returnValues.from).to.equal(sender);478 expect(event.returnValues.to).to.equal(receiverEth);479 expect(event.returnValues.tokenId).to.equal(token.tokenId.toString());480 // Sender's balance decreased:481 const senderBalance = await collectionEvm.methods.balanceOf(sender).call();482 expect(+senderBalance).to.equal(0);483 expect(await token.getBalance({Ethereum: sender})).to.eq(0n);484 // Receiver's balance increased:485 const receiverBalance = await collectionEvm.methods.balanceOf(receiverEth).call();486 expect(+receiverBalance).to.equal(1);487 expect(await token.getBalance({Ethereum: receiverEth})).to.eq(50n);488 }489490 {491 // Can transferCross to substrate address:492 const substrateResult = await collectionEvm.methods.transferCross(receiverCrossSub, token.tokenId).send({from: receiverEth});493 // Check events:494 const event = substrateResult.events.Transfer;495 expect(event.address).to.be.equal(collectionAddress);496 expect(event.returnValues.from).to.be.equal(receiverEth);497 expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(minter.address));498 expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);499 // Sender's balance decreased:500 const senderBalance = await collectionEvm.methods.balanceOf(receiverEth).call();501 expect(+senderBalance).to.equal(0);502 expect(await token.getBalance({Ethereum: receiverEth})).to.eq(0n);503 // Receiver's balance increased:504 const receiverBalance = await helper.nft.getTokensByAddress(collection.collectionId, {Substrate: minter.address});505 expect(receiverBalance).to.contain(token.tokenId);506 expect(await token.getBalance({Substrate: minter.address})).to.eq(50n);507 }508 });509510 ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {511 const sender = await helper.eth.createAccountWithBalance(donor);512 const tokenOwner = await helper.eth.createAccountWithBalance(donor);513 const receiverSub = minter;514 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);515516 const collection = await helper.rft.mintCollection(minter, {});517 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);518 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', sender);519520 await collection.mintToken(minter, 50n, {Ethereum: sender});521 const nonSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});522523 // Cannot transferCross someone else's token:524 const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;525 await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;526 // Cannot transfer token if it does not exist:527 await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;528 }));529530 itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {531 const caller = await helper.eth.createAccountWithBalance(donor);532 const receiver = helper.eth.createAccount();533 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Partial-to-Full', '6', '6');534 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);535536 const result = await contract.methods.mint(caller).send();537 const tokenId = result.events.Transfer.returnValues.tokenId;538539 const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);540541 await tokenContract.methods.repartition(2).send();542 await tokenContract.methods.transfer(receiver, 1).send();543544 const events: any = [];545 contract.events.allEvents((_: any, event: any) => {546 events.push(event);547 });548549 await tokenContract.methods.transfer(receiver, 1).send();550 if(events.length == 0) await helper.wait.newBlocks(1);551 const event = events[0];552553 expect(event.address).to.equal(collectionAddress);554 expect(event.returnValues.from).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');555 expect(event.returnValues.to).to.equal(receiver);556 expect(event.returnValues.tokenId).to.equal(tokenId.toString());557 });558559 itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {560 const caller = await helper.eth.createAccountWithBalance(donor);561 const receiver = helper.eth.createAccount();562 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Full-to-Partial', '6', '6');563 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);564565 const result = await contract.methods.mint(caller).send();566 const tokenId = result.events.Transfer.returnValues.tokenId;567568 const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);569570 await tokenContract.methods.repartition(2).send();571572 const events: any = [];573 contract.events.allEvents((_: any, event: any) => {574 events.push(event);575 });576577 await tokenContract.methods.transfer(receiver, 1).send();578 if(events.length == 0) await helper.wait.newBlocks(1);579 const event = events[0];580581 expect(event.address).to.equal(collectionAddress);582 expect(event.returnValues.from).to.equal(caller);583 expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');584 expect(event.returnValues.tokenId).to.equal(tokenId.toString());585 });586587 itEth('Check balanceOfCross()', async ({helper}) => {588 const collection = await helper.rft.mintCollection(minter, {});589 const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);590 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);591 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner.eth);592593 expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');594595 for(let i = 1n; i < 10n; i++) {596 await collection.mintToken(minter, 100n, {Ethereum: owner.eth});597 expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq(i.toString());598 }599 });600601 itEth('Check ownerOfCross()', async ({helper}) => {602 const collection = await helper.rft.mintCollection(minter, {});603 let owner = await helper.ethCrossAccount.createAccountWithBalance(donor);604 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);605 const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner.eth);606 const {tokenId} = await collection.mintToken(minter, 100n,{Ethereum: owner.eth});607608 for(let i = 1n; i < 10n; i++) {609 const ownerCross = await collectionEvm.methods.ownerOfCross(tokenId).call({from: owner.eth});610 expect(ownerCross.eth).to.be.eq(owner.eth);611 expect(ownerCross.sub).to.be.eq(owner.sub);612613 const newOwner = await helper.ethCrossAccount.createAccountWithBalance(donor);614 await collectionEvm.methods.transferCross(newOwner, tokenId).send({from: owner.eth});615 owner = newOwner;616 }617618 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);619 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, owner.eth, true);620 const newOwner = await helper.ethCrossAccount.createAccountWithBalance(donor);621 await tokenContract.methods.transferCross(newOwner, 50).send({from: owner.eth});622 const ownerCross = await collectionEvm.methods.ownerOfCross(tokenId).call({from: owner.eth});623 expect(ownerCross.eth.toUpperCase()).to.be.eq('0XFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');624 expect(ownerCross.sub).to.be.eq('0');625 });626});627628describe('RFT: Fees', () => {629 let donor: IKeyringPair;630631 before(async function() {632 await usingEthPlaygrounds(async (helper, privateKey) => {633 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);634635 donor = await privateKey({url: import.meta.url});636 });637 });638639 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {640 const caller = await helper.eth.createAccountWithBalance(donor);641 const receiver = helper.eth.createAccount();642 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer-From', '6', '6');643 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);644645 const result = await contract.methods.mint(caller).send();646 const tokenId = result.events.Transfer.returnValues.tokenId;647648 const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());649 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));650 expect(cost > 0n);651 });652653 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {654 const caller = await helper.eth.createAccountWithBalance(donor);655 const receiver = helper.eth.createAccount();656 const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer', '6', '6');657 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);658659 const result = await contract.methods.mint(caller).send();660 const tokenId = result.events.Transfer.returnValues.tokenId;661662 const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());663 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));664 expect(cost > 0n);665 });666});667668describe('Common metadata', () => {669 let donor: IKeyringPair;670 let alice: IKeyringPair;671672 before(async function() {673 await usingEthPlaygrounds(async (helper, privateKey) => {674 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);675676 donor = await privateKey({url: import.meta.url});677 [alice] = await helper.arrange.createAccounts([1000n], donor);678 });679 });680681 itEth('Returns collection name', async ({helper}) => {682 // FIXME: should not have balance to use .call()683 const caller = await helper.eth.createAccountWithBalance(alice);684 const tokenPropertyPermissions = [{685 key: 'URI',686 permission: {687 mutable: true,688 collectionAdmin: true,689 tokenOwner: false,690 },691 }];692 const collection = await helper.rft.mintCollection(693 alice,694 {695 name: 'Leviathan',696 tokenPrefix: '11',697 properties: [{key: 'ERC721Metadata', value: '1'}],698 tokenPropertyPermissions,699 },700 );701702 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);703 const name = await contract.methods.name().call();704 expect(name).to.equal('Leviathan');705 });706707 itEth('Returns symbol name', async ({helper}) => {708 const caller = await helper.eth.createAccountWithBalance(donor);709 const tokenPropertyPermissions = [{710 key: 'URI',711 permission: {712 mutable: true,713 collectionAdmin: true,714 tokenOwner: false,715 },716 }];717 const {collectionId} = await helper.rft.mintCollection(718 alice,719 {720 name: 'Leviathan',721 tokenPrefix: '12',722 properties: [{key: 'ERC721Metadata', value: '1'}],723 tokenPropertyPermissions,724 },725 );726727 const contract = await helper.ethNativeContract.collectionById(collectionId, 'rft', caller);728 const symbol = await contract.methods.symbol().call();729 expect(symbol).to.equal('12');730 });731});732733describe('Negative tests', () => {734 let donor: IKeyringPair;735 let minter: IKeyringPair;736 let alice: IKeyringPair;737738 before(async function() {739 await usingEthPlaygrounds(async (helper, privateKey) => {740 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);741742 donor = await privateKey({url: import.meta.url});743 [minter, alice] = await helper.arrange.createAccounts([100n, 100n], donor);744 });745 });746747 itEth('[negative] Cant perform burn without approval', async ({helper}) => {748 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});749750 const owner = await helper.eth.createAccountWithBalance(donor);751 const spender = await helper.eth.createAccountWithBalance(donor);752753 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});754755 const address = helper.ethAddress.fromCollectionId(collection.collectionId);756 const contract = await helper.ethNativeContract.collection(address, 'rft');757758 const ownerCross = helper.ethCrossAccount.fromAddress(owner);759760 await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;761762 await contract.methods.setApprovalForAll(spender, true).send({from: owner});763 await contract.methods.setApprovalForAll(spender, false).send({from: owner});764765 await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;766 });767768 itEth('[negative] Cant perform transfer without approval', async ({helper}) => {769 const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});770 const owner = await helper.eth.createAccountWithBalance(donor);771 const receiver = alice;772773 const spender = await helper.eth.createAccountWithBalance(donor);774775 const token = await collection.mintToken(minter, 100n, {Ethereum: owner});776777 const address = helper.ethAddress.fromCollectionId(collection.collectionId);778 const contract = await helper.ethNativeContract.collection(address, 'rft');779780 const ownerCross = helper.ethCrossAccount.fromAddress(owner);781 const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);782783 await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;784785 await contract.methods.setApprovalForAll(spender, true).send({from: owner});786 await contract.methods.setApprovalForAll(spender, false).send({from: owner});787788 await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;789 });790});tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -47,7 +47,7 @@
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- if (propertyKey && propertyValue) {
+ if(propertyKey && propertyValue) {
// Set URL or suffix
await contract.methods.setProperties(tokenId, [{key: propertyKey, value: Buffer.from(propertyValue)}]).send();
@@ -229,7 +229,7 @@
}
// 1.2 Cross substrate address:
- if (testCase === 'transferFromCross') {
+ if(testCase === 'transferFromCross') {
const result = await contract.methods.transferFromCross(ownerCross, receiverCrossSub, 51).send({from: spender});
// Check events:
const transferEvent = result.events.Transfer;
@@ -424,7 +424,7 @@
});
await tokenContract.methods.burnFrom(caller, 1).send();
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
@@ -579,7 +579,7 @@
});
expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Approval');
@@ -605,7 +605,7 @@
});
expect(await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n)).to.be.true;
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
let event = events[0];
expect(event.event).to.be.equal('Transfer');
@@ -636,7 +636,7 @@
});
expect(await token.transfer(alice, {Ethereum: receiver}, 51n)).to.be.true;
- if (events.length == 0) await helper.wait.newBlocks(1);
+ if(events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
expect(event.event).to.be.equal('Transfer');
tests/src/eth/tokens/callMethodsERC20.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokens/callMethodsERC20.test.ts
+++ b/tests/src/eth/tokens/callMethodsERC20.test.ts
@@ -37,7 +37,7 @@
const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
- if (testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
+ if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
// Use collection contract for FT or token contract for RFT:
const contract = testCase.mode === 'ft'
@@ -58,7 +58,7 @@
const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
- if (testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
+ if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
// Use collection contract for FT or token contract for RFT:
const contract = testCase.mode === 'ft'
@@ -77,7 +77,7 @@
itEth('decimals', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
- if (testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
+ if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
// Use collection contract for FT or token contract for RFT:
const contract = testCase.mode === 'ft'
tests/src/eth/tokens/minting.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokens/minting.test.ts
+++ b/tests/src/eth/tokens/minting.test.ts
@@ -53,7 +53,7 @@
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.equal(receiver);
- if (testCase.mode === 'ft')
+ if(testCase.mode === 'ft')
expect(event.returnValues.value).to.equal('100');
// Check token exist:
@@ -87,7 +87,7 @@
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.equal(receiver);
- if (testCase.mode === 'ft')
+ if(testCase.mode === 'ft')
expect(event.returnValues.value).to.equal('100');
// Check token exist:
@@ -121,7 +121,7 @@
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.equal(receiver);
- if (testCase.mode === 'ft')
+ if(testCase.mode === 'ft')
expect(event.returnValues.value).to.equal('100');
// Check token exist:
tests/src/eth/util/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/index.ts
+++ b/tests/src/eth/util/index.ts
@@ -40,20 +40,20 @@
await helper.connectWeb3(config.substrateUrl);
const ss58Format = helper.chain.getChainProperties().ss58Format;
const privateKey: PrivateKeyFn = async (seed) => {
- if (typeof seed === 'string') {
+ if(typeof seed === 'string') {
return helper.util.fromSeed(seed, ss58Format);
}
- if (seed.url) {
+ if(seed.url) {
const {filename} = makeNames(seed.url);
seed.filename = filename;
- } else if (seed.filename) {
+ } else if(seed.filename) {
// Pass
} else {
throw new Error('no url nor filename set');
}
const actualSeed = getTestSeed(seed.filename);
let account = helper.util.fromSeed(actualSeed, ss58Format);
- if (await helper.balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND) {
+ if(await helper.balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND) {
console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);
account = helper.util.fromSeed('//Alice', ss58Format);
}
@@ -71,7 +71,7 @@
(opts.only ? it.only :
opts.skip ? it.skip : it)(name, async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
- if (opts.requiredPallets) {
+ if(opts.requiredPallets) {
requirePalletsOrSkip(this, helper, opts.requiredPallets);
}
tests/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
@@ -43,7 +43,7 @@
this.helper = helper;
}
async getGasPrice() {
- if (this.gasPrice)
+ if(this.gasPrice)
return this.gasPrice;
this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();
return this.gasPrice;
@@ -53,17 +53,17 @@
class ContractGroup extends EthGroupBase {
async findImports(imports?: ContractImports[]) {
- if (!imports) return function(path: string) {
+ if(!imports) return function(path: string) {
return {error: `File not found: ${path}`};
};
const knownImports = {} as { [key: string]: string };
- for (const imp of imports) {
+ for(const imp of imports) {
knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
}
return function(path: string) {
- if (path in knownImports) return {contents: knownImports[path]};
+ if(path in knownImports) return {contents: knownImports[path]};
return {error: `File not found: ${path}`};
};
}
@@ -91,7 +91,7 @@
return err.severity == 'error';
});
- if (hasErrors) {
+ if(hasErrors) {
throw compiled.errors;
}
const out = compiled.contracts[`${name}.sol`][name];
@@ -139,7 +139,7 @@
collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {
let abi;
- if (address === this.helper.ethAddress.fromCollectionId(0)) {
+ if(address === this.helper.ethAddress.fromCollectionId(0)) {
abi = nativeFungibleAbi;
} else {
abi ={
@@ -148,7 +148,7 @@
'ft': fungibleAbi,
}[mode];
}
- if (mergeDeprecated) {
+ if(mergeDeprecated) {
const deprecated = {
'nft': nonFungibleDeprecatedAbi,
'rft': refungibleDeprecatedAbi,
@@ -209,7 +209,7 @@
}
async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {
- if (!gasLimit) gasLimit = this.DEFAULT_GAS;
+ if(!gasLimit) gasLimit = this.DEFAULT_GAS;
const web3 = this.helper.getWeb3();
// FIXME: can't send legacy transaction using tx.evm.call
const gasPrice = await web3.eth.getGasPrice();
@@ -341,10 +341,10 @@
normalizeEvents(events: any): NormalizedEvent[] {
const output = [];
- for (const key of Object.keys(events)) {
- if (key.match(/^[0-9]+$/)) {
+ for(const key of Object.keys(events)) {
+ if(key.match(/^[0-9]+$/)) {
output.push(events[key]);
- } else if (Array.isArray(events[key])) {
+ } else if(Array.isArray(events[key])) {
output.push(...events[key]);
} else {
output.push(events[key]);
@@ -353,8 +353,8 @@
output.sort((a, b) => a.logIndex - b.logIndex);
return output.map(({address, event, returnValues}) => {
const args: { [key: string]: string } = {};
- for (const key of Object.keys(returnValues)) {
- if (!key.match(/^[0-9]+$/)) {
+ for(const key of Object.keys(returnValues)) {
+ if(!key.match(/^[0-9]+$/)) {
args[key] = returnValues[key];
}
}
@@ -378,19 +378,19 @@
class EthAddressGroup extends EthGroupBase {
extractCollectionId(address: string): number {
- if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');
+ if(!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');
return parseInt(address.slice(address.length - 8), 16);
}
fromCollectionId(collectionId: number): string {
- if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');
+ if(collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');
return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);
}
extractTokenId(address: string): { collectionId: number, tokenId: number } {
- if (!address.startsWith('0x'))
+ if(!address.startsWith('0x'))
throw 'address not starts with "0x"';
- if (address.length > 42)
+ if(address.length > 42)
throw 'address length is more than 20 bytes';
return {
collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),
@@ -501,18 +501,18 @@
}
getWeb3(): Web3 {
- if (this.web3 === null) throw Error('Web3 not connected');
+ if(this.web3 === null) throw Error('Web3 not connected');
return this.web3;
}
connectWeb3(wsEndpoint: string) {
- if (this.web3 !== null) return;
+ if(this.web3 !== null) return;
this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);
this.web3 = new Web3(this.web3Provider);
}
async disconnect() {
- if (this.web3 === null) return;
+ if(this.web3 === null) return;
this.web3Provider?.connection.close();
await super.disconnect();
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -55,7 +55,7 @@
await collection.transfer(alice, {Substrate: bob.address}, 1000n);
await collection.transfer(alice, ethAcc, 900n);
- for (let i = 0; i < 7; i++) {
+ for(let i = 0; i < 7; i++) {
await collection.transfer(alice, facelessCrowd[i], 1n);
}
tests/src/generateEnv.tsdiffbeforeafterboth--- a/tests/src/generateEnv.ts
+++ b/tests/src/generateEnv.ts
@@ -18,21 +18,21 @@
found = true;
return `${key}=${value}\n`;
});
- if (!found) throw new Error(`env key "${key}" is not found`);
+ if(!found) throw new Error(`env key "${key}" is not found`);
return newEnv;
}
// Fetch and format version string
async function ff(url: string, regex: RegExp, rep: string | ((substring: string, ...params:any[]) => string)): Promise<string> {
const ver = await fetchVersion(url);
- if (ver.match(regex) === null)
+ if(ver.match(regex) === null)
throw new Error(`bad regex for ${url}`);
return ver.replace(regex, rep as any);
}
function fixupUnique(version: string): string {
- if (version === 'release-v930033')
+ if(version === 'release-v930033')
return 'release-v930033-fix-gas-price';
- if (version === 'release-v930034')
+ if(version === 'release-v930034')
return 'release-v930034-fix-gas-price';
return version;
}
tests/src/maintenance.seqtest.tsdiffbeforeafterboth--- a/tests/src/maintenance.seqtest.ts
+++ b/tests/src/maintenance.seqtest.ts
@@ -42,7 +42,7 @@
describe('Maintenance Mode', () => {
before(async function() {
await usingPlaygrounds(async (helper) => {
- if (await maintenanceEnabled(helper.getApi())) {
+ if(await maintenanceEnabled(helper.getApi())) {
console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');
await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;
}
@@ -270,8 +270,8 @@
afterEach(async () => {
await usingPlaygrounds(async helper => {
- if (helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;
- if (await maintenanceEnabled(helper.getApi())) {
+ if(helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;
+ if(await maintenanceEnabled(helper.getApi())) {
console.warn('\tMaintenance mode was left enabled AFTER a test has finished! Be careful. Disabling it now.');
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);
}
@@ -359,9 +359,9 @@
after(async function() {
await usingPlaygrounds(async (helper) => {
- if (helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;
+ if(helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;
- for (const hash of preimageHashes) {
+ for(const hash of preimageHashes) {
await helper.preimage.unnotePreimage(bob, hash);
}
});
tests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -143,7 +143,7 @@
// It is possible to modify a property as many times as needed.
// It will not consume any additional space.
- for (let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {
+ for(let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {
await collection.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);
const consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
@@ -259,7 +259,7 @@
const collection = await helper[testSuite.mode].mintCollection(alice);
const propertiesToBeSet = [];
- for (let i = 0; i < 65; i++) {
+ for(let i = 0; i < 65; i++) {
propertiesToBeSet.push({
key: 'electron_' + i,
value: Math.random() > 0.5 ? 'high' : 'low',
@@ -281,7 +281,7 @@
[{key: 'déjà vu', value: 'hmm...'}],
];
- for (let i = 0; i < invalidProperties.length; i++) {
+ for(let i = 0; i < invalidProperties.length; i++) {
await expect(
collection.setProperties(alice, invalidProperties[i]),
`on rejecting the new badly-named property #${i}`,
@@ -305,7 +305,7 @@
{key: 'CRISPR-Cas9', value: 'rewriting nature!'},
]);
- for (let i = 0; i < invalidProperties.length; i++) {
+ for(let i = 0; i < invalidProperties.length; i++) {
await expect(
collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
`on trying to delete the non-existent badly-named property #${i}`,
tests/src/nesting/propertyPermissions.test.tsdiffbeforeafterboth--- a/tests/src/nesting/propertyPermissions.test.ts
+++ b/tests/src/nesting/propertyPermissions.test.ts
@@ -110,7 +110,7 @@
async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {
const constitution = [];
- for (let i = 0; i < 65; i++) {
+ for(let i = 0; i < 65; i++) {
constitution.push({
key: 'property_' + i,
permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},
@@ -160,7 +160,7 @@
[{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],
];
- for (let i = 0; i < invalidProperties.length; i++) {
+ for(let i = 0; i < invalidProperties.length; i++) {
await expect(
collection.setTokenPropertyPermissions(alice, invalidProperties[i]),
`on setting the new badly-named property #${i}`,
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -75,10 +75,10 @@
const propertyKeys: string[] = [];
let i = 0;
- for (const permission of permissions) {
+ for(const permission of permissions) {
i++;
let j = 0;
- for (const signer of permission.signers) {
+ for(const signer of permission.signers) {
j++;
const key = i + '_' + signer.address;
propertyKeys.push(key);
@@ -92,7 +92,7 @@
const properties = await token.getProperties(propertyKeys);
const tokenData = await token.getData();
- for (let i = 0; i < properties.length; i++) {
+ for(let i = 0; i < properties.length; i++) {
expect(properties[i].value).to.be.equal('Serotonin increase');
expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');
}
@@ -114,12 +114,12 @@
const propertyKeys: string[] = [];
let i = 0;
- for (const permission of permissions) {
+ for(const permission of permissions) {
i++;
- if (!permission.permission.mutable) continue;
+ if(!permission.permission.mutable) continue;
let j = 0;
- for (const signer of permission.signers) {
+ for(const signer of permission.signers) {
j++;
const key = i + '_' + signer.address;
propertyKeys.push(key);
@@ -138,7 +138,7 @@
const properties = await token.getProperties(propertyKeys);
const tokenData = await token.getData();
- for (let i = 0; i < properties.length; i++) {
+ for(let i = 0; i < properties.length; i++) {
expect(properties[i].value).to.be.equal('Serotonin stable');
expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');
}
@@ -161,12 +161,12 @@
const propertyKeys: string[] = [];
let i = 0;
- for (const permission of permissions) {
+ for(const permission of permissions) {
i++;
- if (!permission.permission.mutable) continue;
+ if(!permission.permission.mutable) continue;
let j = 0;
- for (const signer of permission.signers) {
+ for(const signer of permission.signers) {
j++;
const key = i + '_' + signer.address;
propertyKeys.push(key);
@@ -211,10 +211,10 @@
const propertyKeys: string[] = [];
let i = 0;
- for (const permission of permissions) {
+ for(const permission of permissions) {
i++;
let j = 0;
- for (const signer of permission.signers) {
+ for(const signer of permission.signers) {
j++;
const key = i + '_' + signer.address;
propertyKeys.push(key);
@@ -228,7 +228,7 @@
const properties = await nestedToken.getProperties(propertyKeys);
const tokenData = await nestedToken.getData();
- for (let i = 0; i < properties.length; i++) {
+ for(let i = 0; i < properties.length; i++) {
expect(properties[i].value).to.be.equal('Serotonin increase');
expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');
}
@@ -249,12 +249,12 @@
const propertyKeys: string[] = [];
let i = 0;
- for (const permission of permissions) {
+ for(const permission of permissions) {
i++;
- if (!permission.permission.mutable) continue;
+ if(!permission.permission.mutable) continue;
let j = 0;
- for (const signer of permission.signers) {
+ for(const signer of permission.signers) {
j++;
const key = i + '_' + signer.address;
propertyKeys.push(key);
@@ -273,7 +273,7 @@
const properties = await nestedToken.getProperties(propertyKeys);
const tokenData = await nestedToken.getData();
- for (let i = 0; i < properties.length; i++) {
+ for(let i = 0; i < properties.length; i++) {
expect(properties[i].value).to.be.equal('Serotonin stable');
expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');
}
@@ -294,12 +294,12 @@
const propertyKeys: string[] = [];
let i = 0;
- for (const permission of permissions) {
+ for(const permission of permissions) {
i++;
- if (!permission.permission.mutable) continue;
+ if(!permission.permission.mutable) continue;
let j = 0;
- for (const signer of permission.signers) {
+ for(const signer of permission.signers) {
j++;
const key = i + '_' + signer.address;
propertyKeys.push(key);
@@ -362,7 +362,7 @@
// It is possible to modify a property as many times as needed.
// It will not consume any additional space.
- for (let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {
+ for(let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {
await token.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);
const consumedSpace = await token.getTokenPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
@@ -491,7 +491,7 @@
await token.transfer(alice, {Substrate: charlie.address}, pieces);
let i = 0;
- for (const passage of constitution) {
+ for(const passage of constitution) {
i++;
const signer = passage.signers[0];
await expect(
@@ -508,9 +508,9 @@
const originalSpace = await prepare(token, pieces);
let i = 0;
- for (const forbiddance of constitution) {
+ for(const forbiddance of constitution) {
i++;
- if (!forbiddance.permission.mutable) continue;
+ if(!forbiddance.permission.mutable) continue;
await expect(
token.setProperties(forbiddance.sinner, [{key: `${i}`, value: 'Serotonin down'}]),
@@ -541,9 +541,9 @@
const originalSpace = await prepare(token, pieces);
let i = 0;
- for (const permission of constitution) {
+ for(const permission of constitution) {
i++;
- if (permission.permission.mutable) continue;
+ if(permission.permission.mutable) continue;
await expect(
token.setProperties(permission.signers[0], [{key: `${i}`, value: 'Serotonin down'}]),
@@ -650,7 +650,7 @@
const collection = await helper[testCase.mode].mintCollection(alice);
const maxPropertiesPerItem = 64;
- for (let i = 0; i < maxPropertiesPerItem; i++) {
+ for(let i = 0; i < maxPropertiesPerItem; i++) {
await collection.setTokenPropertyPermissions(alice, [{
key: `${i+1}`,
permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
tests/src/nesting/unnest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -117,7 +117,7 @@
const children = await targetNft.getChildren();
- if (childrenShouldPresent) {
+ if(childrenShouldPresent) {
expect(children[0]).to.be.deep.equal({
collectionId: nested.collectionId,
tokenId: (nested instanceof UniqueFTCollection) ? 0 : nested.tokenId,
@@ -137,13 +137,13 @@
const ops = ['transfer', 'burn'];
const cases = [];
- for (const mode of modes) {
+ for(const mode of modes) {
const requiredPallets = (mode === 'rft')
? [Pallets.ReFungible]
: [];
- for (const sender of senders) {
- for (const op of ops) {
+ for(const sender of senders) {
+ for(const op of ops) {
cases.push({
mode: mode as 'ft' | 'nft' | 'rft',
sender,
@@ -183,7 +183,7 @@
const firstUnnestAmount = 2n;
const restUnnestAmount = totalAmount - firstUnnestAmount;
- if (collectionNested instanceof UniqueFTCollection) {
+ if(collectionNested instanceof UniqueFTCollection) {
await collectionNested.mint(owner, totalAmount, {Substrate: charlie.address});
nested = collectionNested;
} else {
@@ -200,13 +200,13 @@
}) => {
const nestedBalanceBeforeOp = await nested.getBalance(targetNft.nestingAccount());
- if (testCase.op === 'transfer') {
+ if(testCase.op === 'transfer') {
const bobBalanceBeforeOp = await nested.getBalance({Substrate: bob.address});
await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address}, amount);
expect(await nested.getBalance({Substrate: bob.address})).to.be.equal(bobBalanceBeforeOp + amount);
} else {
- if (nested instanceof UniqueFTCollection) {
+ if(nested instanceof UniqueFTCollection) {
await nested.burnTokensFrom(unnester, targetNft.nestingAccount(), amount);
} else {
await nested.burnFrom(unnester, targetNft.nestingAccount(), amount);
@@ -274,7 +274,7 @@
tokenId: nested.tokenId,
}]);
- if (testCase.op === 'transfer') {
+ if(testCase.op === 'transfer') {
await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address});
} else {
await nested.burnFrom(unnester, targetNft.nestingAccount());
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -70,7 +70,7 @@
const preimage = ['preimage'];
const testUtils = 'testutils';
- if (chain.eq('OPAL by UNIQUE')) {
+ if(chain.eq('OPAL by UNIQUE')) {
requiredPallets.push(
refungible,
foreignAssets,
@@ -79,7 +79,7 @@
...collatorSelection,
...preimage,
);
- } else if (chain.eq('QUARTZ by UNIQUE') || chain.eq('SAPPHIRE by UNIQUE')) {
+ } else if(chain.eq('QUARTZ by UNIQUE') || chain.eq('SAPPHIRE by UNIQUE')) {
requiredPallets.push(
refungible,
appPromotion,
@@ -87,7 +87,7 @@
...collatorSelection,
...preimage,
);
- } else if (chain.eq('UNIQUE')) {
+ } else if(chain.eq('UNIQUE')) {
// Insert Unique additional pallets here
requiredPallets.push(
refungible,
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -73,7 +73,7 @@
await token.transfer(alice, {Substrate: bob.address}, 1000n);
await token.transfer(alice, ethAcc, 900n);
- for (let i = 0; i < 7; i++) {
+ for(let i = 0; i < 7; i++) {
await token.transfer(alice, facelessCrowd[i], 50n * BigInt(i + 1));
}
tests/src/rpc.test.tsdiffbeforeafterboth--- a/tests/src/rpc.test.ts
+++ b/tests/src/rpc.test.ts
@@ -49,7 +49,7 @@
await collection.transfer(alice, {Substrate: bob.address}, 1000n);
await collection.transfer(alice, ethAcc, 900n);
- for (let i = 0; i < facelessCrowd.length; i++) {
+ for(let i = 0; i < facelessCrowd.length; i++) {
await collection.transfer(alice, facelessCrowd[i], 1n);
}
// Set-up over
tests/src/scheduler.seqtest.tsdiffbeforeafterboth--- a/tests/src/scheduler.seqtest.ts
+++ b/tests/src/scheduler.seqtest.ts
@@ -157,7 +157,7 @@
let fillScheduledIds = new Array(maxScheduledPerBlock);
let extraScheduledId = undefined;
- if (scheduleKind == 'named') {
+ if(scheduleKind == 'named') {
const scheduledIds = helper.arrange.makeScheduledIds(maxScheduledPerBlock + 1);
fillScheduledIds = scheduledIds.slice(0, maxScheduledPerBlock);
extraScheduledId = scheduledIds[maxScheduledPerBlock];
@@ -178,7 +178,7 @@
const balanceBefore = await helper.balance.getSubstrate(bob.address);
// Fill the target block
- for (let i = 0; i < maxScheduledPerBlock; i++) {
+ for(let i = 0; i < maxScheduledPerBlock; i++) {
await helper.scheduler.scheduleAt(executionBlock, {scheduledId: fillScheduledIds[i]})
.balance.transferToSubstrate(superuser, bob.address, amount);
}
@@ -313,7 +313,7 @@
expect(await helper.testUtils.testValue())
.to.be.equal(finalTestVal);
- for (let i = 1; i < periodic.repetitions; i++) {
+ for(let i = 1; i < periodic.repetitions; i++) {
await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + periodic.period * (i + 1));
expect(await helper.testUtils.testValue())
.to.be.equal(finalTestVal);
@@ -505,8 +505,8 @@
// Fill `numFilledBlocks` blocks beginning from the block in which the second execution should occur
const txs = [];
- for (let offset = 0; offset < numFilledBlocks; offset ++) {
- for (let i = 0; i < maxScheduledPerBlock; i++) {
+ for(let offset = 0; offset < numFilledBlocks; offset ++) {
+ for(let i = 0; i < maxScheduledPerBlock; i++) {
const scheduledTx = helper.constructApiCall('api.tx.balances.transfer', [bob.address, 1n]);
@@ -534,7 +534,7 @@
await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + period + numFilledBlocks);
// The periodic operation should be postponed by `numFilledBlocks`
- for (let i = 0; i < numFilledBlocks; i++) {
+ for(let i = 0; i < numFilledBlocks; i++) {
expect(await helper.testUtils.testValue(firstExecutionBlockNumber + period + i)).to.be.equal(firstExecTestVal);
}
tests/src/sub/appPromotion/appPromotion.seqtest.tsdiffbeforeafterboth--- a/tests/src/sub/appPromotion/appPromotion.seqtest.ts
+++ b/tests/src/sub/appPromotion/appPromotion.seqtest.ts
@@ -36,7 +36,7 @@
after(async function () {
await usingPlaygrounds(async (helper) => {
- if (helper.fetchMissingPalletNames([Pallets.AppPromotion]).length != 0) return;
+ if(helper.fetchMissingPalletNames([Pallets.AppPromotion]).length != 0) return;
const api = helper.getApi();
await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
});
tests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -30,7 +30,7 @@
async function getAccounts(accountsNumber: number, balance?: bigint) {
let accs: IKeyringPair[] = [];
- if (balance) {
+ if(balance) {
await usingPlaygrounds(async (helper) => {
accs = await helper.arrange.createAccounts(new Array(accountsNumber).fill(balance), donor);
});
@@ -61,8 +61,8 @@
afterEach(async () => {
await usingPlaygrounds(async (helper) => {
let unstakeTxs = [];
- for (const account of usedAccounts) {
- if (unstakeTxs.length === 3) {
+ for(const account of usedAccounts) {
+ if(unstakeTxs.length === 3) {
await Promise.all(unstakeTxs);
unstakeTxs = [];
}
@@ -112,7 +112,7 @@
itSub(`[${testCase.unstake}] should allow to create maximum 10 stakes for account`, async ({helper}) => {
const [staker] = await getAccounts(1, 2000n);
const ONE_STAKE = 100n * nominal;
- for (let i = 0; i < 10; i++) {
+ for(let i = 0; i < 10; i++) {
await helper.staking.stake(staker, ONE_STAKE);
}
@@ -125,7 +125,7 @@
// After unstake can stake again
// CASE 1: unstakeAll
- if (testCase.unstake === 'unstakeAll') {
+ if(testCase.unstake === 'unstakeAll') {
await helper.staking.unstakeAll(staker);
expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
await helper.staking.stake(staker, 100n * nominal);
@@ -312,7 +312,7 @@
// can't unstake if there are only pendingUnstakes
await helper.staking.stake(staker, 100n * nominal);
- if (testCase.method === 'unstakeAll') {
+ if(testCase.method === 'unstakeAll') {
await helper.staking.unstakeAll(staker);
await helper.staking.unstakeAll(staker);
} else {
@@ -369,7 +369,7 @@
});
itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {
- if (!await helper.arrange.isDevNode()) {
+ if(!await helper.arrange.isDevNode()) {
const stakers = await getAccounts(10);
await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
@@ -894,8 +894,8 @@
await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
let unstakingTxs = [];
- for (const staker of stakers) {
- if (unstakingTxs.length == 3) {
+ for(const staker of stakers) {
+ if(unstakingTxs.length == 3) {
await Promise.all(unstakingTxs);
unstakingTxs = [];
}
@@ -910,7 +910,7 @@
let payouts;
do {
payouts = await helper.admin.payoutStakers(palletAdmin, 20);
- } while (payouts.length !== 0);
+ } while(payouts.length !== 0);
});
});
@@ -972,10 +972,10 @@
// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account
async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {
- for (let i = 0; i < 3; i++) {
+ for(let i = 0; i < 3; i++) {
const payouts = await helper.admin.payoutStakers(palletAdmin, 100);
const accountPayout = payouts.find(p => p.staker === account);
- if (accountPayout) return accountPayout;
+ if(accountPayout) return accountPayout;
}
throw Error(`Cannot find payout for ${account}`);
}
@@ -986,13 +986,13 @@
// 5n / 10_000n = 0.05% p/day
const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;
- if (iter > 1) {
+ if(iter > 1) {
return calculateIncome(income, iter - 1, calcPeriod);
} else return income;
}
function rewardAvailableInBlock(stakedInBlock: bigint) {
- if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;
+ if(stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;
return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
}
@@ -1002,7 +1002,7 @@
const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();
const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;
- if (currentPeriodBlock > waitBlockLessThan) {
+ if(currentPeriodBlock > waitBlockLessThan) {
await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);
}
}
tests/src/sub/nesting/nesting.negative.test.tsdiffbeforeafterboth--- a/tests/src/sub/nesting/nesting.negative.test.ts
+++ b/tests/src/sub/nesting/nesting.negative.test.ts
@@ -66,18 +66,18 @@
const collectionForNesting = testCase.mode === 'ft' ? await helper.ft.mintCollection(alice) : helper.ft.getCollectionObject(0);
// Alice cannot create immediately nested tokens:
- if (testCase.mode === 'ft') {
+ if(testCase.mode === 'ft') {
await expect(collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest');
} else {
await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 100n)).to.be.not.rejected;
}
// Alice can't mint and nest tokens:
- if (testCase.mode === 'ft') {
+ if(testCase.mode === 'ft') {
await collectionForNesting.mint(alice, 100n);
}
- if (testCase.mode === 'ft') {
+ if(testCase.mode === 'ft') {
await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
} else {
await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.not.rejected;
@@ -271,7 +271,7 @@
const maxNestingLevel = 5;
// Create a nested-token matryoshka
- for (let i = 0; i < maxNestingLevel; i++) {
+ for(let i = 0; i < maxNestingLevel; i++) {
token = await collection.mintToken(alice, token.nestingAccount());
}
tests/src/transfer.nload.tsdiffbeforeafterboth--- a/tests/src/transfer.nload.ts
+++ b/tests/src/transfer.nload.ts
@@ -29,7 +29,7 @@
const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
unused = await privateKey(`//${randomSeed}`);
bal = await helper.balance.getSubstrate(unused.address);
- } while (bal !== 0n);
+ } while(bal !== 0n);
return unused;
}
@@ -42,13 +42,13 @@
let counters: { [key: string]: number } = {};
function increaseCounter(name: string, amount: number) {
- if (!counters[name]) {
+ if(!counters[name]) {
counters[name] = 0;
}
counters[name] += amount;
}
function flushCounterToMaster() {
- if (Object.keys(counters).length === 0) {
+ if(Object.keys(counters).length === 0) {
return;
}
process.send!(counters);
@@ -65,12 +65,12 @@
// findUnusedAddresses produces at least 1 request per user
increaseCounter('requests', finalUserAmount);
- for (let stage = 0; stage < stages; stage++) {
+ for(let stage = 0; stage < stages; stage++) {
const usersWithBalance = 2 ** stage;
const amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);
// console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);
const txs: Promise<boolean | void>[] = [];
- for (let i = 0; i < usersWithBalance; i++) {
+ for(let i = 0; i < usersWithBalance; i++) {
const newUser = accounts[i + usersWithBalance];
// console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);
const tx = helper.balance.transferToSubstrate(accounts[i], newUser.address, amount);
@@ -83,19 +83,19 @@
await Promise.all(txs);
}
- for (const account of failedAccounts.reverse()) {
+ for(const account of failedAccounts.reverse()) {
accounts.splice(account, 1);
}
return accounts;
}
-if (cluster.isMaster) {
+if(cluster.isMaster) {
let testDone = false;
usingPlaygrounds(async (helper) => {
const prevCounters: { [key: string]: number } = {};
- while (!testDone) {
- for (const name in counters) {
- if (!(name in prevCounters)) {
+ while(!testDone) {
+ for(const name in counters) {
+ if(!(name in prevCounters)) {
prevCounters[name] = 0;
}
if(counters[name] === prevCounters[name]) {
@@ -111,7 +111,7 @@
console.log(`Starting ${os.cpus().length} workers`);
usingPlaygrounds(async (helper, privateKey) => {
const alice = await privateKey('//Alice');
- for (const id in os.cpus()) {
+ for(const id in os.cpus()) {
const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;
const workerAccount = await privateKey(WORKER_NAME);
await helper.balance.transferToSubstrate(alice, workerAccount.address, 400n * 10n ** 23n);
@@ -121,7 +121,7 @@
STAGES: id + 2,
});
worker.on('message', msg => {
- for (const key in msg) {
+ for(const key in msg) {
increaseCounter(key, msg[key]);
}
});
tests/src/util/globalSetup.tsdiffbeforeafterboth--- a/tests/src/util/globalSetup.ts
+++ b/tests/src/util/globalSetup.ts
@@ -19,12 +19,12 @@
// 2. Create donors for test files
await fundFilenamesWithRetries(3)
.then((result) => {
- if (!result) throw Error('Some problems with fundFilenamesWithRetries');
+ if(!result) throw Error('Some problems with fundFilenamesWithRetries');
});
// 3. Configure App Promotion
const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);
- if (missingPallets.length === 0) {
+ if(missingPallets.length === 0) {
const superuser = await privateKey('//Alice');
const palletAddress = helper.arrange.calculatePalletAddress('appstake');
const palletAdmin = await privateKey('//PromotionAdmin');
@@ -48,9 +48,9 @@
async function getFiles(rootPath: string): Promise<string[]> {
const files = await fs.readdir(rootPath, {withFileTypes: true});
const filenames: string[] = [];
- for (const entry of files) {
+ for(const entry of files) {
const res = path.resolve(rootPath, entry.name);
- if (entry.isDirectory()) {
+ if(entry.isDirectory()) {
filenames.push(...await getFiles(res));
} else {
filenames.push(res);
@@ -69,16 +69,16 @@
// batching is actually undesireable, it takes away the time while all the transactions actually succeed
const batchSize = 300;
let balanceGrantedCounter = 0;
- for (let b = 0; b < filenames.length; b += batchSize) {
+ for(let b = 0; b < filenames.length; b += batchSize) {
const tx = [];
let batchBalanceGrantedCounter = 0;
- for (let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {
+ for(let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {
const f = filenames[b + i];
- if (!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;
+ if(!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;
const account = await privateKey({filename: f, ignoreFundsPresence: true});
const aliceBalance = await helper.balance.getSubstrate(account.address);
- if (aliceBalance < MINIMUM_DONOR_FUND * oneToken) {
+ if(aliceBalance < MINIMUM_DONOR_FUND * oneToken) {
tx.push(helper.executeExtrinsic(
alice,
'api.tx.balances.transfer',
@@ -93,16 +93,16 @@
if(tx.length > 0) {
console.log(`Granting funds to ${batchBalanceGrantedCounter} filename accounts.`);
const result = await Promise.all(tx);
- if (result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');
+ if(result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');
}
}
- if (balanceGrantedCounter == 0) console.log('No account needs additional funding.');
+ if(balanceGrantedCounter == 0) console.log('No account needs additional funding.');
});
};
const fundFilenamesWithRetries = (retriesLeft: number): Promise<boolean> => {
- if (retriesLeft <= 0) return Promise.resolve(false);
+ if(retriesLeft <= 0) return Promise.resolve(false);
return fundFilenames()
.then(() => Promise.resolve(true))
.catch(e => {
tests/src/util/identitySetter.tsdiffbeforeafterboth--- a/tests/src/util/identitySetter.ts
+++ b/tests/src/util/identitySetter.ts
@@ -35,8 +35,8 @@
const identities: [string, any][] = [];
for(const [key, v] of await helper.getApi().query.identity.identityOf.entries()) {
const value = v as any;
- if (value.isNone) {
- if (noneCasePredicate) noneCasePredicate(key, value);
+ if(value.isNone) {
+ if(noneCasePredicate) noneCasePredicate(key, value);
continue;
}
identities.push(extractIdentity(key, value));
@@ -46,9 +46,9 @@
// whether the existing chain data is more important than the coming
function isCurrentChainDataPriority(helper: ChainHelperBase, currentChainId: number | undefined, relayChainId: number) {
- if (!currentChainId) return false;
+ if(!currentChainId) return false;
// information has come from local chain, and is automatically superior
- if (currentChainId == helper.chain.getChainProperties().ss58Format) return true;
+ if(currentChainId == helper.chain.getChainProperties().ss58Format) return true;
// the lower the id, the more important it is (Polkadot has ss58 prefix = 0, Kusama has ss58 prefix = 2)
return currentChainId < relayChainId;
}
@@ -64,7 +64,7 @@
deposit,
subIdentities.map((sub: string): [string, object] | null => {
const sup = supers.find((sup: any) => sup[0] === sub);
- if (!sup) {
+ if(!sup) {
console.error(`Error: Could not find info on super for \nsub-identity account\t${sub} of \nsuper account \t\t${identityAccount}, skipping.`);
return null;
}
@@ -85,8 +85,8 @@
async function uploadPreimage(helper: ChainHelperBase, preimageMaker: IKeyringPair, preimage: string) {
try {
await helper.executeExtrinsic(preimageMaker, 'api.tx.preimage.notePreimage', [preimage]);
- } catch(e: any) {
- if (e.message.includes('AlreadyNoted')) {
+ } catch (e: any) {
+ if(e.message.includes('AlreadyNoted')) {
console.warn('Warning: The same preimage already exists on the chain. Nothing was uploaded.');
} else {
console.error(e);
@@ -107,11 +107,11 @@
for(const [key, value] of await getIdentities(helper, (key, _value) => identitiesToRemove.push((key as any).toHuman()[0]))) {
// if any of the judgements resulted in a good confirmed outcome, keep this identity
let knownGood = false, reasonable = false;
- for (const [_id, judgement] of value.judgements) {
- if (judgement == 'KnownGood') knownGood = true;
- if (judgement == 'Reasonable') reasonable = true;
+ for(const [_id, judgement] of value.judgements) {
+ if(judgement == 'KnownGood') knownGood = true;
+ if(judgement == 'Reasonable') reasonable = true;
}
- if (!(reasonable || knownGood)) continue;
+ if(!(reasonable || knownGood)) continue;
// replace the registrator id with the relay chain's ss58 format
value.judgements = [[helper.chain.getChainProperties().ss58Format, knownGood ? 'KnownGood' : 'Reasonable']];
identitiesOnRelay.push([key, value]);
@@ -124,7 +124,7 @@
for(const [key, value] of await getSubs(helper)) {
// only get subs of the identities interesting to us
const identityIndex = sublessIdentities.findIndex((x: any) => x[0] == key);
- if (identityIndex == -1) continue;
+ if(identityIndex == -1) continue;
sublessIdentities.splice(identityIndex, 1);
subsOnRelay.push(constructSubInfo(key, value, supersOfSubs));
}
@@ -140,8 +140,8 @@
}, relayUrl);
await usingPlaygrounds(async (helper, privateKey) => {
- if (helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) console.error('pallet-identity is not included in parachain.');
- if (helper.fetchMissingPalletNames([Pallets.Preimage]).length != 0) console.error('pallet-preimage is not included in parachain.');
+ if(helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) console.error('pallet-identity is not included in parachain.');
+ if(helper.fetchMissingPalletNames([Pallets.Preimage]).length != 0) console.error('pallet-preimage is not included in parachain.');
try {
const preimageMaker = await privateKey(key);
@@ -151,15 +151,15 @@
const paraAccountsRegistrators: {[name: string]: number} = {};
// cross-reference every account for changes
- for (const [key, value] of identitiesOnRelay) {
+ for(const [key, value] of identitiesOnRelay) {
const encodedKey = encodeAddress(key, ss58Format);
// only update if the identity info does not exist or is changed
const identity = paraIdentities.find(i => i[0] === encodedKey);
- if (identity) {
+ if(identity) {
const registratorId = identity[1].judgements[0][0];
paraAccountsRegistrators[encodedKey] = registratorId;
- if (isCurrentChainDataPriority(helper, registratorId, value.judgements[0][0])
+ if(isCurrentChainDataPriority(helper, registratorId, value.judgements[0][0])
|| JSON.stringify(value.info) === JSON.stringify(identity[1].info)) {
continue;
}
@@ -172,13 +172,13 @@
// identitiesToRemove.push((key as any).toHuman()[0]);
}
- if (identitiesToRemove.length != 0)
+ if(identitiesToRemove.length != 0)
await uploadPreimage(
helper,
preimageMaker,
helper.constructApiCall('api.tx.identity.forceRemoveIdentities', [identitiesToRemove]).method.toHex(),
);
- if (identitiesToAdd.length != 0)
+ if(identitiesToAdd.length != 0)
await uploadPreimage(
helper,
preimageMaker,
@@ -194,22 +194,22 @@
const supersOfSubs = await getSupers(helper);
const subsToUpdate: any[] = [];
- for (const [key, value] of subsOnRelay) {
+ for(const [key, value] of subsOnRelay) {
const encodedKey = encodeAddress(key, ss58Format);
const sub = paraSubs.find(i => i[0] === encodedKey);
- if (sub) {
+ if(sub) {
// only update if the sub-identity info does not exist or is changed
- if (isCurrentChainDataPriority(helper, paraAccountsRegistrators[encodedKey], relaySS58Prefix)
+ if(isCurrentChainDataPriority(helper, paraAccountsRegistrators[encodedKey], relaySS58Prefix)
|| JSON.stringify(value) === JSON.stringify(constructSubInfo(sub[0], sub[1], supersOfSubs)[1])) {
continue;
}
- } else if (value[1].length == 0)
+ } else if(value[1].length == 0)
continue;
subsToUpdate.push([key, value]);
}
- if (subsToUpdate.length != 0)
+ if(subsToUpdate.length != 0)
await uploadPreimage(
helper,
preimageMaker,
@@ -225,5 +225,5 @@
}, paraUrl);
};
-if (process.argv[1] === module.filename)
+if(process.argv[1] === module.filename)
forceInsertIdentities().catch(() => process.exit(1));
tests/src/util/index.tsdiffbeforeafterboth--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -33,13 +33,13 @@
await helper.connect(url);
const ss58Format = helper.chain.getChainProperties().ss58Format;
const privateKey = async (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => {
- if (typeof seed === 'string') {
+ if(typeof seed === 'string') {
return helper.util.fromSeed(seed, ss58Format);
}
- if (seed.url) {
+ if(seed.url) {
const {filename} = makeNames(seed.url);
seed.filename = filename;
- } else if (seed.filename) {
+ } else if(seed.filename) {
// Pass
} else {
throw new Error('no url nor filename set');
@@ -47,7 +47,7 @@
const actualSeed = getTestSeed(seed.filename);
let account = helper.util.fromSeed(actualSeed, ss58Format);
// here's to hoping that no
- if (!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {
+ if(!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {
console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);
account = helper.util.fromSeed('//Alice', ss58Format);
}
@@ -112,7 +112,7 @@
export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: readonly string[]) {
const missingPallets = helper.fetchMissingPalletNames(requiredPallets);
- if (missingPallets.length > 0) {
+ if(missingPallets.length > 0) {
const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);
test.skip();
@@ -123,7 +123,7 @@
(opts.only ? it.only :
opts.skip ? it.skip : it)(name, async function () {
await usingPlaygrounds(async (helper, privateKey) => {
- if (opts.requiredPallets) {
+ if(opts.requiredPallets) {
requirePalletsOrSkip(this, helper, opts.requiredPallets);
}
@@ -168,12 +168,12 @@
describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});
export function sizeOfInt(i: number) {
- if (i < 0 || i > 0xffffffff) throw new Error('out of range');
+ if(i < 0 || i > 0xffffffff) throw new Error('out of range');
if(i < 0b11_1111) {
return 1;
- } else if (i < 0b11_1111_1111_1111) {
+ } else if(i < 0b11_1111_1111_1111) {
return 2;
- } else if (i < 0b11_1111_1111_1111_1111_1111_1111_1111) {
+ } else if(i < 0b11_1111_1111_1111_1111_1111_1111_1111) {
return 4;
} else {
return 5;
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -38,10 +38,10 @@
enable() {
const outFn = (printer: any) => (...args: any[]) => {
- for (const arg of args) {
- if (typeof arg !== 'string')
+ for(const arg of args) {
+ if(typeof arg !== 'string')
continue;
- if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
+ if(arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
return;
}
printer(...args);
@@ -357,10 +357,10 @@
const tokenNominal = this.helper.balance.getOneTokenNominal();
const transactions = [];
const accounts: IKeyringPair[] = [];
- for (const balance of balances) {
+ for(const balance of balances) {
const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);
accounts.push(recipient);
- if (balance !== 0n) {
+ if(balance !== 0n) {
const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);
transactions.push(this.helper.signTransaction(donor, tx, {nonce, era: 0}, 'account generation'));
nonce++;
@@ -372,9 +372,9 @@
//#region TODO remove this region, when nonce problem will be solved
const checkBalances = async () => {
let isSuccess = true;
- for (let i = 0; i < balances.length; i++) {
+ for(let i = 0; i < balances.length; i++) {
const balance = await this.helper.balance.getSubstrate(accounts[i].address);
- if (balance !== balances[i] * tokenNominal) {
+ if(balance !== balances[i] * tokenNominal) {
isSuccess = false;
break;
}
@@ -385,13 +385,13 @@
let accountsCreated = false;
const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;
// checkBalances retry up to 5-50 blocks
- for (let index = 0; index < maxBlocksChecked; index++) {
+ for(let index = 0; index < maxBlocksChecked; index++) {
accountsCreated = await checkBalances();
if(accountsCreated) break;
await wait.newBlocks(1);
}
- if (!accountsCreated) throw Error('Accounts generation failed');
+ if(!accountsCreated) throw Error('Accounts generation failed');
//#endregion
return accounts;
@@ -405,15 +405,15 @@
let nonce = await this.helper.chain.getNonce(donor.address);
const tokenNominal = this.helper.balance.getOneTokenNominal();
const ss58Format = this.helper.chain.getChainProperties().ss58Format;
- for (let i = 0; i < accountsToCreate; i++) {
- if (i === 500) { // if there are too many accounts to create
+ for(let i = 0; i < accountsToCreate; i++) {
+ if(i === 500) { // if there are too many accounts to create
await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled
transactions = []; //
nonce = await this.helper.chain.getNonce(donor.address); // update nonce
}
const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);
accounts.push(recipient);
- if (withBalance !== 0n) {
+ if(withBalance !== 0n) {
const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, withBalance * tokenNominal]);
transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));
nonce++;
@@ -422,9 +422,9 @@
const fullfilledAccounts = [];
await Promise.allSettled(transactions);
- for (const account of accounts) {
+ for(const account of accounts) {
const accountBalance = await this.helper.balance.getSubstrate(account.address);
- if (accountBalance === withBalance * tokenNominal) {
+ if(accountBalance === withBalance * tokenNominal) {
fullfilledAccounts.push(account);
}
}
@@ -434,20 +434,20 @@
const crowd: IKeyringPair[] = [];
// do up to 5 retries
- for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {
+ for(let index = 0; index < 5 && accountsToCreate !== 0; index++) {
const asManyAsCan = await createAsManyAsCan();
crowd.push(...asManyAsCan);
accountsToCreate -= asManyAsCan.length;
}
- if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);
+ if(accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);
return crowd;
};
isDevNode = async () => {
let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();
- if (blockNumber == 0) {
+ if(blockNumber == 0) {
await this.helper.wait.newBlocks(1);
blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();
}
@@ -484,7 +484,7 @@
const kvJson: {[key: string]: string} = {};
- for (const kv of rawPovInfo.keyValues) {
+ for(const kv of rawPovInfo.keyValues) {
kvJson[kv.key.toHex()] = kv.value.toHex();
}
@@ -498,7 +498,7 @@
],
);
- if (!chainql.stdout) {
+ if(!chainql.stdout) {
throw Error('unable to get an output from the `chainql`');
}
@@ -528,7 +528,7 @@
}
const ids = [];
- for (let i = 0; i < num; i++) {
+ for(let i = 0; i < num; i++) {
ids.push(makeId(this.scheduledIdSlider));
this.scheduledIdSlider += 1;
}
@@ -834,7 +834,7 @@
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {
- if (blocksCount > 0) {
+ if(blocksCount > 0) {
blocksCount--;
} else {
unsubscribe();
@@ -860,7 +860,7 @@
const expectedSessionIndex = await (this.helper as DevUniqueHelper).session.getIndex() + sessionCount;
let currentSessionIndex = -1;
- while (currentSessionIndex < expectedSessionIndex) {
+ while(currentSessionIndex < expectedSessionIndex) {
// eslint-disable-next-line no-async-promise-executor
currentSessionIndex = await this.withTimeout(new Promise(async (resolve) => {
await this.newBlocks(1);
@@ -875,7 +875,7 @@
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {
- if (data.number.toNumber() >= blockNumber) {
+ if(data.number.toNumber() >= blockNumber) {
unsubscribe();
resolve();
}
@@ -890,7 +890,7 @@
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {
- if (data.value.relayParentNumber.toNumber() >= blockNumber) {
+ if(data.value.relayParentNumber.toNumber() >= blockNumber) {
// @ts-ignore
unsubscribe();
resolve();
@@ -939,7 +939,7 @@
const eventRecords = (await apiAt.query.system.events()) as any;
const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {
- if (
+ if(
r.event.section == eventHelper.section()
&& r.event.method == eventHelper.method()
) {
@@ -950,10 +950,10 @@
}
});
- if (neededEvent) {
+ if(neededEvent) {
unsubscribe();
resolve(eventHelper);
- } else if (maxBlocksToWait > 0) {
+ } else if(maxBlocksToWait > 0) {
maxBlocksToWait--;
} else {
this.helper.logger.log(`Eligible event \`${eventIdStr}\` is NOT found`);
@@ -971,7 +971,7 @@
filter: (e: T) => boolean = () => true,
) {
const e = await this.event(maxBlocksToWait, eventHelperType, filter);
- if (e == null) {
+ if(e == null) {
const eventHelper = new eventHelperType();
throw Error(`The event '${eventHelper.section()}.${eventHelper.method()}' is expected`);
} else {
@@ -1018,7 +1018,7 @@
}
async enable() {
- if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {
+ if(this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {
return;
}
@@ -1082,7 +1082,7 @@
}
stopCapture() {
- if (this.unsubscribe !== null) {
+ if(this.unsubscribe !== null) {
this.unsubscribe();
}
}
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -54,7 +54,7 @@
Ethereum!: TEthereumAccount;
constructor(account: ICrossAccountId) {
- if ('Substrate' in account) this.Substrate = account.Substrate;
+ if('Substrate' in account) this.Substrate = account.Substrate;
else this.Ethereum = account.Ethereum;
}
@@ -66,7 +66,7 @@
}
static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {
- if ('substrate' in address) return new CrossAccountId({Substrate: address.substrate});
+ if('substrate' in address) return new CrossAccountId({Substrate: address.substrate});
else return new CrossAccountId({Ethereum: address.ethereum});
}
@@ -79,7 +79,7 @@
}
withNormalizedSubstrate(ss58Format = 42): CrossAccountId {
- if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);
+ if(this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);
return this;
}
@@ -88,7 +88,7 @@
}
toEthereum(): CrossAccountId {
- if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});
+ if(this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});
return this;
}
@@ -97,30 +97,30 @@
}
toSubstrate(ss58Format?: number): CrossAccountId {
- if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});
+ if(this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});
return this;
}
toLowerCase(): CrossAccountId {
- if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();
- if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();
+ if(this.Substrate) this.Substrate = this.Substrate.toLowerCase();
+ if(this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();
return this;
}
}
const nesting = {
toChecksumAddress(address: string): string {
- if (typeof address === 'undefined') return '';
+ if(typeof address === 'undefined') return '';
- if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);
+ if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);
address = address.toLowerCase().replace(/^0x/i, '');
const addressHash = keccakAsHex(address).replace(/^0x/i, '');
const checksumAddress = ['0x'];
- for (let i = 0; i < address.length; i++) {
+ for(let i = 0; i < address.length; i++) {
// If ith character is 8 to f then make it uppercase
- if (parseInt(addressHash[i], 16) > 7) {
+ if(parseInt(addressHash[i], 16) > 7) {
checksumAddress.push(address[i].toUpperCase());
} else {
checksumAddress.push(address[i]);
@@ -171,7 +171,7 @@
}
static str2vec(string: string) {
- if (typeof string !== 'string') return string;
+ if(typeof string !== 'string') return string;
return Array.from(string).map(x => x.charCodeAt(0));
}
@@ -181,18 +181,18 @@
}
static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {
- if (creationResult.status !== this.transactionStatus.SUCCESS) {
+ if(creationResult.status !== this.transactionStatus.SUCCESS) {
throw Error('Unable to create collection!');
}
let collectionId = null;
creationResult.result.events.forEach(({event: {data, method, section}}) => {
- if ((section === 'common') && (method === 'CollectionCreated')) {
+ if((section === 'common') && (method === 'CollectionCreated')) {
collectionId = parseInt(data[0].toString(), 10);
}
});
- if (collectionId === null) {
+ if(collectionId === null) {
throw Error('No CollectionCreated event was found!');
}
@@ -203,15 +203,15 @@
success: boolean,
tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],
} {
- if (creationResult.status !== this.transactionStatus.SUCCESS) {
+ if(creationResult.status !== this.transactionStatus.SUCCESS) {
throw Error('Unable to create tokens!');
}
let success = false;
const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];
creationResult.result.events.forEach(({event: {data, method, section}}) => {
- if (method === 'ExtrinsicSuccess') {
+ if(method === 'ExtrinsicSuccess') {
success = true;
- } else if ((section === 'common') && (method === 'ItemCreated')) {
+ } else if((section === 'common') && (method === 'ItemCreated')) {
tokens.push({
collectionId: parseInt(data[0].toString(), 10),
tokenId: parseInt(data[1].toString(), 10),
@@ -227,15 +227,15 @@
success: boolean,
tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],
} {
- if (burnResult.status !== this.transactionStatus.SUCCESS) {
+ if(burnResult.status !== this.transactionStatus.SUCCESS) {
throw Error('Unable to burn tokens!');
}
let success = false;
const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];
burnResult.result.events.forEach(({event: {data, method, section}}) => {
- if (method === 'ExtrinsicSuccess') {
+ if(method === 'ExtrinsicSuccess') {
success = true;
- } else if ((section === 'common') && (method === 'ItemDestroyed')) {
+ } else if((section === 'common') && (method === 'ItemDestroyed')) {
tokens.push({
collectionId: parseInt(data[0].toString(), 10),
tokenId: parseInt(data[1].toString(), 10),
@@ -250,12 +250,12 @@
static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {
let eventId = null;
events.forEach(({event: {data, method, section}}) => {
- if ((section === expectedSection) && (method === expectedMethod)) {
+ if((section === expectedSection) && (method === expectedMethod)) {
eventId = parseInt(data[0].toString(), 10);
}
});
- if (eventId === null) {
+ if(eventId === null) {
throw Error(`No ${expectedMethod} event was found!`);
}
return eventId === collectionId;
@@ -263,18 +263,18 @@
static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {
const normalizeAddress = (address: string | ICrossAccountId) => {
- if (typeof address === 'string') return address;
+ if(typeof address === 'string') return address;
const obj = {} as any;
Object.keys(address).forEach(k => {
obj[k.toLocaleLowerCase()] = (address as any)[k];
});
- if (obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);
- if (obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();
+ if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);
+ if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();
return address;
};
let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;
events.forEach(({event: {data, method, section}}) => {
- if ((section === 'common') && (method === 'Transfer')) {
+ if((section === 'common') && (method === 'Transfer')) {
const hData = (data as any).toJSON();
transfer = {
collectionId: hData[0],
@@ -296,7 +296,7 @@
const numberStr = number.toString();
const dotPos = numberStr.length - decimals;
- if (dotPos <= 0) {
+ if(dotPos <= 0) {
return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;
} else {
const intPart = numberStr.substring(0, dotPos);
@@ -308,7 +308,7 @@
class UniqueEventHelper {
private static extractIndex(index: any): [number, number] | string {
- if (index.toRawType() === '[u8;2]') return [index[0], index[1]];
+ if(index.toRawType() === '[u8;2]') return [index[0], index[1]];
return index.toJSON();
}
@@ -316,8 +316,8 @@
let obj: any = {};
let index = 0;
- if (data.entries) {
- for (const [key, value] of data.entries()) {
+ if(data.entries) {
+ for(const [key, value] of data.entries()) {
obj[key] = this.extractData(value, subTypes[index]);
index++;
}
@@ -331,10 +331,10 @@
}
private static extractData(data: any, type: any): any {
- if (!type) return this.toHuman(data);
- if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();
- if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();
- if (type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);
+ if(!type) return this.toHuman(data);
+ if(['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();
+ if(['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();
+ if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);
return this.toHuman(data);
}
@@ -399,7 +399,7 @@
this.util = UniqueUtil;
this.eventHelper = UniqueEventHelper;
- if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();
+ if(typeof logger == 'undefined') logger = this.util.getDefaultLogger();
this.logger = logger;
this.api = null;
this.forcedNetwork = null;
@@ -425,12 +425,12 @@
}
getEndpoint(): string {
- if (this.wsEndpoint === null) throw Error('No connection was established');
+ if(this.wsEndpoint === null) throw Error('No connection was established');
return this.wsEndpoint;
}
getApi(): ApiPromise {
- if (this.api === null) throw Error('API not initialized');
+ if(this.api === null) throw Error('API not initialized');
return this.api;
}
@@ -440,7 +440,7 @@
const ievents = this.eventHelper.extractEvents(events);
ievents.forEach((event) => {
expectedEvents.forEach((e => {
- if (event.section === e.section && e.names.includes(event.method)) {
+ if(event.section === e.section && e.names.includes(event.method)) {
collectedEvents.push(event);
}
}));
@@ -458,7 +458,7 @@
}
async connect(wsEndpoint: string, listeners?: IApiListeners) {
- if (this.api !== null) throw Error('Already connected');
+ if(this.api !== null) throw Error('Already connected');
const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);
this.wsEndpoint = wsEndpoint;
this.api = api;
@@ -466,11 +466,11 @@
}
async disconnect() {
- for (const child of this.children) {
+ for(const child of this.children) {
child.clearApi();
}
- if (this.api === null) return;
+ if(this.api === null) return;
await this.api.disconnect();
this.clearApi();
}
@@ -484,9 +484,9 @@
const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;
const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];
- if (xcmChains.indexOf(spec.specName) > -1) return spec.specName;
+ if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;
- if (['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;
+ if(['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;
return 'opal';
}
@@ -505,7 +505,7 @@
api: ApiPromise;
network: TNetworks;
}> {
- if (typeof network === 'undefined' || network === null) network = 'opal';
+ if(typeof network === 'undefined' || network === null) network = 'opal';
const supportedRPC = {
opal: {
unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,
@@ -524,7 +524,7 @@
karura: {},
westmint: {},
};
- if (!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);
+ if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);
const rpc = supportedRPC[network];
// TODO: investigate how to replace rpc in runtime
@@ -534,9 +534,9 @@
await api.isReadyOrError;
- if (typeof listeners === 'undefined') listeners = {};
- for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {
- if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;
+ if(typeof listeners === 'undefined') listeners = {};
+ for(const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {
+ if(!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;
api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);
}
@@ -545,18 +545,18 @@
getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {
const {events, status} = data;
- if (status.isReady) {
+ if(status.isReady) {
return this.transactionStatus.NOT_READY;
}
- if (status.isBroadcast) {
+ if(status.isBroadcast) {
return this.transactionStatus.NOT_READY;
}
- if (status.isInBlock || status.isFinalized) {
+ if(status.isInBlock || status.isFinalized) {
const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');
- if (errors.length > 0) {
+ if(errors.length > 0) {
return this.transactionStatus.FAIL;
}
- if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {
+ if(events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {
return this.transactionStatus.SUCCESS;
}
}
@@ -566,7 +566,7 @@
signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {
const sign = (callback: any) => {
- if (options !== null) return transaction.signAndSend(sender, options, callback);
+ if(options !== null) return transaction.signAndSend(sender, options, callback);
return transaction.signAndSend(sender, callback);
};
// eslint-disable-next-line no-async-promise-executor
@@ -575,23 +575,23 @@
const unsub = await sign((result: any) => {
const status = this.getTransactionStatus(result);
- if (status === this.transactionStatus.SUCCESS) {
+ if(status === this.transactionStatus.SUCCESS) {
this.logger.log(`${label} successful`);
unsub();
resolve({result, status, blockHash: result.status.asInBlock.toHuman()});
- } else if (status === this.transactionStatus.FAIL) {
+ } else if(status === this.transactionStatus.FAIL) {
let moduleError = null;
- if (result.hasOwnProperty('dispatchError')) {
+ if(result.hasOwnProperty('dispatchError')) {
const dispatchError = result['dispatchError'];
- if (dispatchError) {
- if (dispatchError.isModule) {
+ if(dispatchError) {
+ if(dispatchError.isModule) {
const modErr = dispatchError.asModule;
const errorMeta = dispatchError.registry.findMetaError(modErr);
moduleError = `${errorMeta.section}.${errorMeta.name}`;
- } else if (dispatchError.isToken) {
+ } else if(dispatchError.isToken) {
moduleError = `Token: ${dispatchError.asToken}`;
} else {
// May be [object Object] in case of unhandled non-unit enum
@@ -641,7 +641,7 @@
nonce: signingInfo.nonce,
});
- if (len === null) {
+ if(len === null) {
return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;
} else {
return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;
@@ -649,11 +649,11 @@
}
constructApiCall(apiCall: string, params: any[]) {
- if (!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);
+ if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);
let call = this.getApi() as any;
- for (const part of apiCall.slice(4).split('.')) {
+ for(const part of apiCall.slice(4).split('.')) {
call = call[part];
- if (!call) {
+ if(!call) {
const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';
throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);
}
@@ -681,8 +681,8 @@
expectSuccess = true,
options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/
): Promise<ITransactionResult> {
- if (this.api === null) throw Error('API not initialized');
- if (!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);
+ if(this.api === null) throw Error('API not initialized');
+ if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);
const startTime = (new Date()).getTime();
let result: ITransactionResult;
@@ -691,11 +691,11 @@
result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;
events = this.eventHelper.extractEvents(result.result.events);
const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');
- if (errorEvent)
+ if(errorEvent)
throw Error(errorEvent.method + ': ' + extrinsic);
}
catch (e) {
- if (!(e as object).hasOwnProperty('status')) throw e;
+ if(!(e as object).hasOwnProperty('status')) throw e;
result = e as ITransactionResult;
}
@@ -713,22 +713,22 @@
let errorMessage = '';
- if (result.status !== this.transactionStatus.SUCCESS) {
- if (result.moduleError) {
+ if(result.status !== this.transactionStatus.SUCCESS) {
+ if(result.moduleError) {
errorMessage = typeof result.moduleError === 'string'
? result.moduleError
: `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;
log.moduleError = errorMessage;
}
- else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;
+ else if(result.result.dispatchError) log.dispatchError = result.result.dispatchError;
}
- if (events.length > 0) log.events = events;
+ if(events.length > 0) log.events = events;
this.chainLog.push(log);
- if (expectSuccess && result.status !== this.transactionStatus.SUCCESS) {
- if (result.moduleError) throw Error(`${errorMessage}`);
- else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));
+ if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {
+ if(result.moduleError) throw Error(`${errorMessage}`);
+ else if(result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));
}
return result as any;
}
@@ -747,9 +747,9 @@
// >
(rpc: string, params?: any[]): Promise<any> {
- if (typeof params === 'undefined') params = [] as any;
- if (this.api === null) throw Error('API not initialized');
- if (!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);
+ if(typeof params === 'undefined') params = [] as any;
+ if(this.api === null) throw Error('API not initialized');
+ if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);
const startTime = (new Date()).getTime();
let result;
@@ -775,18 +775,18 @@
this.chainLog.push(log);
- if (error !== null) throw error;
+ if(error !== null) throw error;
return result;
}
getSignerAddress(signer: IKeyringPair | string): string {
- if (typeof signer === 'string') return signer;
+ if(typeof signer === 'string') return signer;
return signer.address;
}
fetchAllPalletNames(): string[] {
- if (this.api === null) throw Error('API not initialized');
+ if(this.api === null) throw Error('API not initialized');
return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();
}
@@ -852,11 +852,11 @@
id: collectionId, name: null, description: null, tokensCount: 0, admins: [],
raw: humanCollection,
} as any, jsonCollection = collection.toJSON();
- if (humanCollection === null) return null;
+ if(humanCollection === null) return null;
collectionData.raw.limits = jsonCollection.limits;
collectionData.raw.permissions = jsonCollection.permissions;
collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);
- for (const key of ['name', 'description']) {
+ for(const key of ['name', 'description']) {
collectionData[key] = this.helper.util.vec2str(humanCollection[key]);
}
@@ -1279,7 +1279,7 @@
true, // `Unable to burn token for ${label}`,
);
const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);
- if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');
+ if(burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');
return burnedTokens.success;
}
@@ -1427,21 +1427,21 @@
normalizedOwner: CrossAccountId;
} | null> {
let tokenData;
- if (typeof blockHashAt === 'undefined') {
+ if(typeof blockHashAt === 'undefined') {
tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);
}
else {
- if (propertyKeys.length == 0) {
+ if(propertyKeys.length == 0) {
const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();
- if (!collection) return null;
+ if(!collection) return null;
propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);
}
tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);
}
tokenData = tokenData.toHuman();
- if (tokenData === null || tokenData.owner === null) return null;
+ if(tokenData === null || tokenData.owner === null) return null;
const owner = {} as any;
- for (const key of Object.keys(tokenData.owner)) {
+ for(const key of Object.keys(tokenData.owner)) {
owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'
? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])
: tokenData.owner[key];
@@ -1460,7 +1460,7 @@
*/
async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {
let owner;
- if (typeof blockHashAt === 'undefined') {
+ if(typeof blockHashAt === 'undefined') {
owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);
} else {
owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);
@@ -1478,13 +1478,13 @@
*/
async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {
let owner;
- if (typeof blockHashAt === 'undefined') {
+ if(typeof blockHashAt === 'undefined') {
owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);
} else {
owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);
}
- if (owner === null) return null;
+ if(owner === null) return null;
return owner.toHuman();
}
@@ -1500,7 +1500,7 @@
async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {
const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);
const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);
- if (!result) {
+ if(!result) {
throw Error('Unable to nest token!');
}
return result;
@@ -1518,7 +1518,7 @@
async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {
const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);
const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);
- if (!result) {
+ if(!result) {
throw Error('Unable to unnest token!');
}
return result;
@@ -1621,8 +1621,8 @@
async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {
collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object
collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};
- for (const key of ['name', 'description', 'tokenPrefix']) {
- if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);
+ for(const key of ['name', 'description', 'tokenPrefix']) {
+ if(typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);
}
const creationResult = await this.helper.executeExtrinsic(
signer,
@@ -1741,7 +1741,7 @@
*/
async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {
let children;
- if (typeof blockHashAt === 'undefined') {
+ if(typeof blockHashAt === 'undefined') {
children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);
} else {
children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);
@@ -1783,8 +1783,8 @@
true,
);
const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);
- if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');
- if (createdTokens.tokens.length < 1) throw Error('No tokens minted');
+ if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');
+ if(createdTokens.tokens.length < 1) throw Error('No tokens minted');
return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);
}
@@ -1833,7 +1833,7 @@
*/
async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {
const rawTokens = [];
- for (const token of tokens) {
+ for(const token of tokens) {
const raw = {NFT: {properties: token.properties}};
rawTokens.push(raw);
}
@@ -1971,8 +1971,8 @@
true,
);
const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);
- if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');
- if (createdTokens.tokens.length < 1) throw Error('No tokens minted');
+ if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');
+ if(createdTokens.tokens.length < 1) throw Error('No tokens minted');
return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);
}
@@ -1998,7 +1998,7 @@
*/
async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {
const rawTokens = [];
- for (const token of tokens) {
+ for(const token of tokens) {
const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};
rawTokens.push(raw);
}
@@ -2080,7 +2080,7 @@
'api.tx.unique.repartition', [collectionId, tokenId, amount],
true,
);
- if (currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');
+ if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');
return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');
}
}
@@ -2112,10 +2112,10 @@
*/
async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {
collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object
- if (collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');
+ if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');
collectionOptions.mode = {fungible: decimalPoints};
- for (const key of ['name', 'description', 'tokenPrefix']) {
- if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);
+ for(const key of ['name', 'description', 'tokenPrefix']) {
+ if(typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);
}
const creationResult = await this.helper.executeExtrinsic(
signer,
@@ -2157,7 +2157,7 @@
*/
async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {
const rawTokens = [];
- for (const token of tokens) {
+ for(const token of tokens) {
const raw = {Fungible: {Value: token.value}};
rawTokens.push(raw);
}
@@ -2310,14 +2310,14 @@
*/
async getBlockHashByNumber(blockNumber: number): Promise<string | null> {
const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();
- if (blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;
+ if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;
return blockHash;
}
// TODO add docs
async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {
const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);
- if (!blockHash) return null;
+ if(!blockHash) return null;
return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;
}
@@ -2365,7 +2365,7 @@
let transfer = {from: null, to: null, amount: 0n} as any;
result.result.events.forEach(({event: {data, method, section}}) => {
- if ((section === 'balances') && (method === 'Transfer')) {
+ if((section === 'balances') && (method === 'Transfer')) {
transfer = {
from: this.helper.address.normalizeSubstrate(data[0]),
to: this.helper.address.normalizeSubstrate(data[1]),
@@ -2432,7 +2432,7 @@
let transfer = {from: null, to: null, amount: 0n} as any;
result.result.events.forEach(({event: {data, method, section}}) => {
- if ((section === 'balances') && (method === 'Transfer')) {
+ if((section === 'balances') && (method === 'Transfer')) {
transfer = {
from: data[0].toString(),
to: data[1].toString(),
@@ -2547,7 +2547,7 @@
let transfer = {from: null, to: null, amount: 0n} as any;
result.result.events.forEach(({event: {data, method, section}}) => {
- if ((section === 'balances') && (method === 'Transfer')) {
+ if((section === 'balances') && (method === 'Transfer')) {
transfer = {
from: this.helper.address.normalizeSubstrate(data[0]),
to: this.helper.address.normalizeSubstrate(data[1]),
@@ -2574,7 +2574,7 @@
.find(e => e.event.section === 'vesting' &&
e.event.method === 'VestingScheduleAdded' &&
e.event.data[0].toHuman() === signer.address);
- if (!event) throw Error('Cannot find transfer in events');
+ if(!event) throw Error('Cannot find transfer in events');
}
/**
@@ -2602,7 +2602,7 @@
.find(e => e.event.section === 'vesting' &&
e.event.method === 'Claimed' &&
e.event.data[0].toHuman() === signer.address);
- if (!event) throw Error('Cannot find claim in events');
+ if(!event) throw Error('Cannot find claim in events');
}
}
@@ -2662,12 +2662,12 @@
? hexToU8a(key.toString(16))
: key;
- if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {
+ if(ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {
throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);
}
const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];
- if (!allowedDecodedLengths.includes(u8a.length)) {
+ if(!allowedDecodedLengths.includes(u8a.length)) {
throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);
}
@@ -2692,11 +2692,11 @@
* @returns substrate address
*/
restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {
- if (this.helper.api === null) {
+ if(this.helper.api === null) {
throw 'Not connected';
}
const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
- if (res === undefined || res === null) {
+ if(res === undefined || res === null) {
throw 'Restore address error';
}
return res.toString();
@@ -2708,7 +2708,7 @@
* @returns substrate cross account id
*/
convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {
- if (ethCrossAccount.sub === '0') {
+ if(ethCrossAccount.sub === '0') {
return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};
}
@@ -2737,7 +2737,7 @@
* @returns
*/
async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {
- if (typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;
+ if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;
const _stakeResult = await this.helper.executeExtrinsic(
signer, 'api.tx.appPromotion.stake',
[amountToStake], true,
@@ -2754,7 +2754,7 @@
* @returns block hash where unstake happened
*/
async unstakeAll(signer: TSigner, label?: string): Promise<string> {
- if (typeof label === 'undefined') label = `${signer.address}`;
+ if(typeof label === 'undefined') label = `${signer.address}`;
const unstakeResult = await this.helper.executeExtrinsic(
signer, 'api.tx.appPromotion.unstakeAll',
[], true,
@@ -2770,7 +2770,7 @@
* @returns block hash where unstake happened
*/
async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {
- if (typeof label === 'undefined') label = `${signer.address}`;
+ if(typeof label === 'undefined') label = `${signer.address}`;
const unstakeResult = await this.helper.executeExtrinsic(
signer, 'api.tx.appPromotion.unstakePartial',
[amount], true,
@@ -2784,7 +2784,7 @@
* @returns {number}
*/
async getStakesNumber(address: ICrossAccountId): Promise<number> {
- if ('Ethereum' in address) throw Error('only substrate address');
+ if('Ethereum' in address) throw Error('only substrate address');
return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();
}
@@ -2794,7 +2794,7 @@
* @returns total staked amount
*/
async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {
- if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();
+ if(address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();
return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();
}
@@ -3077,12 +3077,12 @@
let beneficiary;
let assets;
- if (xcmVersion == 2) {
+ if(xcmVersion == 2) {
destination = {V1: destinationContent};
beneficiary = {V1: beneficiaryContent};
assets = {V1: assetsContent};
- } else if (xcmVersion == 3) {
+ } else if(xcmVersion == 3) {
destination = {V2: destinationContent};
beneficiary = {V2: beneficiaryContent};
assets = {V2: assetsContent};
@@ -3148,7 +3148,7 @@
await this.helper.callRpc('api.query.assets.account', [assetId, address])
).toJSON()! as any;
- if (accountAsset !== null) {
+ if(accountAsset !== null) {
return BigInt(accountAsset['balance']);
} else {
return null;
@@ -3424,12 +3424,12 @@
let schedArgs;
let scheduleFn;
- if (this.options.scheduledId) {
+ if(this.options.scheduledId) {
schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];
- if (this.scheduleFn == 'schedule') {
+ if(this.scheduleFn == 'schedule') {
scheduleFn = 'scheduleNamed';
- } else if (this.scheduleFn == 'scheduleAfter') {
+ } else if(this.scheduleFn == 'scheduleAfter') {
scheduleFn = 'scheduleNamedAfter';
}
} else {
@@ -3472,15 +3472,15 @@
options,
);
- if (result.status === 'Fail') return result;
+ if(result.status === 'Fail') return result;
const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;
- if (data.isErr) {
- if (data.asErr.isModule) {
+ if(data.isErr) {
+ if(data.asErr.isModule) {
const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;
const metaError = super.getApi()?.registry.findMetaError(error);
throw new Error(`${metaError.section}.${metaError.name}`);
- } else if (data.asErr.isToken) {
+ } else if(data.asErr.isToken) {
throw new Error(`Token: ${data.asErr.asToken}`);
}
// May be [object Object] in case of unhandled non-unit enum
tests/src/util/relayIdentitiesChecker.tsdiffbeforeafterboth--- a/tests/src/util/relayIdentitiesChecker.ts
+++ b/tests/src/util/relayIdentitiesChecker.ts
@@ -22,7 +22,7 @@
// iterate over every identity
for(const [key, value] of await getIdentities(helper)) {
// if any of the judgements resulted in a good confirmed outcome, keep this identity
- if (value.toHuman().judgements.filter((x: any) => x[1] == 'Reasonable' || x[1] == 'KnownGood').length == 0) continue;
+ if(value.toHuman().judgements.filter((x: any) => x[1] == 'Reasonable' || x[1] == 'KnownGood').length == 0) continue;
identities.push([key, value]);
}
@@ -31,7 +31,7 @@
// iterate over every sub-identity
for(const [key, value] of await getSubs(helper)) {
// only get subs of the identities interesting to us
- if (identities.find((x: any) => x[0] == key) == -1) continue;
+ if(identities.find((x: any) => x[0] == key) == -1) continue;
subs.push(constructSubInfo(key, value, supersOfSubs));
}
} catch (error) {
@@ -56,15 +56,15 @@
const matchingAddresses: string[] = [];
const inequalIdentities: {[name: string]: [any, any]} = {};
- for (const [key1, value1] of identitiesOnRelay1) {
+ for(const [key1, value1] of identitiesOnRelay1) {
const address = encodeAddress(key1);
const identity2 = identitiesOnRelay2.find(([key2, _value2]) => address === encodeAddress(key2));
- if (!identity2) continue;
+ if(!identity2) continue;
matchingAddresses.push(address);
//const [[key2, value2]] = identitiesOnRelay2.splice(index2, 1);
const [_key2, value2] = identity2;
- if (JSON.stringify(value1.info) === JSON.stringify(value2.info)) continue;
+ if(JSON.stringify(value1.info) === JSON.stringify(value2.info)) continue;
inequalIdentities[address] = [value1, value2];
}
@@ -81,16 +81,16 @@
const inequalSubIdentities = [];
let matchesFound = 0;
- for (const address of matchingAddresses) {
+ for(const address of matchingAddresses) {
const sub1 = subIdentitiesOnRelay1.find(([key1, _value1]) => address === encodeAddress(key1));
- if (!sub1) continue;
+ if(!sub1) continue;
const sub2 = subIdentitiesOnRelay2.find(([key2, _value2]) => address === encodeAddress(key2));
- if (!sub2) continue;
+ if(!sub2) continue;
const [value1, value2] = [sub1[1], sub2[1]];
matchesFound++;
- if (JSON.stringify(value1[1]) === JSON.stringify(value2[1])) {
+ if(JSON.stringify(value1[1]) === JSON.stringify(value2[1])) {
continue;
}
inequalSubIdentities.push([value1, value2]);
@@ -110,5 +110,5 @@
}
};
-if (process.argv[1] === module.filename)
+if(process.argv[1] === module.filename)
checkRelayIdentities().catch(() => process.exit(1));