1234import * as path from 'path';5import * as crypto from 'crypto';6import type {IKeyringPair} from '@polkadot/types/types/interfaces';7import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';9import chaiSubset from 'chai-subset';10import {Context} from 'mocha';11import config from '../tests/config.js';12import {ChainHelperBase} from '@unique-nft/playgrounds/unique.js';13import type {ILogger} from '@unique-nft/playgrounds/types.js';14import {DevUniqueHelper, SilentLogger, SilentConsole, DevMoonbeamHelper, DevMoonriverHelper, DevAcalaHelper, DevKaruraHelper, DevRelayHelper, DevWestmintHelper, DevStatemineHelper, DevStatemintHelper, DevAstarHelper, DevShidenHelper, DevPolkadexHelper, DevHydraDxHelper} from '@unique/test-utils';15import {dirname} from 'path';16import {fileURLToPath} from 'url';1718chai.config.truncateThreshold = 0;19chai.use(chaiAsPromised);20chai.use(chaiSubset);21export const expect = chai.expect;2223const getTestHash = (filename: string) => crypto.createHash('md5').update(filename).digest('hex');2425export const getTestSeed = (filename: string) => `//Alice+${getTestHash(filename)}`;2627async function usingPlaygroundsGeneral<T extends ChainHelperBase, R = void>(28 helperType: new (logger: ILogger) => T,29 url: string,30 code: (helper: T, privateKey: (seed: string | { filename?: string, url?: string, ignoreFundsPresence?: boolean }) => Promise<IKeyringPair>) => Promise<R>,31): Promise<R> {32 const silentConsole = new SilentConsole();33 silentConsole.enable();3435 const helper = new helperType(new SilentLogger());36 let result;37 try {38 await helper.connect(url);39 const ss58Format = helper.chain.getChainProperties().ss58Format;40 const privateKey = async (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => {41 if(typeof seed === 'string') {42 return helper.util.fromSeed(seed, ss58Format);43 }44 if(seed.url) {45 const {filename} = makeNames(seed.url);46 seed.filename = filename;47 } else if(seed.filename) {48 49 } else {50 throw new Error('no url nor filename set');51 }52 const actualSeed = getTestSeed(seed.filename);53 let account = helper.util.fromSeed(actualSeed, ss58Format);54 55 if(!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {56 console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);57 account = helper.util.fromSeed('//Alice', ss58Format);58 }59 return account;60 };61 result = await code(helper, privateKey);62 }63 finally {64 await helper.disconnect();65 silentConsole.disable();66 }67 return result as any as R;68}6970export const usingPlaygrounds = <R = void>(code: (helper: DevUniqueHelper, privateKey: (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<R>, url: string = config.substrateUrl) => usingPlaygroundsGeneral<DevUniqueHelper, R>(DevUniqueHelper, url, code);7172export const usingWestmintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);7374export const usingStateminePlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemineHelper>(DevWestmintHelper, url, code);7576export const usingStatemintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemintHelper>(DevWestmintHelper, url, code);7778export const usingRelayPlaygrounds = (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevRelayHelper>(DevRelayHelper, url, code);7980export const usingAcalaPlaygrounds = (url: string, code: (helper: DevAcalaHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAcalaHelper>(DevAcalaHelper, url, code);8182export const usingKaruraPlaygrounds = (url: string, code: (helper: DevKaruraHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevKaruraHelper>(DevAcalaHelper, url, code);8384export const usingMoonbeamPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonbeamHelper>(DevMoonbeamHelper, url, code);8586export const usingMoonriverPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonriverHelper>(DevMoonriverHelper, url, code);8788export const usingAstarPlaygrounds = (url: string, code: (helper: DevAstarHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAstarHelper>(DevAstarHelper, url, code);8990export const usingShidenPlaygrounds = (url: string, code: (helper: DevShidenHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevShidenHelper>(DevShidenHelper, url, code);9192export const usingPolkadexPlaygrounds = (url: string, code: (helper: DevPolkadexHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevPolkadexHelper>(DevPolkadexHelper, url, code);9394export const usingHydraDxPlaygrounds = (url: string, code: (helper: DevHydraDxHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevHydraDxHelper>(DevHydraDxHelper, url, code);9596export const MINIMUM_DONOR_FUND = 4_000_000n;97export const DONOR_FUNDING = 4_000_000n;9899100export const LOCKING_PERIOD = 12n; 101export const UNLOCKING_PERIOD = 6n; 102103104export const COLLECTION_HELPER = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';105export const CONTRACT_HELPER = '0x842899ECF380553E8a4de75bF534cdf6fBF64049';106107export enum Pallets {108 Inflation = 'inflation',109 ReFungible = 'refungible',110 Fungible = 'fungible',111 NFT = 'nonfungible',112 Scheduler = 'scheduler',113 UniqueScheduler = 'uniqueScheduler',114 AppPromotion = 'apppromotion',115 CollatorSelection = 'collatorselection',116 Session = 'session',117 Identity = 'identity',118 Democracy = 'democracy',119 Council = 'council',120 FinancialCouncil = 'financialcouncil',121 122 TechnicalCommittee = 'technicalcommittee',123 Fellowship = 'fellowshipcollective',124 Preimage = 'preimage',125 Maintenance = 'maintenance',126 TestUtils = 'testutils',127}128129export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: readonly string[]) {130 const missingPallets = helper.fetchMissingPalletNames(requiredPallets);131132 if(missingPallets.length > 0) {133 const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;134 console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);135 test.skip();136 }137}138139export function itSub(name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: readonly string[] } = {}) {140 (opts.only ? it.only :141 opts.skip ? it.skip : it)(name, async function () {142 await usingPlaygrounds(async (helper, privateKey) => {143 if(opts.requiredPallets) {144 requirePalletsOrSkip(this, helper, opts.requiredPallets);145 }146147 await cb({helper, privateKey});148 });149 });150}151export function itSubIfWithPallet(name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: readonly string[] } = {}) {152 return itSub(name, cb, {requiredPallets: required, ...opts});153}154itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {only: true});155itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {skip: true});156157itSubIfWithPallet.only = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {only: true});158itSubIfWithPallet.skip = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});159itSub.ifWithPallets = itSubIfWithPallet;160161export type SchedKind = 'anon' | 'named';162163export function itSched(164 name: string,165 cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,166 opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},167) {168 itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);169 itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);170}171itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});172itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});173itSched.ifWithPallets = itSchedIfWithPallets;174175function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {176 return itSched(name, cb, {requiredPallets: required, ...opts});177}178179export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {180 (process.env.RUN_XCM_TESTS && !opts.skip181 ? describe182 : describe.skip)(title, fn);183}184185describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});186187export function describeGov(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {188 (process.env.RUN_GOV_TESTS && !opts.skip189 ? describe190 : describe.skip)(title, fn);191}192193describeGov.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeGov(name, fn, {skip: true});194195export function sizeOfInt(i: number) {196 if(i < 0 || i > 0xffffffff) throw new Error('out of range');197 if(i < 0b11_1111) {198 return 1;199 } else if(i < 0b11_1111_1111_1111) {200 return 2;201 } else if(i < 0b11_1111_1111_1111_1111_1111_1111_1111) {202 return 4;203 } else {204 return 5;205 }206}207208const UTF8_ENCODER = new TextEncoder();209export function sizeOfEncodedStr(v: string) {210 const encoded = UTF8_ENCODER.encode(v);211 return sizeOfInt(encoded.length) + encoded.length;212}213214export function sizeOfProperty(prop: {key: string, value: string}) {215 return sizeOfEncodedStr(prop.key) + sizeOfEncodedStr(prop.value);216}217218export function makeNames(url: string) {219 const filename = fileURLToPath(url);220 return {221 filename,222 dirname: dirname(filename),223 };224}