From 381da7372f02210de760e31aa9237cebb1f33ddd Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 11 Aug 2020 23:04:18 +0200 Subject: [PATCH 001/178] persistence service introduced --- tests/network-tests/.env | 4 +- tests/network-tests/package.json | 4 +- .../src/iznik/services/dbService.ts | 106 ++++++++++++++ .../src/iznik/tests/councilSetup.ts | 59 ++++++++ .../fixtures/councilElectionHappyCase.ts | 68 +++++++++ .../tests/fixtures/leaderHiringHappyCase.ts | 126 +++++++++++++++++ .../src/iznik/tests/leaderSetup.ts | 73 ++++++++++ ...entWorkingGroupMintCapacityProposalTest.ts | 51 +++---- .../electionParametersProposalTest.ts | 51 +++---- .../tests/proposals/manageLeaderRoleTest.ts | 55 ++++---- .../tests/proposals/setLeadProposalTest.ts | 51 +++---- .../tests/proposals/spendingProposalTest.ts | 51 +++---- .../iznik/tests/proposals/textProposalTest.ts | 51 +++---- .../iznik/tests/proposals/updateRuntime.ts | 50 +++---- .../proposals/validatorCountProposalTest.ts | 51 +++---- .../workingGroupMintCapacityProposalTest.ts | 51 +++---- .../tests/workingGroup/atLeastValueBugTest.ts | 103 ++++---------- .../workingGroup/manageWorkerAsLeadTest.ts | 93 ++++-------- .../workingGroup/manageWorkerAsWorkerTest.ts | 96 ++++--------- .../workerApplicationHappyCaseTest.ts | 96 ++++--------- .../workerApplicationRejectionCaseTest.ts | 96 ++++--------- .../tests/workingGroup/workerPayoutTest.ts | 132 ++++++------------ tests/network-tests/src/iznik/utils/sender.ts | 21 +-- 23 files changed, 816 insertions(+), 723 deletions(-) create mode 100644 tests/network-tests/src/iznik/services/dbService.ts create mode 100644 tests/network-tests/src/iznik/tests/councilSetup.ts create mode 100644 tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts create mode 100644 tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts create mode 100644 tests/network-tests/src/iznik/tests/leaderSetup.ts diff --git a/tests/network-tests/.env b/tests/network-tests/.env index d18d384452..680e8274c0 100644 --- a/tests/network-tests/.env +++ b/tests/network-tests/.env @@ -1,5 +1,7 @@ # Address of the Joystream node. NODE_URL = ws://127.0.0.1:9944 +# Path to the database for shared keys and nonce +DB_PATH = ../../.tmp/db.json # Account which is expected to provide sufficient funds to test accounts. SUDO_ACCOUNT_URI = //Alice # Amount of members able to buy membership in membership creation test. @@ -49,4 +51,4 @@ SLASH_AMOUNT = 2 # Stake decrement amount for manage working group lead testing scenario STAKE_DECREMENT = 3 # Mint capacity increment value for working gorup mint capacity test -MINT_CAPACITY_INCREMENT = 11 \ No newline at end of file +MINT_CAPACITY_INCREMENT = 11 diff --git a/tests/network-tests/package.json b/tests/network-tests/package.json index 5e9ed9bd34..f1971ac3a7 100644 --- a/tests/network-tests/package.json +++ b/tests/network-tests/package.json @@ -7,7 +7,7 @@ "test": "tap --files src/iznik/tests/proposals/*Test.ts --files src/iznik/tests/workingGroup/*Test.ts -T", "test-migration-constantinople": "tap --files src/rome/tests/romeRuntimeUpgradeTest.ts --files src/constantinople/tests/electingCouncilTest.ts -T", "test-migration-nicaea": "tap --files src/constantinople/tests/proposals/updateRuntimeTest.ts --files src/nicaea/tests/electingCouncilTest.ts -T", - "debug": "tap --files src/iznik/tests/proposals/manageLeaderRoleTest.ts -T", + "debug": "tap --files src/iznik/tests/unknown.unknown src/iznik/tests/councilSetup.ts src/iznik/tests/proposals/*Test.ts src/iznik/tests/leaderSetup.ts src/iznik/tests/workingGroup/*Test.ts -T", "lint": "eslint . --quiet --ext .ts", "checks": "yarn lint && tsc --noEmit --pretty && prettier ./ --check", "format": "prettier ./ --write " @@ -19,9 +19,11 @@ "@polkadot/keyring": "^1.7.0-beta.5", "@rome/types@npm:@joystream/types": "^0.7.0", "@types/bn.js": "^4.11.5", + "@types/lowdb": "^1.0.9", "bn.js": "^4.11.8", "dotenv": "^8.2.0", "fs": "^0.0.1-security", + "lowdb": "^1.0.0", "uuid": "^7.0.3" }, "devDependencies": { diff --git a/tests/network-tests/src/iznik/services/dbService.ts b/tests/network-tests/src/iznik/services/dbService.ts new file mode 100644 index 0000000000..bb2be6e87d --- /dev/null +++ b/tests/network-tests/src/iznik/services/dbService.ts @@ -0,0 +1,106 @@ +import lowdb from 'lowdb/lib/main' +import FileSync from 'lowdb/adapters/FileSync' +import { KeyringPair, KeyringPair$Json } from '@polkadot/keyring/types' +import Keyring from '@polkadot/keyring' +import BN from 'bn.js' + +export class DbService { + private static instance: DbService + + private adapter: any + private db: any + private keyring: Keyring + private dbPath: string + + private static MEMBERS_KEY = 'members' + private static COUNCIL_KEY = 'council' + private static LEADER_KEY = 'leader' + private static NONCE_KEY = 'nonce' + + private constructor() { + this.keyring = new Keyring({ type: 'sr25519' }) + this.dbPath = process.env.DB_PATH! + this.adapter = new FileSync(this.dbPath) + this.db = lowdb(this.adapter) + } + + public static getInstance(): DbService { + if (!DbService.instance) { + DbService.instance = new DbService() + } + return DbService.instance + } + + public setCouncil(council: KeyringPair[]): void { + council.forEach((keyPair, index) => { + this.db.set(`${DbService.COUNCIL_KEY}.${index}`, keyPair.toJson()).write() + }) + } + + public getCouncil(): KeyringPair[] { + const council: KeyringPair[] = [] + const jsonKeyringPairs: KeyringPair$Json[] = this.db.get(DbService.COUNCIL_KEY).value() + jsonKeyringPairs.forEach((jsonKeyringPair) => { + const keyPair: KeyringPair = this.keyring.addFromJson(jsonKeyringPair) + keyPair.decodePkcs8() + council.push(keyPair) + }) + return council + } + + public hasCouncil(): boolean { + return this.db.has(DbService.COUNCIL_KEY).value() + } + + public setMembers(members: KeyringPair[]): void { + members.forEach((keyPair, index) => { + this.db.set(`${DbService.MEMBERS_KEY}.${index}`, keyPair.toJson()).write() + }) + } + + public getMembers(): KeyringPair[] { + const members: KeyringPair[] = [] + const jsonKeyringPairs: KeyringPair$Json[] = this.db.get(DbService.MEMBERS_KEY).value() + jsonKeyringPairs.forEach((jsonKeyringPair) => { + const keyPair: KeyringPair = this.keyring.addFromJson(jsonKeyringPair) + keyPair.decodePkcs8() + members.push(keyPair) + }) + return members + } + + public hasMembers(): boolean { + return this.db.has(DbService.MEMBERS_KEY).value() + } + + public setLeader(leader: KeyringPair, workingGroup: string): void { + this.db.set(`${workingGroup}.${DbService.LEADER_KEY}`, leader.toJson()).write() + } + + public getLeader(workingGroup: string): KeyringPair { + const jsonKeyringPair: KeyringPair$Json = this.db.get(`${workingGroup}.${DbService.LEADER_KEY}`).value() + const keyPair: KeyringPair = this.keyring.addFromJson(jsonKeyringPair) + keyPair.decodePkcs8() + return keyPair + } + + public hasLeader(workingGroup: string): boolean { + return this.db.has(`${workingGroup}.${DbService.LEADER_KEY}`).value() + } + + public setNonce(address: string, nonce: BN): void { + this.db.set(`${DbService.NONCE_KEY}.${address}`, nonce.toString()).write() + } + + public getNonce(address: string): BN { + return new BN(this.db.get(`${DbService.NONCE_KEY}.${address}`).value() as string) + } + + public hasNonce(address: string): boolean { + return this.db.has(`${DbService.NONCE_KEY}.${address}`).value() + } + + public removeNonce(address: string): void { + this.db.unset(`${DbService.NONCE_KEY}.${address}`).write() + } +} diff --git a/tests/network-tests/src/iznik/tests/councilSetup.ts b/tests/network-tests/src/iznik/tests/councilSetup.ts new file mode 100644 index 0000000000..0eecaabd0a --- /dev/null +++ b/tests/network-tests/src/iznik/tests/councilSetup.ts @@ -0,0 +1,59 @@ +import { KeyringPair } from '@polkadot/keyring/types' +import { Keyring, WsProvider } from '@polkadot/api' +import BN from 'bn.js' +import tap from 'tap' +import { registerJoystreamTypes } from '@nicaea/types' +import { PaidTermId } from '@nicaea/types/members' +import { DbService } from '../services/dbService' +import { initConfig } from '../utils/config' +import { ApiWrapper } from '../utils/apiWrapper' +import { Utils } from '../utils/utils' +import { setTestTimeout } from '../utils/setTestTimeout' +import { closeApi } from '../utils/closeApi' +import { CouncilElectionHappyCaseFixture } from './fixtures/councilElectionHappyCase' + +tap.mocha.describe('Electing council scenario', async () => { + initConfig() + registerJoystreamTypes() + + const nodeUrl: string = process.env.NODE_URL! + const sudoUri: string = process.env.SUDO_ACCOUNT_URI! + const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + if (db.hasCouncil()) { + return + } + + const provider = new WsProvider(nodeUrl) + const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) + const sudo: KeyringPair = keyring.addFromUri(sudoUri) + + const N: number = +process.env.MEMBERSHIP_CREATION_N! + const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const K: number = +process.env.COUNCIL_ELECTION_K! + const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) + const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) + + const durationInBlocks = 25 + + setTestTimeout(apiWrapper, durationInBlocks) + + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + await councilElectionHappyCaseFixture.runner(false) + + db.setMembers(m1KeyPairs) + db.setCouncil(m2KeyPairs) + + closeApi(apiWrapper) +}) diff --git a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts new file mode 100644 index 0000000000..36c62a6378 --- /dev/null +++ b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts @@ -0,0 +1,68 @@ +import { Fixture } from './interfaces/fixture' +import { BuyMembershipHappyCaseFixture } from './membershipModule' +import tap from 'tap' +import { ElectCouncilFixture } from './councilElectionModule' +import { ApiWrapper } from '../../utils/apiWrapper' +import { KeyringPair } from '@polkadot/keyring/types' +import { PaidTermId } from '@nicaea/types/members' +import BN from 'bn.js' + +export class CouncilElectionHappyCaseFixture implements Fixture { + private apiWrapper: ApiWrapper + private sudo: KeyringPair + private m1KeyPairs: KeyringPair[] + private m2KeyPairs: KeyringPair[] + private paidTerms: PaidTermId + private K: number + private greaterStake: BN + private lesserStake: BN + + constructor( + apiWrapper: ApiWrapper, + sudo: KeyringPair, + m1KeyPairs: KeyringPair[], + m2KeyPairs: KeyringPair[], + paidTerms: PaidTermId, + K: number, + greaterStake: BN, + lesserStake: BN + ) { + this.apiWrapper = apiWrapper + this.sudo = sudo + this.m1KeyPairs = m1KeyPairs + this.m2KeyPairs = m2KeyPairs + this.paidTerms = paidTerms + this.K = K + this.greaterStake = greaterStake + this.lesserStake = lesserStake + } + + public async runner(expectFailure: boolean): Promise { + const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( + this.apiWrapper, + this.sudo, + this.m1KeyPairs, + this.paidTerms + ) + tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) + + const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( + this.apiWrapper, + this.sudo, + this.m2KeyPairs, + this.paidTerms + ) + tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) + + const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( + this.apiWrapper, + this.m1KeyPairs, + this.m2KeyPairs, + this.K, + this.sudo, + this.greaterStake, + this.lesserStake + ) + tap.test('Elect council', async () => electCouncilFixture.runner(false)) + } +} diff --git a/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts new file mode 100644 index 0000000000..79358fd9b8 --- /dev/null +++ b/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts @@ -0,0 +1,126 @@ +import { Fixture } from './interfaces/fixture' +import tap from 'tap' +import { + AddLeaderOpeningFixture, + ApplyForOpeningFixture, + BeginLeaderApplicationReviewFixture, + FillLeaderOpeningFixture, +} from './workingGroupModule' +import { BuyMembershipHappyCaseFixture } from './membershipModule' +import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' +import { OpeningId } from '@nicaea/types/hiring' +import { KeyringPair } from '@polkadot/keyring/types' +import { PaidTermId } from '@nicaea/types/members' +import BN from 'bn.js' + +export class LeaderHiringHappyCaseFixture implements Fixture { + private apiWrapper: ApiWrapper + private sudo: KeyringPair + private nKeyPairs: KeyringPair[] + private leadKeyPair: KeyringPair[] + private paidTerms: PaidTermId + private applicationStake: BN + private roleStake: BN + private openingActivationDelay: BN + private rewardInterval: BN + private firstRewardInterval: BN + private payoutAmount: BN + private workingGroup: WorkingGroups + + constructor( + apiWrapper: ApiWrapper, + sudo: KeyringPair, + nKeyPairs: KeyringPair[], + leadKeyPair: KeyringPair[], + paidTerms: PaidTermId, + applicationStake: BN, + roleStake: BN, + openingActivationDelay: BN, + rewardInterval: BN, + firstRewardInterval: BN, + payoutAmount: BN, + workingGroup: WorkingGroups + ) { + this.apiWrapper = apiWrapper + this.sudo = sudo + this.nKeyPairs = nKeyPairs + this.leadKeyPair = leadKeyPair + this.paidTerms = paidTerms + this.applicationStake = applicationStake + this.roleStake = roleStake + this.openingActivationDelay = openingActivationDelay + this.rewardInterval = rewardInterval + this.firstRewardInterval = firstRewardInterval + this.payoutAmount = payoutAmount + this.workingGroup = workingGroup + } + + public async runner(expectFailure: boolean): Promise { + const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( + this.apiWrapper, + this.sudo, + this.nKeyPairs, + this.paidTerms + ) + tap.test('Creating a set of members', async () => happyCaseFixture.runner(false)) + + const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( + this.apiWrapper, + this.sudo, + this.leadKeyPair, + this.paidTerms + ) + tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) + + const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( + this.apiWrapper, + this.nKeyPairs, + this.sudo, + this.applicationStake, + this.roleStake, + this.openingActivationDelay, + this.workingGroup + ) + tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) + + let applyForLeaderOpeningFixture: ApplyForOpeningFixture + tap.test('Apply for lead opening', async () => { + applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + this.apiWrapper, + this.leadKeyPair, + this.sudo, + this.applicationStake, + this.roleStake, + addLeaderOpeningFixture.getResult() as OpeningId, + this.workingGroup + ) + await applyForLeaderOpeningFixture.runner(false) + }) + + let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture + tap.test('Begin lead application review', async () => { + beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( + this.apiWrapper, + this.sudo, + addLeaderOpeningFixture.getResult() as OpeningId, + this.workingGroup + ) + await beginLeaderApplicationReviewFixture.runner(false) + }) + + let fillLeaderOpeningFixture: FillLeaderOpeningFixture + tap.test('Fill lead opening', async () => { + fillLeaderOpeningFixture = new FillLeaderOpeningFixture( + this.apiWrapper, + this.leadKeyPair, + this.sudo, + addLeaderOpeningFixture.getResult() as OpeningId, + this.firstRewardInterval, + this.rewardInterval, + this.payoutAmount, + this.workingGroup + ) + await fillLeaderOpeningFixture.runner(false) + }) + } +} diff --git a/tests/network-tests/src/iznik/tests/leaderSetup.ts b/tests/network-tests/src/iznik/tests/leaderSetup.ts new file mode 100644 index 0000000000..f6a09856b5 --- /dev/null +++ b/tests/network-tests/src/iznik/tests/leaderSetup.ts @@ -0,0 +1,73 @@ +import { initConfig } from '../utils/config' +import { registerJoystreamTypes } from '@nicaea/types' +import { closeApi } from '../utils/closeApi' +import { ApiWrapper, WorkingGroups } from '../utils/apiWrapper' +import { WsProvider, Keyring } from '@polkadot/api' +import { KeyringPair } from '@polkadot/keyring/types' +import { setTestTimeout } from '../utils/setTestTimeout' +import BN from 'bn.js' +import tap from 'tap' +import { Utils } from '../utils/utils' +import { PaidTermId } from '@nicaea/types/members' +import { DbService } from '../services/dbService' +import { LeaderHiringHappyCaseFixture } from './fixtures/leaderHiringHappyCase' + +tap.mocha.describe('Worker application happy case scenario', async () => { + initConfig() + registerJoystreamTypes() + + const nodeUrl: string = process.env.NODE_URL! + const sudoUri: string = process.env.SUDO_ACCOUNT_URI! + const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) + const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + return + } + + const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const N: number = +process.env.WORKING_GROUP_N! + const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) + + const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) + const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) + const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) + const rewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) + const payoutAmount: BN = new BN(process.env.PAYOUT_AMOUNT!) + const durationInBlocks = 48 + const openingActivationDelay: BN = new BN(0) + + setTestTimeout(apiWrapper, durationInBlocks) + + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( + apiWrapper, + sudo, + nKeyPairs, + leadKeyPair, + paidTerms, + applicationStake, + roleStake, + openingActivationDelay, + rewardInterval, + firstRewardInterval, + payoutAmount, + WorkingGroups.StorageWorkingGroup + ) + await leaderHiringHappyCaseFixture.runner(false) + + db.setMembers(nKeyPairs) + db.setLeader(leadKeyPair[0], apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + + // const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + // apiWrapper, + // leadKeyPair, + // sudo, + // WorkingGroups.StorageWorkingGroup + // ) + // tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + + closeApi(apiWrapper) +}) diff --git a/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts index de343f7298..61fe40ad68 100644 --- a/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts @@ -8,10 +8,10 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { ContentWorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { Utils } from '../../utils/utils' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Validator count proposal scenario', async () => { initConfig() @@ -23,10 +23,11 @@ tap.mocha.describe('Validator count proposal scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -38,32 +39,22 @@ tap.mocha.describe('Validator count proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const contentWorkingGroupMintCapacityProposalFixture: ContentWorkingGroupMintCapacityProposalFixture = new ContentWorkingGroupMintCapacityProposalFixture( apiWrapper, diff --git a/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts index 56fc3e9a10..153d9b7d39 100644 --- a/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts @@ -7,11 +7,11 @@ import tap from 'tap' import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { Utils } from '../../utils/utils' import { ElectionParametersProposalFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Election parameters proposal scenario', async () => { initConfig() @@ -23,10 +23,11 @@ tap.mocha.describe('Election parameters proposal scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -37,32 +38,22 @@ tap.mocha.describe('Election parameters proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const electionParametersProposalFixture: ElectionParametersProposalFixture = new ElectionParametersProposalFixture( apiWrapper, diff --git a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts index 854c37d520..2ac3b27f9d 100644 --- a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts @@ -8,7 +8,6 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { BeginWorkingGroupLeaderApplicationReviewFixture, CreateWorkingGroupLeaderOpeningFixture, @@ -33,6 +32,8 @@ import { Utils } from '../../utils/utils' import { PaidTermId } from '@nicaea/types/members' import { OpeningId } from '@nicaea/types/hiring' import { ProposalId } from '@nicaea/types/proposals' +import { DbService } from '../../services/dbService' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' tap.mocha.describe('Set lead proposal scenario', async () => { initConfig() @@ -41,13 +42,15 @@ tap.mocha.describe('Set lead proposal scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) @@ -66,21 +69,22 @@ tap.mocha.describe('Set lead proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const leaderMembershipFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( apiWrapper, @@ -90,17 +94,6 @@ tap.mocha.describe('Set lead proposal scenario', async () => { ) tap.test('Buy membership for lead', async () => leaderMembershipFixture.runner(false)) - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) - const createWorkingGroupLeaderOpeningFixture: CreateWorkingGroupLeaderOpeningFixture = new CreateWorkingGroupLeaderOpeningFixture( apiWrapper, m1KeyPairs, @@ -238,13 +231,13 @@ tap.mocha.describe('Set lead proposal scenario', async () => { let expectLeaderStakeDecreasedFixture: ExpectLeaderStakeDecreasedFixture tap.test('Approve decreased leader stake', async () => { newStake = applicationStake.sub(stakeDecrement) - voteForFillLeaderProposalFixture = new VoteForProposalFixture( + voteForDecreaseStakeProposal = new VoteForProposalFixture( apiWrapper, m2KeyPairs, sudo, decreaseLeaderStakeProposalFixture.getResult() as ProposalId ) - voteForFillLeaderProposalFixture.runner(false) + voteForDecreaseStakeProposal.runner(false) expectLeaderStakeDecreasedFixture = new ExpectLeaderStakeDecreasedFixture( apiWrapper, newStake, diff --git a/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts index a5dfeed3c8..2751c15901 100644 --- a/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts @@ -8,10 +8,10 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { SetLeadProposalFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Set lead proposal scenario', async () => { initConfig() @@ -23,10 +23,11 @@ tap.mocha.describe('Set lead proposal scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -37,32 +38,22 @@ tap.mocha.describe('Set lead proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const setLeadProposalFixture: SetLeadProposalFixture = new SetLeadProposalFixture( apiWrapper, diff --git a/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts index 070a2b2beb..a0ab46786c 100644 --- a/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts @@ -8,10 +8,10 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { SpendingProposalFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Spending proposal scenario', async () => { initConfig() @@ -23,10 +23,11 @@ tap.mocha.describe('Spending proposal scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -38,32 +39,22 @@ tap.mocha.describe('Spending proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const spendingProposalFixture: SpendingProposalFixture = new SpendingProposalFixture( apiWrapper, diff --git a/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts index 69705c9388..0e0fbad6b9 100644 --- a/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts @@ -8,10 +8,10 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { TextProposalFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Text proposal scenario', async () => { initConfig() @@ -23,10 +23,11 @@ tap.mocha.describe('Text proposal scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -36,32 +37,22 @@ tap.mocha.describe('Text proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const textProposalFixture: TextProposalFixture = new TextProposalFixture(apiWrapper, m1KeyPairs, m2KeyPairs, sudo) tap.test('Text proposal test', async () => textProposalFixture.runner(false)) diff --git a/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts b/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts index 25595c83ee..476911bb3b 100644 --- a/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts +++ b/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts @@ -9,9 +9,10 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { UpdateRuntimeFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Update runtime scenario', async () => { initConfig() @@ -23,10 +24,11 @@ tap.mocha.describe('Update runtime scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -36,32 +38,22 @@ tap.mocha.describe('Update runtime scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const updateRuntimeFixture: UpdateRuntimeFixture = new UpdateRuntimeFixture(apiWrapper, m1KeyPairs, m2KeyPairs, sudo) tap.test('Upgrade runtime', async () => updateRuntimeFixture.runner(false)) diff --git a/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts index 7bbe0fc9ae..e3e270e5fa 100644 --- a/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts @@ -8,10 +8,10 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { ValidatorCountProposalFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Validator count proposal scenario', async () => { initConfig() @@ -23,10 +23,11 @@ tap.mocha.describe('Validator count proposal scenario', async () => { const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -37,32 +38,22 @@ tap.mocha.describe('Validator count proposal scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const validatorCountProposalFixture: ValidatorCountProposalFixture = new ValidatorCountProposalFixture( apiWrapper, diff --git a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts index fa651aa1b6..0dcf72a1a4 100644 --- a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts @@ -8,12 +8,12 @@ import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { VoteForProposalFixture, WorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' import { ExpectMintCapacityChangedFixture } from '../fixtures/workingGroupModule' import { PaidTermId } from '@nicaea/types/members' import { ProposalId } from '@nicaea/types/proposals' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { DbService } from '../../services/dbService' tap.mocha.describe('Set storage working group mint capacity scenario', async () => { initConfig() @@ -25,10 +25,11 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async () const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) + const db: DbService = DbService.getInstance() const N: number = +process.env.MEMBERSHIP_CREATION_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! @@ -39,32 +40,22 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async () setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( + apiWrapper, + sudo, + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake + ) + councilElectionHappyCaseFixture.runner(false) + } const newMintCapacity: BN = (await apiWrapper.getWorkingGroupMintCapacity(WorkingGroups.StorageWorkingGroup)).add( mintCapacityIncrement diff --git a/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts index 3a54b1e9f2..82164429fe 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts @@ -5,20 +5,13 @@ import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' import { KeyringPair } from '@polkadot/keyring/types' import { setTestTimeout } from '../../utils/setTestTimeout' -import { - AddLeaderOpeningFixture, - AddWorkerOpeningFixture, - ApplyForOpeningFixture, - BeginLeaderApplicationReviewFixture, - FillLeaderOpeningFixture, - LeaveRoleFixture, -} from '../fixtures/workingGroupModule' +import { AddWorkerOpeningFixture, LeaveRoleFixture } from '../fixtures/workingGroupModule' import BN from 'bn.js' import tap from 'tap' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' +import { DbService } from '../../services/dbService' +import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() @@ -27,12 +20,14 @@ tap.mocha.describe('Worker application happy case scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.WORKING_GROUP_N! - const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) @@ -47,72 +42,26 @@ tap.mocha.describe('Worker application happy case scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - nKeyPairs, - paidTerms - ) - tap.test('Creating a set of members', async () => happyCaseFixture.runner(false)) - - const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - leadKeyPair, - paidTerms - ) - tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) - - const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( - apiWrapper, - nKeyPairs, - sudo, - applicationStake, - roleStake, - openingActivationDelay, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) - - let applyForLeaderOpeningFixture: ApplyForOpeningFixture - tap.test('Apply for lead opening', async () => { - applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + nKeyPairs = db.getMembers() + leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + } else { + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( apiWrapper, - leadKeyPair, sudo, + nKeyPairs, + leadKeyPair, + paidTerms, applicationStake, roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await applyForLeaderOpeningFixture.runner(false) - }) - - let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture - tap.test('Begin lead application review', async () => { - beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( - apiWrapper, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await beginLeaderApplicationReviewFixture.runner(false) - }) - - let fillLeaderOpeningFixture: FillLeaderOpeningFixture - tap.test('Fill lead opening', async () => { - fillLeaderOpeningFixture = new FillLeaderOpeningFixture( - apiWrapper, - leadKeyPair, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - firstRewardInterval, + openingActivationDelay, rewardInterval, + firstRewardInterval, payoutAmount, WorkingGroups.StorageWorkingGroup ) - await fillLeaderOpeningFixture.runner(false) - }) + await leaderHiringHappyCaseFixture.runner(false) + } const addWorkerOpeningWithoutStakeFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture( apiWrapper, @@ -144,13 +93,15 @@ tap.mocha.describe('Worker application happy case scenario', async () => { addWorkerOpeningWithoutUnstakingPeriodFixture.runner(true) ) - const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - apiWrapper, - leadKeyPair, - sudo, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + apiWrapper, + leadKeyPair, + sudo, + WorkingGroups.StorageWorkingGroup + ) + tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + } closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts index 01500e6b86..f709e3faac 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts @@ -18,12 +18,13 @@ import { SlashFixture, TerminateRoleFixture, } from '../fixtures/workingGroupModule' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' import BN from 'bn.js' import tap from 'tap' import { PaidTermId } from '@nicaea/types/members' import { OpeningId } from '@nicaea/types/hiring' +import { DbService } from '../../services/dbService' +import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Manage worker as worker scenario', async () => { initConfig() @@ -32,12 +33,14 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.WORKING_GROUP_N! - const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) @@ -52,72 +55,26 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - nKeyPairs, - paidTerms - ) - tap.test('Creating a set of members', async () => happyCaseFixture.runner(false)) - - const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - leadKeyPair, - paidTerms - ) - tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) - - const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( - apiWrapper, - nKeyPairs, - sudo, - applicationStake, - roleStake, - openingActivationDelay, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) - - let applyForLeaderOpeningFixture: ApplyForOpeningFixture - tap.test('Apply for lead opening', async () => { - applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + nKeyPairs = db.getMembers() + leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + } else { + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( apiWrapper, - leadKeyPair, sudo, + nKeyPairs, + leadKeyPair, + paidTerms, applicationStake, roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await applyForLeaderOpeningFixture.runner(false) - }) - - let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture - tap.test('Begin lead application review', async () => { - beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( - apiWrapper, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await beginLeaderApplicationReviewFixture.runner(false) - }) - - let fillLeaderOpeningFixture: FillLeaderOpeningFixture - tap.test('Fill lead opening', async () => { - fillLeaderOpeningFixture = new FillLeaderOpeningFixture( - apiWrapper, - leadKeyPair, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - firstRewardInterval, + openingActivationDelay, rewardInterval, + firstRewardInterval, payoutAmount, WorkingGroups.StorageWorkingGroup ) - await fillLeaderOpeningFixture.runner(false) - }) + await leaderHiringHappyCaseFixture.runner(false) + } const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture( apiWrapper, @@ -269,13 +226,15 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { ) tap.test('Terminate worker role', async () => terminateRoleFixture.runner(false)) - const newLeaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - apiWrapper, - leadKeyPair, - sudo, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Leaving lead role', async () => newLeaveRoleFixture.runner(false)) + if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + apiWrapper, + leadKeyPair, + sudo, + WorkingGroups.StorageWorkingGroup + ) + tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + } closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts index b032842d14..4c9cd833a2 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts @@ -6,23 +6,21 @@ import { WsProvider, Keyring } from '@polkadot/api' import { KeyringPair } from '@polkadot/keyring/types' import { setTestTimeout } from '../../utils/setTestTimeout' import { - AddLeaderOpeningFixture, AddWorkerOpeningFixture, ApplyForOpeningFixture, BeginApplicationReviewFixture, - BeginLeaderApplicationReviewFixture, - FillLeaderOpeningFixture, FillOpeningFixture, IncreaseStakeFixture, LeaveRoleFixture, UpdateRewardAccountFixture, } from '../fixtures/workingGroupModule' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' import BN from 'bn.js' import tap from 'tap' import { PaidTermId } from '@nicaea/types/members' import { OpeningId } from '@nicaea/types/hiring' +import { DbService } from '../../services/dbService' +import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Manage worker as worker scenario', async () => { initConfig() @@ -31,12 +29,14 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.WORKING_GROUP_N! - const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) @@ -51,72 +51,26 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - nKeyPairs, - paidTerms - ) - tap.test('Creating a set of members', async () => happyCaseFixture.runner(false)) - - const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - leadKeyPair, - paidTerms - ) - tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) - - const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( - apiWrapper, - nKeyPairs, - sudo, - applicationStake, - roleStake, - openingActivationDelay, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) - - let applyForLeaderOpeningFixture: ApplyForOpeningFixture - tap.test('Apply for lead opening', async () => { - applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + nKeyPairs = db.getMembers() + leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + } else { + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( apiWrapper, - leadKeyPair, sudo, + nKeyPairs, + leadKeyPair, + paidTerms, applicationStake, roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await applyForLeaderOpeningFixture.runner(false) - }) - - let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture - tap.test('Begin lead application review', async () => { - beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( - apiWrapper, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await beginLeaderApplicationReviewFixture.runner(false) - }) - - let fillLeaderOpeningFixture: FillLeaderOpeningFixture - tap.test('Fill lead opening', async () => { - fillLeaderOpeningFixture = new FillLeaderOpeningFixture( - apiWrapper, - leadKeyPair, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - firstRewardInterval, + openingActivationDelay, rewardInterval, + firstRewardInterval, payoutAmount, WorkingGroups.StorageWorkingGroup ) - await fillLeaderOpeningFixture.runner(false) - }) + await leaderHiringHappyCaseFixture.runner(false) + } const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture( apiWrapper, @@ -199,13 +153,15 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { ) tap.test('Update role account', async () => updateRoleAccountFixture.runner(false)) - const newLeaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - apiWrapper, - leadKeyPair, - sudo, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Leaving lead role', async () => newLeaveRoleFixture.runner(false)) + if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + apiWrapper, + leadKeyPair, + sudo, + WorkingGroups.StorageWorkingGroup + ) + tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + } closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts index 62c9595042..767999d1bd 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts @@ -7,21 +7,19 @@ import { KeyringPair } from '@polkadot/keyring/types' import { setTestTimeout } from '../../utils/setTestTimeout' import BN from 'bn.js' import tap from 'tap' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' import { - AddLeaderOpeningFixture, AddWorkerOpeningFixture, ApplyForOpeningFixture, BeginApplicationReviewFixture, - BeginLeaderApplicationReviewFixture, - FillLeaderOpeningFixture, FillOpeningFixture, LeaveRoleFixture, WithdrawApplicationFixture, } from '../fixtures/workingGroupModule' import { PaidTermId } from '@nicaea/types/members' import { OpeningId } from '@nicaea/types/hiring' +import { DbService } from '../../services/dbService' +import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() @@ -30,12 +28,14 @@ tap.mocha.describe('Worker application happy case scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.WORKING_GROUP_N! - const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) @@ -50,72 +50,26 @@ tap.mocha.describe('Worker application happy case scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - nKeyPairs, - paidTerms - ) - tap.test('Creating a set of members', async () => happyCaseFixture.runner(false)) - - const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - leadKeyPair, - paidTerms - ) - tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) - - const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( - apiWrapper, - nKeyPairs, - sudo, - applicationStake, - roleStake, - openingActivationDelay, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) - - let applyForLeaderOpeningFixture: ApplyForOpeningFixture - tap.test('Apply for lead opening', async () => { - applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + nKeyPairs = db.getMembers() + leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + } else { + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( apiWrapper, - leadKeyPair, sudo, + nKeyPairs, + leadKeyPair, + paidTerms, applicationStake, roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await applyForLeaderOpeningFixture.runner(false) - }) - - let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture - tap.test('Begin lead application review', async () => { - beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( - apiWrapper, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await beginLeaderApplicationReviewFixture.runner(false) - }) - - let fillLeaderOpeningFixture: FillLeaderOpeningFixture - tap.test('Fill lead opening', async () => { - fillLeaderOpeningFixture = new FillLeaderOpeningFixture( - apiWrapper, - leadKeyPair, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - firstRewardInterval, + openingActivationDelay, rewardInterval, + firstRewardInterval, payoutAmount, WorkingGroups.StorageWorkingGroup ) - await fillLeaderOpeningFixture.runner(false) - }) + await leaderHiringHappyCaseFixture.runner(false) + } const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture( apiWrapper, @@ -194,13 +148,15 @@ tap.mocha.describe('Worker application happy case scenario', async () => { await fillOpeningFixture.runner(false) }) - const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - apiWrapper, - leadKeyPair, - sudo, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + apiWrapper, + leadKeyPair, + sudo, + WorkingGroups.StorageWorkingGroup + ) + tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + } closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts index 243a29face..0d071b0702 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts @@ -7,20 +7,18 @@ import { KeyringPair } from '@polkadot/keyring/types' import { setTestTimeout } from '../../utils/setTestTimeout' import BN from 'bn.js' import tap from 'tap' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' import { AcceptApplicationsFixture, - AddLeaderOpeningFixture, AddWorkerOpeningFixture, ApplyForOpeningFixture, - BeginLeaderApplicationReviewFixture, - FillLeaderOpeningFixture, LeaveRoleFixture, TerminateApplicationsFixture, } from '../fixtures/workingGroupModule' import { PaidTermId } from '@nicaea/types/members' import { OpeningId } from '@nicaea/types/hiring' +import { DbService } from '../../services/dbService' +import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() @@ -29,12 +27,14 @@ tap.mocha.describe('Worker application happy case scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.WORKING_GROUP_N! - const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const nonMemberKeyPairs = Utils.createKeyPairs(keyring, N) @@ -51,72 +51,26 @@ tap.mocha.describe('Worker application happy case scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - nKeyPairs, - paidTerms - ) - tap.test('Creating a set of members', async () => happyCaseFixture.runner(false)) - - const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - leadKeyPair, - paidTerms - ) - tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) - - const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( - apiWrapper, - nKeyPairs, - sudo, - applicationStake, - roleStake, - leadOpeningActivationDelay, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) - - let applyForLeaderOpeningFixture: ApplyForOpeningFixture - tap.test('Apply for lead opening', async () => { - applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + nKeyPairs = db.getMembers() + leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + } else { + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( apiWrapper, - leadKeyPair, sudo, + nKeyPairs, + leadKeyPair, + paidTerms, applicationStake, roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await applyForLeaderOpeningFixture.runner(false) - }) - - let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture - tap.test('Begin lead application review', async () => { - beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( - apiWrapper, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await beginLeaderApplicationReviewFixture.runner(false) - }) - - let fillLeaderOpeningFixture: FillLeaderOpeningFixture - tap.test('Fill lead opening', async () => { - fillLeaderOpeningFixture = new FillLeaderOpeningFixture( - apiWrapper, - leadKeyPair, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - firstRewardInterval, + leadOpeningActivationDelay, rewardInterval, + firstRewardInterval, payoutAmount, WorkingGroups.StorageWorkingGroup ) - await fillLeaderOpeningFixture.runner(false) - }) + await leaderHiringHappyCaseFixture.runner(false) + } const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture( apiWrapper, @@ -194,13 +148,15 @@ tap.mocha.describe('Worker application happy case scenario', async () => { ) tap.test('Terminate worker applicaitons', async () => terminateApplicationsFixture.runner(false)) - const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - apiWrapper, - leadKeyPair, - sudo, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + apiWrapper, + leadKeyPair, + sudo, + WorkingGroups.StorageWorkingGroup + ) + tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + } closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts index d662f66db3..623b2ec869 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts @@ -6,26 +6,24 @@ import { WsProvider, Keyring } from '@polkadot/api' import { KeyringPair } from '@polkadot/keyring/types' import { setTestTimeout } from '../../utils/setTestTimeout' import { - AddLeaderOpeningFixture, AddWorkerOpeningFixture, ApplyForOpeningFixture, AwaitPayoutFixture, BeginApplicationReviewFixture, - BeginLeaderApplicationReviewFixture, ExpectMintCapacityChangedFixture, - FillLeaderOpeningFixture, FillOpeningFixture, LeaveRoleFixture, } from '../fixtures/workingGroupModule' import BN from 'bn.js' import tap from 'tap' -import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' -import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { VoteForProposalFixture, WorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' import { PaidTermId } from '@nicaea/types/members' import { OpeningId } from '@nicaea/types/hiring' import { ProposalId } from '@nicaea/types/proposals' +import { DbService } from '../../services/dbService' +import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' +import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() @@ -34,13 +32,15 @@ tap.mocha.describe('Worker application happy case scenario', async () => { const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) + const db: DbService = DbService.getInstance() + const provider = new WsProvider(nodeUrl) const apiWrapper: ApiWrapper = await ApiWrapper.create(provider) const sudo: KeyringPair = keyring.addFromUri(sudoUri) const N: number = +process.env.WORKING_GROUP_N! - const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) + let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) @@ -61,91 +61,43 @@ tap.mocha.describe('Worker application happy case scenario', async () => { setTestTimeout(apiWrapper, durationInBlocks) - const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m1KeyPairs, - paidTerms - ) - tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) - - const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - m2KeyPairs, - paidTerms - ) - tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) - - const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( - apiWrapper, - m1KeyPairs, - m2KeyPairs, - K, - sudo, - greaterStake, - lesserStake - ) - tap.test('Elect council', async () => electCouncilFixture.runner(false)) - - const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( - apiWrapper, - sudo, - leadKeyPair, - paidTerms - ) - tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false)) - - const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture( - apiWrapper, - m1KeyPairs, - sudo, - applicationStake, - roleStake, - openingActivationDelay, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false)) - - let applyForLeaderOpeningFixture: ApplyForOpeningFixture - tap.test('Apply for lead opening', async () => { - applyForLeaderOpeningFixture = new ApplyForOpeningFixture( + if (db.hasCouncil()) { + m1KeyPairs = db.getMembers() + m2KeyPairs = db.getCouncil() + } else { + const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture( apiWrapper, - leadKeyPair, sudo, - applicationStake, - roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup + m1KeyPairs, + m2KeyPairs, + paidTerms, + K, + greaterStake, + lesserStake ) - await applyForLeaderOpeningFixture.runner(false) - }) - - let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture - tap.test('Begin lead application review', async () => { - beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( + councilElectionHappyCaseFixture.runner(false) + } + + if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + m1KeyPairs = db.getMembers() + leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) + } else { + const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture( apiWrapper, sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - WorkingGroups.StorageWorkingGroup - ) - await beginLeaderApplicationReviewFixture.runner(false) - }) - - let fillLeaderOpeningFixture: FillLeaderOpeningFixture - tap.test('Fill lead opening', async () => { - fillLeaderOpeningFixture = new FillLeaderOpeningFixture( - apiWrapper, + m1KeyPairs, leadKeyPair, - sudo, - addLeaderOpeningFixture.getResult() as OpeningId, - leaderFirstRewardInterval, + paidTerms, + applicationStake, + roleStake, + openingActivationDelay, leaderRewardInterval, + leaderFirstRewardInterval, payoutAmount, WorkingGroups.StorageWorkingGroup ) - await fillLeaderOpeningFixture.runner(false) - }) + await leaderHiringHappyCaseFixture.runner(false) + } const workingGroupMintCapacityProposalFixture: WorkingGroupMintCapacityProposalFixture = new WorkingGroupMintCapacityProposalFixture( apiWrapper, @@ -234,13 +186,15 @@ tap.mocha.describe('Worker application happy case scenario', async () => { ) tap.test('Await worker payout', async () => awaitPayoutFixture.runner(false)) - const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - apiWrapper, - leadKeyPair, - sudo, - WorkingGroups.StorageWorkingGroup - ) - tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) { + const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( + apiWrapper, + leadKeyPair, + sudo, + WorkingGroups.StorageWorkingGroup + ) + tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) + } closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/utils/sender.ts b/tests/network-tests/src/iznik/utils/sender.ts index 2fba9b887c..4c8f1bd31b 100644 --- a/tests/network-tests/src/iznik/utils/sender.ts +++ b/tests/network-tests/src/iznik/utils/sender.ts @@ -1,33 +1,36 @@ import BN from 'bn.js' -import { ApiPromise } from '@polkadot/api' +import { ApiPromise, Keyring } from '@polkadot/api' import { Index } from '@polkadot/types/interfaces' import { SubmittableExtrinsic } from '@polkadot/api/types' import { KeyringPair } from '@polkadot/keyring/types' +import { DbService } from '../services/dbService' export class Sender { private readonly api: ApiPromise - private static nonceMap: Map = new Map() + private db: DbService = DbService.getInstance() constructor(api: ApiPromise) { this.api = api } private async getNonce(address: string): Promise { - let oncahinNonce: BN = new BN(0) - if (!Sender.nonceMap.get(address)) { - oncahinNonce = await this.api.query.system.accountNonce(address) + let oncahinNonce: BN = await this.api.query.system.accountNonce(address) + let nonce: BN + if (!this.db.hasNonce(address)) { + nonce = oncahinNonce + } else { + nonce = this.db.getNonce(address) } - let nonce: BN | undefined = Sender.nonceMap.get(address) - if (!nonce) { + if (oncahinNonce.gt(nonce)) { nonce = oncahinNonce } const nextNonce: BN = nonce.addn(1) - Sender.nonceMap.set(address, nextNonce) + this.db.setNonce(address, nextNonce) return nonce } private clearNonce(address: string): void { - Sender.nonceMap.delete(address) + this.db.removeNonce(address) } public async signAndSend( From bf7870dd0bd89b98135fc7235cb32b4694994f0a Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 11 Aug 2020 23:12:01 +0200 Subject: [PATCH 002/178] liter errors fixed --- .../src/iznik/tests/fixtures/councilElectionHappyCase.ts | 8 ++++---- tests/network-tests/src/iznik/utils/sender.ts | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts index 36c62a6378..ae817083d4 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts @@ -13,7 +13,7 @@ export class CouncilElectionHappyCaseFixture implements Fixture { private m1KeyPairs: KeyringPair[] private m2KeyPairs: KeyringPair[] private paidTerms: PaidTermId - private K: number + private k: number private greaterStake: BN private lesserStake: BN @@ -23,7 +23,7 @@ export class CouncilElectionHappyCaseFixture implements Fixture { m1KeyPairs: KeyringPair[], m2KeyPairs: KeyringPair[], paidTerms: PaidTermId, - K: number, + k: number, greaterStake: BN, lesserStake: BN ) { @@ -32,7 +32,7 @@ export class CouncilElectionHappyCaseFixture implements Fixture { this.m1KeyPairs = m1KeyPairs this.m2KeyPairs = m2KeyPairs this.paidTerms = paidTerms - this.K = K + this.k = k this.greaterStake = greaterStake this.lesserStake = lesserStake } @@ -58,7 +58,7 @@ export class CouncilElectionHappyCaseFixture implements Fixture { this.apiWrapper, this.m1KeyPairs, this.m2KeyPairs, - this.K, + this.k, this.sudo, this.greaterStake, this.lesserStake diff --git a/tests/network-tests/src/iznik/utils/sender.ts b/tests/network-tests/src/iznik/utils/sender.ts index 4c8f1bd31b..7513da833c 100644 --- a/tests/network-tests/src/iznik/utils/sender.ts +++ b/tests/network-tests/src/iznik/utils/sender.ts @@ -14,7 +14,7 @@ export class Sender { } private async getNonce(address: string): Promise { - let oncahinNonce: BN = await this.api.query.system.accountNonce(address) + const oncahinNonce: BN = await this.api.query.system.accountNonce(address) let nonce: BN if (!this.db.hasNonce(address)) { nonce = oncahinNonce From e691b12394b13f22613ac26ec584321f1b86823e Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 11 Aug 2020 23:40:32 +0200 Subject: [PATCH 003/178] linter error fixed, conflicting rules disabled --- tests/network-tests/.eslintrc.js | 11 +++++++++-- .../src/iznik/tests/fixtures/proposalsModule.ts | 7 ++++++- .../tests/workingGroup/impl/workingGroupModule.ts | 2 -- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/network-tests/.eslintrc.js b/tests/network-tests/.eslintrc.js index 50ad064e90..c0137bb72e 100644 --- a/tests/network-tests/.eslintrc.js +++ b/tests/network-tests/.eslintrc.js @@ -1,5 +1,12 @@ module.exports = { env: { node: true, - } -} \ No newline at end of file + }, + rules: { + 'no-async-promise-executor': 'off', + 'no-useless-return': 'off', + 'new-cap': 'off', + // Disabled because of the false positive bug: https://github.com/eslint/eslint/issues/11899 + 'require-atomic-updates': 'off', + } +} diff --git a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts index 8cefcbb2bf..7d296075a5 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts @@ -14,7 +14,12 @@ import { OpeningId, StakingPolicy, } from '@alexandria/types/hiring' -import { RewardPolicy, SlashingTerms, WorkerId, WorkingGroupOpeningPolicyCommitment } from '@alexandria/types/working-group' +import { + RewardPolicy, + SlashingTerms, + WorkerId, + WorkingGroupOpeningPolicyCommitment, +} from '@alexandria/types/working-group' import { WorkingGroup } from '@alexandria/types/common' export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { diff --git a/tests/network-tests/src/nicaea/tests/workingGroup/impl/workingGroupModule.ts b/tests/network-tests/src/nicaea/tests/workingGroup/impl/workingGroupModule.ts index ae38c63cbd..e594cb303d 100644 --- a/tests/network-tests/src/nicaea/tests/workingGroup/impl/workingGroupModule.ts +++ b/tests/network-tests/src/nicaea/tests/workingGroup/impl/workingGroupModule.ts @@ -358,8 +358,6 @@ export async function updateRoleAccount( newRoleAccount === createdAccount.address, `Unexpected role account ${newRoleAccount}, expected ${createdAccount.address}` ) - - membersKeyPairs[0] = createdAccount } export async function terminateApplications( From 65b7f9596ccdba204abfdbfab1e857eb1d8bd199 Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Thu, 13 Aug 2020 09:26:40 +0200 Subject: [PATCH 004/178] altered object creation to match new api --- tests/network-tests/package.json | 10 +- .../tests/council/electingCouncilTest.ts | 2 +- .../src/iznik/tests/councilSetup.ts | 7 +- .../fixtures/councilElectionHappyCase.ts | 2 +- .../tests/fixtures/leaderHiringHappyCase.ts | 4 +- .../iznik/tests/fixtures/membershipModule.ts | 2 +- .../src/iznik/tests/leaderSetup.ts | 5 +- .../membership/membershipCreationTest.ts | 2 +- ...entWorkingGroupMintCapacityProposalTest.ts | 2 +- .../electionParametersProposalTest.ts | 2 +- .../tests/proposals/manageLeaderRoleTest.ts | 6 +- .../tests/proposals/setLeadProposalTest.ts | 2 +- .../tests/proposals/spendingProposalTest.ts | 2 +- .../iznik/tests/proposals/textProposalTest.ts | 2 +- .../iznik/tests/proposals/updateRuntime.ts | 2 +- .../proposals/validatorCountProposalTest.ts | 2 +- .../workingGroupMintCapacityProposalTest.ts | 4 +- .../tests/workingGroup/atLeastValueBugTest.ts | 2 +- .../workingGroup/manageWorkerAsLeadTest.ts | 4 +- .../workingGroup/manageWorkerAsWorkerTest.ts | 4 +- .../workerApplicationHappyCaseTest.ts | 4 +- .../workerApplicationRejectionCaseTest.ts | 4 +- .../tests/workingGroup/workerPayoutTest.ts | 6 +- .../src/iznik/utils/apiWrapper.ts | 133 +++++++++--------- tests/network-tests/tsconfig.json | 6 +- 25 files changed, 111 insertions(+), 110 deletions(-) diff --git a/tests/network-tests/package.json b/tests/network-tests/package.json index bfb14dae35..3e24c44258 100644 --- a/tests/network-tests/package.json +++ b/tests/network-tests/package.json @@ -4,10 +4,10 @@ "license": "GPL-3.0-only", "scripts": { "build": "tsc --build tsconfig.json", - "test": "tap --files src/iznik/tests/proposals/*Test.ts --files src/iznik/tests/workingGroup/*Test.ts -T", + "test": "tap --files src/iznik/tests/unknown.unknown src/iznik/tests/councilSetup.ts src/iznik/tests/proposals/*Test.ts src/iznik/tests/leaderSetup.ts src/iznik/tests/workingGroup/*Test.ts -T", "test-migration-constantinople": "tap --files src/rome/tests/romeRuntimeUpgradeTest.ts --files src/constantinople/tests/electingCouncilTest.ts -T", "test-migration-nicaea": "tap --files src/constantinople/tests/proposals/updateRuntimeTest.ts --files src/nicaea/tests/electingCouncilTest.ts -T", - "debug": "tap --files src/iznik/tests/unknown.unknown src/iznik/tests/councilSetup.ts src/iznik/tests/proposals/*Test.ts src/iznik/tests/leaderSetup.ts src/iznik/tests/workingGroup/*Test.ts -T", + "debug": "tap --files src/iznik/tests/councilSetup.ts -T", "lint": "eslint . --quiet --ext .ts", "checks": "yarn lint && tsc --noEmit --pretty && prettier ./ --check", "format": "prettier ./ --write " @@ -15,9 +15,9 @@ "dependencies": { "@constantinople/types@npm:@joystream/types": "^0.10.0", "@nicaea/types@npm:@joystream/types": "^0.12.0", - "@alexandria/types": "link:../../types", - "@polkadot/api": "^0.96.1", - "@polkadot/keyring": "^1.7.0-beta.5", + "@alexandria/types": "./types", + "@polkadot/api": "1.26.1", + "@polkadot/keyring": "3.0.1", "@rome/types@npm:@joystream/types": "^0.7.0", "@types/bn.js": "^4.11.5", "@types/lowdb": "^1.0.9", diff --git a/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts b/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts index c7c75e69b2..4588a526ae 100644 --- a/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts +++ b/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts @@ -10,7 +10,7 @@ import { closeApi } from '../../utils/closeApi' import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { ElectCouncilFixture } from '../fixtures/councilElectionModule' import { Utils } from '../../utils/utils' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' tap.mocha.describe('Electing council scenario', async () => { initConfig() diff --git a/tests/network-tests/src/iznik/tests/councilSetup.ts b/tests/network-tests/src/iznik/tests/councilSetup.ts index 0eecaabd0a..08354708af 100644 --- a/tests/network-tests/src/iznik/tests/councilSetup.ts +++ b/tests/network-tests/src/iznik/tests/councilSetup.ts @@ -2,8 +2,7 @@ import { KeyringPair } from '@polkadot/keyring/types' import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import tap from 'tap' -import { registerJoystreamTypes } from '@nicaea/types' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { DbService } from '../services/dbService' import { initConfig } from '../utils/config' import { ApiWrapper } from '../utils/apiWrapper' @@ -14,7 +13,6 @@ import { CouncilElectionHappyCaseFixture } from './fixtures/councilElectionHappy tap.mocha.describe('Electing council scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -31,7 +29,8 @@ tap.mocha.describe('Electing council scenario', async () => { const N: number = +process.env.MEMBERSHIP_CREATION_N! const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + // const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts index ae817083d4..cee7633b93 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts @@ -4,7 +4,7 @@ import tap from 'tap' import { ElectCouncilFixture } from './councilElectionModule' import { ApiWrapper } from '../../utils/apiWrapper' import { KeyringPair } from '@polkadot/keyring/types' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import BN from 'bn.js' export class CouncilElectionHappyCaseFixture implements Fixture { diff --git a/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts index 79358fd9b8..2347cf422f 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts @@ -8,9 +8,9 @@ import { } from './workingGroupModule' import { BuyMembershipHappyCaseFixture } from './membershipModule' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' -import { OpeningId } from '@nicaea/types/hiring' +import { OpeningId } from '@alexandria/types/hiring' import { KeyringPair } from '@polkadot/keyring/types' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import BN from 'bn.js' export class LeaderHiringHappyCaseFixture implements Fixture { diff --git a/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts b/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts index a89d886155..1e7b9537c2 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts @@ -3,7 +3,7 @@ import { KeyringPair } from '@polkadot/keyring/types' import BN from 'bn.js' import { assert } from 'chai' import { Fixture } from './interfaces/fixture' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' export class BuyMembershipHappyCaseFixture implements Fixture { private apiWrapper: ApiWrapper diff --git a/tests/network-tests/src/iznik/tests/leaderSetup.ts b/tests/network-tests/src/iznik/tests/leaderSetup.ts index f6a09856b5..a8cf5d8903 100644 --- a/tests/network-tests/src/iznik/tests/leaderSetup.ts +++ b/tests/network-tests/src/iznik/tests/leaderSetup.ts @@ -1,5 +1,4 @@ import { initConfig } from '../utils/config' -import { registerJoystreamTypes } from '@nicaea/types' import { closeApi } from '../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -8,14 +7,12 @@ import { setTestTimeout } from '../utils/setTestTimeout' import BN from 'bn.js' import tap from 'tap' import { Utils } from '../utils/utils' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { DbService } from '../services/dbService' import { LeaderHiringHappyCaseFixture } from './fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() - registerJoystreamTypes() - const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! const keyring = new Keyring({ type: 'sr25519' }) diff --git a/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts b/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts index 805b2385fa..e7786f0e95 100644 --- a/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts +++ b/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts @@ -8,7 +8,7 @@ import { ApiWrapper } from '../../utils/apiWrapper' import { closeApi } from '../../utils/closeApi' import { BuyMembershipHappyCaseFixture, BuyMembershipWithInsufficienFundsFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' tap.mocha.describe('Membership creation scenario', async () => { initConfig() diff --git a/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts index 5bd0311203..5ffb53cb79 100644 --- a/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts @@ -9,7 +9,7 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { ContentWorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' import { Utils } from '../../utils/utils' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts index b7d4d8ec01..50c8231a89 100644 --- a/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts @@ -9,7 +9,7 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { ElectionParametersProposalFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts index b4d44cb1d8..89ae1912e6 100644 --- a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts @@ -29,9 +29,9 @@ import { ExpectLeadOpeningAddedFixture, } from '../fixtures/workingGroupModule' import { Utils } from '../../utils/utils' -import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' -import { ProposalId } from '@nicaea/types/proposals' +import { PaidTermId } from '@alexandria/types/members' +import { OpeningId } from '@alexandria/types/hiring' +import { ProposalId } from '@alexandria/types/proposals' import { DbService } from '../../services/dbService' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' diff --git a/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts index d569e301b6..d006199842 100644 --- a/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts @@ -9,7 +9,7 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { SetLeadProposalFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts index 524e2ad0cf..c3fea9f770 100644 --- a/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts @@ -9,7 +9,7 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { SpendingProposalFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts index 6fb2464036..7b90509b7e 100644 --- a/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts @@ -9,7 +9,7 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { TextProposalFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts b/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts index aff3e6f188..9896119671 100644 --- a/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts +++ b/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts @@ -10,7 +10,7 @@ import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' import { UpdateRuntimeFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts index 8b69807e68..8ad845e35a 100644 --- a/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts @@ -9,7 +9,7 @@ import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { ValidatorCountProposalFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts index 9f45b2c99e..2c3996b543 100644 --- a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts @@ -10,8 +10,8 @@ import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' import { VoteForProposalFixture, WorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' import { ExpectMintCapacityChangedFixture } from '../fixtures/workingGroupModule' -import { PaidTermId } from '@nicaea/types/members' -import { ProposalId } from '@nicaea/types/proposals' +import { PaidTermId } from '@alexandria/types/members' +import { ProposalId } from '@alexandria/types/proposals' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { DbService } from '../../services/dbService' diff --git a/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts index c5ab6e06f4..8f4b80771d 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts @@ -9,7 +9,7 @@ import { AddWorkerOpeningFixture, LeaveRoleFixture } from '../fixtures/workingGr import BN from 'bn.js' import tap from 'tap' import { Utils } from '../../utils/utils' -import { PaidTermId } from '@nicaea/types/members' +import { PaidTermId } from '@alexandria/types/members' import { DbService } from '../../services/dbService' import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts index dac54c8445..ed826a0d66 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts @@ -21,8 +21,8 @@ import { import { Utils } from '../../utils/utils' import BN from 'bn.js' import tap from 'tap' -import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' +import { PaidTermId } from '@alexandria/types/members' +import { OpeningId } from '@alexandria/types/hiring' import { DbService } from '../../services/dbService' import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts index 592fbfd580..620d853274 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts @@ -17,8 +17,8 @@ import { import { Utils } from '../../utils/utils' import BN from 'bn.js' import tap from 'tap' -import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' +import { PaidTermId } from '@alexandria/types/members' +import { OpeningId } from '@alexandria/types/hiring' import { DbService } from '../../services/dbService' import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts index 1ad0e91266..ab31718214 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts @@ -16,8 +16,8 @@ import { LeaveRoleFixture, WithdrawApplicationFixture, } from '../fixtures/workingGroupModule' -import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' +import { PaidTermId } from '@alexandria/types/members' +import { OpeningId } from '@alexandria/types/hiring' import { DbService } from '../../services/dbService' import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts index fb6255d9e8..040f51012d 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts @@ -15,8 +15,8 @@ import { LeaveRoleFixture, TerminateApplicationsFixture, } from '../fixtures/workingGroupModule' -import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' +import { PaidTermId } from '@alexandria/types/members' +import { OpeningId } from '@alexandria/types/hiring' import { DbService } from '../../services/dbService' import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts index f4c872a3fe..7b28a5b644 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts @@ -18,9 +18,9 @@ import BN from 'bn.js' import tap from 'tap' import { Utils } from '../../utils/utils' import { VoteForProposalFixture, WorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' -import { PaidTermId } from '@nicaea/types/members' -import { OpeningId } from '@nicaea/types/hiring' -import { ProposalId } from '@nicaea/types/proposals' +import { PaidTermId } from '@alexandria/types/members' +import { OpeningId } from '@alexandria/types/hiring' +import { ProposalId } from '@alexandria/types/proposals' import { DbService } from '../../services/dbService' import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase' import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' diff --git a/tests/network-tests/src/iznik/utils/apiWrapper.ts b/tests/network-tests/src/iznik/utils/apiWrapper.ts index 147e0cd623..f574a73d16 100644 --- a/tests/network-tests/src/iznik/utils/apiWrapper.ts +++ b/tests/network-tests/src/iznik/utils/apiWrapper.ts @@ -2,7 +2,7 @@ import { ApiPromise, WsProvider } from '@polkadot/api' import { Bytes, Option, u32, Vec } from '@polkadot/types' import { Codec } from '@polkadot/types/types' import { KeyringPair } from '@polkadot/keyring/types' -import { MemberId, PaidMembershipTerms, PaidTermId, UserInfo } from '@alexandria/types/members' +import { MemberId, PaidMembershipTerms, PaidTermId } from '@alexandria/types/members' import { Mint, MintId } from '@alexandria/types/mint' import { Lead, LeadId } from '@alexandria/types/content-working-group' import { @@ -65,6 +65,10 @@ export class ApiWrapper { } } + public createPaidTermId(value: BN): PaidTermId { + return this.api.createType('PaidTermId', value) + } + public async buyMembership( account: KeyringPair, paidTermsId: PaidTermId, @@ -264,44 +268,44 @@ export class ApiWrapper { public estimateVoteForProposalFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsEngine.vote( - new MemberId(0), - new ProposalId(0), + this.api.createType('MemberId', 0), + this.api.createType('ProposalId', 0), 'Approve' ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateAddOpeningFee(module: WorkingGroups): BN { - const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({ - application_rationing_policy: new Option(ApplicationRationingPolicy, { + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', { + application_rationing_policy: this.api.createType('Option', { max_active_applicants: new BN(32) as u32, }), max_review_period_length: new BN(32) as u32, - application_staking_policy: new Option(StakingPolicy, { + application_staking_policy: this.api.createType('Option', { amount: new BN(1), amount_mode: 'AtLeast', crowded_out_unstaking_period_length: new BN(1), review_period_expired_unstaking_period_length: new BN(1), }), - role_staking_policy: new Option(StakingPolicy, { + role_staking_policy: this.api.createType('Option', { amount: new BN(1), amount_mode: 'AtLeast', crowded_out_unstaking_period_length: new BN(1), review_period_expired_unstaking_period_length: new BN(1), }), - role_slashing_terms: new SlashingTerms({ + role_slashing_terms: this.api.createType('SlashingTerms', { Slashable: { max_count: new BN(0), max_percent_pts_per_time: new BN(0), }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), + terminate_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + terminate_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), + exit_role_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + exit_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), }) return this.estimateTxFee( @@ -316,15 +320,15 @@ export class ApiWrapper { public estimateAcceptApplicationsFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].acceptApplications(new OpeningId(0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].acceptApplications(this.api.createType('OpeningId',0)) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateApplyOnOpeningFee(account: KeyringPair, module: WorkingGroups): BN { return this.estimateTxFee( (this.api.tx[module].applyOnOpening( - new MemberId(0), - new OpeningId(0), + this.api.createType('MemberId', 0), + this.api.createType('OpeningId', 0), account.address, 0, 0, @@ -335,13 +339,13 @@ export class ApiWrapper { public estimateBeginApplicantReviewFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].beginApplicantReview(new OpeningId(0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].beginApplicantReview(this.api.createType('OpeningId', 0)) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateFillOpeningFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].fillOpening(new OpeningId(0), [new ApplicationId(0)], { + (this.api.tx[module].fillOpening(this.api.createType('OpeningId', 0), [this.api.createType('ApplicationId', 0)], { 'amount_per_payout': 0, 'next_payment_at_block': 0, 'payout_interval': 0, @@ -351,31 +355,31 @@ export class ApiWrapper { public estimateIncreaseStakeFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].increaseStake(new WorkerId(0), 0) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].increaseStake(this.api.createType('WorkerId',0), 0) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateDecreaseStakeFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].decreaseStake(new WorkerId(0), 0) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].decreaseStake(this.api.createType('WorkerId',0), 0) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateUpdateRoleAccountFee(address: string, module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].updateRoleAccount(new WorkerId(0), address) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].updateRoleAccount(this.api.createType('WorkerId',0), address) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateUpdateRewardAccountFee(address: string, module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].updateRewardAccount(new WorkerId(0), address) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].updateRewardAccount(this.api.createType('WorkerId',0), address) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateLeaveRoleFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].leaveRole(new WorkerId(0), 'Long justification text') as unknown) as SubmittableExtrinsic< + (this.api.tx[module].leaveRole(this.api.createType('WorkerId',0), 'Long justification text') as unknown) as SubmittableExtrinsic< 'promise' > ) @@ -383,26 +387,26 @@ export class ApiWrapper { public estimateWithdrawApplicationFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].withdrawApplication(new ApplicationId(0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].withdrawApplication(this.api.createType('ApplicationId',0)) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateTerminateApplicationFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].terminateApplication(new ApplicationId(0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].terminateApplication(this.api.createType('ApplicationId',0)) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateSlashStakeFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].slashStake(new WorkerId(0), 0) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].slashStake(this.api.createType('WorkerId',0), 0) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateTerminateRoleFee(module: WorkingGroups): BN { return this.estimateTxFee( (this.api.tx[module].terminateRole( - new WorkerId(0), + this.api.createType('WorkerId',0), 'Long justification text explaining why the worker role will be terminated', false ) as unknown) as SubmittableExtrinsic<'promise'> @@ -410,41 +414,41 @@ export class ApiWrapper { } public estimateProposeCreateWorkingGroupLeaderOpeningFee(): BN { - const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({ - application_rationing_policy: new Option(ApplicationRationingPolicy, { + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment',{ + application_rationing_policy: this.api.createType('Option', { max_active_applicants: new BN(32) as u32, }), max_review_period_length: new BN(32) as u32, - application_staking_policy: new Option(StakingPolicy, { + application_staking_policy: this.api.createType('Option', { amount: new BN(1), amount_mode: 'AtLeast', crowded_out_unstaking_period_length: new BN(1), review_period_expired_unstaking_period_length: new BN(1), }), - role_staking_policy: new Option(StakingPolicy, { + role_staking_policy: this.api.createType('Option', { amount: new BN(1), amount_mode: 'AtLeast', crowded_out_unstaking_period_length: new BN(1), review_period_expired_unstaking_period_length: new BN(1), }), - role_slashing_terms: new SlashingTerms({ + role_slashing_terms: this.api.createType('SlashingTerms',{ Slashable: { max_count: new BN(0), max_percent_pts_per_time: new BN(0), }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), + terminate_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + terminate_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), + exit_role_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + exit_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), }) return this.estimateTxFee( (this.api.tx.proposalsCodex.createAddWorkingGroupLeaderOpeningProposal( - new MemberId(0), + this.api.createType('MemberId',0), 'some long title for the purpose of testing', 'some long description for the purpose of testing', 0, @@ -461,34 +465,31 @@ export class ApiWrapper { public estimateProposeBeginWorkingGroupLeaderApplicationReviewFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createBeginReviewWorkingGroupLeaderApplicationsProposal( - new MemberId(0), + this.api.createType('MemberId',0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, - new OpeningId(0), + this.api.createType('OpeningId',0), 'Storage' ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateProposeFillLeaderOpeningFee(): BN { - const fillOpeningParameters: FillOpeningParameters = new FillOpeningParameters({ - opening_id: new OpeningId(0), - successful_application_id: new ApplicationId(0), - reward_policy: new Option( - RewardPolicy, - new RewardPolicy({ + const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters',{ + opening_id: this.api.createType('OpeningId',0), + successful_application_id: this.api.createType('ApplicationId',0), + reward_policy: this.api.createType('Option', { amount_per_payout: new BN(1) as Balance, next_payment_at_block: new BN(99999) as BlockNumber, - payout_interval: new Option(u32, new u32(99999)), - }) - ), - working_group: new WorkingGroup('Storage'), + payout_interval: this.api.createType('Option', new BN(99999)), + }), + working_group: this.api.createType('WorkingGroup','Storage'), }) return this.estimateTxFee( (this.api.tx.proposalsCodex.createFillWorkingGroupLeaderOpeningProposal( - new MemberId(0), + this.api.createType('MemberId',0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, @@ -500,12 +501,12 @@ export class ApiWrapper { public estimateProposeTerminateLeaderRoleFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createTerminateWorkingGroupLeaderRoleProposal( - new MemberId(0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, { - 'worker_id': new WorkerId(0), + 'worker_id': this.api.createType('WorkerId', 0), 'rationale': 'Exceptionaly long and extraordinary descriptive rationale', 'slash': true, 'working_group': 'Storage', @@ -517,11 +518,11 @@ export class ApiWrapper { public estimateProposeLeaderRewardFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createSetWorkingGroupLeaderRewardProposal( - new MemberId(0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, - new WorkerId(0), + this.api.createType('WorkerId', 0), 0, 'Storage' ) as unknown) as SubmittableExtrinsic<'promise'> @@ -531,11 +532,11 @@ export class ApiWrapper { public estimateProposeDecreaseLeaderStakeFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createDecreaseWorkingGroupLeaderStakeProposal( - new MemberId(0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, - new WorkerId(0), + this.api.createType('WorkerId', 0), 0, 'Storage' ) as unknown) as SubmittableExtrinsic<'promise'> @@ -545,11 +546,11 @@ export class ApiWrapper { public estimateProposeSlashLeaderStakeFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createSlashWorkingGroupLeaderStakeProposal( - new MemberId(0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, - new WorkerId(0), + this.api.createType('WorkerId', 0), 0, 'Storage' ) as unknown) as SubmittableExtrinsic<'promise'> @@ -559,7 +560,7 @@ export class ApiWrapper { public estimateProposeWorkingGroupMintCapacityFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createSetWorkingGroupMintCapacityProposal( - new MemberId(0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, @@ -951,14 +952,14 @@ export class ApiWrapper { const mintId: MintId = await this.api.query.contentWorkingGroup.mint() const mintCodec = await this.api.query.minting.mints(mintId) const mint: Mint = (mintCodec[0] as unknown) as Mint - return mint.getField('capacity') + return mint.capacity } public async getWorkingGroupMintCapacity(module: WorkingGroups): Promise { const mintId: MintId = await this.api.query[module].mint() const mintCodec = await this.api.query.minting.mints(mintId) const mint: Mint = (mintCodec[0] as unknown) as Mint - return mint.getField('capacity') + return mint.capacity } public getValidatorCount(): Promise { diff --git a/tests/network-tests/tsconfig.json b/tests/network-tests/tsconfig.json index 9707b1cdc9..62d9448609 100644 --- a/tests/network-tests/tsconfig.json +++ b/tests/network-tests/tsconfig.json @@ -7,6 +7,10 @@ "strict": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, - "skipLibCheck": true + "skipLibCheck": true, + "baseUrl": ".", + "paths": { + "@polkadot/types/augment": ["../../types/src/definitions/augment-types.ts"] + } } } From a89bd8ba8d323180641878756c76a3f76937e46b Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Thu, 13 Aug 2020 14:43:14 +0200 Subject: [PATCH 005/178] altering code to match new api --- tests/network-tests/package.json | 2 +- .../src/iznik/tests/councilSetup.ts | 3 +-- .../src/iznik/utils/apiWrapper.ts | 18 ++++++++---------- types/src/definitions/augment-types.ts | 5 +---- 4 files changed, 11 insertions(+), 17 deletions(-) diff --git a/tests/network-tests/package.json b/tests/network-tests/package.json index 3e24c44258..3471380d4b 100644 --- a/tests/network-tests/package.json +++ b/tests/network-tests/package.json @@ -15,7 +15,7 @@ "dependencies": { "@constantinople/types@npm:@joystream/types": "^0.10.0", "@nicaea/types@npm:@joystream/types": "^0.12.0", - "@alexandria/types": "./types", + "@alexandria/types": "link:../../types", "@polkadot/api": "1.26.1", "@polkadot/keyring": "3.0.1", "@rome/types@npm:@joystream/types": "^0.7.0", diff --git a/tests/network-tests/src/iznik/tests/councilSetup.ts b/tests/network-tests/src/iznik/tests/councilSetup.ts index 08354708af..82183b4921 100644 --- a/tests/network-tests/src/iznik/tests/councilSetup.ts +++ b/tests/network-tests/src/iznik/tests/councilSetup.ts @@ -29,8 +29,7 @@ tap.mocha.describe('Electing council scenario', async () => { const N: number = +process.env.MEMBERSHIP_CREATION_N! const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - // const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) - const paidTerms: PaidTermId = apiWrapper.createPaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/utils/apiWrapper.ts b/tests/network-tests/src/iznik/utils/apiWrapper.ts index f574a73d16..b4a1c46441 100644 --- a/tests/network-tests/src/iznik/utils/apiWrapper.ts +++ b/tests/network-tests/src/iznik/utils/apiWrapper.ts @@ -8,8 +8,6 @@ import { Lead, LeadId } from '@alexandria/types/content-working-group' import { Application, ApplicationIdToWorkerIdMap, - RewardPolicy, - SlashingTerms, Worker, WorkerId, WorkingGroupOpeningPolicyCommitment, @@ -22,17 +20,15 @@ import { Sender } from './sender' import { Utils } from './utils' import { Stake, StakedState, StakeId } from '@alexandria/types/stake' import { RewardRelationship, RewardRelationshipId } from '@alexandria/types/recurring-rewards' +import { types } from '@alexandria/types'; import { ActivateOpeningAt, Application as HiringApplication, ApplicationId, - ApplicationRationingPolicy, Opening as HiringOpening, OpeningId, - StakingPolicy, } from '@alexandria/types/hiring' import { FillOpeningParameters, ProposalId } from '@alexandria/types/proposals' -import { WorkingGroup } from '@alexandria/types/common' export enum WorkingGroups { StorageWorkingGroup = 'storageWorkingGroup', @@ -43,7 +39,8 @@ export class ApiWrapper { private readonly sender: Sender public static async create(provider: WsProvider): Promise { - const api = await ApiPromise.create({ provider }) + const api = await ApiPromise.create({ provider, types }) + // ApiPromise.create({ types }); return new ApiWrapper(api) } @@ -99,12 +96,13 @@ export class ApiWrapper { return this.sender.signAndSend(this.api.tx.balances.transfer(to, amount), from) } - public getPaidMembershipTerms(paidTermsId: PaidTermId): Promise> { - return this.api.query.members.paidMembershipTermsById>(paidTermsId) + public getPaidMembershipTerms(paidTermsId: PaidTermId): Promise { + return this.api.query.members.paidMembershipTermsById(paidTermsId) } - public getMembershipFee(paidTermsId: PaidTermId): Promise { - return this.getPaidMembershipTerms(paidTermsId).then((terms) => terms.unwrap().fee) + public async getMembershipFee(paidTermsId: PaidTermId): Promise { + const terms: PaidMembershipTerms = (await this.getPaidMembershipTerms(paidTermsId)); + return terms.fee } public async transferBalanceToAccounts(from: KeyringPair, to: KeyringPair[], amount: BN): Promise { diff --git a/types/src/definitions/augment-types.ts b/types/src/definitions/augment-types.ts index a5f75ca2a5..ff420e0d55 100644 --- a/types/src/definitions/augment-types.ts +++ b/types/src/definitions/augment-types.ts @@ -59,7 +59,7 @@ import { Class as Class, Entity as Entity, ClassSchema as ClassSchema, Property import { EntityPermissions as EntityPermissions, ReferenceConstraint as ReferenceConstraint, ClassPermissionsType as ClassPermissionsType, Operation as Operation, OperationType as OperationType, CreateEntity as CreateEntity, UpdatePropertyValues as UpdatePropertyValues, AddSchemaSupportToEntity as AddSchemaSupportToEntity, ParametrizedEntity as ParametrizedEntity, ParametrizedClassPropertyValue as ParametrizedClassPropertyValue, ParametrizedPropertyValue as ParametrizedPropertyValue } from '../versioned-store/permissions' import { OptionalText as OptionalText, Channel as Channel, ChannelContentType as ChannelContentType, ChannelCurationStatus as ChannelCurationStatus, ChannelPublicationStatus as ChannelPublicationStatus, CurationActor as CurationActor, Curator as Curator, CuratorApplication as CuratorApplication, CuratorOpening as CuratorOpening, Lead as Lead, OpeningPolicyCommitment as OpeningPolicyCommitment, Principal as Principal, WorkingGroupUnstaker as WorkingGroupUnstaker, CuratorApplicationIdToCuratorIdMap as CuratorApplicationIdToCuratorIdMap, CuratorApplicationIdSet as CuratorApplicationIdSet, CuratorRoleStakeProfile as CuratorRoleStakeProfile, CuratorRoleStage as CuratorRoleStage, CuratorExitSummary as CuratorExitSummary, CuratorExitInitiationOrigin as CuratorExitInitiationOrigin, ExitedLeadRole as ExitedLeadRole, CuratorInduction as CuratorInduction } from '../content-working-group' import { RationaleText as RationaleText, Application as ApplicationOf, ApplicationIdSet as ApplicationIdSet, ApplicationIdToWorkerIdMap as ApplicationIdToWorkerIdMap, WorkerId as WorkerId, Worker as WorkerOf, Opening as OpeningOf, StorageProviderId as StorageProviderId, OpeningType as OpeningType, ApplicationId as HiringApplicationId, RewardPolicy as RewardPolicy, OpeningId as working_group__OpeningId, WorkerId as working_group__WorkerId, WorkingGroupOpeningPolicyCommitment as WorkingGroupOpeningPolicyCommitment, RoleStakeProfile as RoleStakeProfile } from '../working-group' -import { Url as Url, IPNSIdentity as IPNSIdentity, ServiceProviderRecord as ServiceProviderRecord } from '../discovery' +import { Url as Url, IPNSIdentity as IPNSIdentity } from '../discovery' import { ContentId as ContentId, LiaisonJudgement as LiaisonJudgement, DataObject as DataObject, DataObjectStorageRelationshipId as DataObjectStorageRelationshipId, DataObjectStorageRelationship as DataObjectStorageRelationship, DataObjectTypeId as DataObjectTypeId, DataObjectType as DataObjectType, DataObjectsMap as DataObjectsMap } from '../media' import { ProposalId as ProposalId, ProposalStatus as ProposalStatus, Proposal as ProposalOf, ProposalDetails as ProposalDetails, ProposalDetails as ProposalDetailsOf, VotingResults as VotingResults, ProposalParameters as ProposalParameters, VoteKind as VoteKind, ThreadCounter as ThreadCounter, DiscussionThread as DiscussionThread, DiscussionPost as DiscussionPost, AddOpeningParameters as AddOpeningParameters, FillOpeningParameters as FillOpeningParameters, TerminateRoleParameters as TerminateRoleParameters, ActiveStake as ActiveStake, FinalizationData as FinalizationData, ProposalDecisionStatus as ProposalDecisionStatus, ExecutionFailed as ExecutionFailed } from '../proposals' /** /CUSTOMIMPORTS **/ @@ -2282,9 +2282,6 @@ declare module '@polkadot/types/types/registry' { "IPNSIdentity": IPNSIdentity; "Option": Option; "Vec": Vec; - "ServiceProviderRecord": ServiceProviderRecord; - "Option": Option; - "Vec": Vec; "ContentId": ContentId; "Option": Option; "Vec": Vec; From 5d4a1949599cb2f04f2b8951c7aff10d0fc39a37 Mon Sep 17 00:00:00 2001 From: Leszek Wiesner Date: Fri, 14 Aug 2020 10:23:35 +0200 Subject: [PATCH 006/178] Upgrade joy-election --- package.json | 3 +- pioneer/.eslintignore | 1 - pioneer/packages/apps-routing/src/index.ts | 3 + .../packages/apps-routing/src/joy-election.ts | 17 +++ pioneer/packages/apps-routing/src/types.ts | 2 + pioneer/packages/apps/src/Content/index.tsx | 29 +++- pioneer/packages/apps/src/SideBar/Item.tsx | 7 +- pioneer/packages/joy-election/.skip-build | 0 pioneer/packages/joy-election/package.json | 6 +- .../packages/joy-election/src/Applicant.tsx | 4 +- .../packages/joy-election/src/Applicants.tsx | 29 ++-- .../packages/joy-election/src/ApplyForm.tsx | 40 +++--- .../joy-election/src/CandidatePreview.tsx | 4 +- pioneer/packages/joy-election/src/Council.tsx | 6 +- .../packages/joy-election/src/Dashboard.tsx | 128 +++++++++++------- pioneer/packages/joy-election/src/Reveals.tsx | 28 ++-- .../packages/joy-election/src/SealedVote.tsx | 20 ++- .../packages/joy-election/src/SealedVotes.tsx | 29 ++-- .../joy-election/src/SidebarSubtitle.tsx | 34 +++++ .../packages/joy-election/src/VoteForm.tsx | 54 ++++---- pioneer/packages/joy-election/src/Votes.tsx | 35 ++++- pioneer/packages/joy-election/src/index.css | 28 ---- pioneer/packages/joy-election/src/index.tsx | 22 +-- .../packages/joy-election/src/myVotesStore.ts | 2 +- pioneer/packages/joy-election/src/style.ts | 21 +++ pioneer/packages/joy-election/src/utils.tsx | 3 +- .../packages/joy-utils-old/src/InputStake.tsx | 35 ----- .../src/MemberByAccountPreview.tsx | 48 ------- .../joy-utils-old/src/transport/base.ts | 107 --------------- .../joy-utils-old/src/transport/index.ts | 34 ----- .../src/react/components/InputStake.tsx | 46 +++++++ .../components/MemberByAccountPreview.tsx | 43 ++++++ .../components}/MemberProfilePreview.tsx | 0 .../src/react/components}/MembersDropdown.tsx | 14 +- .../src/react/components/PromiseComponent.tsx | 0 .../joy-utils/src/react/context/index.tsx | 1 + .../src/react/context/transport.tsx | 0 .../joy-utils/src/react/hooks/index.ts | 2 + .../src/react/hooks/usePromise.tsx | 0 .../src/react/hooks/useTransport.tsx | 0 .../src/transport}/APIQueryCache.ts | 0 .../packages/joy-utils/src/transport/base.ts | 66 +++++++++ .../packages/joy-utils/src/transport/index.ts | 34 +++++ .../src/transport/members.ts | 16 +++ .../src/types/members.ts | 4 + .../old-apps/apps-routing/src/joy-election.ts | 19 --- .../react-components/src/styles/joystream.ts | 93 +++++-------- pioneer/tsconfig.json | 5 +- 48 files changed, 609 insertions(+), 513 deletions(-) create mode 100644 pioneer/packages/apps-routing/src/joy-election.ts delete mode 100644 pioneer/packages/joy-election/.skip-build create mode 100644 pioneer/packages/joy-election/src/SidebarSubtitle.tsx delete mode 100644 pioneer/packages/joy-election/src/index.css create mode 100644 pioneer/packages/joy-election/src/style.ts delete mode 100644 pioneer/packages/joy-utils-old/src/InputStake.tsx delete mode 100644 pioneer/packages/joy-utils-old/src/MemberByAccountPreview.tsx delete mode 100644 pioneer/packages/joy-utils-old/src/transport/base.ts delete mode 100644 pioneer/packages/joy-utils-old/src/transport/index.ts create mode 100644 pioneer/packages/joy-utils/src/react/components/InputStake.tsx create mode 100644 pioneer/packages/joy-utils/src/react/components/MemberByAccountPreview.tsx rename pioneer/packages/{joy-utils-old/src => joy-utils/src/react/components}/MemberProfilePreview.tsx (100%) rename pioneer/packages/{joy-utils-old/src => joy-utils/src/react/components}/MembersDropdown.tsx (82%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/components/PromiseComponent.tsx (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/context/transport.tsx (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/hooks/usePromise.tsx (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/hooks/useTransport.tsx (100%) rename pioneer/packages/{joy-utils-old/src => joy-utils/src/transport}/APIQueryCache.ts (100%) create mode 100644 pioneer/packages/joy-utils/src/transport/base.ts create mode 100644 pioneer/packages/joy-utils/src/transport/index.ts rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/members.ts (53%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/types/members.ts (64%) delete mode 100644 pioneer/packages/old-apps/apps-routing/src/joy-election.ts diff --git a/package.json b/package.json index 2928330f15..ad47384381 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "pioneer/packages/react*", "pioneer/packages/joy-utils", "pioneer/packages/joy-members", - "pioneer/packages/joy-pages" + "pioneer/packages/joy-pages", + "pioneer/packages/joy-election" ], "resolutions": { "@polkadot/api": "1.26.1", diff --git a/pioneer/.eslintignore b/pioneer/.eslintignore index 42a2471efd..57bb4f9e3e 100644 --- a/pioneer/.eslintignore +++ b/pioneer/.eslintignore @@ -2,7 +2,6 @@ **/coverage/* **/node_modules/* packages/old-apps/* -packages/joy-election/* packages/joy-forum/* packages/joy-help/* packages/joy-media/* diff --git a/pioneer/packages/apps-routing/src/index.ts b/pioneer/packages/apps-routing/src/index.ts index f4ba69e507..36f9671d31 100644 --- a/pioneer/packages/apps-routing/src/index.ts +++ b/pioneer/packages/apps-routing/src/index.ts @@ -20,11 +20,13 @@ import transfer from './transfer'; // Joy packages import members from './joy-members'; import { terms, privacyPolicy } from './joy-pages'; +import election from './joy-election'; export default function create (t: (key: string, text: string, options: { ns: string }) => T): Routes { return appSettings.uiMode === 'light' ? [ members(t), + election(t), null, transfer(t), accounts(t), @@ -32,6 +34,7 @@ export default function create (t: (key: string, text: string, opti ] : [ members(t), + election(t), null, transfer(t), accounts(t), diff --git a/pioneer/packages/apps-routing/src/joy-election.ts b/pioneer/packages/apps-routing/src/joy-election.ts new file mode 100644 index 0000000000..ebf857ad81 --- /dev/null +++ b/pioneer/packages/apps-routing/src/joy-election.ts @@ -0,0 +1,17 @@ +import { Route } from './types'; + +import Election from '@polkadot/joy-election/index'; +import SidebarSubtitle from '@polkadot/joy-election/SidebarSubtitle'; + +export default function create (t: (key: string, text: string, options: { ns: string }) => T): Route { + return { + Component: Election, + display: { + needsApi: ['query.council.activeCouncil', 'query.councilElection.stage'] + }, + text: t('nav.election', 'Council', { ns: 'apps-routing' }), + icon: 'university', + name: 'council', + SubtitleComponent: SidebarSubtitle + } +} diff --git a/pioneer/packages/apps-routing/src/types.ts b/pioneer/packages/apps-routing/src/types.ts index 6dce432d8c..4a6695fef2 100644 --- a/pioneer/packages/apps-routing/src/types.ts +++ b/pioneer/packages/apps-routing/src/types.ts @@ -24,6 +24,8 @@ export interface Route { name: string; text: string; useCounter?: () => number | string | null; + // Joystream-specific + SubtitleComponent?: React.ComponentType; } export type Routes = (Route | null)[]; diff --git a/pioneer/packages/apps/src/Content/index.tsx b/pioneer/packages/apps/src/Content/index.tsx index 63f0238535..cf2dc00224 100644 --- a/pioneer/packages/apps/src/Content/index.tsx +++ b/pioneer/packages/apps/src/Content/index.tsx @@ -16,6 +16,11 @@ import { useTranslation } from '../translate'; import NotFound from './NotFound'; import Status from './Status'; +// Joystream-specific +// We must use transport provider here instead of /apps/src/index +// to avoid "Cannot create Transport: The Substrate API is not ready yet." error +import { TransportProvider } from '@polkadot/joy-utils/react/context'; + interface Props { className?: string; } @@ -60,11 +65,25 @@ function Content ({ className }: Props): React.ReactElement { ? : ( - + { needsApi + // Add transport provider for routes that need the api + // (the above condition makes sure it's aleady initialized at this point) + ? ( + + + + ) + : ( + + ) } ) } diff --git a/pioneer/packages/apps/src/SideBar/Item.tsx b/pioneer/packages/apps/src/SideBar/Item.tsx index abcd801144..629f9c9c19 100644 --- a/pioneer/packages/apps/src/SideBar/Item.tsx +++ b/pioneer/packages/apps/src/SideBar/Item.tsx @@ -79,12 +79,15 @@ function Item ({ isCollapsed, onClick, route }: Props): React.ReactElement - {text} + + {text} + { SubtitleComponent && } + {!!count && ( ; + stage?: Option; }; class Applicants extends React.PureComponent { @@ -38,12 +41,21 @@ class Applicants extends React.PureComponent { ) render () { - const { myAddress, applicants = [], candidacyLimit = new BN(0) } = this.props; + const { myAddress, applicants = [], candidacyLimit = new BN(0), stage } = this.props; const title = Applicants {applicants.length}/{formatNumber(candidacyLimit)}; return <>
- + { stage?.unwrapOr(undefined)?.isOfType('Announcing') + ? ( + + ) + : ( + + Applying to council is only possible during Announcing stage. + + ) + }
{!applicants.length @@ -59,6 +71,7 @@ class Applicants extends React.PureComponent { export default translate( withCalls( queryToProp('query.councilElection.candidacyLimit'), - queryToProp('query.councilElection.applicants') + queryToProp('query.councilElection.applicants'), + queryToProp('query.councilElection.stage') )(withMyAccount(Applicants)) ); diff --git a/pioneer/packages/joy-election/src/ApplyForm.tsx b/pioneer/packages/joy-election/src/ApplyForm.tsx index f058fc992c..f0f753f37c 100644 --- a/pioneer/packages/joy-election/src/ApplyForm.tsx +++ b/pioneer/packages/joy-election/src/ApplyForm.tsx @@ -3,21 +3,21 @@ import React from 'react'; import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; -import { withCalls, withMulti } from '@polkadot/react-api/with'; +import { withCalls, withMulti } from '@polkadot/react-api/hoc'; import { Labelled } from '@polkadot/react-components/index'; import { Balance } from '@polkadot/types/interfaces'; import translate from './translate'; -import TxButton from '@polkadot/joy-utils/TxButton'; -import InputStake from '@polkadot/joy-utils/InputStake'; +import TxButton from '@polkadot/joy-utils/react/components/TxButton'; +import InputStake from '@polkadot/joy-utils/react/components/InputStake'; import { ElectionStake } from '@joystream/types/council'; -import { calcTotalStake, ZERO } from '@polkadot/joy-utils/index'; -import { MyAddressProps, withOnlyMembers } from '@polkadot/joy-utils/MyAccount'; +import { calcTotalStake, ZERO } from '@polkadot/joy-utils/functions/misc'; +import { MyAddressProps } from '@polkadot/joy-utils/react/hocs/accounts'; +import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards'; type Props = ApiProps & I18nProps & MyAddressProps & { minStake?: Balance; alreadyStaked?: ElectionStake; - myBalance?: Balance; }; type State = { @@ -48,15 +48,17 @@ class ApplyForm extends React.PureComponent { isValid={isStakeValid} onChange={this.onChangeStake} /> - - - +
+ + + +
); } @@ -71,10 +73,8 @@ class ApplyForm extends React.PureComponent { private onChangeStake = (stake?: BN): void => { stake = stake || ZERO; - const { myBalance = ZERO } = this.props; - const isStakeLteBalance = stake.lte(myBalance); const isStakeGteMinStake = stake.add(this.alreadyStaked()).gte(this.minStake()); - const isStakeValid = !stake.isZero() && isStakeGteMinStake && isStakeLteBalance; + const isStakeValid = !stake.isZero() && isStakeGteMinStake; this.setState({ stake, isStakeValid }); } } @@ -88,8 +88,6 @@ export default withMulti( ['query.councilElection.minCouncilStake', { propName: 'minStake' }], ['query.councilElection.applicantStakes', - { paramName: 'myAddress', propName: 'alreadyStaked' }], - ['query.balances.freeBalance', - { paramName: 'myAddress', propName: 'myBalance' }] + { paramName: 'myAddress', propName: 'alreadyStaked' }] ) ); diff --git a/pioneer/packages/joy-election/src/CandidatePreview.tsx b/pioneer/packages/joy-election/src/CandidatePreview.tsx index 9e6571efb6..bab07182e7 100644 --- a/pioneer/packages/joy-election/src/CandidatePreview.tsx +++ b/pioneer/packages/joy-election/src/CandidatePreview.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import AddressMini from '@polkadot/react-components/AddressMiniJoy'; -import MemberByAccount from '@polkadot/joy-utils/MemberByAccountPreview'; +import AddressMini from '@polkadot/react-components/AddressMini'; +import MemberByAccount from '@polkadot/joy-utils/react/components/MemberByAccountPreview'; import { AccountId } from '@polkadot/types/interfaces'; import styled from 'styled-components'; diff --git a/pioneer/packages/joy-election/src/Council.tsx b/pioneer/packages/joy-election/src/Council.tsx index b81c144883..72f4ff5ea8 100644 --- a/pioneer/packages/joy-election/src/Council.tsx +++ b/pioneer/packages/joy-election/src/Council.tsx @@ -2,15 +2,15 @@ import React from 'react'; import { ApiProps } from '@polkadot/react-api/types'; import { I18nProps } from '@polkadot/react-components/types'; -import { withCalls } from '@polkadot/react-api/with'; +import { withCalls } from '@polkadot/react-api/hoc'; import { Table } from 'semantic-ui-react'; import { formatBalance } from '@polkadot/util'; import CouncilCandidate from './CandidatePreview'; -import { calcBackersStake } from '@polkadot/joy-utils/index'; +import { calcBackersStake } from '@polkadot/joy-utils/functions/misc'; import { Seat } from '@joystream/types/council'; import translate from './translate'; -import Section from '@polkadot/joy-utils/Section'; +import Section from '@polkadot/joy-utils/react/components/Section'; type Props = ApiProps & I18nProps & { diff --git a/pioneer/packages/joy-election/src/Dashboard.tsx b/pioneer/packages/joy-election/src/Dashboard.tsx index c7f64ef811..b962c1e5aa 100644 --- a/pioneer/packages/joy-election/src/Dashboard.tsx +++ b/pioneer/packages/joy-election/src/Dashboard.tsx @@ -3,14 +3,14 @@ import React from 'react'; import { ApiProps } from '@polkadot/react-api/types'; import { I18nProps } from '@polkadot/react-components/types'; -import { withCalls } from '@polkadot/react-api/with'; +import { withCalls } from '@polkadot/react-api/hoc'; import { Option } from '@polkadot/types'; import { BlockNumber, Balance } from '@polkadot/types/interfaces'; -import { Bubble } from '@polkadot/react-components/index'; +import { Label, Icon } from 'semantic-ui-react'; import { formatNumber, formatBalance } from '@polkadot/util'; -import Section from '@polkadot/joy-utils/Section'; -import { queryToProp } from '@polkadot/joy-utils/index'; +import Section from '@polkadot/joy-utils/react/components/Section'; +import { queryToProp } from '@polkadot/joy-utils/functions/misc'; import { ElectionStage, Seat } from '@joystream/types/council'; import translate from './translate'; @@ -45,12 +45,17 @@ class Dashboard extends React.PureComponent { const title = `Council ${activeCouncil.length > 0 ? '' : '(not elected)'}`; return
- - {activeCouncil.length} - - - {formatNumber(p.termEndsAt)} - + + + +
; } @@ -76,20 +81,28 @@ class Dashboard extends React.PureComponent { const title = <>Election ({stateText}); return
- - {formatNumber(round)} - - {isRunning && <> - - {stageName} - - - {formatNumber(leftBlocks)} - - - {formatNumber(stageEndsAt)} - - } + + + {isRunning && <> + + + + } +
; } @@ -98,33 +111,46 @@ class Dashboard extends React.PureComponent { const isAutoStart = (p.autoStart || false).valueOf(); return
- - {isAutoStart ? 'Yes' : 'No'} - - - {formatNumber(p.newTermDuration)} - - - {formatNumber(p.candidacyLimit)} - - - {formatNumber(p.councilSize)} - - - {formatBalance(p.minCouncilStake)} - - - {formatBalance(p.minVotingStake)} - - - {formatNumber(p.announcingPeriod)} blocks - - - {formatNumber(p.votingPeriod)} blocks - - - {formatNumber(p.revealingPeriod)} blocks - + + + + + + + + + + + + +
; } diff --git a/pioneer/packages/joy-election/src/Reveals.tsx b/pioneer/packages/joy-election/src/Reveals.tsx index 6a20dad6f9..b54330d5f7 100644 --- a/pioneer/packages/joy-election/src/Reveals.tsx +++ b/pioneer/packages/joy-election/src/Reveals.tsx @@ -2,16 +2,16 @@ import React from 'react'; import { AppProps, I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; -import { withCalls, withMulti } from '@polkadot/react-api/with'; +import { withCalls, withMulti } from '@polkadot/react-api/hoc'; import { AccountId } from '@polkadot/types/interfaces'; import { Input, Labelled, InputAddress } from '@polkadot/react-components/index'; import translate from './translate'; -import { nonEmptyStr, queryToProp, getUrlParam } from '@polkadot/joy-utils/index'; +import { nonEmptyStr, queryToProp, getUrlParam } from '@polkadot/joy-utils/functions/misc'; import { accountIdsToOptions, hashVote } from './utils'; -import TxButton from '@polkadot/joy-utils/TxButton'; +import TxButton from '@polkadot/joy-utils/react/components/TxButton'; import { findVoteByHash } from './myVotesStore'; -import { withOnlyMembers } from '@polkadot/joy-utils/MyAccount'; +import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards'; // AppsProps is needed to get a location from the route. type Props = AppProps & ApiProps & I18nProps & { @@ -81,15 +81,17 @@ class RevealVoteForm extends React.PureComponent { onChange={this.onChangeSalt} /> } - - - +
+ + + +
); } diff --git a/pioneer/packages/joy-election/src/SealedVote.tsx b/pioneer/packages/joy-election/src/SealedVote.tsx index 54650328c1..b935d04e11 100644 --- a/pioneer/packages/joy-election/src/SealedVote.tsx +++ b/pioneer/packages/joy-election/src/SealedVote.tsx @@ -1,28 +1,30 @@ import React from 'react'; import { Link } from 'react-router-dom'; -import { Table } from 'semantic-ui-react'; +import { Table, Message } from 'semantic-ui-react'; import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; -import { withCalls } from '@polkadot/react-api/with'; +import { withCalls } from '@polkadot/react-api/hoc'; import { Hash } from '@polkadot/types/interfaces'; import { formatBalance } from '@polkadot/util'; import translate from './translate'; -import { calcTotalStake } from '@polkadot/joy-utils/index'; +import { calcTotalStake } from '@polkadot/joy-utils/functions/misc'; import { SealedVote } from '@joystream/types/council'; -import AddressMini from '@polkadot/react-components/AddressMiniJoy'; +import AddressMini from '@polkadot/react-components/AddressMini'; import CandidatePreview from './CandidatePreview'; import { findVoteByHash } from './myVotesStore'; type Props = ApiProps & I18nProps & { hash: Hash; sealedVote?: SealedVote; + isStageRevealing: boolean; + isMyVote: boolean; }; class Comp extends React.PureComponent { renderCandidateOrAction () { - const { hash, sealedVote } = this.props; + const { hash, sealedVote, isStageRevealing, isMyVote } = this.props; if (!sealedVote) { return Unknown hashed vote: {hash.toHex()}; } @@ -30,10 +32,16 @@ class Comp extends React.PureComponent { if (sealedVote.vote.isSome) { const candidateId = sealedVote.vote.unwrap(); return ; - } else { + } else if (isStageRevealing && isMyVote) { const revealUrl = `/council/reveals?hashedVote=${hash.toHex()}`; return Reveal this vote; } + else if (isMyVote) { + return Wait until Revealing stage in order to reveal this vote. + } + else { + return This vote has not been revealed yet. + } } render () { diff --git a/pioneer/packages/joy-election/src/SealedVotes.tsx b/pioneer/packages/joy-election/src/SealedVotes.tsx index 1f03b66ac0..8dd5abf374 100644 --- a/pioneer/packages/joy-election/src/SealedVotes.tsx +++ b/pioneer/packages/joy-election/src/SealedVotes.tsx @@ -4,19 +4,20 @@ import { Button } from 'semantic-ui-react'; import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; -import { withCalls } from '@polkadot/react-api/with'; +import { withCalls } from '@polkadot/react-api/hoc'; import { Hash } from '@polkadot/types/interfaces'; import translate from './translate'; import SealedVote from './SealedVote'; -import { queryToProp } from '@polkadot/joy-utils/index'; -import { MyAddressProps } from '@polkadot/joy-utils/MyAccount'; +import { queryToProp } from '@polkadot/joy-utils/functions/misc'; +import { MyAddressProps } from '@polkadot/joy-utils/react/hocs/accounts'; import { SavedVote } from './myVotesStore'; -import Section from '@polkadot/joy-utils/Section'; +import Section from '@polkadot/joy-utils/react/components/Section'; type Props = ApiProps & I18nProps & MyAddressProps & { myVotes?: SavedVote[]; commitments?: Hash[]; + isStageRevealing: boolean; }; class Comp extends React.PureComponent { @@ -28,9 +29,13 @@ class Comp extends React.PureComponent { return commitments.filter(x => myVotesOnly === isMyVote(x.toHex())); } - private renderVotes = (votes: Hash[]) => { + private renderVotes = (votes: Hash[], areVotesMine: boolean) => { return votes.map((hash, index) => - + ); } @@ -39,17 +44,19 @@ class Comp extends React.PureComponent { const otherVotes = this.filterVotes(false); return <> -
{ +
+ { !myVotes.length ? No votes by the current account found on the current browser. - : this.renderVotes(myVotes) - }
+ : this.renderVotes(myVotes, true) + } + { this.props.isStageRevealing && } +
- { !otherVotes.length ? No votes submitted by other accounts yet. - : this.renderVotes(otherVotes) + : this.renderVotes(otherVotes, false) }
; diff --git a/pioneer/packages/joy-election/src/SidebarSubtitle.tsx b/pioneer/packages/joy-election/src/SidebarSubtitle.tsx new file mode 100644 index 0000000000..bbd59e6c6b --- /dev/null +++ b/pioneer/packages/joy-election/src/SidebarSubtitle.tsx @@ -0,0 +1,34 @@ +/** Component providing election stage subtitle for SideBar menu **/ +import React from 'react'; +import { ElectionStage } from '@joystream/types/council'; +import { Option } from '@polkadot/types/codec'; +import { useApi, useCall } from '@polkadot/react-hooks'; +import styled from 'styled-components'; + +const colorByStage = { + Announcing: '#4caf50', + Voting: '#2196f3', + Revealing: '#ff5722' +} as const; + +type StyledSubtitleProps = { + stage?: keyof typeof colorByStage; +} +const StyledSubtitle = styled.div` + display: block; + font-size: 0.85rem; + color: ${ (props: StyledSubtitleProps) => props.stage ? colorByStage[props.stage] : 'grey' }; +`; + +export default function SidebarSubtitle () { + const apiProps = useApi(); + const electionStage = useCall>(apiProps.isApiReady && apiProps.api.query.councilElection.stage, []); + + if (electionStage) { + const stageName = electionStage.unwrapOr(undefined)?.type; + const text = stageName ? `${stageName} stage` : 'No active election'; + return {text}; + } + + return null; +} diff --git a/pioneer/packages/joy-election/src/VoteForm.tsx b/pioneer/packages/joy-election/src/VoteForm.tsx index 63fbb78b17..b567669d7f 100644 --- a/pioneer/packages/joy-election/src/VoteForm.tsx +++ b/pioneer/packages/joy-election/src/VoteForm.tsx @@ -6,7 +6,7 @@ import { Message, Table } from 'semantic-ui-react'; import { AppProps, I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; -import { withCalls, withMulti } from '@polkadot/react-api/with'; +import { withCalls, withMulti } from '@polkadot/react-api/hoc'; import { AccountId, Balance } from '@polkadot/types/interfaces'; import { Button, Input, Labelled } from '@polkadot/react-components/index'; import { SubmittableResult } from '@polkadot/api'; @@ -14,12 +14,13 @@ import { formatBalance } from '@polkadot/util'; import translate from './translate'; import { hashVote } from './utils'; -import { queryToProp, ZERO, getUrlParam, nonEmptyStr } from '@polkadot/joy-utils/index'; -import TxButton from '@polkadot/joy-utils/TxButton'; -import InputStake from '@polkadot/joy-utils/InputStake'; +import { queryToProp, ZERO, getUrlParam, nonEmptyStr } from '@polkadot/joy-utils/functions/misc'; +import TxButton from '@polkadot/joy-utils/react/components/TxButton'; +import InputStake from '@polkadot/joy-utils/react/components/InputStake'; import CandidatePreview from './CandidatePreview'; -import { MyAccountProps, withOnlyMembers } from '@polkadot/joy-utils/MyAccount'; -import MembersDropdown from '@polkadot/joy-utils/MembersDropdown'; +import { MyAccountProps } from '@polkadot/joy-utils/react/hocs/accounts'; +import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards' +import MembersDropdown from '@polkadot/joy-utils/react/components/MembersDropdown'; import { saveVote, NewVote } from './myVotesStore'; import { TxFailedCallback } from '@polkadot/react-components/Status/types'; @@ -103,14 +104,11 @@ class Component extends React.PureComponent { - - + } + { + !myVotes.length + ? No votes by the current account found on the current browser. + : this.renderVotes(myVotes, true) + } + { this.props.isStageRevealing && }
{ diff --git a/pioneer/packages/joy-election/src/SidebarSubtitle.tsx b/pioneer/packages/joy-election/src/SidebarSubtitle.tsx index bbd59e6c6b..82e63d39bf 100644 --- a/pioneer/packages/joy-election/src/SidebarSubtitle.tsx +++ b/pioneer/packages/joy-election/src/SidebarSubtitle.tsx @@ -17,7 +17,7 @@ type StyledSubtitleProps = { const StyledSubtitle = styled.div` display: block; font-size: 0.85rem; - color: ${ (props: StyledSubtitleProps) => props.stage ? colorByStage[props.stage] : 'grey' }; + color: ${(props: StyledSubtitleProps) => props.stage ? colorByStage[props.stage] : 'grey'}; `; export default function SidebarSubtitle () { @@ -27,6 +27,7 @@ export default function SidebarSubtitle () { if (electionStage) { const stageName = electionStage.unwrapOr(undefined)?.type; const text = stageName ? `${stageName} stage` : 'No active election'; + return {text}; } diff --git a/pioneer/packages/joy-election/src/VoteForm.tsx b/pioneer/packages/joy-election/src/VoteForm.tsx index b567669d7f..1a7e1232ff 100644 --- a/pioneer/packages/joy-election/src/VoteForm.tsx +++ b/pioneer/packages/joy-election/src/VoteForm.tsx @@ -19,7 +19,7 @@ import TxButton from '@polkadot/joy-utils/react/components/TxButton'; import InputStake from '@polkadot/joy-utils/react/components/InputStake'; import CandidatePreview from './CandidatePreview'; import { MyAccountProps } from '@polkadot/joy-utils/react/hocs/accounts'; -import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards' +import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards'; import MembersDropdown from '@polkadot/joy-utils/react/components/MembersDropdown'; import { saveVote, NewVote } from './myVotesStore'; import { TxFailedCallback } from '@polkadot/react-components/Status/types'; @@ -50,6 +50,7 @@ class Component extends React.PureComponent { super(props); let { applicantId, location } = this.props; + applicantId = applicantId || getUrlParam(location, 'applicantId'); this.state = { @@ -118,7 +119,7 @@ class Component extends React.PureComponent { onChange={ (event, data) => this.onChangeApplicant(data.value as string) } accounts={this.props.applicants || []} value={applicantId || ''} - placeholder="Select an applicant you support" + placeholder='Select an applicant you support' /> { private onTxSuccess = (vote: NewVote, txResult: SubmittableResult): void => { let hasVotedEvent = false; + txResult.events.forEach((event, i) => { const { section, method } = event.event; + if (section === 'councilElection' && method === 'Voted') { hasVotedEvent = true; } }); + if (hasVotedEvent) { saveVote(vote); this.setState({ isFormSubmitted: true }); @@ -203,6 +207,7 @@ class Component extends React.PureComponent { private onChangeStake = (stake?: BN) => { const isStakeValid = stake && stake.gte(this.minStake()); + this.setState({ stake, isStakeValid }); } diff --git a/pioneer/packages/joy-election/src/Votes.tsx b/pioneer/packages/joy-election/src/Votes.tsx index d238dcd6c6..1d1baadea3 100644 --- a/pioneer/packages/joy-election/src/Votes.tsx +++ b/pioneer/packages/joy-election/src/Votes.tsx @@ -26,7 +26,7 @@ class Component extends React.PureComponent { return <>
- { stage?.unwrapOr(undefined)?.isOfType('Voting') + { stage?.unwrapOr(undefined)?.isOfType('Voting') ? ( ) @@ -35,7 +35,7 @@ class Component extends React.PureComponent { Voting is only possible during Voting stage. ) - } + }
{ private buildTabs (): TabItem[] { const { t, activeCouncil = [], applicants = [], commitments = [] } = this.props; + return [ { isRoot: true, @@ -62,6 +63,7 @@ class App extends React.PureComponent { render () { const { basePath } = this.props; const tabs = this.buildTabs(); + return (
diff --git a/pioneer/packages/joy-election/src/myVotesStore.ts b/pioneer/packages/joy-election/src/myVotesStore.ts index cfc3bc3d96..62b0006e40 100644 --- a/pioneer/packages/joy-election/src/myVotesStore.ts +++ b/pioneer/packages/joy-election/src/myVotesStore.ts @@ -20,22 +20,25 @@ export type SavedVote = NewVote & { /** Get all votes that are stored in a local sotrage. */ export const getAllVotes = (): SavedVote[] => { const votes = store.get(MY_VOTES); + return nonEmptyArr(votes) ? votes as SavedVote[] : []; }; export const getVotesByVoter = (voterId: string): SavedVote[] => { - return getAllVotes().filter(v => v.voterId === voterId); + return getAllVotes().filter((v) => v.voterId === voterId); }; export const findVoteByHash = (hash: string): SavedVote | undefined => { - return getAllVotes().find(v => v.hash === hash); + return getAllVotes().find((v) => v.hash === hash); }; export const saveVote = (vote: NewVote): void => { const votes = getAllVotes(); - const similarVote = votes.find(v => v.hash === vote.hash); + const similarVote = votes.find((v) => v.hash === vote.hash); + if (similarVote) { console.log('There is a vote with the same hash in a storage:', similarVote); + return; } @@ -45,7 +48,8 @@ export const saveVote = (vote: NewVote): void => { export const revealVote = (hash: string): void => { const votes = getAllVotes(); - const savedVote = votes.find(v => v.hash === hash); + const savedVote = votes.find((v) => v.hash === hash); + if (savedVote && !savedVote.isRevealed) { savedVote.isRevealed = true; savedVote.revealedOnTime = Date.now(); diff --git a/pioneer/packages/joy-election/src/utils.tsx b/pioneer/packages/joy-election/src/utils.tsx index 5a4cafb55a..812fa652ad 100644 --- a/pioneer/packages/joy-election/src/utils.tsx +++ b/pioneer/packages/joy-election/src/utils.tsx @@ -22,16 +22,19 @@ export type HashedVote = { const createAddressOption = (address: string) => { const name = findNameByAddress(address); + return createItem(address, name); }; -export const accountIdsToOptions = (applicants: Array): any => { +export const accountIdsToOptions = (applicants: Array) => { if (applicants && applicants.length) { - return applicants.map(a => { + return applicants.map((a) => { const addr = a.toString(); + return createAddressOption(addr); }); } + return []; }; @@ -45,10 +48,12 @@ export const hashVote = (accountId?: string | null, salt?: string): string | nul const accountU8a = decodeAddress(accountId); const saltU8a = stringToU8a(salt); const voteU8a = new Uint8Array(accountU8a.length + saltU8a.length); + voteU8a.set(accountU8a); voteU8a.set(saltU8a, accountU8a.length); const hash = blake2AsHex(voteU8a, 256); + // console.log('Vote hash:', hash, 'for', { accountId, salt }); return hash; }; diff --git a/pioneer/packages/joy-utils/src/react/components/InputStake.tsx b/pioneer/packages/joy-utils/src/react/components/InputStake.tsx index 8e012fe42f..5c18e525ee 100644 --- a/pioneer/packages/joy-utils/src/react/components/InputStake.tsx +++ b/pioneer/packages/joy-utils/src/react/components/InputStake.tsx @@ -14,6 +14,7 @@ type Props = { export default class Component extends React.PureComponent { render () { const { min, label, isValid, onChange } = this.props; + return (
{ color={ isValid ? 'green' : 'red' } icon={isValid ? 'check' : 'warning sign'} label='Minimum stake' - pointing="left" + pointing='left' > Minimum stake {formatBalance(min)} diff --git a/pioneer/packages/joy-utils/src/react/components/MemberByAccountPreview.tsx b/pioneer/packages/joy-utils/src/react/components/MemberByAccountPreview.tsx index 2fc8e28d83..bcae5779f7 100644 --- a/pioneer/packages/joy-utils/src/react/components/MemberByAccountPreview.tsx +++ b/pioneer/packages/joy-utils/src/react/components/MemberByAccountPreview.tsx @@ -23,7 +23,7 @@ const MemberByAccountPreview: React.FunctionComponent = ({ accountId }) = ); return ( - + { member && ( member.profile diff --git a/pioneer/packages/joy-utils/src/react/components/MemberProfilePreview.tsx b/pioneer/packages/joy-utils/src/react/components/MemberProfilePreview.tsx index af503bc575..69ea8b7cab 100644 --- a/pioneer/packages/joy-utils/src/react/components/MemberProfilePreview.tsx +++ b/pioneer/packages/joy-utils/src/react/components/MemberProfilePreview.tsx @@ -48,9 +48,9 @@ export default function ProfilePreview ( const Preview = ( {avatar_uri.toString() ? ( - + ) : ( - + )}
{handle.toString()} @@ -77,6 +77,7 @@ export function ProfilePreviewFromStruct ( { profile, link, id, children }: React.PropsWithChildren ) { const { avatar_uri, root_account, handle } = profile; + return ( {children} diff --git a/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx b/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx index accada8040..6777c33944 100644 --- a/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx +++ b/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx @@ -14,7 +14,8 @@ const StyledMembersDropdown = styled(Dropdown)` `; function membersToOptions (members: MemberFromAccount[]) { - const validMembers = members.filter(m => m.profile !== undefined) as (MemberFromAccount & { profile: Membership })[]; + const validMembers = members.filter((m) => m.profile !== undefined) as (MemberFromAccount & { profile: Membership })[]; + return validMembers .map(({ memberId, profile, account }) => ({ key: profile.handle, @@ -37,17 +38,20 @@ const MembersDropdown: React.FunctionComponent = ({ accounts, ...passedPr // State const [loading, setLoading] = useState(true); const [membersOptions, setMembersOptions] = useState([] as DropdownItemProps[]); + // Generate members options array on load useEffect(() => { let isSubscribed = true; + Promise - .all(accounts.map(acc => transport.members.membershipFromAccount(acc))) - .then(members => { + .all(accounts.map((acc) => transport.members.membershipFromAccount(acc))) + .then((members) => { if (isSubscribed) { setMembersOptions(membersToOptions(members)); setLoading(false); } }); + return () => { isSubscribed = false; }; }, [accounts]); diff --git a/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx b/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx index 18395aa101..b91c54ef75 100644 --- a/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx +++ b/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx @@ -7,6 +7,7 @@ type ErrorProps = { export function Error ({ error }: ErrorProps) { console.error(error); + return ( @@ -34,6 +35,7 @@ type PromiseComponentProps = { error: any; message: string; } + const PromiseComponent: React.FunctionComponent = ({ loading, error, message, children }) => { if (loading && !error) { return ; diff --git a/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx b/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx index 67f4d679ff..7dcc60475c 100644 --- a/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx +++ b/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx @@ -17,18 +17,21 @@ export default function usePromise ( let isSubscribed = true; const execute = useCallback(() => { setState({ value: state.value, error: null, isPending: true }); + return promise() - .then(value => { + .then((value) => { if (isSubscribed) { setState({ value, error: null, isPending: false }); + if (onUpdate) { onUpdate(value); } } }) - .catch(error => { + .catch((error) => { if (isSubscribed) { setState({ value: defaultValue, error: error, isPending: false }); + if (onUpdate) { onUpdate(defaultValue); // This should represent an empty value in most cases } @@ -38,11 +41,13 @@ export default function usePromise ( useEffect(() => { execute(); + return () => { isSubscribed = false; }; }, dependsOn); const { value, error, isPending } = state; + return [value, error, isPending, execute]; } diff --git a/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts b/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts index 8643a7b7e1..07bd9d1fd1 100644 --- a/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts +++ b/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts @@ -40,22 +40,28 @@ export class APIQueryCache { } protected buildQuery () { - const modules = Object.keys(this.api.query).map(key => ({ name: key, storage: this.api.query[key] })); + const modules = Object.keys(this.api.query).map((key) => ({ name: key, storage: this.api.query[key] })); + modules.map((module) => { this.query[module.name] = {}; - const funcs = Object.keys(module.storage).map(key => ({ name: key, storage: module.storage[key] })); + const funcs = Object.keys(module.storage).map((key) => ({ name: key, storage: module.storage[key] })); + funcs.map((func) => { this.query[module.name][func.name] = async (...args: any): Promise => { const cacheKey = module.name + func.name + JSON.stringify(args); const cacheValue = this.cache.get(cacheKey); + if (cacheValue) { this.cacheHits++; + return cacheValue; } const toCache = await this.api.query[module.name][func.name](...args); + this.cache.set(cacheKey, toCache); + return toCache; }; }); diff --git a/pioneer/packages/joy-utils/src/transport/base.ts b/pioneer/packages/joy-utils/src/transport/base.ts index b8a1433d1b..102a9d2083 100644 --- a/pioneer/packages/joy-utils/src/transport/base.ts +++ b/pioneer/packages/joy-utils/src/transport/base.ts @@ -61,6 +61,7 @@ export default abstract class BaseTransport { protected queryMethodByName (name: string) { const [module, method] = name.split('.'); + return this.api.query[module][method]; } } diff --git a/pioneer/packages/joy-utils/src/transport/members.ts b/pioneer/packages/joy-utils/src/transport/members.ts index 5a90bf74df..059b1a2f61 100644 --- a/pioneer/packages/joy-utils/src/transport/members.ts +++ b/pioneer/packages/joy-utils/src/transport/members.ts @@ -7,6 +7,7 @@ import { MemberFromAccount } from '../types/members'; export default class MembersTransport extends BaseTransport { async membershipById (id: MemberId | number): Promise { const member = (await this.members.membershipById(id)) as Membership; + // Can't just use member.isEmpty because member.suspended is Bool (which isEmpty method always returns false) return member.handle.isEmpty ? null : member; } @@ -14,6 +15,7 @@ export default class MembersTransport extends BaseTransport { // Throws if profile not found async expectedMembership (id: MemberId | number): Promise { const member = await this.membershipById(id); + if (!member) { throw new Error(`Expected member profile not found! ID: ${id.toString()}`); } @@ -34,7 +36,7 @@ export default class MembersTransport extends BaseTransport { return { account: accountId.toString(), memberId: memberId && memberId.toNumber(), - profile, + profile }; } } From 2e655f7f8f3dca6500145641487e12c40e8a4c7b Mon Sep 17 00:00:00 2001 From: Leszek Wiesner Date: Fri, 14 Aug 2020 14:14:39 +0200 Subject: [PATCH 008/178] Linting: Manual fixes (required refactoring usePromise) --- .../packages/joy-election/src/Applicants.tsx | 3 +- pioneer/packages/joy-election/src/Council.tsx | 6 +-- .../packages/joy-election/src/Dashboard.tsx | 5 ++- pioneer/packages/joy-election/src/Reveals.tsx | 10 ++--- .../packages/joy-election/src/VoteForm.tsx | 8 ++-- pioneer/packages/joy-election/src/Votes.tsx | 5 ++- pioneer/packages/joy-election/src/index.tsx | 7 +-- .../packages/joy-election/src/myVotesStore.ts | 2 +- .../packages/joy-utils/src/functions/misc.ts | 14 ++++++ .../src/react/components/MembersDropdown.tsx | 15 ++++--- .../src/react/components/PromiseComponent.tsx | 6 +-- .../joy-utils/src/react/context/transport.tsx | 2 +- .../joy-utils/src/react/hooks/usePromise.tsx | 44 +++++++++++++------ .../joy-utils/src/transport/APIQueryCache.ts | 8 ++-- .../packages/joy-utils/src/transport/base.ts | 1 - 15 files changed, 87 insertions(+), 49 deletions(-) diff --git a/pioneer/packages/joy-election/src/Applicants.tsx b/pioneer/packages/joy-election/src/Applicants.tsx index e999dc675c..68a8c916fb 100644 --- a/pioneer/packages/joy-election/src/Applicants.tsx +++ b/pioneer/packages/joy-election/src/Applicants.tsx @@ -16,8 +16,9 @@ import Section from '@polkadot/joy-utils/react/components/Section'; import { queryToProp } from '@polkadot/joy-utils/functions/misc'; import { withMyAccount, MyAccountProps } from '@polkadot/joy-utils/react/hocs/accounts'; import { ElectionStage } from '@joystream/types/src/council'; +import { RouteProps } from 'react-router-dom'; -type Props = ApiProps & I18nProps & MyAccountProps & { +type Props = RouteProps & ApiProps & I18nProps & MyAccountProps & { candidacyLimit?: BN; applicants?: Array; stage?: Option; diff --git a/pioneer/packages/joy-election/src/Council.tsx b/pioneer/packages/joy-election/src/Council.tsx index 6ad36df3f5..f4e9e9597d 100644 --- a/pioneer/packages/joy-election/src/Council.tsx +++ b/pioneer/packages/joy-election/src/Council.tsx @@ -11,13 +11,13 @@ import { calcBackersStake } from '@polkadot/joy-utils/functions/misc'; import { Seat } from '@joystream/types/council'; import translate from './translate'; import Section from '@polkadot/joy-utils/react/components/Section'; +import { RouteProps } from 'react-router-dom'; -type Props = ApiProps & -I18nProps & { +type Props = RouteProps & ApiProps & I18nProps & { council?: Seat[]; }; -type State = {}; +type State = Record; class Council extends React.PureComponent { state: State = {}; diff --git a/pioneer/packages/joy-election/src/Dashboard.tsx b/pioneer/packages/joy-election/src/Dashboard.tsx index f115cc1917..da6fffbd9c 100644 --- a/pioneer/packages/joy-election/src/Dashboard.tsx +++ b/pioneer/packages/joy-election/src/Dashboard.tsx @@ -13,8 +13,9 @@ import Section from '@polkadot/joy-utils/react/components/Section'; import { queryToProp } from '@polkadot/joy-utils/functions/misc'; import { ElectionStage, Seat } from '@joystream/types/council'; import translate from './translate'; +import { RouteProps } from 'react-router-dom'; -type Props = ApiProps & I18nProps & { +type Props = RouteProps & ApiProps & I18nProps & { bestNumber?: BN; activeCouncil?: Seat[]; @@ -34,7 +35,7 @@ type Props = ApiProps & I18nProps & { stage?: Option; }; -type State = {}; +type State = Record; class Dashboard extends React.PureComponent { state: State = {}; diff --git a/pioneer/packages/joy-election/src/Reveals.tsx b/pioneer/packages/joy-election/src/Reveals.tsx index ae556d042d..0c980ac7ff 100644 --- a/pioneer/packages/joy-election/src/Reveals.tsx +++ b/pioneer/packages/joy-election/src/Reveals.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import { AppProps, I18nProps } from '@polkadot/react-components/types'; +import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; import { withCalls, withMulti } from '@polkadot/react-api/hoc'; import { AccountId } from '@polkadot/types/interfaces'; @@ -12,12 +12,12 @@ import { accountIdsToOptions, hashVote } from './utils'; import TxButton from '@polkadot/joy-utils/react/components/TxButton'; import { findVoteByHash } from './myVotesStore'; import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards'; +import { RouteProps } from 'react-router-dom'; // AppsProps is needed to get a location from the route. -type Props = AppProps & ApiProps & I18nProps & { +type Props = RouteProps & ApiProps & I18nProps & { applicantId?: string | null; applicants?: AccountId[]; - location: any; }; type State = { @@ -31,8 +31,8 @@ class RevealVoteForm extends React.PureComponent { super(props); let { applicantId, location } = this.props; - applicantId = applicantId || getUrlParam(location, 'applicantId'); - const hashedVote = getUrlParam(location, 'hashedVote'); + applicantId = applicantId || (location && getUrlParam(location, 'applicantId')); + const hashedVote = location && getUrlParam(location, 'hashedVote'); this.state = { applicantId, diff --git a/pioneer/packages/joy-election/src/VoteForm.tsx b/pioneer/packages/joy-election/src/VoteForm.tsx index 1a7e1232ff..fdb74b95d8 100644 --- a/pioneer/packages/joy-election/src/VoteForm.tsx +++ b/pioneer/packages/joy-election/src/VoteForm.tsx @@ -4,7 +4,7 @@ import uuid from 'uuid/v4'; import React from 'react'; import { Message, Table } from 'semantic-ui-react'; -import { AppProps, I18nProps } from '@polkadot/react-components/types'; +import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; import { withCalls, withMulti } from '@polkadot/react-api/hoc'; import { AccountId, Balance } from '@polkadot/types/interfaces'; @@ -23,6 +23,7 @@ import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards'; import MembersDropdown from '@polkadot/joy-utils/react/components/MembersDropdown'; import { saveVote, NewVote } from './myVotesStore'; import { TxFailedCallback } from '@polkadot/react-components/Status/types'; +import { RouteProps } from 'react-router-dom'; // TODO use a crypto-prooven generator instead of UUID 4. function randomSalt () { @@ -30,11 +31,10 @@ function randomSalt () { } // AppsProps is needed to get a location from the route. -type Props = AppProps & ApiProps & I18nProps & MyAccountProps & { +type Props = RouteProps & ApiProps & I18nProps & MyAccountProps & { applicantId?: string | null; minVotingStake?: Balance; applicants?: AccountId[]; - location?: any; }; type State = { @@ -51,7 +51,7 @@ class Component extends React.PureComponent { let { applicantId, location } = this.props; - applicantId = applicantId || getUrlParam(location, 'applicantId'); + applicantId = applicantId || (location && getUrlParam(location, 'applicantId')); this.state = { applicantId, diff --git a/pioneer/packages/joy-election/src/Votes.tsx b/pioneer/packages/joy-election/src/Votes.tsx index 1d1baadea3..7890d30781 100644 --- a/pioneer/packages/joy-election/src/Votes.tsx +++ b/pioneer/packages/joy-election/src/Votes.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import { AppProps, I18nProps } from '@polkadot/react-components/types'; +import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; import { withCalls } from '@polkadot/react-api/hoc'; import { Message } from 'semantic-ui-react'; @@ -14,8 +14,9 @@ import { getVotesByVoter } from './myVotesStore'; import VoteForm from './VoteForm'; import { queryToProp } from '@polkadot/joy-utils/functions/misc'; import { ElectionStage } from '@joystream/types/src/council'; +import { RouteProps } from 'react-router-dom'; -type Props = AppProps & ApiProps & I18nProps & MyAccountProps & { +type Props = RouteProps & ApiProps & I18nProps & MyAccountProps & { stage?: Option; }; diff --git a/pioneer/packages/joy-election/src/index.tsx b/pioneer/packages/joy-election/src/index.tsx index 918178c188..7e6be023af 100644 --- a/pioneer/packages/joy-election/src/index.tsx +++ b/pioneer/packages/joy-election/src/index.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { Route, Switch } from 'react-router'; import { I18nProps } from '@polkadot/react-components/types'; -import { RouteProps } from '@polkadot/apps-routing/types'; +import { RouteProps as AppMainRouteProps } from '@polkadot/apps-routing/types'; import { withCalls } from '@polkadot/react-api/hoc'; import { AccountId, Hash } from '@polkadot/types/interfaces'; import Tabs from '@polkadot/react-components/Tabs'; @@ -21,17 +21,18 @@ import Votes from './Votes'; import Reveals from './Reveals'; import { queryToProp } from '@polkadot/joy-utils/functions/misc'; import { Seat } from '@joystream/types/council'; +import { ApiProps } from '@polkadot/react-api/types'; const ElectionMain = styled.main`${style}`; // define out internal types -type Props = RouteProps & I18nProps & { +type Props = AppMainRouteProps & ApiProps & I18nProps & { activeCouncil?: Seat[]; applicants?: AccountId[]; commitments?: Hash[]; }; -type State = {}; +type State = Record; class App extends React.PureComponent { state: State = {}; diff --git a/pioneer/packages/joy-election/src/myVotesStore.ts b/pioneer/packages/joy-election/src/myVotesStore.ts index 62b0006e40..16921a8b72 100644 --- a/pioneer/packages/joy-election/src/myVotesStore.ts +++ b/pioneer/packages/joy-election/src/myVotesStore.ts @@ -19,7 +19,7 @@ export type SavedVote = NewVote & { /** Get all votes that are stored in a local sotrage. */ export const getAllVotes = (): SavedVote[] => { - const votes = store.get(MY_VOTES); + const votes = store.get(MY_VOTES) as unknown; return nonEmptyArr(votes) ? votes as SavedVote[] : []; }; diff --git a/pioneer/packages/joy-utils/src/functions/misc.ts b/pioneer/packages/joy-utils/src/functions/misc.ts index 5f9deaf90e..5f96730c33 100644 --- a/pioneer/packages/joy-utils/src/functions/misc.ts +++ b/pioneer/packages/joy-utils/src/functions/misc.ts @@ -6,6 +6,7 @@ import { Options as QueryOptions } from '@polkadot/react-api/hoc/types'; import queryString from 'query-string'; import { SubmittableResult } from '@polkadot/api'; import { Codec } from '@polkadot/types/types'; +import { Location } from 'history'; export const ZERO = new BN(0); @@ -165,3 +166,16 @@ export function includeKeys (obj: T, ...allowedK export function bytesToString (bytes: Bytes) { return Buffer.from(bytes.toString().substr(2), 'hex').toString(); } + +export function normalizeError (e: any): string { + let message: string; + + if (e instanceof Error) { + message = e.message; + } else { + message = JSON.stringify(e); + } + + // Prevent returning falsely value + return message || 'Unexpected error'; +} diff --git a/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx b/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx index 6777c33944..d53a4ba490 100644 --- a/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx +++ b/pioneer/packages/joy-utils/src/react/components/MembersDropdown.tsx @@ -1,6 +1,5 @@ import React, { useEffect, useState } from 'react'; import { Dropdown, DropdownItemProps, DropdownProps } from 'semantic-ui-react'; -import { Membership } from '@joystream/types/members'; import { MemberFromAccount } from '../../types/members'; import { useTransport } from '../hooks'; import { AccountId } from '@polkadot/types/interfaces'; @@ -14,14 +13,15 @@ const StyledMembersDropdown = styled(Dropdown)` `; function membersToOptions (members: MemberFromAccount[]) { - const validMembers = members.filter((m) => m.profile !== undefined) as (MemberFromAccount & { profile: Membership })[]; + const validMembers = members.filter((m) => m.profile !== undefined); + // Here we can assert "profile!" and "memberId!", because we filtered out those that don't have it. return validMembers .map(({ memberId, profile, account }) => ({ - key: profile.handle, - text: `${profile.handle} (id:${memberId})`, + key: profile!.handle.toString(), + text: `${profile!.handle.toString()} (id:${memberId!})`, value: account, - image: profile.avatar_uri.toString() ? { avatar: true, src: profile.avatar_uri } : null + image: profile!.avatar_uri.toString() ? { avatar: true, src: profile!.avatar_uri } : null })); } @@ -50,9 +50,12 @@ const MembersDropdown: React.FunctionComponent = ({ accounts, ...passedPr setMembersOptions(membersToOptions(members)); setLoading(false); } - }); + }) + .catch((e) => { throw e; }); return () => { isSubscribed = false; }; + // We don't need transport.members as dependency here, because we assume it's always the same, so: + // eslint-disable-next-line react-hooks/exhaustive-deps }, [accounts]); return ( diff --git a/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx b/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx index b91c54ef75..bc46d329e8 100644 --- a/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx +++ b/pioneer/packages/joy-utils/src/react/components/PromiseComponent.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { Container, Message, Loader } from 'semantic-ui-react'; type ErrorProps = { - error: any; + error: string | null; }; export function Error ({ error }: ErrorProps) { @@ -12,7 +12,7 @@ export function Error ({ error }: ErrorProps) { Oops! We got an error! -

{error.message}

+

{error}

); @@ -32,7 +32,7 @@ export function Loading ({ text }: LoadingProps) { type PromiseComponentProps = { loading: boolean; - error: any; + error: string | null; message: string; } diff --git a/pioneer/packages/joy-utils/src/react/context/transport.tsx b/pioneer/packages/joy-utils/src/react/context/transport.tsx index 29acbdae87..91a599572a 100644 --- a/pioneer/packages/joy-utils/src/react/context/transport.tsx +++ b/pioneer/packages/joy-utils/src/react/context/transport.tsx @@ -6,7 +6,7 @@ import Transport from '../../transport/index'; export const TransportContext = createContext((null as unknown) as Transport); -export function TransportProvider ({ children }: { children: React.PropsWithChildren<{}> }) { +export function TransportProvider ({ children }: { children: React.PropsWithChildren }) { const api: ApiProps = useContext(ApiContext); if (!api) { diff --git a/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx b/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx index 7dcc60475c..cb4f8f8190 100644 --- a/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx +++ b/pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx @@ -1,6 +1,8 @@ -import { useState, useEffect, useCallback } from 'react'; +import { useState, useEffect, useRef } from 'react'; +import { normalizeError } from '../../functions/misc'; +import { randomBytes } from 'crypto'; -export type UsePromiseReturnValues = [T, any, boolean, () => Promise]; +export type UsePromiseReturnValues = [T, string | null, boolean]; export default function usePromise ( promise: () => Promise, @@ -10,44 +12,58 @@ export default function usePromise ( ): UsePromiseReturnValues { const [state, setState] = useState<{ value: T; - error: any; + error: string | null; isPending: boolean; }>({ value: defaultValue, error: null, isPending: true }); - let isSubscribed = true; - const execute = useCallback(() => { - setState({ value: state.value, error: null, isPending: true }); + const subscribedPromiseToken = useRef(null); - return promise() + const executeAndSubscribePromise = () => { + setState((state) => ({ ...state, error: null, isPending: true })); + + const thisPromiseToken = randomBytes(32).toString('hex'); + + subscribedPromiseToken.current = thisPromiseToken; + + promise() .then((value) => { - if (isSubscribed) { + if (subscribedPromiseToken.current === thisPromiseToken) { setState({ value, error: null, isPending: false }); if (onUpdate) { onUpdate(value); } + } else { + console.warn('usePromise: Token didn\'t match on .then()'); + console.warn(`Subscribed promise: ${subscribedPromiseToken.current || 'NONE'}. Resolved promise: ${thisPromiseToken}.`); } }) .catch((error) => { - if (isSubscribed) { - setState({ value: defaultValue, error: error, isPending: false }); + if (subscribedPromiseToken.current === thisPromiseToken) { + setState({ value: defaultValue, error: normalizeError(error), isPending: false }); if (onUpdate) { onUpdate(defaultValue); // This should represent an empty value in most cases } + } else { + console.warn('usePromise: Token didn\'t match on .catch()'); + console.warn(`Subscribed promise: ${subscribedPromiseToken.current || 'NONE'}. Rejected promise: ${thisPromiseToken}.`); } }); - }, [promise]); + }; useEffect(() => { - execute(); + executeAndSubscribePromise(); return () => { - isSubscribed = false; + subscribedPromiseToken.current = null; }; + // Silence "React Hook useEffect was passed a dependency list that is not an array literal", + // since we want to preserve the ability to pass custom "depnendencies". + // eslint-disable-next-line react-hooks/exhaustive-deps }, dependsOn); const { value, error, isPending } = state; - return [value, error, isPending, execute]; + return [value, error, isPending]; } diff --git a/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts b/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts index 07bd9d1fd1..d04b9579f2 100644 --- a/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts +++ b/pioneer/packages/joy-utils/src/transport/APIQueryCache.ts @@ -24,15 +24,17 @@ export class APIQueryCache { this.api = api; this.buildQuery(); this.cache = new Map(); - this.breakCacheOnNewBlocks(); + this.breakCacheOnNewBlocks() + .then((unsub) => { this.unsubscribeFn = unsub; }) + .catch((e) => { throw e; }); } unsubscribe () { this.unsubscribeFn(); } - protected async breakCacheOnNewBlocks () { - this.unsubscribeFn = await this.api.rpc.chain.subscribeNewHeads((header) => { + protected breakCacheOnNewBlocks () { + return this.api.rpc.chain.subscribeNewHeads((header) => { this.cache = new Map(); // console.log("cache hits in this block", this.cacheHits) this.cacheHits = 0; diff --git a/pioneer/packages/joy-utils/src/transport/base.ts b/pioneer/packages/joy-utils/src/transport/base.ts index 102a9d2083..0e37496ee2 100644 --- a/pioneer/packages/joy-utils/src/transport/base.ts +++ b/pioneer/packages/joy-utils/src/transport/base.ts @@ -1,5 +1,4 @@ import { ApiPromise } from '@polkadot/api'; -import { Codec } from '@polkadot/types/types'; import { APIQueryCache } from './APIQueryCache'; export default abstract class BaseTransport { From 9fadcaf0be61f876522d2fb244635370f3f16caf Mon Sep 17 00:00:00 2001 From: Leszek Wiesner Date: Fri, 14 Aug 2020 16:17:12 +0200 Subject: [PATCH 009/178] Minor UI improvements --- .../packages/joy-election/src/Applicant.tsx | 11 +++--- .../packages/joy-election/src/Applicants.tsx | 36 +++++++++++-------- .../packages/joy-election/src/SealedVotes.tsx | 4 +-- 3 files changed, 30 insertions(+), 21 deletions(-) diff --git a/pioneer/packages/joy-election/src/Applicant.tsx b/pioneer/packages/joy-election/src/Applicant.tsx index c8435a3f7f..0626c53e1e 100644 --- a/pioneer/packages/joy-election/src/Applicant.tsx +++ b/pioneer/packages/joy-election/src/Applicant.tsx @@ -17,11 +17,12 @@ type Props = ApiProps & I18nProps & { index: number; accountId: AccountId; stake?: ElectionStake; + isVotingStage: boolean; }; class Applicant extends React.PureComponent { render () { - const { index, accountId, stake } = this.props; + const { index, accountId, stake, isVotingStage } = this.props; const voteUrl = `/council/votes?applicantId=${accountId.toString()}`; return ( @@ -33,9 +34,11 @@ class Applicant extends React.PureComponent { {formatBalance(calcTotalStake(stake))} - - Vote - + { isVotingStage && ( + + Vote + + ) } ); } diff --git a/pioneer/packages/joy-election/src/Applicants.tsx b/pioneer/packages/joy-election/src/Applicants.tsx index 68a8c916fb..3ee84db4d7 100644 --- a/pioneer/packages/joy-election/src/Applicants.tsx +++ b/pioneer/packages/joy-election/src/Applicants.tsx @@ -25,21 +25,27 @@ type Props = RouteProps & ApiProps & I18nProps & MyAccountProps & { }; class Applicants extends React.PureComponent { - private renderTable = (applicants: Array) => ( - - - - # - Applicant - Total stake - Actions - - - {applicants.map((accountId, index) => ( - - ))} -
- ) + private renderTable = (applicants: Array) => { + const isVotingStage = this.props.stage?.unwrapOr(undefined)?.isOfType('Voting') || false; + + return ( + + + + # + Applicant + Total stake + { isVotingStage && ( + Actions + ) } + + + {applicants.map((accountId, index) => ( + + ))} +
+ ); + } render () { const { myAddress, applicants = [], candidacyLimit = new BN(0), stage } = this.props; diff --git a/pioneer/packages/joy-election/src/SealedVotes.tsx b/pioneer/packages/joy-election/src/SealedVotes.tsx index f7908e4c48..5effd2b117 100644 --- a/pioneer/packages/joy-election/src/SealedVotes.tsx +++ b/pioneer/packages/joy-election/src/SealedVotes.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { Link } from 'react-router-dom'; -import { Button } from 'semantic-ui-react'; +import { Button, Message } from 'semantic-ui-react'; import { I18nProps } from '@polkadot/react-components/types'; import { ApiProps } from '@polkadot/react-api/types'; @@ -49,7 +49,7 @@ class Comp extends React.PureComponent {
{ !myVotes.length - ? No votes by the current account found on the current browser. + ? No votes by the current account found on the current browser. : this.renderVotes(myVotes, true) } { this.props.isStageRevealing && } From f64e5c0751d50c27d9961239ebe08a6b753a2f9c Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Mon, 17 Aug 2020 16:39:32 +0200 Subject: [PATCH 010/178] made tests working with new API --- .../run_tests_single_node/tasks/main.yml | 4 +- devops/dockerfiles/ansible-node/Dockerfile | 2 + devops/dockerfiles/rust-builder/Dockerfile | 4 +- tests/network-tests/package.json | 4 +- .../iznik/tests/fixtures/proposalsModule.ts | 131 +++---- .../tests/fixtures/workingGroupModule.ts | 199 ++++------ .../src/iznik/tests/leaderSetup.ts | 2 +- ...entWorkingGroupMintCapacityProposalTest.ts | 4 +- .../electionParametersProposalTest.ts | 4 +- .../tests/proposals/manageLeaderRoleTest.ts | 4 +- .../tests/proposals/setLeadProposalTest.ts | 4 +- .../tests/proposals/spendingProposalTest.ts | 4 +- .../iznik/tests/proposals/textProposalTest.ts | 4 +- .../iznik/tests/proposals/updateRuntime.ts | 4 +- .../proposals/validatorCountProposalTest.ts | 4 +- .../workingGroupMintCapacityProposalTest.ts | 4 +- .../tests/workingGroup/atLeastValueBugTest.ts | 4 +- .../workingGroup/manageWorkerAsLeadTest.ts | 4 +- .../workingGroup/manageWorkerAsWorkerTest.ts | 4 +- .../workerApplicationHappyCaseTest.ts | 4 +- .../workerApplicationRejectionCaseTest.ts | 4 +- .../tests/workingGroup/workerPayoutTest.ts | 4 +- .../src/iznik/utils/apiWrapper.ts | 344 +++++++++++++----- tests/network-tests/src/iznik/utils/sender.ts | 8 +- 24 files changed, 403 insertions(+), 355 deletions(-) diff --git a/devops/ansible/roles/run_tests_single_node/tasks/main.yml b/devops/ansible/roles/run_tests_single_node/tasks/main.yml index 281d9cdcef..a64d78529e 100644 --- a/devops/ansible/roles/run_tests_single_node/tasks/main.yml +++ b/devops/ansible/roles/run_tests_single_node/tasks/main.yml @@ -7,14 +7,14 @@ image: "joystream/node-testing" ports: - "9944:9944" - entrypoint: ./node --chain=chainspec.json --alice --validator --ws-external --rpc-cors=all + entrypoint: ./node --chain=chainspec.json --alice --validator --unsafe-ws-external --rpc-cors=all state: started - name: execute network tests shell: yarn debug >> ../../.tmp/tests.log args: chdir: ../../tests/network-tests/ - + always: - name: stop docker container docker_container: diff --git a/devops/dockerfiles/ansible-node/Dockerfile b/devops/dockerfiles/ansible-node/Dockerfile index 22074f1c88..8d6d751d88 100644 --- a/devops/dockerfiles/ansible-node/Dockerfile +++ b/devops/dockerfiles/ansible-node/Dockerfile @@ -4,6 +4,8 @@ WORKDIR /joystream COPY . /joystream # Build joystream-node and its dependencies - runtime +RUN rustup override set 1.45.2 +RUN rustc --version RUN cargo build --release -p joystream-node RUN /joystream/scripts/create-test-chainspec.sh diff --git a/devops/dockerfiles/rust-builder/Dockerfile b/devops/dockerfiles/rust-builder/Dockerfile index c6e0d9283f..fc5f56f016 100644 --- a/devops/dockerfiles/rust-builder/Dockerfile +++ b/devops/dockerfiles/rust-builder/Dockerfile @@ -1,8 +1,8 @@ -FROM liuchong/rustup:1.43.0 AS builder +FROM liuchong/rustup:nightly AS builder LABEL description="Rust and WASM build environment for joystream and substrate" WORKDIR /setup COPY setup.sh /setup ENV TERM=xterm -RUN ./setup.sh \ No newline at end of file +RUN ./setup.sh diff --git a/tests/network-tests/package.json b/tests/network-tests/package.json index 3471380d4b..2e00211d8c 100644 --- a/tests/network-tests/package.json +++ b/tests/network-tests/package.json @@ -7,7 +7,7 @@ "test": "tap --files src/iznik/tests/unknown.unknown src/iznik/tests/councilSetup.ts src/iznik/tests/proposals/*Test.ts src/iznik/tests/leaderSetup.ts src/iznik/tests/workingGroup/*Test.ts -T", "test-migration-constantinople": "tap --files src/rome/tests/romeRuntimeUpgradeTest.ts --files src/constantinople/tests/electingCouncilTest.ts -T", "test-migration-nicaea": "tap --files src/constantinople/tests/proposals/updateRuntimeTest.ts --files src/nicaea/tests/electingCouncilTest.ts -T", - "debug": "tap --files src/iznik/tests/councilSetup.ts -T", + "debug": "tap --files src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts -T", "lint": "eslint . --quiet --ext .ts", "checks": "yarn lint && tsc --noEmit --pretty && prettier ./ --check", "format": "prettier ./ --write " @@ -15,7 +15,7 @@ "dependencies": { "@constantinople/types@npm:@joystream/types": "^0.10.0", "@nicaea/types@npm:@joystream/types": "^0.12.0", - "@alexandria/types": "link:../../types", + "@alexandria/types": "./types", "@polkadot/api": "1.26.1", "@polkadot/keyring": "3.0.1", "@rome/types@npm:@joystream/types": "^0.7.0", diff --git a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts index 7d296075a5..cd8655d81d 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts @@ -1,26 +1,13 @@ -import { KeyringPair } from '@polkadot/keyring/types' -import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' -import { v4 as uuid } from 'uuid' +import {KeyringPair} from '@polkadot/keyring/types' +import {ApiWrapper, WorkingGroups} from '../../utils/apiWrapper' +import {v4 as uuid} from 'uuid' import BN from 'bn.js' -import { FillOpeningParameters, ProposalId } from '@alexandria/types/proposals' -import { Fixture } from './interfaces/fixture' -import { Bytes, Option, u32 } from '@polkadot/types' -import { Balance, BlockNumber } from '@polkadot/types/interfaces' -import { assert } from 'chai' -import { - ActivateOpeningAt, - ApplicationId, - ApplicationRationingPolicy, - OpeningId, - StakingPolicy, -} from '@alexandria/types/hiring' -import { - RewardPolicy, - SlashingTerms, - WorkerId, - WorkingGroupOpeningPolicyCommitment, -} from '@alexandria/types/working-group' -import { WorkingGroup } from '@alexandria/types/common' +import {ProposalId} from '@alexandria/types/proposals' +import {Fixture} from './interfaces/fixture' +import {Bytes} from '@polkadot/types' +import {assert} from 'chai' +import {ApplicationId, OpeningId,} from '@alexandria/types/hiring' +import {WorkerId,} from '@alexandria/types/working-group' export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { private apiWrapper: ApiWrapper @@ -62,51 +49,34 @@ export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { const proposalFee: BN = this.apiWrapper.estimateProposeCreateWorkingGroupLeaderOpeningFee() await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) - // Opening construction - const activateAtBlock: ActivateOpeningAt = new ActivateOpeningAt('CurrentBlock') - const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({ - application_rationing_policy: new Option(ApplicationRationingPolicy, { - max_active_applicants: new BN(this.m1KeyPairs.length) as u32, - }), - max_review_period_length: new BN(32) as u32, - application_staking_policy: new Option(StakingPolicy, { - amount: this.applicationStake, - amount_mode: 'AtLeast', - crowded_out_unstaking_period_length: new BN(1), - review_period_expired_unstaking_period_length: new BN(1), - }), - role_staking_policy: new Option(StakingPolicy, { - amount: this.roleStake, - amount_mode: 'AtLeast', - crowded_out_unstaking_period_length: new BN(1), - review_period_expired_unstaking_period_length: new BN(1), - }), - role_slashing_terms: new SlashingTerms({ - Slashable: { - max_count: new BN(1), - max_percent_pts_per_time: new BN(100), - }, - }), - fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - }) - // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeCreateWorkingGroupLeaderOpening( - this.m1KeyPairs[0], - proposalTitle, - description, - proposalStake, - activateAtBlock, - commitment, - uuid().substring(0, 8), - this.workingGroup + { + account: this.m1KeyPairs[0], + title: proposalTitle, + description: description, + proposalStake: proposalStake, + actiavteAt: 'CurrentBlock', + maxActiveApplicants: new BN(this.m1KeyPairs.length), + maxReviewPeriodLength: new BN(32), + applicationStakingPolicyAmount: this.applicationStake, + applicationCrowdedOutUnstakingPeriodLength: new BN(1), + applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + roleStakingPolicyAmount: this.roleStake, + roleCrowdedOutUnstakingPeriodLength: new BN(1), + roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + slashableMaxCount: new BN(1), + slashableMaxPercentPtsPerTime: new BN(100), + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: new BN(1), + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: new BN(1), + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: new BN(1), + terminateApplicationStakeUnstakingPeriod: new BN(1), + terminateRoleStakeUnstakingPeriod: new BN(1), + exitRoleApplicationStakeUnstakingPeriod: new BN(1), + exitRoleStakeUnstakingPeriod: new BN(1), + text: uuid().substring(0, 8), + workingGroup: this.workingGroup} ) this.result = await proposalPromise if (expectFailure) { @@ -220,32 +190,27 @@ export class FillLeaderOpeningProposalFixture implements Fixture { await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation - const applicationId: BN = ( + const applicationId: ApplicationId = ( await this.apiWrapper.getActiveApplicationsIdsByRoleAccount(this.applicantRoleAccountAddress, this.workingGroup) )[0] const now: BN = await this.apiWrapper.getBestBlock() - const fillOpeningParameters: FillOpeningParameters = new FillOpeningParameters({ - opening_id: this.openingId as OpeningId, - successful_application_id: applicationId as ApplicationId, - reward_policy: new Option( - RewardPolicy, - new RewardPolicy({ - amount_per_payout: this.payoutAmount as Balance, - next_payment_at_block: now.add(this.firstRewardInterval) as BlockNumber, - payout_interval: new Option(u32, this.rewardInterval as u32), - }) - ), - working_group: new WorkingGroup(workingGroupString), - }) + console.log('Successfull application id ' + applicationId) const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeFillLeaderOpening( - this.m1KeyPairs[0], - proposalTitle, - description, - proposalStake, - fillOpeningParameters + { + account: this.m1KeyPairs[0], + title: proposalTitle, + description: description, + proposalStake: proposalStake, + openingId: this.openingId, + successfulApplicationId: applicationId, + amountPerPayout: this.payoutAmount, + nextPaymentAtBlock: now.add(this.firstRewardInterval), + payoutInterval: this.rewardInterval, + workingGroup: workingGroupString + } ) this.result = await proposalPromise if (expectFailure) { diff --git a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts index 66cba821fc..3fe72c7549 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts @@ -1,30 +1,15 @@ import BN from 'bn.js' -import { assert } from 'chai' -import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' -import { KeyringPair } from '@polkadot/keyring/types' -import { Balance, BlockNumber, Event } from '@polkadot/types/interfaces' -import { Keyring } from '@polkadot/api' -import { Option, u32 } from '@polkadot/types' -import { v4 as uuid } from 'uuid' -import { RewardRelationship } from '@alexandria/types/recurring-rewards' -import { - Application, - ApplicationIdToWorkerIdMap, - SlashingTerms, - Worker, - WorkerId, - WorkingGroupOpeningPolicyCommitment, -} from '@alexandria/types/working-group' -import { Utils } from '../../utils/utils' -import { - ActivateOpeningAt, - ApplicationId, - ApplicationRationingPolicy, - Opening as HiringOpening, - OpeningId, - StakingPolicy, -} from '@alexandria/types/hiring' -import { Fixture } from './interfaces/fixture' +import {assert} from 'chai' +import {ApiWrapper, WorkingGroups} from '../../utils/apiWrapper' +import {KeyringPair} from '@polkadot/keyring/types' +import {Event} from '@polkadot/types/interfaces' +import {Keyring} from '@polkadot/api' +import {v4 as uuid} from 'uuid' +import {RewardRelationship} from '@alexandria/types/recurring-rewards' +import {Application, ApplicationIdToWorkerIdMap, Worker, WorkerId,} from '@alexandria/types/working-group' +import {Utils} from '../../utils/utils' +import {ApplicationId, Opening as HiringOpening, OpeningId,} from '@alexandria/types/hiring' +import {Fixture} from './interfaces/fixture' export class AddWorkerOpeningFixture implements Fixture { private apiWrapper: ApiWrapper @@ -66,50 +51,6 @@ export class AddWorkerOpeningFixture implements Fixture { } public async runner(expectFailure: boolean): Promise { - // Worker opening construction - const activateAtBlock: ActivateOpeningAt = new ActivateOpeningAt( - this.activationDelay.eqn(0) - ? 'CurrentBlock' - : { ExactBlock: (await this.apiWrapper.getBestBlock()).add(this.activationDelay) } - ) - const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({ - application_rationing_policy: new Option(ApplicationRationingPolicy, { - max_active_applicants: new BN(this.membersKeyPairs.length) as u32, - }), - max_review_period_length: new BN(32) as u32, - application_staking_policy: new Option(StakingPolicy, { - amount: this.applicationStake, - amount_mode: 'AtLeast', - crowded_out_unstaking_period_length: new BN(1), - review_period_expired_unstaking_period_length: new BN(1), - }), - role_staking_policy: new Option(StakingPolicy, { - amount: this.roleStake, - amount_mode: 'AtLeast', - crowded_out_unstaking_period_length: new BN(1), - review_period_expired_unstaking_period_length: new BN(1), - }), - role_slashing_terms: new SlashingTerms({ - Slashable: { - max_count: new BN(1), - max_percent_pts_per_time: new BN(100), - }, - }), - fill_opening_successful_applicant_application_stake_unstaking_period: new Option( - u32, - this.unstakingPeriod as BlockNumber - ), - fill_opening_failed_applicant_application_stake_unstaking_period: new Option( - u32, - this.unstakingPeriod as BlockNumber - ), - fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber), - terminate_application_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber), - terminate_role_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber), - exit_role_application_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber), - exit_role_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber), - }) - // Fee estimation and transfer const addOpeningFee: BN = this.apiWrapper.estimateAddOpeningFee(this.module) await this.apiWrapper.transferBalance(this.sudo, this.lead.address, addOpeningFee) @@ -117,13 +58,30 @@ export class AddWorkerOpeningFixture implements Fixture { // Worker opening creation const addOpeningPromise: Promise = this.apiWrapper.expectEvent('OpeningAdded') await this.apiWrapper.addOpening( - this.lead, - activateAtBlock, - commitment, - uuid().substring(0, 8), - 'Worker', - this.module, - expectFailure + { + leader: this.lead, + activationDelay: this.activationDelay, + maxActiveApplicants: new BN(this.membersKeyPairs.length), + maxReviewPeriodLength: new BN(32), + applicationStakingPolicyAmount: this.applicationStake, + applicationCrowdedOutUnstakingPeriodLength: new BN(1), + applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + roleStakingPolicyAmount: this.roleStake, + roleCrowdedOutUnstakingPeriodLength: new BN(1), + roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + slashableMaxCount: new BN(1), + slashableMaxPercentPtsPerTime: new BN(100), + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: this.unstakingPeriod, + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: this.unstakingPeriod, + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: this.unstakingPeriod, + terminateApplicationStakeUnstakingPeriod: this.unstakingPeriod, + terminateRoleStakeUnstakingPeriod: this.unstakingPeriod, + exitRoleApplicationStakeUnstakingPeriod: this.unstakingPeriod, + exitRoleStakeUnstakingPeriod: this.unstakingPeriod, + text: uuid().substring(0, 8), + type: 'Worker', + module: this.module, + expectFailure: expectFailure} ) if (!expectFailure) { const openingId: OpeningId = (await addOpeningPromise).data[0] as OpeningId @@ -166,52 +124,32 @@ export class AddLeaderOpeningFixture implements Fixture { } public async runner(expectFailure: boolean): Promise { - // Leader opening creation - const activateAtBlock: ActivateOpeningAt = new ActivateOpeningAt( - this.activationDelay.eqn(0) - ? 'CurrentBlock' - : { ExactBlock: (await this.apiWrapper.getBestBlock()).add(this.activationDelay) } - ) - const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({ - application_rationing_policy: new Option(ApplicationRationingPolicy, { - max_active_applicants: new BN(this.membersKeyPairs.length) as u32, - }), - max_review_period_length: new BN(32) as u32, - application_staking_policy: new Option(StakingPolicy, { - amount: this.applicationStake, - amount_mode: 'AtLeast', - crowded_out_unstaking_period_length: new BN(1), - review_period_expired_unstaking_period_length: new BN(1), - }), - role_staking_policy: new Option(StakingPolicy, { - amount: this.roleStake, - amount_mode: 'AtLeast', - crowded_out_unstaking_period_length: new BN(1), - review_period_expired_unstaking_period_length: new BN(1), - }), - role_slashing_terms: new SlashingTerms({ - Slashable: { - max_count: new BN(1), - max_percent_pts_per_time: new BN(100), - }, - }), - fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber), - }) - const addOpeningPromise: Promise = this.apiWrapper.expectEvent('OpeningAdded') await this.apiWrapper.sudoAddOpening( - this.sudo, - activateAtBlock, - commitment, - uuid().substring(0, 8), - 'Leader', - this.module + { + sudo: this.sudo, + activationDelay: this.activationDelay, + maxActiveApplicants: new BN(this.membersKeyPairs.length), + maxReviewPeriodLength: new BN(32), + applicationStakingPolicyAmount: this.applicationStake, + applicationCrowdedOutUnstakingPeriodLength: new BN(1), + applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + roleStakingPolicyAmount: this.roleStake, + roleCrowdedOutUnstakingPeriodLength: new BN(1), + roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + slashableMaxCount: new BN(1), + slashableMaxPercentPtsPerTime: new BN(100), + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: new BN(1), + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: new BN(1), + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: new BN(1), + terminateApplicationStakeUnstakingPeriod: new BN(1), + terminateRoleStakeUnstakingPeriod: new BN(1), + exitRoleApplicationStakeUnstakingPeriod: new BN(1), + exitRoleStakeUnstakingPeriod: new BN(1), + text: uuid().substring(0, 8), + type: 'Leader', + module: this.module + } ) this.result = (await addOpeningPromise).data[0] as OpeningId if (expectFailure) { @@ -853,16 +791,12 @@ export class TerminateRoleFixture implements Fixture { this.module ) - // Slash worker + // Terminate worker role await this.apiWrapper.terminateRole(this.lead, workerId, uuid().substring(0, 8), this.module, expectFailure) // Assertions - this.apiWrapper.getWorkerIdByRoleAccount(this.membersKeyPairs[0].address, this.module) - const newWorkerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount( - this.membersKeyPairs[0].address, - this.module - ) - assert(newWorkerId === undefined, `Worker with account ${this.membersKeyPairs[0].address} is not terminated`) + const isWorker: boolean = await this.apiWrapper.isWorker(this.membersKeyPairs[0].address, this.module) + assert(!isWorker, `Worker with account ${this.membersKeyPairs[0].address} is not terminated`) } } @@ -888,9 +822,8 @@ export class LeaveRoleFixture implements Fixture { // Assertions this.membersKeyPairs.forEach(async (keyPair) => { - this.apiWrapper.getWorkerIdByRoleAccount(keyPair.address, this.module) - const newWorkerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(keyPair.address, this.module) - assert(newWorkerId === undefined, `Worker with account ${keyPair.address} is not terminated`) + const isWorker: boolean = await this.apiWrapper.isWorker(this.membersKeyPairs[0].address, this.module) + assert(!isWorker, `Worker with account ${keyPair.address} is not terminated`) }) } } @@ -1101,9 +1034,7 @@ export class ExpectLeaderRewardAmountUpdatedFixture implements Fixture { const event: Event = await this.apiWrapper.expectEvent('WorkerRewardAmountUpdated') this.events.push(event) const leadWorkerId: WorkerId = (await this.apiWrapper.getLeadWorkerId(this.module))! - const receivedReward: BN = (await this.apiWrapper.getRewardRelationship(leadWorkerId)).getField( - 'amount_per_payout' - ) + const receivedReward: BN = (await this.apiWrapper.getRewardRelationship(leadWorkerId)).amount_per_payout assert( receivedReward.eq(this.expectedReward), `Unexpected reward amount for worker with id ${leadWorkerId}: ${receivedReward}, expected ${this.expectedReward}` diff --git a/tests/network-tests/src/iznik/tests/leaderSetup.ts b/tests/network-tests/src/iznik/tests/leaderSetup.ts index a8cf5d8903..57dc24bc5a 100644 --- a/tests/network-tests/src/iznik/tests/leaderSetup.ts +++ b/tests/network-tests/src/iznik/tests/leaderSetup.ts @@ -28,7 +28,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) diff --git a/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts index 5ffb53cb79..8b2f0f9c45 100644 --- a/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { ContentWorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule' @@ -15,7 +14,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Validator count proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -29,7 +27,7 @@ tap.mocha.describe('Validator count proposal scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts index 50c8231a89..7916e286fb 100644 --- a/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -15,7 +14,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Election parameters proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -29,7 +27,7 @@ tap.mocha.describe('Election parameters proposal scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts index 89ae1912e6..890ba6afef 100644 --- a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' @@ -37,7 +36,6 @@ import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHapp tap.mocha.describe('Set lead proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -53,7 +51,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts index d006199842..cf8d8ed9b9 100644 --- a/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -15,7 +14,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Set lead proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -29,7 +27,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts index c3fea9f770..e9a21b08ae 100644 --- a/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -15,7 +14,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Spending proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -29,7 +27,7 @@ tap.mocha.describe('Spending proposal scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts index 7b90509b7e..81fe621ae3 100644 --- a/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -15,7 +14,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Text proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -29,7 +27,7 @@ tap.mocha.describe('Text proposal scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts b/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts index 9896119671..fbc9b95854 100644 --- a/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts +++ b/tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -16,7 +15,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Update runtime scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -30,7 +28,7 @@ tap.mocha.describe('Update runtime scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts index 8ad845e35a..286b477df5 100644 --- a/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -15,7 +14,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Validator count proposal scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -29,7 +27,7 @@ tap.mocha.describe('Validator count proposal scenario', async () => { let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts index 2c3996b543..0f99b1625b 100644 --- a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import BN from 'bn.js' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { Utils } from '../../utils/utils' @@ -17,7 +16,6 @@ import { DbService } from '../../services/dbService' tap.mocha.describe('Set storage working group mint capacity scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -31,7 +29,7 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async () let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts index 8f4b80771d..0ed8d65b5c 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts @@ -1,5 +1,4 @@ import { initConfig } from '../../utils/config' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -15,7 +14,6 @@ import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -30,7 +28,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts index ed826a0d66..6b38fbd3d8 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts @@ -1,5 +1,4 @@ import { initConfig } from '../../utils/config' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -28,7 +27,6 @@ import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Manage worker as worker scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -43,7 +41,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts index 620d853274..8f8c2b7adf 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts @@ -1,5 +1,4 @@ import { initConfig } from '../../utils/config' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -24,7 +23,6 @@ import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Manage worker as worker scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -39,7 +37,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts index ab31718214..a5055158c7 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts @@ -1,5 +1,4 @@ import { initConfig } from '../../utils/config' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -23,7 +22,6 @@ import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -38,7 +36,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts index 040f51012d..7b557c4515 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts @@ -1,5 +1,4 @@ import { initConfig } from '../../utils/config' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -22,7 +21,6 @@ import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -38,7 +36,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) const nonMemberKeyPairs = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!) const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!) const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts index 7b28a5b644..c51894d362 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts @@ -1,5 +1,4 @@ import { initConfig } from '../../utils/config' -import { registerJoystreamTypes } from '@alexandria/types' import { closeApi } from '../../utils/closeApi' import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' import { WsProvider, Keyring } from '@polkadot/api' @@ -27,7 +26,6 @@ import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase' tap.mocha.describe('Worker application happy case scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -43,7 +41,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/utils/apiWrapper.ts b/tests/network-tests/src/iznik/utils/apiWrapper.ts index b4a1c46441..324bfe51ea 100644 --- a/tests/network-tests/src/iznik/utils/apiWrapper.ts +++ b/tests/network-tests/src/iznik/utils/apiWrapper.ts @@ -1,10 +1,10 @@ -import { ApiPromise, WsProvider } from '@polkadot/api' -import { Bytes, Option, u32, Vec } from '@polkadot/types' -import { Codec } from '@polkadot/types/types' -import { KeyringPair } from '@polkadot/keyring/types' -import { MemberId, PaidMembershipTerms, PaidTermId } from '@alexandria/types/members' -import { Mint, MintId } from '@alexandria/types/mint' -import { Lead, LeadId } from '@alexandria/types/content-working-group' +import {ApiPromise, WsProvider} from '@polkadot/api' +import {Bytes, Option, u32, Vec, StorageKey} from '@polkadot/types' +import {Codec} from '@polkadot/types/types' +import {KeyringPair} from '@polkadot/keyring/types' +import {MemberId, PaidMembershipTerms, PaidTermId} from '@alexandria/types/members' +import {Mint, MintId} from '@alexandria/types/mint' +import {Lead, LeadId} from '@alexandria/types/content-working-group' import { Application, ApplicationIdToWorkerIdMap, @@ -12,15 +12,15 @@ import { WorkerId, WorkingGroupOpeningPolicyCommitment, } from '@alexandria/types/working-group' -import { ElectionStake, Seat } from '@alexandria/types/council' -import { AccountId, Balance, BalanceOf, BlockNumber, Event, EventRecord } from '@polkadot/types/interfaces' +import {ElectionStake, Seat} from '@alexandria/types/council' +import {AccountId, AccountInfo, Balance, BalanceOf, BlockNumber, Event, EventRecord} from '@polkadot/types/interfaces' import BN from 'bn.js' -import { SubmittableExtrinsic } from '@polkadot/api/types' -import { Sender } from './sender' -import { Utils } from './utils' -import { Stake, StakedState, StakeId } from '@alexandria/types/stake' -import { RewardRelationship, RewardRelationshipId } from '@alexandria/types/recurring-rewards' -import { types } from '@alexandria/types'; +import {SubmittableExtrinsic} from '@polkadot/api/types' +import {Sender} from './sender' +import {Utils} from './utils' +import {Stake, StakedState, StakeId} from '@alexandria/types/stake' +import {RewardRelationship, RewardRelationshipId} from '@alexandria/types/recurring-rewards' +import {types} from '@alexandria/types'; import { ActivateOpeningAt, Application as HiringApplication, @@ -28,7 +28,7 @@ import { Opening as HiringOpening, OpeningId, } from '@alexandria/types/hiring' -import { FillOpeningParameters, ProposalId } from '@alexandria/types/proposals' +import {FillOpeningParameters, ProposalId} from '@alexandria/types/proposals' export enum WorkingGroups { StorageWorkingGroup = 'storageWorkingGroup', @@ -40,7 +40,6 @@ export class ApiWrapper { public static async create(provider: WsProvider): Promise { const api = await ApiPromise.create({ provider, types }) - // ApiPromise.create({ types }); return new ApiWrapper(api) } @@ -88,8 +87,13 @@ export class ApiWrapper { return this.api.query.members.memberIdsByControllerAccountId>(address) } - public getBalance(address: string): Promise { - return this.api.query.balances.freeBalance(address) + public async getBalance(address: string): Promise { + const accountData: AccountInfo = await this.api.query.system.account(address) + console.log('free ' + accountData.data.free) + console.log('reserved ' + accountData.data.reserved) + console.log('feeFrozen ' + accountData.data.feeFrozen) + console.log('miscFrozen ' + accountData.data.miscFrozen) + return (await this.api.query.system.account(address)).data.free } public async transferBalance(from: KeyringPair, to: string, amount: BN): Promise { @@ -948,15 +952,13 @@ export class ApiWrapper { public async getContentWorkingGroupMintCapacity(): Promise { const mintId: MintId = await this.api.query.contentWorkingGroup.mint() - const mintCodec = await this.api.query.minting.mints(mintId) - const mint: Mint = (mintCodec[0] as unknown) as Mint + const mint: Mint = await this.api.query.minting.mints(mintId) return mint.capacity } public async getWorkingGroupMintCapacity(module: WorkingGroups): Promise { const mintId: MintId = await this.api.query[module].mint() - const mintCodec = await this.api.query.minting.mints(mintId) - const mint: Mint = (mintCodec[0] as unknown) as Mint + const mint: Mint = await this.api.query.minting.mints(mintId) return mint.capacity } @@ -966,8 +968,7 @@ export class ApiWrapper { public async getCurrentLeadAddress(): Promise { const leadId: Option = await this.api.query.contentWorkingGroup.currentLeadId>() - const leadCodec = await this.api.query.contentWorkingGroup.leadById(leadId.unwrap()) - const lead = (leadCodec[0] as unknown) as Lead + const lead = await this.api.query.contentWorkingGroup.leadById(leadId.unwrap()) return lead.role_account.toString() } @@ -979,84 +980,260 @@ export class ApiWrapper { return accountWorkers !== undefined } - public async addOpening( + public async addOpening(openingParameters: { leader: KeyringPair, - actiavteAt: ActivateOpeningAt, - commitment: WorkingGroupOpeningPolicyCommitment, + activationDelay: BN, + maxActiveApplicants: BN, + maxReviewPeriodLength: BN, + applicationStakingPolicyAmount: BN, + applicationCrowdedOutUnstakingPeriodLength: BN, + applicationReviewPeriodExpiredUnstakingPeriodLength: BN, + roleStakingPolicyAmount: BN, + roleCrowdedOutUnstakingPeriodLength: BN, + roleReviewPeriodExpiredUnstakingPeriodLength: BN, + slashableMaxCount: BN, + slashableMaxPercentPtsPerTime: BN, + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN, + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN, + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN, + terminateApplicationStakeUnstakingPeriod: BN, + terminateRoleStakeUnstakingPeriod: BN, + exitRoleApplicationStakeUnstakingPeriod: BN, + exitRoleStakeUnstakingPeriod: BN, text: string, type: string, module: WorkingGroups, - expectFailure: boolean + expectFailure: boolean} ): Promise { + const activateAt: ActivateOpeningAt = this.api.createType('ActivateOpeningAt', + openingParameters.activationDelay.eqn(0) + ? 'CurrentBlock' + : { ExactBlock: (await this.getBestBlock()).add(openingParameters.activationDelay) } + ) + + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', { + application_rationing_policy: this.api.createType('Option', { + max_active_applicants: openingParameters.maxActiveApplicants as u32, + }), + max_review_period_length: openingParameters.maxReviewPeriodLength as u32, + application_staking_policy: this.api.createType('Option', { + amount: openingParameters.applicationStakingPolicyAmount, + amount_mode: 'AtLeast', + crowded_out_unstaking_period_length: openingParameters.applicationCrowdedOutUnstakingPeriodLength, + review_period_expired_unstaking_period_length: openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength, + }), + role_staking_policy: this.api.createType('Option', { + amount: openingParameters.roleStakingPolicyAmount, + amount_mode: 'AtLeast', + crowded_out_unstaking_period_length: openingParameters.roleCrowdedOutUnstakingPeriodLength, + review_period_expired_unstaking_period_length: openingParameters.roleReviewPeriodExpiredUnstakingPeriodLength, + }), + role_slashing_terms: this.api.createType('SlashingTerms', { + Slashable: { + max_count: openingParameters.slashableMaxCount, + max_percent_pts_per_time: openingParameters.slashableMaxPercentPtsPerTime, + }, + }), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod), + terminate_application_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateApplicationStakeUnstakingPeriod), + terminate_role_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateRoleStakeUnstakingPeriod), + exit_role_application_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleApplicationStakeUnstakingPeriod), + exit_role_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleStakeUnstakingPeriod), + }) + return this.sender.signAndSend( - this.createAddOpeningTransaction(actiavteAt, commitment, text, type, module), - leader, - expectFailure + this.createAddOpeningTransaction(activateAt, commitment, openingParameters.text, openingParameters.type, openingParameters.module), + openingParameters.leader, + openingParameters.expectFailure ) } - public async sudoAddOpening( + public async sudoAddOpening(openingParameters: { sudo: KeyringPair, - actiavteAt: ActivateOpeningAt, - commitment: WorkingGroupOpeningPolicyCommitment, + activationDelay: BN, + maxActiveApplicants: BN, + maxReviewPeriodLength: BN, + applicationStakingPolicyAmount: BN, + applicationCrowdedOutUnstakingPeriodLength: BN, + applicationReviewPeriodExpiredUnstakingPeriodLength: BN, + roleStakingPolicyAmount: BN, + roleCrowdedOutUnstakingPeriodLength: BN, + roleReviewPeriodExpiredUnstakingPeriodLength: BN, + slashableMaxCount: BN, + slashableMaxPercentPtsPerTime: BN, + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN, + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN, + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN, + terminateApplicationStakeUnstakingPeriod: BN, + terminateRoleStakeUnstakingPeriod: BN, + exitRoleApplicationStakeUnstakingPeriod: BN, + exitRoleStakeUnstakingPeriod: BN, text: string, type: string, module: WorkingGroups + } ): Promise { + const activateAt: ActivateOpeningAt = this.api.createType('ActivateOpeningAt', + openingParameters.activationDelay.eqn(0) + ? 'CurrentBlock' + : { ExactBlock: (await this.getBestBlock()).add(openingParameters.activationDelay) } + ) + + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', { + application_rationing_policy: this.api.createType('Option', { + max_active_applicants: openingParameters.maxActiveApplicants as u32, + }), + max_review_period_length: openingParameters.maxReviewPeriodLength as u32, + application_staking_policy: this.api.createType('Option', { + amount: openingParameters.applicationStakingPolicyAmount, + amount_mode: 'AtLeast', + crowded_out_unstaking_period_length: openingParameters.applicationCrowdedOutUnstakingPeriodLength, + review_period_expired_unstaking_period_length: openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength, + }), + role_staking_policy: this.api.createType('Option', { + amount: openingParameters.roleStakingPolicyAmount, + amount_mode: 'AtLeast', + crowded_out_unstaking_period_length: openingParameters.roleCrowdedOutUnstakingPeriodLength, + review_period_expired_unstaking_period_length: openingParameters.roleReviewPeriodExpiredUnstakingPeriodLength, + }), + role_slashing_terms: this.api.createType('SlashingTerms', { + Slashable: { + max_count: openingParameters.slashableMaxCount, + max_percent_pts_per_time: openingParameters.slashableMaxPercentPtsPerTime, + }, + }), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod), + terminate_application_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateApplicationStakeUnstakingPeriod), + terminate_role_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateRoleStakeUnstakingPeriod), + exit_role_application_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleApplicationStakeUnstakingPeriod), + exit_role_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleStakeUnstakingPeriod), + }) + return this.sender.signAndSend( - this.api.tx.sudo.sudo(this.createAddOpeningTransaction(actiavteAt, commitment, text, type, module)), - sudo, + this.api.tx.sudo.sudo(this.createAddOpeningTransaction(activateAt, commitment, openingParameters.text, openingParameters.type, openingParameters.module)), + openingParameters.sudo, false ) } - public async proposeCreateWorkingGroupLeaderOpening( - account: KeyringPair, + public async proposeCreateWorkingGroupLeaderOpening(leaderOpening: + { + account: KeyringPair, title: string, description: string, proposalStake: BN, - actiavteAt: ActivateOpeningAt, - commitment: WorkingGroupOpeningPolicyCommitment, + actiavteAt: string, + maxActiveApplicants: BN, + maxReviewPeriodLength: BN, + applicationStakingPolicyAmount: BN, + applicationCrowdedOutUnstakingPeriodLength: BN, + applicationReviewPeriodExpiredUnstakingPeriodLength: BN, + roleStakingPolicyAmount: BN, + roleCrowdedOutUnstakingPeriodLength: BN, + roleReviewPeriodExpiredUnstakingPeriodLength: BN, + slashableMaxCount: BN, + slashableMaxPercentPtsPerTime: BN, + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN, + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN, + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN, + terminateApplicationStakeUnstakingPeriod: BN, + terminateRoleStakeUnstakingPeriod: BN, + exitRoleApplicationStakeUnstakingPeriod: BN, + exitRoleStakeUnstakingPeriod: BN, text: string, - workingGroup: string + workingGroup: string} ): Promise { - const memberId: MemberId = (await this.getMemberIds(account.address))[0] + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment',{ + application_rationing_policy: this.api.createType('Option', { + max_active_applicants: leaderOpening.maxActiveApplicants as u32, + }), + max_review_period_length: leaderOpening.maxReviewPeriodLength as u32, + application_staking_policy: this.api.createType('Option', { + amount: leaderOpening.applicationStakingPolicyAmount, + amount_mode: 'AtLeast', + crowded_out_unstaking_period_length: leaderOpening.applicationCrowdedOutUnstakingPeriodLength, + review_period_expired_unstaking_period_length: leaderOpening.applicationReviewPeriodExpiredUnstakingPeriodLength, + }), + role_staking_policy: this.api.createType('Option', { + amount: leaderOpening.roleStakingPolicyAmount, + amount_mode: 'AtLeast', + crowded_out_unstaking_period_length: leaderOpening.roleCrowdedOutUnstakingPeriodLength, + review_period_expired_unstaking_period_length: leaderOpening.roleReviewPeriodExpiredUnstakingPeriodLength, + }), + role_slashing_terms: this.api.createType('SlashingTerms',{ + Slashable: { + max_count: leaderOpening.slashableMaxCount, + max_percent_pts_per_time: leaderOpening.slashableMaxPercentPtsPerTime, + }, + }), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', leaderOpening.fillOpeningFailedApplicantRoleStakeUnstakingPeriod), + terminate_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.terminateApplicationStakeUnstakingPeriod), + terminate_role_stake_unstaking_period: this.api.createType('Option', leaderOpening.terminateRoleStakeUnstakingPeriod), + exit_role_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.exitRoleApplicationStakeUnstakingPeriod), + exit_role_stake_unstaking_period: this.api.createType('Option', leaderOpening.exitRoleStakeUnstakingPeriod), + }) + + const memberId: MemberId = (await this.getMemberIds(leaderOpening.account.address))[0] return this.sender.signAndSend( (this.api.tx.proposalsCodex.createAddWorkingGroupLeaderOpeningProposal( memberId, - title, - description, - proposalStake, + leaderOpening.title, + leaderOpening.description, + leaderOpening.proposalStake, { - activate_at: actiavteAt, + activate_at: leaderOpening.actiavteAt, commitment: commitment, - human_readable_text: text, - working_group: workingGroup, + human_readable_text: leaderOpening.text, + working_group: leaderOpening.workingGroup, } ) as unknown) as SubmittableExtrinsic<'promise'>, - account, + leaderOpening.account, false ) } - public async proposeFillLeaderOpening( + public async proposeFillLeaderOpening(fillOpening: + { account: KeyringPair, title: string, description: string, proposalStake: BN, - fillOpeningParameters: FillOpeningParameters + openingId: OpeningId, + successfulApplicationId: ApplicationId, + amountPerPayout: BN, + nextPaymentAtBlock: BN, + payoutInterval: BN, + workingGroup: string + } ): Promise { - const memberId: MemberId = (await this.getMemberIds(account.address))[0] + const memberId: MemberId = (await this.getMemberIds(fillOpening.account.address))[0] + + const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters',{ + opening_id: fillOpening.openingId, + successful_application_id: fillOpening.successfulApplicationId, + reward_policy: this.api.createType('Option', { + amount_per_payout: fillOpening.amountPerPayout as Balance, + next_payment_at_block: fillOpening.nextPaymentAtBlock as BlockNumber, + payout_interval: this.api.createType('Option', fillOpening.payoutInterval), + }), + working_group: this.api.createType('WorkingGroup',fillOpening.workingGroup), + }) return this.sender.signAndSend( (this.api.tx.proposalsCodex.createFillWorkingGroupLeaderOpeningProposal( memberId, - title, - description, - proposalStake, + fillOpening.title, + fillOpening.description, + fillOpening.proposalStake, fillOpeningParameters ) as unknown) as SubmittableExtrinsic<'promise'>, - account, + fillOpening.account, false ) } @@ -1397,7 +1574,8 @@ export class ApiWrapper { public async batchWithdrawApplication(accounts: KeyringPair[], module: WorkingGroups): Promise { return Promise.all( accounts.map(async (keyPair) => { - const applicationIds: ApplicationId[] = await this.getApplicationsIdsByRoleAccount(keyPair.address, module) + const applicationIds: ApplicationId[] = await this.getActiveApplicationsIdsByRoleAccount(keyPair.address, module) + console.log('application ids ' + applicationIds) await this.withdrawApplication(keyPair, applicationIds[0], module) }) ) @@ -1505,54 +1683,58 @@ export class ApiWrapper { } public async getHiringOpening(id: OpeningId): Promise { - return ((await this.api.query.hiring.openingById(id))[0] as unknown) as HiringOpening + return await this.api.query.hiring.openingById(id) } public async getWorkers(module: WorkingGroups): Promise { - return ((await this.api.query[module].workerById())[1] as unknown) as Worker[] + return (await this.api.query[module].workerById.entries()).map(workerWithId => workerWithId[1]) } public async getWorkerById(id: WorkerId, module: WorkingGroups): Promise { - return ((await this.api.query[module].workerById(id))[0] as unknown) as Worker + return await this.api.query[module].workerById(id) } public async getWorkerIdByRoleAccount(address: string, module: WorkingGroups): Promise { - const workersAndIds = await this.api.query[module].workerById() - const workers: Worker[] = (workersAndIds[1] as unknown) as Worker[] - const ids: WorkerId[] = (workersAndIds[0] as unknown) as WorkerId[] - const index: number = workers.findIndex((worker) => worker.role_account_id.toString() === address) - return ids[index] + const workersAndIds: [StorageKey, Worker][] = await this.api.query[module].workerById.entries() + const index: number = workersAndIds.findIndex((workersAndId) => workersAndId[1].role_account_id.toString() === address) + return workersAndIds[index][0].args[0] as WorkerId + } + + public async isWorker(address: string, module: WorkingGroups): Promise { + const workersAndIds: [StorageKey, Worker][] = await this.api.query[module].workerById.entries() + const index: number = workersAndIds.findIndex((workersAndId) => workersAndId[1].role_account_id.toString() === address) + return index !== -1; } public async getApplicationsIdsByRoleAccount(address: string, module: WorkingGroups): Promise { - const applicationsAndIds = await this.api.query[module].applicationById() - const applications: Application[] = (applicationsAndIds[1] as unknown) as Application[] - const ids: ApplicationId[] = (applicationsAndIds[0] as unknown) as ApplicationId[] - return applications - .map((application, index) => (application.role_account_id.toString() === address ? ids[index] : undefined)) + const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries() + return applicationsAndIds + .map((applicationWithId) => { + const application: Application = applicationWithId[1] + return (application.role_account_id.toString() === address ? applicationWithId[0].args[0] as ApplicationId : undefined)}) .filter((id) => id !== undefined) as ApplicationId[] } public async getHiringApplicationById(id: ApplicationId): Promise { - return ((await this.api.query.hiring.applicationById(id))[0] as unknown) as HiringApplication + return this.api.query.hiring.applicationById(id) } public async getApplicationById(id: ApplicationId, module: WorkingGroups): Promise { - return ((await this.api.query[module].applicationById(id))[0] as unknown) as Application + return this.api.query[module].applicationById(id) } public async getActiveApplicationsIdsByRoleAccount(address: string, module: WorkingGroups): Promise { - const applicationsAndIds = await this.api.query[module].applicationById() - const applications: Application[] = (applicationsAndIds[1] as unknown) as Application[] - const ids: ApplicationId[] = (applicationsAndIds[0] as unknown) as ApplicationId[] + const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries() + console.log('applications here 1 ' + applicationsAndIds) return ( await Promise.all( - applications.map(async (application, index) => { + applicationsAndIds.map(async (applicationWithId) => { + const application: Application = applicationWithId[1] if ( application.role_account_id.toString() === address && (await this.getHiringApplicationById(application.application_id)).stage.type === 'Active' ) { - return ids[index] + return applicationWithId[0].args[0] as ApplicationId } else { return undefined } @@ -1562,7 +1744,7 @@ export class ApiWrapper { } public async getStake(id: StakeId): Promise { - return ((await this.api.query.stake.stakes(id))[0] as unknown) as Stake + return this.api.query.stake.stakes(id) } public async getWorkerStakeAmount(workerId: WorkerId, module: WorkingGroups): Promise { @@ -1571,9 +1753,7 @@ export class ApiWrapper { } public async getRewardRelationship(id: RewardRelationshipId): Promise { - return (( - await this.api.query.recurringRewards.rewardRelationships(id) - )[0] as unknown) as RewardRelationship + return this.api.query.recurringRewards.rewardRelationships(id) } public async getWorkerRewardAccount(workerId: WorkerId, module: WorkingGroups): Promise { diff --git a/tests/network-tests/src/iznik/utils/sender.ts b/tests/network-tests/src/iznik/utils/sender.ts index 7513da833c..f53b34d10d 100644 --- a/tests/network-tests/src/iznik/utils/sender.ts +++ b/tests/network-tests/src/iznik/utils/sender.ts @@ -1,7 +1,7 @@ import BN from 'bn.js' -import { ApiPromise, Keyring } from '@polkadot/api' -import { Index } from '@polkadot/types/interfaces' +import { ApiPromise } from '@polkadot/api' import { SubmittableExtrinsic } from '@polkadot/api/types' +import { AccountInfo } from '@polkadot/types/interfaces' import { KeyringPair } from '@polkadot/keyring/types' import { DbService } from '../services/dbService' @@ -14,7 +14,7 @@ export class Sender { } private async getNonce(address: string): Promise { - const oncahinNonce: BN = await this.api.query.system.accountNonce(address) + const oncahinNonce: BN = (await this.api.query.system.account(address)).nonce let nonce: BN if (!this.db.hasNonce(address)) { nonce = oncahinNonce @@ -43,7 +43,7 @@ export class Sender { const signedTx = tx.sign(account, { nonce }) await signedTx .send(async (result) => { - if (result.status.isFinalized === true && result.events !== undefined) { + if (result.status.isInBlock && result.events !== undefined) { result.events.forEach((event) => { if (event.event.method === 'ExtrinsicFailed') { if (expectFailure) { From 2b48b7d46f3f65f71479112c3d13c0ee7c165882 Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Mon, 17 Aug 2020 18:04:13 +0200 Subject: [PATCH 011/178] prettier changes applied --- .../iznik/tests/fixtures/proposalsModule.ts | 97 ++-- .../tests/fixtures/workingGroupModule.ts | 39 +- .../src/iznik/utils/apiWrapper.ts | 483 +++++++++++------- 3 files changed, 369 insertions(+), 250 deletions(-) diff --git a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts index cd8655d81d..c30ec9c3b2 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts @@ -1,13 +1,13 @@ -import {KeyringPair} from '@polkadot/keyring/types' -import {ApiWrapper, WorkingGroups} from '../../utils/apiWrapper' -import {v4 as uuid} from 'uuid' +import { KeyringPair } from '@polkadot/keyring/types' +import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' +import { v4 as uuid } from 'uuid' import BN from 'bn.js' -import {ProposalId} from '@alexandria/types/proposals' -import {Fixture} from './interfaces/fixture' -import {Bytes} from '@polkadot/types' -import {assert} from 'chai' -import {ApplicationId, OpeningId,} from '@alexandria/types/hiring' -import {WorkerId,} from '@alexandria/types/working-group' +import { ProposalId } from '@alexandria/types/proposals' +import { Fixture } from './interfaces/fixture' +import { Bytes } from '@polkadot/types' +import { assert } from 'chai' +import { ApplicationId, OpeningId } from '@alexandria/types/hiring' +import { WorkerId } from '@alexandria/types/working-group' export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { private apiWrapper: ApiWrapper @@ -51,33 +51,32 @@ export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() - await this.apiWrapper.proposeCreateWorkingGroupLeaderOpening( - { - account: this.m1KeyPairs[0], - title: proposalTitle, - description: description, - proposalStake: proposalStake, - actiavteAt: 'CurrentBlock', - maxActiveApplicants: new BN(this.m1KeyPairs.length), - maxReviewPeriodLength: new BN(32), - applicationStakingPolicyAmount: this.applicationStake, - applicationCrowdedOutUnstakingPeriodLength: new BN(1), - applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1), - roleStakingPolicyAmount: this.roleStake, - roleCrowdedOutUnstakingPeriodLength: new BN(1), - roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1), - slashableMaxCount: new BN(1), - slashableMaxPercentPtsPerTime: new BN(100), - fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: new BN(1), - fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: new BN(1), - fillOpeningFailedApplicantRoleStakeUnstakingPeriod: new BN(1), - terminateApplicationStakeUnstakingPeriod: new BN(1), - terminateRoleStakeUnstakingPeriod: new BN(1), - exitRoleApplicationStakeUnstakingPeriod: new BN(1), - exitRoleStakeUnstakingPeriod: new BN(1), - text: uuid().substring(0, 8), - workingGroup: this.workingGroup} - ) + await this.apiWrapper.proposeCreateWorkingGroupLeaderOpening({ + account: this.m1KeyPairs[0], + title: proposalTitle, + description: description, + proposalStake: proposalStake, + actiavteAt: 'CurrentBlock', + maxActiveApplicants: new BN(this.m1KeyPairs.length), + maxReviewPeriodLength: new BN(32), + applicationStakingPolicyAmount: this.applicationStake, + applicationCrowdedOutUnstakingPeriodLength: new BN(1), + applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + roleStakingPolicyAmount: this.roleStake, + roleCrowdedOutUnstakingPeriodLength: new BN(1), + roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1), + slashableMaxCount: new BN(1), + slashableMaxPercentPtsPerTime: new BN(100), + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: new BN(1), + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: new BN(1), + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: new BN(1), + terminateApplicationStakeUnstakingPeriod: new BN(1), + terminateRoleStakeUnstakingPeriod: new BN(1), + exitRoleApplicationStakeUnstakingPeriod: new BN(1), + exitRoleStakeUnstakingPeriod: new BN(1), + text: uuid().substring(0, 8), + workingGroup: this.workingGroup, + }) this.result = await proposalPromise if (expectFailure) { throw new Error('Successful fixture run while expecting failure') @@ -198,20 +197,18 @@ export class FillLeaderOpeningProposalFixture implements Fixture { console.log('Successfull application id ' + applicationId) const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() - await this.apiWrapper.proposeFillLeaderOpening( - { - account: this.m1KeyPairs[0], - title: proposalTitle, - description: description, - proposalStake: proposalStake, - openingId: this.openingId, - successfulApplicationId: applicationId, - amountPerPayout: this.payoutAmount, - nextPaymentAtBlock: now.add(this.firstRewardInterval), - payoutInterval: this.rewardInterval, - workingGroup: workingGroupString - } - ) + await this.apiWrapper.proposeFillLeaderOpening({ + account: this.m1KeyPairs[0], + title: proposalTitle, + description: description, + proposalStake: proposalStake, + openingId: this.openingId, + successfulApplicationId: applicationId, + amountPerPayout: this.payoutAmount, + nextPaymentAtBlock: now.add(this.firstRewardInterval), + payoutInterval: this.rewardInterval, + workingGroup: workingGroupString, + }) this.result = await proposalPromise if (expectFailure) { throw new Error('Successful fixture run while expecting failure') diff --git a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts index 3fe72c7549..8cd30e6199 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts @@ -1,15 +1,15 @@ import BN from 'bn.js' -import {assert} from 'chai' -import {ApiWrapper, WorkingGroups} from '../../utils/apiWrapper' -import {KeyringPair} from '@polkadot/keyring/types' -import {Event} from '@polkadot/types/interfaces' -import {Keyring} from '@polkadot/api' -import {v4 as uuid} from 'uuid' -import {RewardRelationship} from '@alexandria/types/recurring-rewards' -import {Application, ApplicationIdToWorkerIdMap, Worker, WorkerId,} from '@alexandria/types/working-group' -import {Utils} from '../../utils/utils' -import {ApplicationId, Opening as HiringOpening, OpeningId,} from '@alexandria/types/hiring' -import {Fixture} from './interfaces/fixture' +import { assert } from 'chai' +import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper' +import { KeyringPair } from '@polkadot/keyring/types' +import { Event } from '@polkadot/types/interfaces' +import { Keyring } from '@polkadot/api' +import { v4 as uuid } from 'uuid' +import { RewardRelationship } from '@alexandria/types/recurring-rewards' +import { Application, ApplicationIdToWorkerIdMap, Worker, WorkerId } from '@alexandria/types/working-group' +import { Utils } from '../../utils/utils' +import { ApplicationId, Opening as HiringOpening, OpeningId } from '@alexandria/types/hiring' +import { Fixture } from './interfaces/fixture' export class AddWorkerOpeningFixture implements Fixture { private apiWrapper: ApiWrapper @@ -57,8 +57,7 @@ export class AddWorkerOpeningFixture implements Fixture { // Worker opening creation const addOpeningPromise: Promise = this.apiWrapper.expectEvent('OpeningAdded') - await this.apiWrapper.addOpening( - { + await this.apiWrapper.addOpening({ leader: this.lead, activationDelay: this.activationDelay, maxActiveApplicants: new BN(this.membersKeyPairs.length), @@ -81,8 +80,8 @@ export class AddWorkerOpeningFixture implements Fixture { text: uuid().substring(0, 8), type: 'Worker', module: this.module, - expectFailure: expectFailure} - ) + expectFailure: expectFailure, + }) if (!expectFailure) { const openingId: OpeningId = (await addOpeningPromise).data[0] as OpeningId this.result = openingId @@ -125,10 +124,9 @@ export class AddLeaderOpeningFixture implements Fixture { public async runner(expectFailure: boolean): Promise { const addOpeningPromise: Promise = this.apiWrapper.expectEvent('OpeningAdded') - await this.apiWrapper.sudoAddOpening( - { + await this.apiWrapper.sudoAddOpening({ sudo: this.sudo, - activationDelay: this.activationDelay, + activationDelay: this.activationDelay, maxActiveApplicants: new BN(this.membersKeyPairs.length), maxReviewPeriodLength: new BN(32), applicationStakingPolicyAmount: this.applicationStake, @@ -148,9 +146,8 @@ export class AddLeaderOpeningFixture implements Fixture { exitRoleStakeUnstakingPeriod: new BN(1), text: uuid().substring(0, 8), type: 'Leader', - module: this.module - } - ) + module: this.module, + }) this.result = (await addOpeningPromise).data[0] as OpeningId if (expectFailure) { throw new Error('Successful fixture run while expecting failure') diff --git a/tests/network-tests/src/iznik/utils/apiWrapper.ts b/tests/network-tests/src/iznik/utils/apiWrapper.ts index 324bfe51ea..77b496eddc 100644 --- a/tests/network-tests/src/iznik/utils/apiWrapper.ts +++ b/tests/network-tests/src/iznik/utils/apiWrapper.ts @@ -1,10 +1,10 @@ -import {ApiPromise, WsProvider} from '@polkadot/api' -import {Bytes, Option, u32, Vec, StorageKey} from '@polkadot/types' -import {Codec} from '@polkadot/types/types' -import {KeyringPair} from '@polkadot/keyring/types' -import {MemberId, PaidMembershipTerms, PaidTermId} from '@alexandria/types/members' -import {Mint, MintId} from '@alexandria/types/mint' -import {Lead, LeadId} from '@alexandria/types/content-working-group' +import { ApiPromise, WsProvider } from '@polkadot/api' +import { Bytes, Option, u32, Vec, StorageKey } from '@polkadot/types' +import { Codec } from '@polkadot/types/types' +import { KeyringPair } from '@polkadot/keyring/types' +import { MemberId, PaidMembershipTerms, PaidTermId } from '@alexandria/types/members' +import { Mint, MintId } from '@alexandria/types/mint' +import { Lead, LeadId } from '@alexandria/types/content-working-group' import { Application, ApplicationIdToWorkerIdMap, @@ -12,15 +12,15 @@ import { WorkerId, WorkingGroupOpeningPolicyCommitment, } from '@alexandria/types/working-group' -import {ElectionStake, Seat} from '@alexandria/types/council' -import {AccountId, AccountInfo, Balance, BalanceOf, BlockNumber, Event, EventRecord} from '@polkadot/types/interfaces' +import { ElectionStake, Seat } from '@alexandria/types/council' +import { AccountId, AccountInfo, Balance, BalanceOf, BlockNumber, Event, EventRecord } from '@polkadot/types/interfaces' import BN from 'bn.js' -import {SubmittableExtrinsic} from '@polkadot/api/types' -import {Sender} from './sender' -import {Utils} from './utils' -import {Stake, StakedState, StakeId} from '@alexandria/types/stake' -import {RewardRelationship, RewardRelationshipId} from '@alexandria/types/recurring-rewards' -import {types} from '@alexandria/types'; +import { SubmittableExtrinsic } from '@polkadot/api/types' +import { Sender } from './sender' +import { Utils } from './utils' +import { Stake, StakedState, StakeId } from '@alexandria/types/stake' +import { RewardRelationship, RewardRelationshipId } from '@alexandria/types/recurring-rewards' +import { types } from '@alexandria/types' import { ActivateOpeningAt, Application as HiringApplication, @@ -28,7 +28,7 @@ import { Opening as HiringOpening, OpeningId, } from '@alexandria/types/hiring' -import {FillOpeningParameters, ProposalId} from '@alexandria/types/proposals' +import { FillOpeningParameters, ProposalId } from '@alexandria/types/proposals' export enum WorkingGroups { StorageWorkingGroup = 'storageWorkingGroup', @@ -105,7 +105,7 @@ export class ApiWrapper { } public async getMembershipFee(paidTermsId: PaidTermId): Promise { - const terms: PaidMembershipTerms = (await this.getPaidMembershipTerms(paidTermsId)); + const terms: PaidMembershipTerms = await this.getPaidMembershipTerms(paidTermsId) return terms.fee } @@ -301,8 +301,14 @@ export class ApiWrapper { max_percent_pts_per_time: new BN(0), }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), - fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + new BN(1) + ), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + new BN(1) + ), fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), terminate_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), terminate_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), @@ -322,15 +328,17 @@ export class ApiWrapper { public estimateAcceptApplicationsFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].acceptApplications(this.api.createType('OpeningId',0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].acceptApplications(this.api.createType('OpeningId', 0)) as unknown) as SubmittableExtrinsic< + 'promise' + > ) } public estimateApplyOnOpeningFee(account: KeyringPair, module: WorkingGroups): BN { return this.estimateTxFee( (this.api.tx[module].applyOnOpening( - this.api.createType('MemberId', 0), - this.api.createType('OpeningId', 0), + this.api.createType('MemberId', 0), + this.api.createType('OpeningId', 0), account.address, 0, 0, @@ -341,7 +349,9 @@ export class ApiWrapper { public estimateBeginApplicantReviewFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].beginApplicantReview(this.api.createType('OpeningId', 0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].beginApplicantReview( + this.api.createType('OpeningId', 0) + ) as unknown) as SubmittableExtrinsic<'promise'> ) } @@ -357,58 +367,75 @@ export class ApiWrapper { public estimateIncreaseStakeFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].increaseStake(this.api.createType('WorkerId',0), 0) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].increaseStake(this.api.createType('WorkerId', 0), 0) as unknown) as SubmittableExtrinsic< + 'promise' + > ) } public estimateDecreaseStakeFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].decreaseStake(this.api.createType('WorkerId',0), 0) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].decreaseStake(this.api.createType('WorkerId', 0), 0) as unknown) as SubmittableExtrinsic< + 'promise' + > ) } public estimateUpdateRoleAccountFee(address: string, module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].updateRoleAccount(this.api.createType('WorkerId',0), address) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].updateRoleAccount( + this.api.createType('WorkerId', 0), + address + ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateUpdateRewardAccountFee(address: string, module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].updateRewardAccount(this.api.createType('WorkerId',0), address) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].updateRewardAccount( + this.api.createType('WorkerId', 0), + address + ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateLeaveRoleFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].leaveRole(this.api.createType('WorkerId',0), 'Long justification text') as unknown) as SubmittableExtrinsic< - 'promise' - > + (this.api.tx[module].leaveRole( + this.api.createType('WorkerId', 0), + 'Long justification text' + ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateWithdrawApplicationFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].withdrawApplication(this.api.createType('ApplicationId',0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].withdrawApplication( + this.api.createType('ApplicationId', 0) + ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateTerminateApplicationFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].terminateApplication(this.api.createType('ApplicationId',0)) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].terminateApplication( + this.api.createType('ApplicationId', 0) + ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateSlashStakeFee(module: WorkingGroups): BN { return this.estimateTxFee( - (this.api.tx[module].slashStake(this.api.createType('WorkerId',0), 0) as unknown) as SubmittableExtrinsic<'promise'> + (this.api.tx[module].slashStake(this.api.createType('WorkerId', 0), 0) as unknown) as SubmittableExtrinsic< + 'promise' + > ) } public estimateTerminateRoleFee(module: WorkingGroups): BN { return this.estimateTxFee( (this.api.tx[module].terminateRole( - this.api.createType('WorkerId',0), + this.api.createType('WorkerId', 0), 'Long justification text explaining why the worker role will be terminated', false ) as unknown) as SubmittableExtrinsic<'promise'> @@ -416,7 +443,7 @@ export class ApiWrapper { } public estimateProposeCreateWorkingGroupLeaderOpeningFee(): BN { - const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment',{ + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', { application_rationing_policy: this.api.createType('Option', { max_active_applicants: new BN(32) as u32, }), @@ -433,14 +460,20 @@ export class ApiWrapper { crowded_out_unstaking_period_length: new BN(1), review_period_expired_unstaking_period_length: new BN(1), }), - role_slashing_terms: this.api.createType('SlashingTerms',{ + role_slashing_terms: this.api.createType('SlashingTerms', { Slashable: { max_count: new BN(0), max_percent_pts_per_time: new BN(0), }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), - fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + new BN(1) + ), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + new BN(1) + ), fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), terminate_application_stake_unstaking_period: this.api.createType('Option', new BN(1)), terminate_role_stake_unstaking_period: this.api.createType('Option', new BN(1)), @@ -450,7 +483,7 @@ export class ApiWrapper { return this.estimateTxFee( (this.api.tx.proposalsCodex.createAddWorkingGroupLeaderOpeningProposal( - this.api.createType('MemberId',0), + this.api.createType('MemberId', 0), 'some long title for the purpose of testing', 'some long description for the purpose of testing', 0, @@ -467,31 +500,31 @@ export class ApiWrapper { public estimateProposeBeginWorkingGroupLeaderApplicationReviewFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createBeginReviewWorkingGroupLeaderApplicationsProposal( - this.api.createType('MemberId',0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, - this.api.createType('OpeningId',0), + this.api.createType('OpeningId', 0), 'Storage' ) as unknown) as SubmittableExtrinsic<'promise'> ) } public estimateProposeFillLeaderOpeningFee(): BN { - const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters',{ - opening_id: this.api.createType('OpeningId',0), - successful_application_id: this.api.createType('ApplicationId',0), + const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters', { + opening_id: this.api.createType('OpeningId', 0), + successful_application_id: this.api.createType('ApplicationId', 0), reward_policy: this.api.createType('Option', { - amount_per_payout: new BN(1) as Balance, - next_payment_at_block: new BN(99999) as BlockNumber, - payout_interval: this.api.createType('Option', new BN(99999)), - }), - working_group: this.api.createType('WorkingGroup','Storage'), + amount_per_payout: new BN(1) as Balance, + next_payment_at_block: new BN(99999) as BlockNumber, + payout_interval: this.api.createType('Option', new BN(99999)), + }), + working_group: this.api.createType('WorkingGroup', 'Storage'), }) return this.estimateTxFee( (this.api.tx.proposalsCodex.createFillWorkingGroupLeaderOpeningProposal( - this.api.createType('MemberId',0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, @@ -503,7 +536,7 @@ export class ApiWrapper { public estimateProposeTerminateLeaderRoleFee(): BN { return this.estimateTxFee( (this.api.tx.proposalsCodex.createTerminateWorkingGroupLeaderRoleProposal( - this.api.createType('MemberId', 0), + this.api.createType('MemberId', 0), 'Some testing text used for estimation purposes which is longer than text expected during the test', 'Some testing text used for estimation purposes which is longer than text expected during the test', 0, @@ -981,31 +1014,32 @@ export class ApiWrapper { } public async addOpening(openingParameters: { - leader: KeyringPair, - activationDelay: BN, - maxActiveApplicants: BN, - maxReviewPeriodLength: BN, - applicationStakingPolicyAmount: BN, - applicationCrowdedOutUnstakingPeriodLength: BN, - applicationReviewPeriodExpiredUnstakingPeriodLength: BN, - roleStakingPolicyAmount: BN, - roleCrowdedOutUnstakingPeriodLength: BN, - roleReviewPeriodExpiredUnstakingPeriodLength: BN, - slashableMaxCount: BN, - slashableMaxPercentPtsPerTime: BN, - fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN, - fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN, - fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN, - terminateApplicationStakeUnstakingPeriod: BN, - terminateRoleStakeUnstakingPeriod: BN, - exitRoleApplicationStakeUnstakingPeriod: BN, - exitRoleStakeUnstakingPeriod: BN, - text: string, - type: string, - module: WorkingGroups, - expectFailure: boolean} - ): Promise { - const activateAt: ActivateOpeningAt = this.api.createType('ActivateOpeningAt', + leader: KeyringPair + activationDelay: BN + maxActiveApplicants: BN + maxReviewPeriodLength: BN + applicationStakingPolicyAmount: BN + applicationCrowdedOutUnstakingPeriodLength: BN + applicationReviewPeriodExpiredUnstakingPeriodLength: BN + roleStakingPolicyAmount: BN + roleCrowdedOutUnstakingPeriodLength: BN + roleReviewPeriodExpiredUnstakingPeriodLength: BN + slashableMaxCount: BN + slashableMaxPercentPtsPerTime: BN + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN + terminateApplicationStakeUnstakingPeriod: BN + terminateRoleStakeUnstakingPeriod: BN + exitRoleApplicationStakeUnstakingPeriod: BN + exitRoleStakeUnstakingPeriod: BN + text: string + type: string + module: WorkingGroups + expectFailure: boolean + }): Promise { + const activateAt: ActivateOpeningAt = this.api.createType( + 'ActivateOpeningAt', openingParameters.activationDelay.eqn(0) ? 'CurrentBlock' : { ExactBlock: (await this.getBestBlock()).add(openingParameters.activationDelay) } @@ -1020,7 +1054,8 @@ export class ApiWrapper { amount: openingParameters.applicationStakingPolicyAmount, amount_mode: 'AtLeast', crowded_out_unstaking_period_length: openingParameters.applicationCrowdedOutUnstakingPeriodLength, - review_period_expired_unstaking_period_length: openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength, + review_period_expired_unstaking_period_length: + openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength, }), role_staking_policy: this.api.createType('Option', { amount: openingParameters.roleStakingPolicyAmount, @@ -1034,48 +1069,75 @@ export class ApiWrapper { max_percent_pts_per_time: openingParameters.slashableMaxPercentPtsPerTime, }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod), - fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod), - fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod), - terminate_application_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateApplicationStakeUnstakingPeriod), - terminate_role_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateRoleStakeUnstakingPeriod), - exit_role_application_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleApplicationStakeUnstakingPeriod), - exit_role_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleStakeUnstakingPeriod), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod + ), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod + ), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod + ), + terminate_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.terminateApplicationStakeUnstakingPeriod + ), + terminate_role_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.terminateRoleStakeUnstakingPeriod + ), + exit_role_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.exitRoleApplicationStakeUnstakingPeriod + ), + exit_role_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.exitRoleStakeUnstakingPeriod + ), }) return this.sender.signAndSend( - this.createAddOpeningTransaction(activateAt, commitment, openingParameters.text, openingParameters.type, openingParameters.module), + this.createAddOpeningTransaction( + activateAt, + commitment, + openingParameters.text, + openingParameters.type, + openingParameters.module + ), openingParameters.leader, openingParameters.expectFailure ) } public async sudoAddOpening(openingParameters: { - sudo: KeyringPair, - activationDelay: BN, - maxActiveApplicants: BN, - maxReviewPeriodLength: BN, - applicationStakingPolicyAmount: BN, - applicationCrowdedOutUnstakingPeriodLength: BN, - applicationReviewPeriodExpiredUnstakingPeriodLength: BN, - roleStakingPolicyAmount: BN, - roleCrowdedOutUnstakingPeriodLength: BN, - roleReviewPeriodExpiredUnstakingPeriodLength: BN, - slashableMaxCount: BN, - slashableMaxPercentPtsPerTime: BN, - fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN, - fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN, - fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN, - terminateApplicationStakeUnstakingPeriod: BN, - terminateRoleStakeUnstakingPeriod: BN, - exitRoleApplicationStakeUnstakingPeriod: BN, - exitRoleStakeUnstakingPeriod: BN, - text: string, - type: string, + sudo: KeyringPair + activationDelay: BN + maxActiveApplicants: BN + maxReviewPeriodLength: BN + applicationStakingPolicyAmount: BN + applicationCrowdedOutUnstakingPeriodLength: BN + applicationReviewPeriodExpiredUnstakingPeriodLength: BN + roleStakingPolicyAmount: BN + roleCrowdedOutUnstakingPeriodLength: BN + roleReviewPeriodExpiredUnstakingPeriodLength: BN + slashableMaxCount: BN + slashableMaxPercentPtsPerTime: BN + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN + terminateApplicationStakeUnstakingPeriod: BN + terminateRoleStakeUnstakingPeriod: BN + exitRoleApplicationStakeUnstakingPeriod: BN + exitRoleStakeUnstakingPeriod: BN + text: string + type: string module: WorkingGroups - } - ): Promise { - const activateAt: ActivateOpeningAt = this.api.createType('ActivateOpeningAt', + }): Promise { + const activateAt: ActivateOpeningAt = this.api.createType( + 'ActivateOpeningAt', openingParameters.activationDelay.eqn(0) ? 'CurrentBlock' : { ExactBlock: (await this.getBestBlock()).add(openingParameters.activationDelay) } @@ -1090,7 +1152,8 @@ export class ApiWrapper { amount: openingParameters.applicationStakingPolicyAmount, amount_mode: 'AtLeast', crowded_out_unstaking_period_length: openingParameters.applicationCrowdedOutUnstakingPeriodLength, - review_period_expired_unstaking_period_length: openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength, + review_period_expired_unstaking_period_length: + openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength, }), role_staking_policy: this.api.createType('Option', { amount: openingParameters.roleStakingPolicyAmount, @@ -1104,50 +1167,78 @@ export class ApiWrapper { max_percent_pts_per_time: openingParameters.slashableMaxPercentPtsPerTime, }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod), - fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod), - fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod), - terminate_application_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateApplicationStakeUnstakingPeriod), - terminate_role_stake_unstaking_period: this.api.createType('Option', openingParameters.terminateRoleStakeUnstakingPeriod), - exit_role_application_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleApplicationStakeUnstakingPeriod), - exit_role_stake_unstaking_period: this.api.createType('Option', openingParameters.exitRoleStakeUnstakingPeriod), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod + ), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod + ), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod + ), + terminate_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.terminateApplicationStakeUnstakingPeriod + ), + terminate_role_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.terminateRoleStakeUnstakingPeriod + ), + exit_role_application_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.exitRoleApplicationStakeUnstakingPeriod + ), + exit_role_stake_unstaking_period: this.api.createType( + 'Option', + openingParameters.exitRoleStakeUnstakingPeriod + ), }) return this.sender.signAndSend( - this.api.tx.sudo.sudo(this.createAddOpeningTransaction(activateAt, commitment, openingParameters.text, openingParameters.type, openingParameters.module)), + this.api.tx.sudo.sudo( + this.createAddOpeningTransaction( + activateAt, + commitment, + openingParameters.text, + openingParameters.type, + openingParameters.module + ) + ), openingParameters.sudo, false ) } - public async proposeCreateWorkingGroupLeaderOpening(leaderOpening: - { - account: KeyringPair, - title: string, - description: string, - proposalStake: BN, - actiavteAt: string, - maxActiveApplicants: BN, - maxReviewPeriodLength: BN, - applicationStakingPolicyAmount: BN, - applicationCrowdedOutUnstakingPeriodLength: BN, - applicationReviewPeriodExpiredUnstakingPeriodLength: BN, - roleStakingPolicyAmount: BN, - roleCrowdedOutUnstakingPeriodLength: BN, - roleReviewPeriodExpiredUnstakingPeriodLength: BN, - slashableMaxCount: BN, - slashableMaxPercentPtsPerTime: BN, - fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN, - fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN, - fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN, - terminateApplicationStakeUnstakingPeriod: BN, - terminateRoleStakeUnstakingPeriod: BN, - exitRoleApplicationStakeUnstakingPeriod: BN, - exitRoleStakeUnstakingPeriod: BN, - text: string, - workingGroup: string} - ): Promise { - const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment',{ + public async proposeCreateWorkingGroupLeaderOpening(leaderOpening: { + account: KeyringPair + title: string + description: string + proposalStake: BN + actiavteAt: string + maxActiveApplicants: BN + maxReviewPeriodLength: BN + applicationStakingPolicyAmount: BN + applicationCrowdedOutUnstakingPeriodLength: BN + applicationReviewPeriodExpiredUnstakingPeriodLength: BN + roleStakingPolicyAmount: BN + roleCrowdedOutUnstakingPeriodLength: BN + roleReviewPeriodExpiredUnstakingPeriodLength: BN + slashableMaxCount: BN + slashableMaxPercentPtsPerTime: BN + fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN + fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN + fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN + terminateApplicationStakeUnstakingPeriod: BN + terminateRoleStakeUnstakingPeriod: BN + exitRoleApplicationStakeUnstakingPeriod: BN + exitRoleStakeUnstakingPeriod: BN + text: string + workingGroup: string + }): Promise { + const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', { application_rationing_policy: this.api.createType('Option', { max_active_applicants: leaderOpening.maxActiveApplicants as u32, }), @@ -1156,7 +1247,8 @@ export class ApiWrapper { amount: leaderOpening.applicationStakingPolicyAmount, amount_mode: 'AtLeast', crowded_out_unstaking_period_length: leaderOpening.applicationCrowdedOutUnstakingPeriodLength, - review_period_expired_unstaking_period_length: leaderOpening.applicationReviewPeriodExpiredUnstakingPeriodLength, + review_period_expired_unstaking_period_length: + leaderOpening.applicationReviewPeriodExpiredUnstakingPeriodLength, }), role_staking_policy: this.api.createType('Option', { amount: leaderOpening.roleStakingPolicyAmount, @@ -1164,19 +1256,40 @@ export class ApiWrapper { crowded_out_unstaking_period_length: leaderOpening.roleCrowdedOutUnstakingPeriodLength, review_period_expired_unstaking_period_length: leaderOpening.roleReviewPeriodExpiredUnstakingPeriodLength, }), - role_slashing_terms: this.api.createType('SlashingTerms',{ + role_slashing_terms: this.api.createType('SlashingTerms', { Slashable: { max_count: leaderOpening.slashableMaxCount, max_percent_pts_per_time: leaderOpening.slashableMaxPercentPtsPerTime, }, }), - fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod), - fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod), - fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option', leaderOpening.fillOpeningFailedApplicantRoleStakeUnstakingPeriod), - terminate_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.terminateApplicationStakeUnstakingPeriod), - terminate_role_stake_unstaking_period: this.api.createType('Option', leaderOpening.terminateRoleStakeUnstakingPeriod), - exit_role_application_stake_unstaking_period: this.api.createType('Option', leaderOpening.exitRoleApplicationStakeUnstakingPeriod), - exit_role_stake_unstaking_period: this.api.createType('Option', leaderOpening.exitRoleStakeUnstakingPeriod), + fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod + ), + fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod + ), + fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.fillOpeningFailedApplicantRoleStakeUnstakingPeriod + ), + terminate_application_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.terminateApplicationStakeUnstakingPeriod + ), + terminate_role_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.terminateRoleStakeUnstakingPeriod + ), + exit_role_application_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.exitRoleApplicationStakeUnstakingPeriod + ), + exit_role_stake_unstaking_period: this.api.createType( + 'Option', + leaderOpening.exitRoleStakeUnstakingPeriod + ), }) const memberId: MemberId = (await this.getMemberIds(leaderOpening.account.address))[0] @@ -1198,23 +1311,21 @@ export class ApiWrapper { ) } - public async proposeFillLeaderOpening(fillOpening: - { - account: KeyringPair, - title: string, - description: string, - proposalStake: BN, - openingId: OpeningId, - successfulApplicationId: ApplicationId, - amountPerPayout: BN, - nextPaymentAtBlock: BN, - payoutInterval: BN, - workingGroup: string - } - ): Promise { + public async proposeFillLeaderOpening(fillOpening: { + account: KeyringPair + title: string + description: string + proposalStake: BN + openingId: OpeningId + successfulApplicationId: ApplicationId + amountPerPayout: BN + nextPaymentAtBlock: BN + payoutInterval: BN + workingGroup: string + }): Promise { const memberId: MemberId = (await this.getMemberIds(fillOpening.account.address))[0] - const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters',{ + const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters', { opening_id: fillOpening.openingId, successful_application_id: fillOpening.successfulApplicationId, reward_policy: this.api.createType('Option', { @@ -1222,7 +1333,7 @@ export class ApiWrapper { next_payment_at_block: fillOpening.nextPaymentAtBlock as BlockNumber, payout_interval: this.api.createType('Option', fillOpening.payoutInterval), }), - working_group: this.api.createType('WorkingGroup',fillOpening.workingGroup), + working_group: this.api.createType('WorkingGroup', fillOpening.workingGroup), }) return this.sender.signAndSend( @@ -1574,7 +1685,10 @@ export class ApiWrapper { public async batchWithdrawApplication(accounts: KeyringPair[], module: WorkingGroups): Promise { return Promise.all( accounts.map(async (keyPair) => { - const applicationIds: ApplicationId[] = await this.getActiveApplicationsIdsByRoleAccount(keyPair.address, module) + const applicationIds: ApplicationId[] = await this.getActiveApplicationsIdsByRoleAccount( + keyPair.address, + module + ) console.log('application ids ' + applicationIds) await this.withdrawApplication(keyPair, applicationIds[0], module) }) @@ -1687,7 +1801,7 @@ export class ApiWrapper { } public async getWorkers(module: WorkingGroups): Promise { - return (await this.api.query[module].workerById.entries()).map(workerWithId => workerWithId[1]) + return (await this.api.query[module].workerById.entries()).map((workerWithId) => workerWithId[1]) } public async getWorkerById(id: WorkerId, module: WorkingGroups): Promise { @@ -1696,22 +1810,31 @@ export class ApiWrapper { public async getWorkerIdByRoleAccount(address: string, module: WorkingGroups): Promise { const workersAndIds: [StorageKey, Worker][] = await this.api.query[module].workerById.entries() - const index: number = workersAndIds.findIndex((workersAndId) => workersAndId[1].role_account_id.toString() === address) + const index: number = workersAndIds.findIndex( + (workersAndId) => workersAndId[1].role_account_id.toString() === address + ) return workersAndIds[index][0].args[0] as WorkerId } public async isWorker(address: string, module: WorkingGroups): Promise { const workersAndIds: [StorageKey, Worker][] = await this.api.query[module].workerById.entries() - const index: number = workersAndIds.findIndex((workersAndId) => workersAndId[1].role_account_id.toString() === address) - return index !== -1; + const index: number = workersAndIds.findIndex( + (workersAndId) => workersAndId[1].role_account_id.toString() === address + ) + return index !== -1 } public async getApplicationsIdsByRoleAccount(address: string, module: WorkingGroups): Promise { - const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries() + const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries< + Application + >() return applicationsAndIds .map((applicationWithId) => { const application: Application = applicationWithId[1] - return (application.role_account_id.toString() === address ? applicationWithId[0].args[0] as ApplicationId : undefined)}) + return application.role_account_id.toString() === address + ? (applicationWithId[0].args[0] as ApplicationId) + : undefined + }) .filter((id) => id !== undefined) as ApplicationId[] } @@ -1724,7 +1847,9 @@ export class ApiWrapper { } public async getActiveApplicationsIdsByRoleAccount(address: string, module: WorkingGroups): Promise { - const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries() + const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries< + Application + >() console.log('applications here 1 ' + applicationsAndIds) return ( await Promise.all( From 8eca0cce5fb3d9f26d44784af5d163988ce8779c Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Mon, 17 Aug 2020 18:07:25 +0200 Subject: [PATCH 012/178] package.json change reverted --- tests/network-tests/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/network-tests/package.json b/tests/network-tests/package.json index 2e00211d8c..6d56a53dac 100644 --- a/tests/network-tests/package.json +++ b/tests/network-tests/package.json @@ -15,7 +15,7 @@ "dependencies": { "@constantinople/types@npm:@joystream/types": "^0.10.0", "@nicaea/types@npm:@joystream/types": "^0.12.0", - "@alexandria/types": "./types", + "@alexandria/types": "link:../../types", "@polkadot/api": "1.26.1", "@polkadot/keyring": "3.0.1", "@rome/types@npm:@joystream/types": "^0.7.0", From 0888bae5de9ba19e4214210067504868a1eaa000 Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Mon, 17 Aug 2020 19:42:14 +0200 Subject: [PATCH 013/178] code cleaning --- .../src/iznik/tests/fixtures/proposalsModule.ts | 2 -- tests/network-tests/src/iznik/tests/leaderSetup.ts | 8 -------- tests/network-tests/src/iznik/utils/apiWrapper.ts | 6 ------ 3 files changed, 16 deletions(-) diff --git a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts index c30ec9c3b2..3b8dcf0339 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts @@ -194,8 +194,6 @@ export class FillLeaderOpeningProposalFixture implements Fixture { )[0] const now: BN = await this.apiWrapper.getBestBlock() - console.log('Successfull application id ' + applicationId) - const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeFillLeaderOpening({ account: this.m1KeyPairs[0], diff --git a/tests/network-tests/src/iznik/tests/leaderSetup.ts b/tests/network-tests/src/iznik/tests/leaderSetup.ts index 57dc24bc5a..ebf331cb03 100644 --- a/tests/network-tests/src/iznik/tests/leaderSetup.ts +++ b/tests/network-tests/src/iznik/tests/leaderSetup.ts @@ -58,13 +58,5 @@ tap.mocha.describe('Worker application happy case scenario', async () => { db.setMembers(nKeyPairs) db.setLeader(leadKeyPair[0], apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup)) - // const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture( - // apiWrapper, - // leadKeyPair, - // sudo, - // WorkingGroups.StorageWorkingGroup - // ) - // tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false)) - closeApi(apiWrapper) }) diff --git a/tests/network-tests/src/iznik/utils/apiWrapper.ts b/tests/network-tests/src/iznik/utils/apiWrapper.ts index 77b496eddc..25f82b8d1f 100644 --- a/tests/network-tests/src/iznik/utils/apiWrapper.ts +++ b/tests/network-tests/src/iznik/utils/apiWrapper.ts @@ -89,10 +89,6 @@ export class ApiWrapper { public async getBalance(address: string): Promise { const accountData: AccountInfo = await this.api.query.system.account(address) - console.log('free ' + accountData.data.free) - console.log('reserved ' + accountData.data.reserved) - console.log('feeFrozen ' + accountData.data.feeFrozen) - console.log('miscFrozen ' + accountData.data.miscFrozen) return (await this.api.query.system.account(address)).data.free } @@ -1689,7 +1685,6 @@ export class ApiWrapper { keyPair.address, module ) - console.log('application ids ' + applicationIds) await this.withdrawApplication(keyPair, applicationIds[0], module) }) ) @@ -1850,7 +1845,6 @@ export class ApiWrapper { const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries< Application >() - console.log('applications here 1 ' + applicationsAndIds) return ( await Promise.all( applicationsAndIds.map(async (applicationWithId) => { From a2ae706ee89b3ee88c836f2bd541e3f09b33669b Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 18 Aug 2020 00:02:53 +0200 Subject: [PATCH 014/178] members and council scenarion fixes --- .../src/iznik/tests/council/electingCouncilTest.ts | 4 +--- .../src/iznik/tests/membership/membershipCreationTest.ts | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts b/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts index 4588a526ae..43c006220d 100644 --- a/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts +++ b/tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts @@ -4,7 +4,6 @@ import { Keyring, WsProvider } from '@polkadot/api' import { setTestTimeout } from '../../utils/setTestTimeout' import BN from 'bn.js' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { ApiWrapper } from '../../utils/apiWrapper' import { closeApi } from '../../utils/closeApi' import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule' @@ -14,7 +13,6 @@ import { PaidTermId } from '@alexandria/types/members' tap.mocha.describe('Electing council scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -26,7 +24,7 @@ tap.mocha.describe('Electing council scenario', async () => { const N: number = +process.env.MEMBERSHIP_CREATION_N! const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const K: number = +process.env.COUNCIL_ELECTION_K! const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!) const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!) diff --git a/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts b/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts index e7786f0e95..8760b7377b 100644 --- a/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts +++ b/tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts @@ -3,16 +3,15 @@ import { Keyring, WsProvider } from '@polkadot/api' import { initConfig } from '../../utils/config' import { setTestTimeout } from '../../utils/setTestTimeout' import tap from 'tap' -import { registerJoystreamTypes } from '@alexandria/types' import { ApiWrapper } from '../../utils/apiWrapper' import { closeApi } from '../../utils/closeApi' import { BuyMembershipHappyCaseFixture, BuyMembershipWithInsufficienFundsFixture } from '../fixtures/membershipModule' import { Utils } from '../../utils/utils' import { PaidTermId } from '@alexandria/types/members' +import BN from "bn.js"; tap.mocha.describe('Membership creation scenario', async () => { initConfig() - registerJoystreamTypes() const nodeUrl: string = process.env.NODE_URL! const sudoUri: string = process.env.SUDO_ACCOUNT_URI! @@ -24,7 +23,7 @@ tap.mocha.describe('Membership creation scenario', async () => { const N: number = +process.env.MEMBERSHIP_CREATION_N! const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N) const aKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1) - const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!) + const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!)) const durationInBlocks = 7 From 1b492d427bfc3260c56ee5a9f1712af2ca1c39d9 Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 18 Aug 2020 00:31:45 +0200 Subject: [PATCH 015/178] verbose fixture arguments --- .../fixtures/councilElectionHappyCase.ts | 20 +- .../tests/fixtures/councilElectionModule.ts | 50 +-- .../iznik/tests/fixtures/membershipModule.ts | 20 +- .../iznik/tests/fixtures/proposalsModule.ts | 312 +++++++++--------- .../tests/fixtures/workingGroupModule.ts | 118 +++---- 5 files changed, 260 insertions(+), 260 deletions(-) diff --git a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts index cee7633b93..5ade3ae93d 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts @@ -10,8 +10,8 @@ import BN from 'bn.js' export class CouncilElectionHappyCaseFixture implements Fixture { private apiWrapper: ApiWrapper private sudo: KeyringPair - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] private paidTerms: PaidTermId private k: number private greaterStake: BN @@ -20,8 +20,8 @@ export class CouncilElectionHappyCaseFixture implements Fixture { constructor( apiWrapper: ApiWrapper, sudo: KeyringPair, - m1KeyPairs: KeyringPair[], - m2KeyPairs: KeyringPair[], + membersKeyPairs: KeyringPair[], + councilKeyPairs: KeyringPair[], paidTerms: PaidTermId, k: number, greaterStake: BN, @@ -29,8 +29,8 @@ export class CouncilElectionHappyCaseFixture implements Fixture { ) { this.apiWrapper = apiWrapper this.sudo = sudo - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs this.paidTerms = paidTerms this.k = k this.greaterStake = greaterStake @@ -41,7 +41,7 @@ export class CouncilElectionHappyCaseFixture implements Fixture { const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( this.apiWrapper, this.sudo, - this.m1KeyPairs, + this.membersKeyPairs, this.paidTerms ) tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false)) @@ -49,15 +49,15 @@ export class CouncilElectionHappyCaseFixture implements Fixture { const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture( this.apiWrapper, this.sudo, - this.m2KeyPairs, + this.councilKeyPairs, this.paidTerms ) tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false)) const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture( this.apiWrapper, - this.m1KeyPairs, - this.m2KeyPairs, + this.membersKeyPairs, + this.councilKeyPairs, this.k, this.sudo, this.greaterStake, diff --git a/tests/network-tests/src/iznik/tests/fixtures/councilElectionModule.ts b/tests/network-tests/src/iznik/tests/fixtures/councilElectionModule.ts index 96a8961093..5de8d84c4d 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/councilElectionModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/councilElectionModule.ts @@ -9,8 +9,8 @@ import { Fixture } from './interfaces/fixture' export class ElectCouncilFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] private k: number private sudo: KeyringPair private greaterStake: BN @@ -18,16 +18,16 @@ export class ElectCouncilFixture implements Fixture { public constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - m2KeyPairs: KeyringPair[], + membersKeyPairs: KeyringPair[], + councilKeyPairs: KeyringPair[], k: number, sudo: KeyringPair, greaterStake: BN, lesserStake: BN ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs this.k = k this.sudo = sudo this.greaterStake = greaterStake @@ -43,7 +43,7 @@ export class ElectCouncilFixture implements Fixture { this.greaterStake ) const salt: string[] = [] - this.m1KeyPairs.forEach(() => { + this.membersKeyPairs.forEach(() => { salt.push(''.concat(uuid().replace(/-/g, ''))) }) const revealVoteFee: BN = this.apiWrapper.estimateRevealVoteFee(this.sudo.address, salt[0]) @@ -51,19 +51,19 @@ export class ElectCouncilFixture implements Fixture { // Topping the balances await this.apiWrapper.transferBalanceToAccounts( this.sudo, - this.m2KeyPairs, + this.councilKeyPairs, applyForCouncilFee.add(this.greaterStake) ) await this.apiWrapper.transferBalanceToAccounts( this.sudo, - this.m1KeyPairs, + this.membersKeyPairs, voteForCouncilFee.add(revealVoteFee).add(this.greaterStake) ) // First K members stake more await this.apiWrapper.sudoStartAnnouncingPerion(this.sudo, now.addn(100)) - await this.apiWrapper.batchApplyForCouncilElection(this.m2KeyPairs.slice(0, this.k), this.greaterStake) - this.m2KeyPairs.slice(0, this.k).forEach((keyPair) => + await this.apiWrapper.batchApplyForCouncilElection(this.councilKeyPairs.slice(0, this.k), this.greaterStake) + this.councilKeyPairs.slice(0, this.k).forEach((keyPair) => this.apiWrapper.getCouncilElectionStake(keyPair.address).then((stake) => { assert( stake.eq(this.greaterStake), @@ -73,8 +73,8 @@ export class ElectCouncilFixture implements Fixture { ) // Last members stake less - await this.apiWrapper.batchApplyForCouncilElection(this.m2KeyPairs.slice(this.k), this.lesserStake) - this.m2KeyPairs.slice(this.k).forEach((keyPair) => + await this.apiWrapper.batchApplyForCouncilElection(this.councilKeyPairs.slice(this.k), this.lesserStake) + this.councilKeyPairs.slice(this.k).forEach((keyPair) => this.apiWrapper.getCouncilElectionStake(keyPair.address).then((stake) => { assert( stake.eq(this.lesserStake), @@ -86,14 +86,14 @@ export class ElectCouncilFixture implements Fixture { // Voting await this.apiWrapper.sudoStartVotingPerion(this.sudo, now.addn(100)) await this.apiWrapper.batchVoteForCouncilMember( - this.m1KeyPairs.slice(0, this.k), - this.m2KeyPairs.slice(0, this.k), + this.membersKeyPairs.slice(0, this.k), + this.councilKeyPairs.slice(0, this.k), salt.slice(0, this.k), this.lesserStake ) await this.apiWrapper.batchVoteForCouncilMember( - this.m1KeyPairs.slice(this.k), - this.m2KeyPairs.slice(this.k), + this.membersKeyPairs.slice(this.k), + this.councilKeyPairs.slice(this.k), salt.slice(this.k), this.greaterStake ) @@ -101,13 +101,13 @@ export class ElectCouncilFixture implements Fixture { // Revealing await this.apiWrapper.sudoStartRevealingPerion(this.sudo, now.addn(100)) await this.apiWrapper.batchRevealVote( - this.m1KeyPairs.slice(0, this.k), - this.m2KeyPairs.slice(0, this.k), + this.membersKeyPairs.slice(0, this.k), + this.councilKeyPairs.slice(0, this.k), salt.slice(0, this.k) ) await this.apiWrapper.batchRevealVote( - this.m1KeyPairs.slice(this.k), - this.m2KeyPairs.slice(this.k), + this.membersKeyPairs.slice(this.k), + this.councilKeyPairs.slice(this.k), salt.slice(this.k) ) now = await this.apiWrapper.getBestBlock() @@ -119,14 +119,14 @@ export class ElectCouncilFixture implements Fixture { const seats: Seat[] = await this.apiWrapper.getCouncil() // Preparing collections to increase assertion readability - const m2addresses: string[] = this.m2KeyPairs.map((keyPair) => keyPair.address) - const m1addresses: string[] = this.m1KeyPairs.map((keyPair) => keyPair.address) + const councilAddresses: string[] = this.councilKeyPairs.map((keyPair) => keyPair.address) + const membersAddresses: string[] = this.membersKeyPairs.map((keyPair) => keyPair.address) const members: string[] = seats.map((seat) => seat.member.toString()) const bakers: string[] = seats.map((seat) => seat.backers.map((baker) => baker.member.toString())).flat() // Assertions - m2addresses.forEach((address) => assert(members.includes(address), `Account ${address} is not in the council`)) - m1addresses.forEach((address) => assert(bakers.includes(address), `Account ${address} is not in the voters`)) + councilAddresses.forEach((address) => assert(members.includes(address), `Account ${address} is not in the council`)) + membersAddresses.forEach((address) => assert(bakers.includes(address), `Account ${address} is not in the voters`)) seats.forEach((seat) => assert( Utils.getTotalStake(seat).eq(this.greaterStake.add(this.lesserStake)), diff --git a/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts b/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts index 1e7b9537c2..9696b83944 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts @@ -7,13 +7,13 @@ import { PaidTermId } from '@alexandria/types/members' export class BuyMembershipHappyCaseFixture implements Fixture { private apiWrapper: ApiWrapper - private sudo: KeyringPair + private treasury: KeyringPair private keyPairs: KeyringPair[] private paidTerms: PaidTermId - public constructor(apiWrapper: ApiWrapper, sudo: KeyringPair, keyPairs: KeyringPair[], paidTerms: PaidTermId) { + public constructor(apiWrapper: ApiWrapper, treasury: KeyringPair, keyPairs: KeyringPair[], paidTerms: PaidTermId) { this.apiWrapper = apiWrapper - this.sudo = sudo + this.treasury = treasury this.keyPairs = keyPairs this.paidTerms = paidTerms } @@ -22,12 +22,12 @@ export class BuyMembershipHappyCaseFixture implements Fixture { // Fee estimation and transfer const membershipFee: BN = await this.apiWrapper.getMembershipFee(this.paidTerms) const membershipTransactionFee: BN = this.apiWrapper.estimateBuyMembershipFee( - this.sudo, + this.treasury, this.paidTerms, 'member_name_which_is_longer_than_expected' ) await this.apiWrapper.transferBalanceToAccounts( - this.sudo, + this.treasury, this.keyPairs, membershipTransactionFee.add(new BN(membershipFee)) ) @@ -57,13 +57,13 @@ export class BuyMembershipHappyCaseFixture implements Fixture { export class BuyMembershipWithInsufficienFundsFixture implements Fixture { private apiWrapper: ApiWrapper - private sudo: KeyringPair + private treasury: KeyringPair private aKeyPair: KeyringPair private paidTerms: PaidTermId - public constructor(apiWrapper: ApiWrapper, sudo: KeyringPair, aKeyPair: KeyringPair, paidTerms: PaidTermId) { + public constructor(apiWrapper: ApiWrapper, treasury: KeyringPair, aKeyPair: KeyringPair, paidTerms: PaidTermId) { this.apiWrapper = apiWrapper - this.sudo = sudo + this.treasury = treasury this.aKeyPair = aKeyPair this.paidTerms = paidTerms } @@ -72,11 +72,11 @@ export class BuyMembershipWithInsufficienFundsFixture implements Fixture { // Fee estimation and transfer const membershipFee: BN = await this.apiWrapper.getMembershipFee(this.paidTerms) const membershipTransactionFee: BN = this.apiWrapper.estimateBuyMembershipFee( - this.sudo, + this.treasury, this.paidTerms, 'member_name_which_is_longer_than_expected' ) - await this.apiWrapper.transferBalance(this.sudo, this.aKeyPair.address, membershipTransactionFee) + await this.apiWrapper.transferBalance(this.treasury, this.aKeyPair.address, membershipTransactionFee) // Balance assertion await this.apiWrapper diff --git a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts index 3b8dcf0339..4b1cc21557 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts @@ -11,8 +11,8 @@ import { WorkerId } from '@alexandria/types/working-group' export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private treasury: KeyringPair private applicationStake: BN private roleStake: BN private workingGroup: string @@ -21,15 +21,15 @@ export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + treasury: KeyringPair, applicationStake: BN, roleStake: BN, workingGroup: string ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.treasury = treasury this.applicationStake = applicationStake this.roleStake = roleStake this.workingGroup = workingGroup @@ -47,17 +47,17 @@ export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(100000) const proposalFee: BN = this.apiWrapper.estimateProposeCreateWorkingGroupLeaderOpeningFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeCreateWorkingGroupLeaderOpening({ - account: this.m1KeyPairs[0], + account: this.membersKeyPairs[0], title: proposalTitle, description: description, proposalStake: proposalStake, actiavteAt: 'CurrentBlock', - maxActiveApplicants: new BN(this.m1KeyPairs.length), + maxActiveApplicants: new BN(this.membersKeyPairs.length), maxReviewPeriodLength: new BN(32), applicationStakingPolicyAmount: this.applicationStake, applicationCrowdedOutUnstakingPeriodLength: new BN(1), @@ -86,8 +86,8 @@ export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { export class BeginWorkingGroupLeaderApplicationReviewFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private treasury: KeyringPair private openingId: OpeningId private workingGroup: string @@ -95,14 +95,14 @@ export class BeginWorkingGroupLeaderApplicationReviewFixture implements Fixture constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + treasury: KeyringPair, openingId: OpeningId, workingGroup: string ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.treasury = treasury this.openingId = openingId this.workingGroup = workingGroup } @@ -119,12 +119,12 @@ export class BeginWorkingGroupLeaderApplicationReviewFixture implements Fixture // Proposal stake calculation const proposalStake: BN = new BN(25000) const proposalFee: BN = this.apiWrapper.estimateProposeBeginWorkingGroupLeaderApplicationReviewFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeBeginWorkingGroupLeaderApplicationReview( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -140,9 +140,9 @@ export class BeginWorkingGroupLeaderApplicationReviewFixture implements Fixture export class FillLeaderOpeningProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] + private membersKeyPairs: KeyringPair[] private applicantRoleAccountAddress: string - private sudo: KeyringPair + private treasury: KeyringPair private firstRewardInterval: BN private rewardInterval: BN private payoutAmount: BN @@ -153,9 +153,9 @@ export class FillLeaderOpeningProposalFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], + membersKeyPairs: KeyringPair[], applicantRoleAccountAddress: string, - sudo: KeyringPair, + treasury: KeyringPair, firstRewardInterval: BN, rewardInterval: BN, payoutAmount: BN, @@ -163,9 +163,9 @@ export class FillLeaderOpeningProposalFixture implements Fixture { workingGroup: WorkingGroups ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs + this.membersKeyPairs = membersKeyPairs this.applicantRoleAccountAddress = applicantRoleAccountAddress - this.sudo = sudo + this.treasury = treasury this.firstRewardInterval = firstRewardInterval this.rewardInterval = rewardInterval this.payoutAmount = payoutAmount @@ -186,7 +186,7 @@ export class FillLeaderOpeningProposalFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(50000) const proposalFee: BN = this.apiWrapper.estimateProposeFillLeaderOpeningFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const applicationId: ApplicationId = ( @@ -196,7 +196,7 @@ export class FillLeaderOpeningProposalFixture implements Fixture { const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeFillLeaderOpening({ - account: this.m1KeyPairs[0], + account: this.membersKeyPairs[0], title: proposalTitle, description: description, proposalStake: proposalStake, @@ -216,9 +216,9 @@ export class FillLeaderOpeningProposalFixture implements Fixture { export class TerminateLeaderRoleProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] + private membersKeyPairs: KeyringPair[] private leaderRoleAccountAddress: string - private sudo: KeyringPair + private treasury: KeyringPair private slash: boolean private workingGroup: WorkingGroups @@ -226,16 +226,16 @@ export class TerminateLeaderRoleProposalFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], + membersKeyPairs: KeyringPair[], leaderRoleAccountAddress: string, - sudo: KeyringPair, + treasury: KeyringPair, slash: boolean, workingGroup: WorkingGroups ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs + this.membersKeyPairs = membersKeyPairs this.leaderRoleAccountAddress = leaderRoleAccountAddress - this.sudo = sudo + this.treasury = treasury this.slash = slash this.workingGroup = workingGroup } @@ -258,12 +258,12 @@ export class TerminateLeaderRoleProposalFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(100000) const proposalFee: BN = this.apiWrapper.estimateProposeTerminateLeaderRoleFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeTerminateLeaderRole( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -281,8 +281,8 @@ export class TerminateLeaderRoleProposalFixture implements Fixture { export class SetLeaderRewardProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private treasury: KeyringPair private payoutAmount: BN private workingGroup: WorkingGroups @@ -290,14 +290,14 @@ export class SetLeaderRewardProposalFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + treasury: KeyringPair, payoutAmount: BN, workingGroup: WorkingGroups ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.treasury = treasury this.payoutAmount = payoutAmount this.workingGroup = workingGroup } @@ -316,12 +316,12 @@ export class SetLeaderRewardProposalFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(50000) const proposalFee: BN = this.apiWrapper.estimateProposeLeaderRewardFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeLeaderReward( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -338,8 +338,8 @@ export class SetLeaderRewardProposalFixture implements Fixture { export class DecreaseLeaderStakeProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private treasury: KeyringPair private stakeDecrement: BN private workingGroup: WorkingGroups @@ -347,14 +347,14 @@ export class DecreaseLeaderStakeProposalFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + treasury: KeyringPair, stakeDecrement: BN, workingGroup: WorkingGroups ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.treasury = treasury this.stakeDecrement = stakeDecrement this.workingGroup = workingGroup } @@ -373,12 +373,12 @@ export class DecreaseLeaderStakeProposalFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(50000) const proposalFee: BN = this.apiWrapper.estimateProposeDecreaseLeaderStakeFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeDecreaseLeaderStake( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -395,8 +395,8 @@ export class DecreaseLeaderStakeProposalFixture implements Fixture { export class SlashLeaderProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private treasury: KeyringPair private slashAmount: BN private workingGroup: WorkingGroups @@ -404,14 +404,14 @@ export class SlashLeaderProposalFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + treasury: KeyringPair, slashAmount: BN, workingGroup: WorkingGroups ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.treasury = treasury this.slashAmount = slashAmount this.workingGroup = workingGroup } @@ -430,12 +430,12 @@ export class SlashLeaderProposalFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(50000) const proposalFee: BN = this.apiWrapper.estimateProposeSlashLeaderStakeFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeSlashLeaderStake( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -452,8 +452,8 @@ export class SlashLeaderProposalFixture implements Fixture { export class WorkingGroupMintCapacityProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private treasury: KeyringPair private mintCapacity: BN private workingGroup: WorkingGroups @@ -461,14 +461,14 @@ export class WorkingGroupMintCapacityProposalFixture implements Fixture { constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + treasury: KeyringPair, mintCapacity: BN, workingGroup: WorkingGroups ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.treasury = treasury this.mintCapacity = mintCapacity this.workingGroup = workingGroup } @@ -486,12 +486,12 @@ export class WorkingGroupMintCapacityProposalFixture implements Fixture { // Proposal stake calculation const proposalStake: BN = new BN(50000) const proposalFee: BN = this.apiWrapper.estimateProposeWorkingGroupMintCapacityFee() - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeWorkingGroupMintCapacity( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -507,15 +507,15 @@ export class WorkingGroupMintCapacityProposalFixture implements Fixture { export class ElectionParametersProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair - constructor(apiWrapper: ApiWrapper, m1KeyPairs: KeyringPair[], m2KeyPairs: KeyringPair[], sudo: KeyringPair) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], councilKeyPairs: KeyringPair[], treasury: KeyringPair) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury } public async runner(expectFailure: boolean): Promise { @@ -523,7 +523,7 @@ export class ElectionParametersProposalFixture implements Fixture { const proposalTitle: string = 'Testing proposal ' + uuid().substring(0, 8) const description: string = 'Testing validator count proposal ' + uuid().substring(0, 8) const runtimeVoteFee: BN = this.apiWrapper.estimateVoteForProposalFee() - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, runtimeVoteFee) const announcingPeriod: BN = await this.apiWrapper.getAnnouncingPeriod() const votingPeriod: BN = await this.apiWrapper.getVotingPeriod() const revealingPeriod: BN = await this.apiWrapper.getRevealingPeriod() @@ -548,7 +548,7 @@ export class ElectionParametersProposalFixture implements Fixture { minCouncilStake, minVotingStake ) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposedAnnouncingPeriod: BN = announcingPeriod.subn(1) @@ -561,7 +561,7 @@ export class ElectionParametersProposalFixture implements Fixture { const proposedMinVotingStake: BN = minVotingStake.addn(1) const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeElectionParameters( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -578,7 +578,7 @@ export class ElectionParametersProposalFixture implements Fixture { // Approving the proposal const proposalExecutionPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await proposalExecutionPromise // Assertions @@ -630,15 +630,15 @@ export class ElectionParametersProposalFixture implements Fixture { export class SetLeadProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair - constructor(apiWrapper: ApiWrapper, m1KeyPairs: KeyringPair[], m2KeyPairs: KeyringPair[], sudo: KeyringPair) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], councilKeyPairs: KeyringPair[], treasury: KeyringPair) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury } public async runner(expectFailure: boolean): Promise { @@ -646,7 +646,7 @@ export class SetLeadProposalFixture implements Fixture { const proposalTitle: string = 'Testing proposal ' + uuid().substring(0, 8) const description: string = 'Testing validator count proposal ' + uuid().substring(0, 8) const runtimeVoteFee: BN = this.apiWrapper.estimateVoteForProposalFee() - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, runtimeVoteFee) // Proposal stake calculation const proposalStake: BN = new BN(50000) @@ -654,23 +654,23 @@ export class SetLeadProposalFixture implements Fixture { description, description, proposalStake, - this.sudo.address + this.treasury.address ) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() - await this.apiWrapper.proposeLead(this.m1KeyPairs[0], proposalTitle, description, proposalStake, this.m1KeyPairs[1]) + await this.apiWrapper.proposeLead(this.membersKeyPairs[0], proposalTitle, description, proposalStake, this.membersKeyPairs[1]) const proposalNumber: ProposalId = await proposalPromise // Approving the proposal const proposalExecutionPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await proposalExecutionPromise const newLead: string = await this.apiWrapper.getCurrentLeadAddress() assert( - newLead === this.m1KeyPairs[1].address, - `New lead has unexpected value ${newLead}, expected ${this.m1KeyPairs[1].address}` + newLead === this.membersKeyPairs[1].address, + `New lead has unexpected value ${newLead}, expected ${this.membersKeyPairs[1].address}` ) if (expectFailure) { throw new Error('Successful fixture run while expecting failure') @@ -680,23 +680,23 @@ export class SetLeadProposalFixture implements Fixture { export class SpendingProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] private sudo: KeyringPair private spendingBalance: BN private mintCapacity: BN constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - m2KeyPairs: KeyringPair[], + membersKeyPairs: KeyringPair[], + councilKeyPairs: KeyringPair[], sudo: KeyringPair, spendingBalance: BN, mintCapacity: BN ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs this.sudo = sudo this.spendingBalance = spendingBalance this.mintCapacity = mintCapacity @@ -716,14 +716,14 @@ export class SpendingProposalFixture implements Fixture { this.spendingBalance, this.sudo.address ) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, runtimeProposalFee.add(proposalStake)) - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalance(this.sudo, this.membersKeyPairs[0].address, runtimeProposalFee.add(proposalStake)) + await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.councilKeyPairs, runtimeVoteFee) await this.apiWrapper.sudoSetCouncilMintCapacity(this.sudo, this.mintCapacity) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeSpending( - this.m1KeyPairs[0], + this.membersKeyPairs[0], 'testing spending' + uuid().substring(0, 8), 'spending to test proposal functionality' + uuid().substring(0, 8), proposalStake, @@ -735,13 +735,13 @@ export class SpendingProposalFixture implements Fixture { // Approving spending proposal const balanceBeforeMinting: BN = await this.apiWrapper.getBalance(this.sudo.address) const spendingPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await spendingPromise const balanceAfterMinting: BN = await this.apiWrapper.getBalance(this.sudo.address) assert( balanceAfterMinting.sub(balanceBeforeMinting).eq(this.spendingBalance), `member ${ - this.m1KeyPairs[0].address + this.membersKeyPairs[0].address } has unexpected balance ${balanceAfterMinting}, expected ${balanceBeforeMinting.add(this.spendingBalance)}` ) if (expectFailure) { @@ -752,15 +752,15 @@ export class SpendingProposalFixture implements Fixture { export class TextProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair - constructor(apiWrapper: ApiWrapper, m1KeyPairs: KeyringPair[], m2KeyPairs: KeyringPair[], sudo: KeyringPair) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], councilKeyPairs: KeyringPair[], treasury: KeyringPair) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury } public async runner(expectFailure: boolean): Promise { @@ -769,7 +769,7 @@ export class TextProposalFixture implements Fixture { const description: string = 'Testing text proposal ' + uuid().substring(0, 8) const proposalText: string = 'Text of the testing proposal ' + uuid().substring(0, 8) const runtimeVoteFee: BN = this.apiWrapper.estimateVoteForProposalFee() - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, runtimeVoteFee) // Proposal stake calculation const proposalStake: BN = new BN(25000) @@ -779,16 +779,16 @@ export class TextProposalFixture implements Fixture { description, proposalText ) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, runtimeProposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, runtimeProposalFee.add(proposalStake)) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() - await this.apiWrapper.proposeText(this.m1KeyPairs[0], proposalStake, proposalTitle, description, proposalText) + await this.apiWrapper.proposeText(this.membersKeyPairs[0], proposalStake, proposalTitle, description, proposalText) const proposalNumber: ProposalId = await proposalPromise // Approving text proposal const textProposalPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await textProposalPromise if (expectFailure) { throw new Error('Successful fixture run while expecting failure') @@ -798,22 +798,22 @@ export class TextProposalFixture implements Fixture { export class ValidatorCountProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair private validatorCountIncrement: BN constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - m2KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + councilKeyPairs: KeyringPair[], + treasury: KeyringPair, validatorCountIncrement: BN ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury this.validatorCountIncrement = validatorCountIncrement } @@ -822,19 +822,19 @@ export class ValidatorCountProposalFixture implements Fixture { const proposalTitle: string = 'Testing proposal ' + uuid().substring(0, 8) const description: string = 'Testing validator count proposal ' + uuid().substring(0, 8) const runtimeVoteFee: BN = this.apiWrapper.estimateVoteForProposalFee() - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, runtimeVoteFee) // Proposal stake calculation const proposalStake: BN = new BN(100000) const proposalFee: BN = this.apiWrapper.estimateProposeValidatorCountFee(description, description, proposalStake) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, proposalFee.add(proposalStake)) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, proposalFee.add(proposalStake)) const validatorCount: BN = await this.apiWrapper.getValidatorCount() // Proposal creation const proposedValidatorCount: BN = validatorCount.add(this.validatorCountIncrement) const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeValidatorCount( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalTitle, description, proposalStake, @@ -844,7 +844,7 @@ export class ValidatorCountProposalFixture implements Fixture { // Approving the proposal const proposalExecutionPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await proposalExecutionPromise const newValidatorCount: BN = await this.apiWrapper.getValidatorCount() assert( @@ -859,22 +859,22 @@ export class ValidatorCountProposalFixture implements Fixture { export class ContentWorkingGroupMintCapacityProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair private mintingCapacityIncrement: BN constructor( apiWrapper: ApiWrapper, - m1KeyPairs: KeyringPair[], - m2KeyPairs: KeyringPair[], - sudo: KeyringPair, + membersKeyPairs: KeyringPair[], + councilKeyPairs: KeyringPair[], + treasury: KeyringPair, mintingCapacityIncrement: BN ) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury this.mintingCapacityIncrement = mintingCapacityIncrement } @@ -892,14 +892,14 @@ export class ContentWorkingGroupMintCapacityProposalFixture implements Fixture { proposalStake, initialMintingCapacity.add(this.mintingCapacityIncrement) ) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, runtimeProposalFee.add(proposalStake)) - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, runtimeProposalFee.add(proposalStake)) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, runtimeVoteFee) // Proposal creation const proposedMintingCapacity: BN = initialMintingCapacity.add(this.mintingCapacityIncrement) const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeContentWorkingGroupMintCapacity( - this.m1KeyPairs[0], + this.membersKeyPairs[0], 'testing mint capacity' + uuid().substring(0, 8), 'mint capacity to test proposal functionality' + uuid().substring(0, 8), proposalStake, @@ -909,7 +909,7 @@ export class ContentWorkingGroupMintCapacityProposalFixture implements Fixture { // Approving mint capacity proposal const mintCapacityPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await mintCapacityPromise const newMintingCapacity: BN = await this.apiWrapper.getContentWorkingGroupMintCapacity() assert( @@ -924,15 +924,15 @@ export class ContentWorkingGroupMintCapacityProposalFixture implements Fixture { export class UpdateRuntimeFixture implements Fixture { private apiWrapper: ApiWrapper - private m1KeyPairs: KeyringPair[] - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private membersKeyPairs: KeyringPair[] + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair - constructor(apiWrapper: ApiWrapper, m1KeyPairs: KeyringPair[], m2KeyPairs: KeyringPair[], sudo: KeyringPair) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], councilKeyPairs: KeyringPair[], treasury: KeyringPair) { this.apiWrapper = apiWrapper - this.m1KeyPairs = m1KeyPairs - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.membersKeyPairs = membersKeyPairs + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury } public async runner(expectFailure: boolean): Promise { @@ -949,13 +949,13 @@ export class UpdateRuntimeFixture implements Fixture { description, runtime ) - await this.apiWrapper.transferBalance(this.sudo, this.m1KeyPairs[0].address, runtimeProposalFee.add(proposalStake)) - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, runtimeVoteFee) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, runtimeProposalFee.add(proposalStake)) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, runtimeVoteFee) // Proposal creation const proposalPromise: Promise = this.apiWrapper.expectProposalCreated() await this.apiWrapper.proposeRuntime( - this.m1KeyPairs[0], + this.membersKeyPairs[0], proposalStake, 'testing runtime' + uuid().substring(0, 8), 'runtime to test proposal functionality' + uuid().substring(0, 8), @@ -965,7 +965,7 @@ export class UpdateRuntimeFixture implements Fixture { // Approving runtime update proposal const runtimePromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, proposalNumber) await runtimePromise if (expectFailure) { throw new Error('Successful fixture run while expecting failure') @@ -975,24 +975,24 @@ export class UpdateRuntimeFixture implements Fixture { export class VoteForProposalFixture implements Fixture { private apiWrapper: ApiWrapper - private m2KeyPairs: KeyringPair[] - private sudo: KeyringPair + private councilKeyPairs: KeyringPair[] + private treasury: KeyringPair private proposalNumber: ProposalId - constructor(apiWrapper: ApiWrapper, m2KeyPairs: KeyringPair[], sudo: KeyringPair, proposalNumber: ProposalId) { + constructor(apiWrapper: ApiWrapper, councilKeyPairs: KeyringPair[], treasury: KeyringPair, proposalNumber: ProposalId) { this.apiWrapper = apiWrapper - this.m2KeyPairs = m2KeyPairs - this.sudo = sudo + this.councilKeyPairs = councilKeyPairs + this.treasury = treasury this.proposalNumber = proposalNumber } public async runner(expectFailure: boolean): Promise { const proposalVoteFee: BN = this.apiWrapper.estimateVoteForProposalFee() - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.m2KeyPairs, proposalVoteFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.councilKeyPairs, proposalVoteFee) // Approving the proposal const proposalExecutionPromise: Promise = this.apiWrapper.expectProposalFinalized() - await this.apiWrapper.batchApproveProposal(this.m2KeyPairs, this.proposalNumber) + await this.apiWrapper.batchApproveProposal(this.councilKeyPairs, this.proposalNumber) await proposalExecutionPromise if (expectFailure) { throw new Error('Successful fixture run while expecting failure') diff --git a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts index 8cd30e6199..f1e16b6069 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts @@ -15,7 +15,7 @@ export class AddWorkerOpeningFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private applicationStake: BN private roleStake: BN private activationDelay: BN @@ -32,7 +32,7 @@ export class AddWorkerOpeningFixture implements Fixture { apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, applicationStake: BN, roleStake: BN, activationDelay: BN, @@ -42,7 +42,7 @@ export class AddWorkerOpeningFixture implements Fixture { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.lead = lead - this.sudo = sudo + this.treasury = treasury this.applicationStake = applicationStake this.roleStake = roleStake this.activationDelay = activationDelay @@ -53,7 +53,7 @@ export class AddWorkerOpeningFixture implements Fixture { public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const addOpeningFee: BN = this.apiWrapper.estimateAddOpeningFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, addOpeningFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, addOpeningFee) // Worker opening creation const addOpeningPromise: Promise = this.apiWrapper.expectEvent('OpeningAdded') @@ -158,20 +158,20 @@ export class AddLeaderOpeningFixture implements Fixture { export class AcceptApplicationsFixture implements Fixture { private apiWrapper: ApiWrapper private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private openingId: OpeningId private module: WorkingGroups public constructor( apiWrapper: ApiWrapper, lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, openingId: OpeningId, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.lead = lead - this.sudo = sudo + this.treasury = treasury this.openingId = openingId this.module = module } @@ -179,7 +179,7 @@ export class AcceptApplicationsFixture implements Fixture { public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const acceptApplicationsFee: BN = this.apiWrapper.estimateAcceptApplicationsFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, acceptApplicationsFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, acceptApplicationsFee) // Begin accepting applications await this.apiWrapper.acceptApplications(this.lead, this.openingId, this.module) @@ -195,7 +195,7 @@ export class AcceptApplicationsFixture implements Fixture { export class ApplyForOpeningFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] - private sudo: KeyringPair + private treasury: KeyringPair private applicationStake: BN private roleStake: BN private openingId: OpeningId @@ -204,7 +204,7 @@ export class ApplyForOpeningFixture implements Fixture { public constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], - sudo: KeyringPair, + treasury: KeyringPair, applicationStake: BN, roleStake: BN, openingId: OpeningId, @@ -212,7 +212,7 @@ export class ApplyForOpeningFixture implements Fixture { ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs - this.sudo = sudo + this.treasury = treasury this.applicationStake = applicationStake this.roleStake = roleStake this.openingId = openingId @@ -222,10 +222,10 @@ export class ApplyForOpeningFixture implements Fixture { public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const applyOnOpeningFee: BN = this.apiWrapper - .estimateApplyOnOpeningFee(this.sudo, this.module) + .estimateApplyOnOpeningFee(this.treasury, this.module) .add(this.applicationStake) .add(this.roleStake) - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.membersKeyPairs, applyOnOpeningFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.membersKeyPairs, applyOnOpeningFee) // Applying for created worker opening await this.apiWrapper.batchApplyOnOpening( @@ -243,20 +243,20 @@ export class ApplyForOpeningFixture implements Fixture { export class WithdrawApplicationFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups - constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], sudo: KeyringPair, module: WorkingGroups) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], treasury: KeyringPair, module: WorkingGroups) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const withdrawApplicaitonFee: BN = this.apiWrapper.estimateWithdrawApplicationFee(this.module) - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.membersKeyPairs, withdrawApplicaitonFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.membersKeyPairs, withdrawApplicaitonFee) // Application withdrawal await this.apiWrapper.batchWithdrawApplication(this.membersKeyPairs, this.module) @@ -278,20 +278,20 @@ export class WithdrawApplicationFixture implements Fixture { export class BeginApplicationReviewFixture implements Fixture { private apiWrapper: ApiWrapper private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private openingId: OpeningId private module: WorkingGroups constructor( apiWrapper: ApiWrapper, lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, openingId: OpeningId, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.lead = lead - this.sudo = sudo + this.treasury = treasury this.openingId = openingId this.module = module } @@ -299,7 +299,7 @@ export class BeginApplicationReviewFixture implements Fixture { public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const beginReviewFee: BN = this.apiWrapper.estimateBeginApplicantReviewFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, beginReviewFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, beginReviewFee) // Begin application review const beginApplicantReviewPromise: Promise = this.apiWrapper.expectApplicationReviewBegan() @@ -337,7 +337,7 @@ export class FillOpeningFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private openingId: OpeningId private firstPayoutInterval: BN private payoutInterval: BN @@ -348,7 +348,7 @@ export class FillOpeningFixture implements Fixture { apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, openingId: OpeningId, firstPayoutInterval: BN, payoutInterval: BN, @@ -358,7 +358,7 @@ export class FillOpeningFixture implements Fixture { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.lead = lead - this.sudo = sudo + this.treasury = treasury this.openingId = openingId this.firstPayoutInterval = firstPayoutInterval this.payoutInterval = payoutInterval @@ -369,7 +369,7 @@ export class FillOpeningFixture implements Fixture { public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const beginReviewFee: BN = this.apiWrapper.estimateFillOpeningFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, beginReviewFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, beginReviewFee) const applicationIds: ApplicationId[] = ( await Promise.all( this.membersKeyPairs.map(async (keypair) => @@ -492,13 +492,13 @@ export class FillLeaderOpeningFixture implements Fixture { export class IncreaseStakeFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups - constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], sudo: KeyringPair, module: WorkingGroups) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], treasury: KeyringPair, module: WorkingGroups) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs - this.sudo = sudo + this.treasury = treasury this.module = module } @@ -507,7 +507,7 @@ export class IncreaseStakeFixture implements Fixture { const increaseStakeFee: BN = this.apiWrapper.estimateIncreaseStakeFee(this.module) const stakeIncrement: BN = new BN(1) await this.apiWrapper.transferBalance( - this.sudo, + this.treasury, this.membersKeyPairs[0].address, increaseStakeFee.add(stakeIncrement) ) @@ -536,27 +536,27 @@ export class UpdateRewardAccountFixture implements Fixture { public apiWrapper: ApiWrapper public membersKeyPairs: KeyringPair[] public keyring: Keyring - public sudo: KeyringPair + public treasury: KeyringPair public module: WorkingGroups constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], keyring: Keyring, - sudo: KeyringPair, + treasury: KeyringPair, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.keyring = keyring - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer - const updateRewardAccountFee: BN = this.apiWrapper.estimateUpdateRewardAccountFee(this.sudo.address, this.module) - await this.apiWrapper.transferBalance(this.sudo, this.membersKeyPairs[0].address, updateRewardAccountFee) + const updateRewardAccountFee: BN = this.apiWrapper.estimateUpdateRewardAccountFee(this.treasury.address, this.module) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, updateRewardAccountFee) const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount( this.membersKeyPairs[0].address, this.module @@ -580,27 +580,27 @@ export class UpdateRoleAccountFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private keyring: Keyring - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], keyring: Keyring, - sudo: KeyringPair, + treasury: KeyringPair, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.keyring = keyring - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer - const updateRoleAccountFee: BN = this.apiWrapper.estimateUpdateRoleAccountFee(this.sudo.address, this.module) - await this.apiWrapper.transferBalance(this.sudo, this.membersKeyPairs[0].address, updateRoleAccountFee) + const updateRoleAccountFee: BN = this.apiWrapper.estimateUpdateRoleAccountFee(this.treasury.address, this.module) + await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, updateRoleAccountFee) const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount( this.membersKeyPairs[0].address, this.module @@ -628,20 +628,20 @@ export class TerminateApplicationsFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.lead = lead - this.sudo = sudo + this.treasury = treasury this.module = module } @@ -649,7 +649,7 @@ export class TerminateApplicationsFixture implements Fixture { // Fee estimation and transfer const terminateApplicationFee: BN = this.apiWrapper.estimateTerminateApplicationFee(this.module) await this.apiWrapper.transferBalance( - this.sudo, + this.treasury, this.lead.address, terminateApplicationFee.muln(this.membersKeyPairs.length) ) @@ -673,27 +673,27 @@ export class DecreaseStakeFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.lead = lead - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const decreaseStakeFee: BN = this.apiWrapper.estimateDecreaseStakeFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, decreaseStakeFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, decreaseStakeFee) const workerStakeDecrement: BN = new BN(1) const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount( this.membersKeyPairs[0].address, @@ -721,27 +721,27 @@ export class SlashFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.lead = lead - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const slashStakeFee: BN = this.apiWrapper.estimateSlashStakeFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, slashStakeFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, slashStakeFee) const slashAmount: BN = new BN(1) const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount( this.membersKeyPairs[0].address, @@ -762,27 +762,27 @@ export class TerminateRoleFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] private lead: KeyringPair - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups constructor( apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], lead: KeyringPair, - sudo: KeyringPair, + treasury: KeyringPair, module: WorkingGroups ) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs this.lead = lead - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const terminateRoleFee: BN = this.apiWrapper.estimateTerminateRoleFee(this.module) - await this.apiWrapper.transferBalance(this.sudo, this.lead.address, terminateRoleFee) + await this.apiWrapper.transferBalance(this.treasury, this.lead.address, terminateRoleFee) const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount( this.membersKeyPairs[0].address, this.module @@ -800,20 +800,20 @@ export class TerminateRoleFixture implements Fixture { export class LeaveRoleFixture implements Fixture { private apiWrapper: ApiWrapper private membersKeyPairs: KeyringPair[] - private sudo: KeyringPair + private treasury: KeyringPair private module: WorkingGroups - constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], sudo: KeyringPair, module: WorkingGroups) { + constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], treasury: KeyringPair, module: WorkingGroups) { this.apiWrapper = apiWrapper this.membersKeyPairs = membersKeyPairs - this.sudo = sudo + this.treasury = treasury this.module = module } public async runner(expectFailure: boolean): Promise { // Fee estimation and transfer const leaveRoleFee: BN = this.apiWrapper.estimateLeaveRoleFee(this.module) - await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.membersKeyPairs, leaveRoleFee) + await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.membersKeyPairs, leaveRoleFee) await this.apiWrapper.batchLeaveRole(this.membersKeyPairs, uuid().substring(0, 8), expectFailure, this.module) From dd2061975894c5d442827b5a367272e9b6761ac5 Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 18 Aug 2020 01:02:45 +0200 Subject: [PATCH 016/178] verbose result functions for fixtures --- .../tests/fixtures/leaderHiringHappyCase.ts | 6 ++-- .../iznik/tests/fixtures/membershipModule.ts | 5 +++ .../iznik/tests/fixtures/proposalsModule.ts | 16 ++++----- .../tests/fixtures/workingGroupModule.ts | 30 +++------------- .../tests/proposals/manageLeaderRoleTest.ts | 20 +++++------ .../workingGroupMintCapacityProposalTest.ts | 2 +- .../workingGroup/manageWorkerAsLeadTest.ts | 12 +++---- .../workingGroup/manageWorkerAsWorkerTest.ts | 6 ++-- .../workerApplicationHappyCaseTest.ts | 8 ++--- .../workerApplicationRejectionCaseTest.ts | 8 ++--- .../tests/workingGroup/workerPayoutTest.ts | 8 ++--- yarn.lock | 35 +++++++++++++++++++ 12 files changed, 88 insertions(+), 68 deletions(-) diff --git a/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts b/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts index 2347cf422f..2fc710531e 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts @@ -91,7 +91,7 @@ export class LeaderHiringHappyCaseFixture implements Fixture { this.sudo, this.applicationStake, this.roleStake, - addLeaderOpeningFixture.getResult() as OpeningId, + addLeaderOpeningFixture.getCreatedOpeningId() as OpeningId, this.workingGroup ) await applyForLeaderOpeningFixture.runner(false) @@ -102,7 +102,7 @@ export class LeaderHiringHappyCaseFixture implements Fixture { beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( this.apiWrapper, this.sudo, - addLeaderOpeningFixture.getResult() as OpeningId, + addLeaderOpeningFixture.getCreatedOpeningId() as OpeningId, this.workingGroup ) await beginLeaderApplicationReviewFixture.runner(false) @@ -114,7 +114,7 @@ export class LeaderHiringHappyCaseFixture implements Fixture { this.apiWrapper, this.leadKeyPair, this.sudo, - addLeaderOpeningFixture.getResult() as OpeningId, + addLeaderOpeningFixture.getCreatedOpeningId() as OpeningId, this.firstRewardInterval, this.rewardInterval, this.payoutAmount, diff --git a/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts b/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts index 9696b83944..94a4a49fb3 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts @@ -69,6 +69,11 @@ export class BuyMembershipWithInsufficienFundsFixture implements Fixture { } public async runner(expectFailure: boolean) { + // Assertions + this.apiWrapper + .getMemberIds(this.aKeyPair.address) + .then((membership) => assert(membership.length === 0, 'Account A is a member')) + // Fee estimation and transfer const membershipFee: BN = await this.apiWrapper.getMembershipFee(this.paidTerms) const membershipTransactionFee: BN = this.apiWrapper.estimateBuyMembershipFee( diff --git a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts index 4b1cc21557..d479b84c4b 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts @@ -35,7 +35,7 @@ export class CreateWorkingGroupLeaderOpeningFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -107,7 +107,7 @@ export class BeginWorkingGroupLeaderApplicationReviewFixture implements Fixture this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -173,7 +173,7 @@ export class FillLeaderOpeningProposalFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -240,7 +240,7 @@ export class TerminateLeaderRoleProposalFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -302,7 +302,7 @@ export class SetLeaderRewardProposalFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -359,7 +359,7 @@ export class DecreaseLeaderStakeProposalFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -416,7 +416,7 @@ export class SlashLeaderProposalFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } @@ -473,7 +473,7 @@ export class WorkingGroupMintCapacityProposalFixture implements Fixture { this.workingGroup = workingGroup } - public getResult(): ProposalId | undefined { + public getCreatedProposalId(): ProposalId | undefined { return this.result } diff --git a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts index f1e16b6069..cf247bb2f6 100644 --- a/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts +++ b/tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts @@ -24,7 +24,7 @@ export class AddWorkerOpeningFixture implements Fixture { private result: OpeningId | undefined - public getResult(): OpeningId | undefined { + public getCreatedOpeningId(): OpeningId | undefined { return this.result } @@ -100,7 +100,7 @@ export class AddLeaderOpeningFixture implements Fixture { private result: OpeningId | undefined - public getResult(): OpeningId | undefined { + public getCreatedOpeningId(): OpeningId | undefined { return this.result } @@ -886,7 +886,7 @@ export class ExpectLeadOpeningAddedFixture implements Fixture { this.apiWrapper = apiWrapper } - public getResult(): OpeningId | undefined { + public getCreatedOpeningId(): OpeningId | undefined { return this.result } @@ -918,7 +918,7 @@ export class ExpectLeaderSetFixture implements Fixture { this.module = module } - public getResult(): WorkerId | undefined { + public getLeaderWorkerId(): WorkerId | undefined { return this.result } @@ -956,7 +956,7 @@ export class ExpectBeganApplicationReviewFixture implements Fixture { this.apiWrapper = apiWrapper } - public getResult(): ApplicationId | undefined { + public getApplicationId(): ApplicationId | undefined { return this.result } @@ -978,7 +978,6 @@ export class ExpectLeaderRoleTerminatedFixture implements Fixture { private apiWrapper: ApiWrapper private module: WorkingGroups - private result: BN | undefined private events: Event[] = [] constructor(apiWrapper: ApiWrapper, module: WorkingGroups) { @@ -986,10 +985,6 @@ export class ExpectLeaderRoleTerminatedFixture implements Fixture { this.module = module } - public getResult(): BN | undefined { - return this.result - } - public getEvents(): Event[] { return this.events } @@ -1010,7 +1005,6 @@ export class ExpectLeaderRewardAmountUpdatedFixture implements Fixture { private expectedReward: BN private module: WorkingGroups - private result: BN | undefined private events: Event[] = [] constructor(apiWrapper: ApiWrapper, expectedReward: BN, module: WorkingGroups) { @@ -1019,10 +1013,6 @@ export class ExpectLeaderRewardAmountUpdatedFixture implements Fixture { this.module = module } - public getResult(): BN | undefined { - return this.result - } - public getEvents(): Event[] { return this.events } @@ -1047,7 +1037,6 @@ export class ExpectLeaderStakeDecreasedFixture implements Fixture { private expectedStake: BN private module: WorkingGroups - private result: BN | undefined private events: Event[] = [] constructor(apiWrapper: ApiWrapper, expectedStake: BN, module: WorkingGroups) { @@ -1056,10 +1045,6 @@ export class ExpectLeaderStakeDecreasedFixture implements Fixture { this.module = module } - public getResult(): BN | undefined { - return this.result - } - public getEvents(): Event[] { return this.events } @@ -1084,7 +1069,6 @@ export class ExpectLeaderSlashedFixture implements Fixture { private expectedStake: BN private module: WorkingGroups - private result: BN | undefined private events: Event[] = [] constructor(apiWrapper: ApiWrapper, expectedStake: BN, module: WorkingGroups) { @@ -1093,10 +1077,6 @@ export class ExpectLeaderSlashedFixture implements Fixture { this.module = module } - public getResult(): BN | undefined { - return this.result - } - public getEvents(): Event[] { return this.events } diff --git a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts index 890ba6afef..19db843256 100644 --- a/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts @@ -109,7 +109,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - createWorkingGroupLeaderOpeningFixture.getResult() as OpeningId + createWorkingGroupLeaderOpeningFixture.getCreatedProposalId() as OpeningId ) voteForCreateOpeningProposalFixture.runner(false) await expectLeadOpeningAddedFixture.runner(false) @@ -123,7 +123,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { sudo, applicationStake, roleStake, - expectLeadOpeningAddedFixture.getResult() as OpeningId, + expectLeadOpeningAddedFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForLeaderOpeningFixture.runner(false) @@ -135,7 +135,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m1KeyPairs, sudo, - expectLeadOpeningAddedFixture.getResult() as OpeningId, + expectLeadOpeningAddedFixture.getCreatedOpeningId() as OpeningId, 'Storage' ) await beginWorkingGroupLeaderApplicationReviewFixture.runner(false) @@ -150,7 +150,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - beginWorkingGroupLeaderApplicationReviewFixture.getResult() as ProposalId + beginWorkingGroupLeaderApplicationReviewFixture.getCreatedProposalId() as ProposalId ) voteForBeginReviewProposal.runner(false) await expectBeganApplicationReviewFixture.runner(false) @@ -166,7 +166,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { firstRewardInterval, rewardInterval, payoutAmount, - expectLeadOpeningAddedFixture.getResult() as OpeningId, + expectLeadOpeningAddedFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await fillLeaderOpeningProposalFixture.runner(false) @@ -183,7 +183,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - fillLeaderOpeningProposalFixture.getResult() as ProposalId + fillLeaderOpeningProposalFixture.getCreatedProposalId() as ProposalId ) voteForFillLeaderProposalFixture.runner(false) await expectLeaderSetFixture.runner(false) @@ -209,7 +209,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - setLeaderRewardProposalFixture.getResult() as ProposalId + setLeaderRewardProposalFixture.getCreatedProposalId() as ProposalId ) voteForeLeaderRewardFixture.runner(false) await expectLeaderRewardAmountUpdatedFixture.runner(false) @@ -233,7 +233,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - decreaseLeaderStakeProposalFixture.getResult() as ProposalId + decreaseLeaderStakeProposalFixture.getCreatedProposalId() as ProposalId ) voteForDecreaseStakeProposal.runner(false) expectLeaderStakeDecreasedFixture = new ExpectLeaderStakeDecreasedFixture( @@ -261,7 +261,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - slashLeaderProposalFixture.getResult() as ProposalId + slashLeaderProposalFixture.getCreatedProposalId() as ProposalId ) voteForSlashProposalFixture.runner(false) expectLeaderSlashedFixture = new ExpectLeaderSlashedFixture(apiWrapper, newStake, WorkingGroups.StorageWorkingGroup) @@ -288,7 +288,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => { apiWrapper, m2KeyPairs, sudo, - terminateLeaderRoleProposalFixture.getResult() as ProposalId + terminateLeaderRoleProposalFixture.getCreatedProposalId() as ProposalId ) voteForLeaderRoleTerminationFixture.runner(false) await expectLeaderRoleTerminatedFixture.runner(false) diff --git a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts index 0f99b1625b..ecbbab0e17 100644 --- a/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts +++ b/tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts @@ -77,7 +77,7 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async () apiWrapper, m2KeyPairs, sudo, - workingGroupMintCapacityProposalFixture.getResult() as ProposalId + workingGroupMintCapacityProposalFixture.getCreatedProposalId() as ProposalId ) voteForProposalFixture.runner(false) await expectMintCapacityChanged.runner(false) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts index 6b38fbd3d8..735d31e03a 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts @@ -95,7 +95,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForWorkerOpeningFixture.runner(false) @@ -107,7 +107,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { apiWrapper, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await beginApplicationReviewFixture.runner(false) @@ -120,7 +120,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { nKeyPairs, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, firstRewardInterval, rewardInterval, payoutAmount, @@ -165,7 +165,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { sudo, applicationStake, roleStake, - addNewLeaderOpeningFixture.getResult() as OpeningId, + addNewLeaderOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForNewLeaderOpeningFixture.runner(false) @@ -176,7 +176,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { beginNewLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture( apiWrapper, sudo, - addNewLeaderOpeningFixture.getResult() as OpeningId, + addNewLeaderOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await beginNewLeaderApplicationReviewFixture.runner(false) @@ -188,7 +188,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { apiWrapper, leadKeyPair, sudo, - addNewLeaderOpeningFixture.getResult() as OpeningId, + addNewLeaderOpeningFixture.getCreatedOpeningId() as OpeningId, firstRewardInterval, rewardInterval, payoutAmount, diff --git a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts index 8f8c2b7adf..91bc53745c 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts @@ -91,7 +91,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForWorkerOpeningFixture.runner(false) @@ -103,7 +103,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { apiWrapper, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await beginApplicationReviewFixture.runner(false) @@ -116,7 +116,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => { nKeyPairs, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, firstRewardInterval, rewardInterval, payoutAmount, diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts index a5055158c7..07fdd4bd31 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts @@ -90,7 +90,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await firstApplyForWorkerOpeningFixture.runner(false) @@ -112,7 +112,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await secondApplyForWorkerOpeningFixture.runner(false) @@ -124,7 +124,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { apiWrapper, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await beginApplicationReviewFixture.runner(false) @@ -137,7 +137,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { nKeyPairs, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, firstRewardInterval, rewardInterval, payoutAmount, diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts index 7b557c4515..24168f0e2f 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts @@ -91,7 +91,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForWorkerOpeningBeforeAcceptanceFixture.runner(true) @@ -103,7 +103,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { apiWrapper, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) acceptApplicationsFixture.runner(false) @@ -117,7 +117,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForWorkerOpeningAsNonMemberFixture.runner(true) @@ -131,7 +131,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForWorkerOpeningFixture.runner(false) diff --git a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts index c51894d362..43abfc5f61 100644 --- a/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts +++ b/tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts @@ -116,7 +116,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { apiWrapper, m2KeyPairs, sudo, - workingGroupMintCapacityProposalFixture.getResult() as ProposalId + workingGroupMintCapacityProposalFixture.getCreatedProposalId() as ProposalId ) voteForProposalFixture.runner(false) await expectMintCapacityChanged.runner(false) @@ -143,7 +143,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { sudo, applicationStake, roleStake, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await applyForWorkerOpeningFixture.runner(false) @@ -155,7 +155,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { apiWrapper, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, WorkingGroups.StorageWorkingGroup ) await beginApplicationReviewFixture.runner(false) @@ -168,7 +168,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => { m1KeyPairs, leadKeyPair[0], sudo, - addWorkerOpeningFixture.getResult() as OpeningId, + addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId, firstRewardInterval, rewardInterval, payoutAmount, diff --git a/yarn.lock b/yarn.lock index d3920c80a7..07d8600c1f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4200,6 +4200,13 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.157.tgz#fdac1c52448861dfde1a2e1515dbc46e54926dc8" integrity sha512-Ft5BNFmv2pHDgxV5JDsndOWTRJ+56zte0ZpYLowp03tW+K+t8u8YMOzAnpuqPgzX6WO1XpDIUm7u04M8vdDiVQ== +"@types/lowdb@^1.0.9": + version "1.0.9" + resolved "https://registry.yarnpkg.com/@types/lowdb/-/lowdb-1.0.9.tgz#1f6c27df72dd1c64522cc9a4566796d2dd058d38" + integrity sha512-LBRG5EPXFOJDoJc9jACstMhtMP+u+UkPYllBeGQXXKiaHc+uzJs9+/Aynb/5KkX33DtrIiKyzNVTPQc/4RcD6A== + dependencies: + "@types/lodash" "*" + "@types/marked@^0.7.0": version "0.7.2" resolved "https://registry.yarnpkg.com/@types/marked/-/marked-0.7.2.tgz#1393f076773b55cc7078c0fbeb86a497c69db97e" @@ -11944,6 +11951,11 @@ graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2 resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" integrity sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ== +graceful-fs@^4.1.3: + version "4.2.4" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" + integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== + graphviz@0.0.9: version "0.0.9" resolved "https://registry.yarnpkg.com/graphviz/-/graphviz-0.0.9.tgz#0bbf1df588c6a92259282da35323622528c4bbc4" @@ -15320,6 +15332,11 @@ lodash.zip@^4.2.0: resolved "https://registry.yarnpkg.com/lodash.zip/-/lodash.zip-4.2.0.tgz#ec6662e4896408ed4ab6c542a3990b72cc080020" integrity sha1-7GZi5IlkCO1KtsVCo5kLcswIACA= +lodash@4: + version "4.17.20" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" + integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== + lodash@^4.0.0, lodash@^4.0.1, lodash@^4.15.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.3, lodash@^4.17.4, lodash@^4.17.5, lodash@^4.2.1, lodash@~4.17.10: version "4.17.15" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" @@ -15403,6 +15420,17 @@ loud-rejection@^1.0.0: currently-unhandled "^0.4.1" signal-exit "^3.0.0" +lowdb@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lowdb/-/lowdb-1.0.0.tgz#5243be6b22786ccce30e50c9a33eac36b20c8064" + integrity sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ== + dependencies: + graceful-fs "^4.1.3" + is-promise "^2.1.0" + lodash "4" + pify "^3.0.0" + steno "^0.4.1" + lower-case@^1.1.1: version "1.1.4" resolved "https://registry.yarnpkg.com/lower-case/-/lower-case-1.1.4.tgz#9a2cabd1b9e8e0ae993a4bf7d5875c39c42e8eac" @@ -21770,6 +21798,13 @@ stealthy-require@^1.1.1: resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b" integrity sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks= +steno@^0.4.1: + version "0.4.4" + resolved "https://registry.yarnpkg.com/steno/-/steno-0.4.4.tgz#071105bdfc286e6615c0403c27e9d7b5dcb855cb" + integrity sha1-BxEFvfwobmYVwEA8J+nXtdy4Vcs= + dependencies: + graceful-fs "^4.1.3" + store2@^2.7.1: version "2.10.0" resolved "https://registry.yarnpkg.com/store2/-/store2-2.10.0.tgz#46b82bb91878daf1b0d56dec2f1d41e54d5103cf" From a1c9fff5f5a6431f6d9461c61e710c875f170b53 Mon Sep 17 00:00:00 2001 From: Gleb Urvanov Date: Tue, 18 Aug 2020 10:27:59 +0200 Subject: [PATCH 017/178] lockfile updated --- yarn.lock | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/yarn.lock b/yarn.lock index 308cd3a9fe..916e279654 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4353,6 +4353,13 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.157.tgz#fdac1c52448861dfde1a2e1515dbc46e54926dc8" integrity sha512-Ft5BNFmv2pHDgxV5JDsndOWTRJ+56zte0ZpYLowp03tW+K+t8u8YMOzAnpuqPgzX6WO1XpDIUm7u04M8vdDiVQ== +"@types/lowdb@^1.0.9": + version "1.0.9" + resolved "https://registry.yarnpkg.com/@types/lowdb/-/lowdb-1.0.9.tgz#1f6c27df72dd1c64522cc9a4566796d2dd058d38" + integrity sha512-LBRG5EPXFOJDoJc9jACstMhtMP+u+UkPYllBeGQXXKiaHc+uzJs9+/Aynb/5KkX33DtrIiKyzNVTPQc/4RcD6A== + dependencies: + "@types/lodash" "*" + "@types/marked@^0.7.0": version "0.7.4" resolved "https://registry.yarnpkg.com/@types/marked/-/marked-0.7.4.tgz#607685669bb1bbde2300bc58ba43486cbbee1f0a" @@ -12556,7 +12563,7 @@ graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2 resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" integrity sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ== -graceful-fs@^4.2.2, graceful-fs@^4.2.4: +graceful-fs@^4.1.3, graceful-fs@^4.2.2, graceful-fs@^4.2.4: version "4.2.4" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== @@ -16227,6 +16234,11 @@ lodash.zip@^4.2.0: resolved "https://registry.yarnpkg.com/lodash.zip/-/lodash.zip-4.2.0.tgz#ec6662e4896408ed4ab6c542a3990b72cc080020" integrity sha1-7GZi5IlkCO1KtsVCo5kLcswIACA= +lodash@4: + version "4.17.20" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" + integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== + lodash@^4.0.0, lodash@^4.0.1, lodash@^4.17.10, lodash@^4.17.19, lodash@^4.17.3, lodash@^4.17.5, lodash@^4.2.1, lodash@~4.17.10: version "4.17.19" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" @@ -16324,6 +16336,17 @@ loud-rejection@^1.0.0: currently-unhandled "^0.4.1" signal-exit "^3.0.0" +lowdb@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lowdb/-/lowdb-1.0.0.tgz#5243be6b22786ccce30e50c9a33eac36b20c8064" + integrity sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ== + dependencies: + graceful-fs "^4.1.3" + is-promise "^2.1.0" + lodash "4" + pify "^3.0.0" + steno "^0.4.1" + lower-case@^1.1.1: version "1.1.4" resolved "https://registry.yarnpkg.com/lower-case/-/lower-case-1.1.4.tgz#9a2cabd1b9e8e0ae993a4bf7d5875c39c42e8eac" @@ -22651,6 +22674,13 @@ stealthy-require@^1.1.1: resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b" integrity sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks= +steno@^0.4.1: + version "0.4.4" + resolved "https://registry.yarnpkg.com/steno/-/steno-0.4.4.tgz#071105bdfc286e6615c0403c27e9d7b5dcb855cb" + integrity sha1-BxEFvfwobmYVwEA8J+nXtdy4Vcs= + dependencies: + graceful-fs "^4.1.3" + store2@^2.7.1: version "2.11.2" resolved "https://registry.yarnpkg.com/store2/-/store2-2.11.2.tgz#a298e5e97b21b3ce7419b732540bc7c79cb007db" From f7d87da7fa803169254d005616c947cf0a4cc228 Mon Sep 17 00:00:00 2001 From: Leszek Wiesner Date: Tue, 18 Aug 2020 13:14:19 +0200 Subject: [PATCH 018/178] joy-proposals upgrade --- pioneer/.eslintignore | 1 - pioneer/packages/apps-routing/src/index.ts | 3 + .../apps-routing/src/joy-proposals.ts | 16 ++ .../packages/joy-election/src/ApplyForm.tsx | 1 - pioneer/packages/joy-election/src/Reveals.tsx | 1 - .../packages/joy-election/src/VoteForm.tsx | 1 - pioneer/packages/joy-members/src/EditForm.tsx | 1 - pioneer/packages/joy-proposals/.skip-build | 0 .../joy-proposals/src/Proposal/Body.tsx | 253 ++++++++++-------- .../src/Proposal/ChooseProposalType.tsx | 2 +- .../joy-proposals/src/Proposal/Details.tsx | 2 +- .../src/Proposal/ProposalDetails.tsx | 8 +- .../src/Proposal/ProposalFromId.tsx | 7 +- .../src/Proposal/ProposalPreview.tsx | 3 - .../src/Proposal/ProposalPreviewList.tsx | 2 +- .../joy-proposals/src/Proposal/Votes.tsx | 2 +- .../src/Proposal/VotingSection.tsx | 39 ++- .../Proposal/discussion/DiscussionPost.tsx | 2 +- .../discussion/DiscussionPostForm.tsx | 5 +- .../discussion/ProposalDiscussion.tsx | 2 +- .../src/forms/AddWorkingGroupOpeningForm.tsx | 3 +- .../BeginReviewLeaderApplicationsForm.tsx | 3 +- .../DecreaseWorkingGroupLeadStakeForm.tsx | 1 - .../FillWorkingGroupLeaderOpeningForm.tsx | 40 ++- .../src/forms/GenericProposalForm.tsx | 41 ++- .../forms/GenericWorkingGroupProposalForm.tsx | 5 +- .../src/forms/MintCapacityForm.tsx | 1 - .../src/forms/RuntimeUpgradeForm.tsx | 1 - .../forms/SetContentWorkingGroupLeadForm.tsx | 3 +- .../SetContentWorkingGroupMintCapForm.tsx | 2 +- .../src/forms/SetCouncilParamsForm.tsx | 31 ++- .../src/forms/SetMaxValidatorCountForm.tsx | 1 - .../forms/SetWorkingGroupLeadRewardForm.tsx | 1 - .../forms/SetWorkingGroupMintCapacityForm.tsx | 1 - .../joy-proposals/src/forms/SignalForm.tsx | 1 - .../forms/SlashWorkingGroupLeadStakeForm.tsx | 1 - .../src/forms/SpendingProposalForm.tsx | 1 - .../forms/TerminateWorkingGroupLeaderForm.tsx | 25 +- .../joy-proposals/src/forms/forms.css | 23 -- pioneer/packages/joy-proposals/src/index.css | 0 pioneer/packages/joy-proposals/src/index.tsx | 111 ++++---- .../src/stories/data/ProposalDetails.mock.ts | 6 +- .../src/{Proposal/Proposal.css => style.ts} | 8 +- .../joy-proposals/src/validationSchema.ts | 35 ++- .../src/consts/members.ts | 0 .../src/consts/proposals.ts | 0 .../src/consts/workingGroups.ts | 0 .../src/react/components/TxButton.tsx | 141 +++++----- .../working-groups/ApplicationDetails.tsx | 2 +- .../components/working-groups/LeadInfo.tsx | 2 +- .../joy-utils/src/react/hooks/index.ts | 1 + .../proposals/useProposalSubscription.tsx | 0 .../joy-utils/src/react/hooks/usePromise.tsx | 4 +- .../packages/joy-utils/src/transport/base.ts | 17 ++ .../src/transport/chain.ts | 0 .../src/transport/contentWorkingGroup.ts | 13 +- .../src/transport/council.ts | 38 ++- .../packages/joy-utils/src/transport/index.ts | 36 +-- .../joy-utils/src/transport/members.ts | 7 +- .../src/transport/proposals.ts | 69 ++--- .../src/transport/validators.ts | 0 .../src/transport/workingGroups.ts | 104 +++---- .../src/types/common.ts | 0 .../src/types/proposals.ts | 15 +- .../src/types/storageProviders.ts | 0 .../src/types/workingGroups.ts | 0 .../apps-routing/src/joy-proposals.ts | 17 -- pioneer/tsconfig.json | 5 +- types/src/index.ts | 10 + 69 files changed, 598 insertions(+), 579 deletions(-) create mode 100644 pioneer/packages/apps-routing/src/joy-proposals.ts delete mode 100644 pioneer/packages/joy-proposals/.skip-build delete mode 100644 pioneer/packages/joy-proposals/src/forms/forms.css delete mode 100644 pioneer/packages/joy-proposals/src/index.css rename pioneer/packages/joy-proposals/src/{Proposal/Proposal.css => style.ts} (80%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/consts/members.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/consts/proposals.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/consts/workingGroups.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/components/working-groups/ApplicationDetails.tsx (97%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/components/working-groups/LeadInfo.tsx (95%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/react/hooks/proposals/useProposalSubscription.tsx (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/chain.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/contentWorkingGroup.ts (72%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/council.ts (75%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/proposals.ts (77%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/validators.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/transport/workingGroups.ts (61%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/types/common.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/types/proposals.ts (83%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/types/storageProviders.ts (100%) rename pioneer/packages/{joy-utils-old => joy-utils}/src/types/workingGroups.ts (100%) delete mode 100644 pioneer/packages/old-apps/apps-routing/src/joy-proposals.ts diff --git a/pioneer/.eslintignore b/pioneer/.eslintignore index 57bb4f9e3e..6abdb1d141 100644 --- a/pioneer/.eslintignore +++ b/pioneer/.eslintignore @@ -5,7 +5,6 @@ packages/old-apps/* packages/joy-forum/* packages/joy-help/* packages/joy-media/* -packages/joy-proposals/* packages/joy-roles/* packages/joy-settings/* packages/joy-utils-old/* diff --git a/pioneer/packages/apps-routing/src/index.ts b/pioneer/packages/apps-routing/src/index.ts index 36f9671d31..597d45b1a3 100644 --- a/pioneer/packages/apps-routing/src/index.ts +++ b/pioneer/packages/apps-routing/src/index.ts @@ -21,12 +21,14 @@ import transfer from './transfer'; import members from './joy-members'; import { terms, privacyPolicy } from './joy-pages'; import election from './joy-election'; +import proposals from './joy-proposals'; export default function create (t: (key: string, text: string, options: { ns: string }) => T): Routes { return appSettings.uiMode === 'light' ? [ members(t), election(t), + proposals(t), null, transfer(t), accounts(t), @@ -35,6 +37,7 @@ export default function create (t: (key: string, text: string, opti : [ members(t), election(t), + proposals(t), null, transfer(t), accounts(t), diff --git a/pioneer/packages/apps-routing/src/joy-proposals.ts b/pioneer/packages/apps-routing/src/joy-proposals.ts new file mode 100644 index 0000000000..0399968997 --- /dev/null +++ b/pioneer/packages/apps-routing/src/joy-proposals.ts @@ -0,0 +1,16 @@ +import { Route } from './types'; + +import Proposals from '@polkadot/joy-proposals/index'; + +export default function create (t: (key: string, text: string, options: { ns: string }) => T): Route { + return { + Component: Proposals, + display: { + needsApi: ['query.proposalsEngine.proposalCount'] + }, + text: t('nav.proposals', 'Proposals', { ns: 'apps-routing' }), + icon: 'tasks', + name: 'proposals', + // TODO: useCounter with active proposals count? (could be a nice addition) + }; +} diff --git a/pioneer/packages/joy-election/src/ApplyForm.tsx b/pioneer/packages/joy-election/src/ApplyForm.tsx index 5685d3371b..518d95ce51 100644 --- a/pioneer/packages/joy-election/src/ApplyForm.tsx +++ b/pioneer/packages/joy-election/src/ApplyForm.tsx @@ -51,7 +51,6 @@ class ApplyForm extends React.PureComponent {
{
{
{
NONE; } return ( - + ); } @@ -62,7 +64,7 @@ function ProposedMember (props: { memberId?: MemberId | number | null }) { return ( - { (member && !member.handle.isEmpty) ? ( + { (member && !member.isEmpty) ? ( ParsedParam[]} = { - Text: ([content]) => [ +const paramParsers: { [k in ProposalType]: (params: SpecificProposalDetails) => ParsedParam[]} = { + Text: content => [ new ParsedParam( 'Content', - , + , true ) ], @@ -111,63 +113,65 @@ const paramParsers: { [x in ProposalType]: (params: any[]) => ParsedParam[]} = { new ParsedParam('Blake2b256 hash of WASM code', hash, true), new ParsedParam('File size', filesize + ' bytes') ], - SetElectionParameters: ([params]) => [ - new ParsedParam('Announcing period', params.announcing_period + ' blocks'), - new ParsedParam('Voting period', params.voting_period + ' blocks'), - new ParsedParam('Revealing period', params.revealing_period + ' blocks'), - new ParsedParam('Council size', params.council_size + ' members'), - new ParsedParam('Candidacy limit', params.candidacy_limit + ' members'), - new ParsedParam('New term duration', params.new_term_duration + ' blocks'), + SetElectionParameters: params => [ + new ParsedParam('Announcing period', params.announcing_period.toString() + ' blocks'), + new ParsedParam('Voting period', params.voting_period.toString() + ' blocks'), + new ParsedParam('Revealing period', params.revealing_period.toString() + ' blocks'), + new ParsedParam('Council size', params.council_size.toString() + ' members'), + new ParsedParam('Candidacy limit', params.candidacy_limit.toString() + ' members'), + new ParsedParam('New term duration', params.new_term_duration.toString() + ' blocks'), new ParsedParam('Min. council stake', formatBalance(params.min_council_stake)), new ParsedParam('Min. voting stake', formatBalance(params.min_voting_stake)) ], Spending: ([amount, account]) => [ - new ParsedParam('Amount', formatBalance(amount)), - new ParsedParam('Account', ) + new ParsedParam('Amount', formatBalance(amount as Balance)), + new ParsedParam('Account', ) ], - SetLead: ([memberId, accountId]) => [ - new ParsedParam('Member', ), - new ParsedParam('Account id', ) + SetLead: params => [ + new ParsedParam('Member', ), + new ParsedParam('Account id', ) ], - SetContentWorkingGroupMintCapacity: ([capacity]) => [ + SetContentWorkingGroupMintCapacity: capacity => [ new ParsedParam('Mint capacity', formatBalance(capacity)) ], - EvictStorageProvider: ([accountId]) => [ - new ParsedParam('Storage provider account', ) + EvictStorageProvider: accountId => [ + new ParsedParam('Storage provider account', ) ], - SetValidatorCount: ([count]) => [ - new ParsedParam('Validator count', count) + SetValidatorCount: count => [ + new ParsedParam('Validator count', count.toString()) ], - SetStorageRoleParameters: ([params]) => [ + SetStorageRoleParameters: params => [ new ParsedParam('Min. stake', formatBalance(params.min_stake)), // "Min. actors": params.min_actors, - new ParsedParam('Max. actors', params.max_actors), + new ParsedParam('Max. actors', params.max_actors.toString()), new ParsedParam('Reward', formatBalance(params.reward)), - new ParsedParam('Reward period', params.reward_period + ' blocks'), + new ParsedParam('Reward period', `${params.reward_period.toString()} blocks`), // "Bonding period": params.bonding_period + " blocks", - new ParsedParam('Unbonding period', params.unbonding_period + ' blocks'), + new ParsedParam('Unbonding period', `${params.unbonding_period.toString()} blocks`), // "Min. service period": params.min_service_period + " blocks", // "Startup grace period": params.startup_grace_period + " blocks", new ParsedParam('Entry request fee', formatBalance(params.entry_request_fee)) ], - AddWorkingGroupLeaderOpening: ([{ activate_at, commitment, human_readable_text, working_group }]) => { - const workingGroup = new WorkingGroup(working_group); - const activateAt = new ActivateOpeningAt(activate_at); - const activateAtBlock = activateAt.type === ActivateOpeningAtKeys.ExactBlock ? activateAt.value : null; - const OPCommitment = new WorkingGroupOpeningPolicyCommitment(commitment); + AddWorkingGroupLeaderOpening: ({ + activate_at: activateAt, + commitment, + human_readable_text: humanReadableText, + working_group: workingGroup + }) => { + const activateAtBlock = activateAt.isOfType('ExactBlock') ? activateAt.asType('ExactBlock') : null; const { application_staking_policy: applicationSP, role_staking_policy: roleSP, application_rationing_policy: rationingPolicy - } = OPCommitment; - let HRT = bytesToString(new Bytes(human_readable_text)); + } = commitment; + let HRT = bytesToString(humanReadableText); try { HRT = JSON.stringify(JSON.parse(HRT), undefined, 4); } catch (e) { /* Do nothing */ } const formatStake = (stake: Option) => ( - stake.isSome ? stake.unwrap().amount_mode.type + `(${stake.unwrap().amount})` : 'NONE' + stake.isSome ? stake.unwrap().amount_mode.type + `(${stake.unwrap().amount.toString()})` : 'NONE' ); const formatPeriod = (unstakingPeriod: Option) => ( - unstakingPeriod.unwrapOr(0) + ' blocks' - ); + `${unstakingPeriod.unwrapOr(new BN(0)).toString()} blocks` + ) return [ new ParsedParam('Working group', workingGroup.type), new ParsedParam('Activate at', `${activateAt.type}${activateAtBlock ? `(${activateAtBlock.toString()})` : ''}`), @@ -177,34 +181,35 @@ const paramParsers: { [x in ProposalType]: (params: any[]) => ParsedParam[]} = { 'Max. applications', rationingPolicy.isSome ? rationingPolicy.unwrap().max_active_applicants.toNumber() : 'UNLIMITED' ), + new ParsedParam('Max. review period length', `${commitment.max_review_period_length.toString()} blocks`), new ParsedParam( 'Terminate unstaking period (role stake)', - formatPeriod(OPCommitment.terminate_role_stake_unstaking_period) + formatPeriod(commitment.terminate_role_stake_unstaking_period) ), new ParsedParam( 'Exit unstaking period (role stake)', - formatPeriod(OPCommitment.exit_role_stake_unstaking_period) + formatPeriod(commitment.exit_role_stake_unstaking_period) ), // new ParsedParam( 'Terminate unstaking period (appl. stake)', - formatPeriod(OPCommitment.terminate_application_stake_unstaking_period) + formatPeriod(commitment.terminate_application_stake_unstaking_period) ), new ParsedParam( 'Exit unstaking period (appl. stake)', - formatPeriod(OPCommitment.exit_role_application_stake_unstaking_period) + formatPeriod(commitment.exit_role_application_stake_unstaking_period) ), new ParsedParam( 'Appl. accepted unstaking period (appl. stake)', - formatPeriod(OPCommitment.fill_opening_successful_applicant_application_stake_unstaking_period) + formatPeriod(commitment.fill_opening_successful_applicant_application_stake_unstaking_period) ), new ParsedParam( 'Appl. failed unstaking period (role stake)', - formatPeriod(OPCommitment.fill_opening_failed_applicant_role_stake_unstaking_period) + formatPeriod(commitment.fill_opening_failed_applicant_role_stake_unstaking_period) ), new ParsedParam( 'Appl. failed unstaking period (appl. stake)', - formatPeriod(OPCommitment.fill_opening_failed_applicant_application_stake_unstaking_period) + formatPeriod(commitment.fill_opening_failed_applicant_application_stake_unstaking_period) ), new ParsedParam( 'Crowded out unstaking period (role stake)', @@ -227,55 +232,76 @@ const paramParsers: { [x in ProposalType]: (params: any[]) => ParsedParam[]} = { ]; }, SetWorkingGroupMintCapacity: ([capacity, group]) => [ - new ParsedParam('Working group', (new WorkingGroup(group)).type), - new ParsedParam('Mint capacity', formatBalance(capacity)) + new ParsedParam('Working group', (group as WorkingGroup).type), + new ParsedParam('Mint capacity', formatBalance((capacity as Balance))) ], BeginReviewWorkingGroupLeaderApplication: ([id, group]) => [ - new ParsedParam('Working group', (new WorkingGroup(group)).type), + new ParsedParam('Working group', (group as WorkingGroup).type), // TODO: Adjust the link to work with multiple groups after working-groups are normalized! - new ParsedParam('Opening id', #{id}) + new ParsedParam( + 'Opening id', + #{id.toString()} + ) + ], + FillWorkingGroupLeaderOpening: ({ + opening_id: openingId, + successful_application_id: succesfulApplicationId, + reward_policy: rewardPolicy, + working_group: workingGroup + }) => [ + new ParsedParam('Working group', workingGroup.type), + // TODO: Adjust the link to work with multiple groups after working-groups are normalized! + new ParsedParam( + 'Opening id', + #{openingId.toString()}), + new ParsedParam('Reward policy', rewardPolicy.isSome ? formatReward(rewardPolicy.unwrap(), true) : 'NONE'), + new ParsedParam( + 'Result', + , + true + ) ], - FillWorkingGroupLeaderOpening: ([params]) => { - const { opening_id, successful_application_id, reward_policy, working_group } = params; - const rewardPolicy = reward_policy && new RewardPolicy(reward_policy); - return [ - new ParsedParam('Working group', (new WorkingGroup(working_group)).type), - // TODO: Adjust the link to work with multiple groups after working-groups are normalized! - new ParsedParam('Opening id', #{opening_id}), - new ParsedParam('Reward policy', rewardPolicy ? formatReward(rewardPolicy, true) : 'NONE'), - new ParsedParam( - 'Result', - , - true - ) - ]; - }, SlashWorkingGroupLeaderStake: ([leadId, amount, group]) => [ - new ParsedParam('Working group', (new WorkingGroup(group)).type), - new ParsedParam('Slash amount', formatBalance(amount)), - new ParsedParam('Lead', , true) + new ParsedParam('Working group', (group as WorkingGroup).type), + new ParsedParam('Slash amount', formatBalance(amount as Balance)), + new ParsedParam( + 'Lead', + , + true + ) ], DecreaseWorkingGroupLeaderStake: ([leadId, amount, group]) => [ - new ParsedParam('Working group', (new WorkingGroup(group)).type), - new ParsedParam('Decrease amount', formatBalance(amount)), - new ParsedParam('Lead', , true) + new ParsedParam('Working group', (group as WorkingGroup).type), + new ParsedParam('Decrease amount', formatBalance(amount as Balance)), + new ParsedParam( + 'Lead', + , + true + ) ], SetWorkingGroupLeaderReward: ([leadId, amount, group]) => [ - new ParsedParam('Working group', (new WorkingGroup(group)).type), - new ParsedParam('New reward amount', formatBalance(amount)), - new ParsedParam('Lead', , true) + new ParsedParam('Working group', (group as WorkingGroup).type), + new ParsedParam('New reward amount', formatBalance(amount as Balance)), + new ParsedParam( + 'Lead', + , + true + ) ], - TerminateWorkingGroupLeaderRole: ([params]) => { - const paramsObj = new TerminateRoleParameters(params); - const { working_group: workingGroup, rationale, worker_id: leadId, slash } = paramsObj; + TerminateWorkingGroupLeaderRole: ({ + working_group: workingGroup, + rationale, + worker_id: leadId, + slash + }) => { return [ new ParsedParam('Working group', workingGroup.type), new ParsedParam('Rationale', bytesToString(rationale), true), new ParsedParam('Slash stake', slash.isTrue ? 'YES' : 'NO'), - new ParsedParam('Lead', , true) + new ParsedParam('Lead', , true) ]; } }; @@ -330,15 +356,20 @@ export default function Body ({ type, title, description, - params = [], + params, iAmProposer, proposalId, proposerId, isCancellable, cancellationFee }: BodyProps) { - const parseParams = paramParsers[type]; - const parsedParams = parseParams(params); + // Assert more generic type (since TypeScript cannot possibly know the value of "type" here yet) + const parseParams = paramParsers[type] as (params: SpecificProposalDetails) => ParsedParam[]; + const parsedParams = parseParams( + type === 'RuntimeUpgrade' + ? params as RuntimeUpgradeProposalDetails + : (params as ProposalDetails).asType(type) + ); return ( @@ -368,17 +399,17 @@ export default function Body ({ The cancellation fee for this type of proposal is:  { cancellationFee ? formatBalance(cancellationFee) : 'NONE' }

- - { sendTx(); } } - className={'icon left labeled'} - > - - Withdraw proposal - - + { sendTx(); } } + icon + color={ 'red' } + labelPosition={ 'left' } + > + + Withdraw proposal + ) } diff --git a/pioneer/packages/joy-proposals/src/Proposal/ChooseProposalType.tsx b/pioneer/packages/joy-proposals/src/Proposal/ChooseProposalType.tsx index fbd8194ab6..a207d37153 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/ChooseProposalType.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/ChooseProposalType.tsx @@ -4,7 +4,7 @@ import { Item, Dropdown } from 'semantic-ui-react'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; import { Categories } from '@polkadot/joy-utils/types/proposals'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import './ChooseProposalType.css'; import { RouteComponentProps } from 'react-router-dom'; diff --git a/pioneer/packages/joy-proposals/src/Proposal/Details.tsx b/pioneer/packages/joy-proposals/src/Proposal/Details.tsx index 3289f0037b..4e0ce73193 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/Details.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/Details.tsx @@ -5,7 +5,7 @@ import { metadata as proposalConsts } from '@polkadot/joy-utils/consts/proposals import { ExtendedProposalStatus } from './ProposalDetails'; import styled from 'styled-components'; -import ProfilePreview from '@polkadot/joy-utils/MemberProfilePreview'; +import ProfilePreview from '@polkadot/joy-utils/react/components/MemberProfilePreview'; const DetailsContainer = styled(Item.Group)` display: grid; diff --git a/pioneer/packages/joy-proposals/src/Proposal/ProposalDetails.tsx b/pioneer/packages/joy-proposals/src/Proposal/ProposalDetails.tsx index f3f85b5fe7..cd15d109e7 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/ProposalDetails.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/ProposalDetails.tsx @@ -4,17 +4,15 @@ import Details from './Details'; import Body from './Body'; import VotingSection from './VotingSection'; import Votes from './Votes'; -import { MyAccountProps, withMyAccount } from '@polkadot/joy-utils/MyAccount'; +import { MyAccountProps, withMyAccount } from '@polkadot/joy-utils/react/hocs/accounts'; import { ParsedProposal, ProposalVotes } from '@polkadot/joy-utils/types/proposals'; import { withCalls } from '@polkadot/react-api'; -import { withMulti } from '@polkadot/react-api/with'; - -import './Proposal.css'; +import { withMulti } from '@polkadot/react-api/hoc'; import { ProposalId, ProposalDecisionStatuses, ApprovedProposalStatuses, ExecutionFailedStatus } from '@joystream/types/proposals'; import { BlockNumber } from '@polkadot/types/interfaces'; import { MemberId } from '@joystream/types/members'; import { Seat } from '@joystream/types/council'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import ProposalDiscussion from './discussion/ProposalDiscussion'; import styled from 'styled-components'; diff --git a/pioneer/packages/joy-proposals/src/Proposal/ProposalFromId.tsx b/pioneer/packages/joy-proposals/src/Proposal/ProposalFromId.tsx index 9750685060..dfab2be622 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/ProposalFromId.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/ProposalFromId.tsx @@ -2,8 +2,8 @@ import React from 'react'; import { RouteComponentProps } from 'react-router-dom'; import ProposalDetails from './ProposalDetails'; import { useProposalSubscription } from '@polkadot/joy-utils/react/hooks'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; -import { ProposalId } from '@joystream/types/proposals'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; +import { useApi } from '@polkadot/react-hooks'; export default function ProposalFromId (props: RouteComponentProps) { const { @@ -11,8 +11,9 @@ export default function ProposalFromId (props: RouteComponentProps) { params: { id } } } = props; + const { api } = useApi(); - const { proposal: proposalState, votes: votesState } = useProposalSubscription(new ProposalId(id)); + const { proposal: proposalState, votes: votesState } = useProposalSubscription(api.createType('ProposalId', id)); return ( { `#${proposal.id.toString()}` } diff --git a/pioneer/packages/joy-proposals/src/Proposal/ProposalPreviewList.tsx b/pioneer/packages/joy-proposals/src/Proposal/ProposalPreviewList.tsx index 22df3b8803..ad031539db 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/ProposalPreviewList.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/ProposalPreviewList.tsx @@ -6,7 +6,7 @@ import { Link, useLocation } from 'react-router-dom'; import ProposalPreview from './ProposalPreview'; import { ParsedProposal, proposalStatusFilters, ProposalStatusFilter, ProposalsBatch } from '@polkadot/joy-utils/types/proposals'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import { withCalls } from '@polkadot/react-api'; import { BlockNumber } from '@polkadot/types/interfaces'; import { Dropdown } from '@polkadot/react-components'; diff --git a/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx b/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx index 576e10e1c9..dbe2815d8c 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx @@ -4,7 +4,7 @@ import useVoteStyles from './useVoteStyles'; import { ProposalVotes } from '@polkadot/joy-utils/types/proposals'; import { VoteKind } from '@joystream/types/proposals'; import { VoteKindStr } from './VotingSection'; -import ProfilePreview from '@polkadot/joy-utils/MemberProfilePreview'; +import ProfilePreview from '@polkadot/joy-utils/react/components/MemberProfilePreview'; type VotesProps = { votes: ProposalVotes; diff --git a/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx b/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx index 7e10d4b1fb..086dcd5d53 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx @@ -1,8 +1,8 @@ import React, { useState } from 'react'; -import { Icon, Button, Message, Divider, Header } from 'semantic-ui-react'; +import { Icon, Message, Divider, Header } from 'semantic-ui-react'; import useVoteStyles from './useVoteStyles'; -import TxButton from '@polkadot/joy-utils/TxButton'; +import { SemanticTxButton } from '@polkadot/joy-utils/react/components/TxButton'; import { MemberId } from '@joystream/types/members'; import { ProposalId, VoteKind, VoteKinds } from '@joystream/types/proposals'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; @@ -35,24 +35,23 @@ type VoteButtonProps = { function VoteButton ({ voteKind, proposalId, memberId, onSuccess }: VoteButtonProps) { const { icon, color } = useVoteStyles(voteKind); return ( - // Button.Group "cheat" to force TxButton color - - sendTx() } - txFailedCb={ () => null } - txSuccessCb={ onSuccess } - className={'icon left labeled'}> - - { voteKind } - - + sendTx() } + txFailedCb={ () => null } + txSuccessCb={ onSuccess } + color={color} + style={{ marginRight: '5px' }} + icon + labelPosition={ 'left' }> + + { voteKind } + ); } diff --git a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx index 40d3125e22..4869c5dac0 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx @@ -1,7 +1,7 @@ import React, { useState } from 'react'; import { Button, Icon } from 'semantic-ui-react'; import { ParsedPost } from '@polkadot/joy-utils/types/proposals'; -import MemberProfilePreview from '@polkadot/joy-utils/MemberProfilePreview'; +import MemberProfilePreview from '@polkadot/joy-utils/react/components/MemberProfilePreview'; import DiscussionPostForm from './DiscussionPostForm'; import { MemberId } from '@joystream/types/members'; import { useTransport } from '@polkadot/joy-utils/react/hooks'; diff --git a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx index 5b7ff204fd..c19a25a4ee 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx @@ -2,8 +2,8 @@ import React from 'react'; import { Form, Field, withFormik, FormikProps } from 'formik'; import * as Yup from 'yup'; -import TxButton from '@polkadot/joy-utils/TxButton'; -import * as JoyForms from '@polkadot/joy-utils/forms'; +import TxButton from '@polkadot/joy-utils/react/components/TxButton'; +import * as JoyForms from '@polkadot/joy-utils/react/components/forms'; import { SubmittableResult } from '@polkadot/api'; import { Button } from 'semantic-ui-react'; import { TxFailedCallback, TxCallback } from '@polkadot/react-components/Status/types'; @@ -89,7 +89,6 @@ const DiscussionPostFormInner = (props: InnerProps) => { ({ ...genericFormDefaultOptions.validationSchema, ...Validation.AddWorkingGroupLeaderOpening( props.currentBlock?.toNumber() || 0, - props.HRTConstraint || InputValidationLengthConstraint.createWithMaxAllowed() + props.HRTConstraint ) }), handleSubmit: genericFormDefaultOptions.handleSubmit, diff --git a/pioneer/packages/joy-proposals/src/forms/BeginReviewLeaderApplicationsForm.tsx b/pioneer/packages/joy-proposals/src/forms/BeginReviewLeaderApplicationsForm.tsx index 22431c13a1..2e2b30b2fc 100644 --- a/pioneer/packages/joy-proposals/src/forms/BeginReviewLeaderApplicationsForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/BeginReviewLeaderApplicationsForm.tsx @@ -14,13 +14,12 @@ import { } from './GenericWorkingGroupProposalForm'; import FormField from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import { Dropdown, Message } from 'semantic-ui-react'; import _ from 'lodash'; import Validation from '../validationSchema'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; import { OpeningData } from '@polkadot/joy-utils/types/workingGroups'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import { getFormErrorLabelsProps } from './errorHandling'; export type FormValues = WGFormValues & { diff --git a/pioneer/packages/joy-proposals/src/forms/DecreaseWorkingGroupLeadStakeForm.tsx b/pioneer/packages/joy-proposals/src/forms/DecreaseWorkingGroupLeadStakeForm.tsx index 735a57275f..7809b1c37b 100644 --- a/pioneer/packages/joy-proposals/src/forms/DecreaseWorkingGroupLeadStakeForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/DecreaseWorkingGroupLeadStakeForm.tsx @@ -15,7 +15,6 @@ import { } from './GenericWorkingGroupProposalForm'; import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import { Grid } from 'semantic-ui-react'; import { formatBalance } from '@polkadot/util'; import _ from 'lodash'; diff --git a/pioneer/packages/joy-proposals/src/forms/FillWorkingGroupLeaderOpeningForm.tsx b/pioneer/packages/joy-proposals/src/forms/FillWorkingGroupLeaderOpeningForm.tsx index 527ace5488..38b8bb5800 100644 --- a/pioneer/packages/joy-proposals/src/forms/FillWorkingGroupLeaderOpeningForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/FillWorkingGroupLeaderOpeningForm.tsx @@ -14,24 +14,19 @@ import { } from './GenericWorkingGroupProposalForm'; import { FormField, RewardPolicyFields } from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import { Dropdown, DropdownItemProps, Header, Checkbox, Message } from 'semantic-ui-react'; import _ from 'lodash'; import Validation from '../validationSchema'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; import { OpeningData, ParsedApplication } from '@polkadot/joy-utils/types/workingGroups'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import { formatBalance } from '@polkadot/util'; import { withCalls } from '@polkadot/react-api'; -import { Option } from '@polkadot/types'; import { BlockNumber } from '@polkadot/types/interfaces'; -import { u32 as U32, u128 as U128 } from '@polkadot/types/primitive'; import { getFormErrorLabelsProps } from './errorHandling'; -import { RewardPolicy } from '@joystream/types/working-group'; -import { FillOpeningParameters } from '@joystream/types/proposals'; -import { WorkingGroup } from '@joystream/types/common'; -import { OpeningId, ApplicationId } from '@joystream/types/hiring'; import { ApplicationsDetails } from '@polkadot/joy-utils/react/components/working-groups/ApplicationDetails'; +import { SimplifiedTypeInterface } from '@polkadot/joy-utils/types/common'; +import { IFillOpeningParameters } from '@joystream/types/src/proposals'; export type FormValues = WGFormValues & { openingId: string; @@ -61,23 +56,20 @@ type FormContainerProps = ProposalFormContainerProps & { }; type FormInnerProps = ProposalFormInnerProps; -const valuesToFillOpeningParams = (values: FormValues): FillOpeningParameters => ( - new FillOpeningParameters({ - working_group: new WorkingGroup(values.workingGroup), - successful_application_id: new ApplicationId(values.successfulApplicant), - opening_id: new OpeningId(values.openingId), - reward_policy: new (Option.with(RewardPolicy))( +const valuesToFillOpeningParams = (values: FormValues): SimplifiedTypeInterface => ( + { + working_group: values.workingGroup, + successful_application_id: values.successfulApplicant, + opening_id: values.openingId, + reward_policy: values.includeReward - ? new RewardPolicy({ - amount_per_payout: new U128(values.rewardAmount), - next_payment_at_block: new U32(values.rewardNextBlock), - payout_interval: new (Option.with('BlockNumber'))( - values.rewardRecurring ? values.rewardInterval : null - ) as Option - }) - : null - ) as Option - }) + ? { + amount_per_payout: values.rewardAmount, + next_payment_at_block: values.rewardNextBlock, + payout_interval: values.rewardRecurring ? values.rewardInterval : undefined + } + : undefined + } ); const FillWorkingGroupLeaderOpeningForm: React.FunctionComponent = props => { diff --git a/pioneer/packages/joy-proposals/src/forms/GenericProposalForm.tsx b/pioneer/packages/joy-proposals/src/forms/GenericProposalForm.tsx index 3c0aca1c8a..f5f86a4557 100644 --- a/pioneer/packages/joy-proposals/src/forms/GenericProposalForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/GenericProposalForm.tsx @@ -4,11 +4,12 @@ import { Form, Icon, Button, Message } from 'semantic-ui-react'; import { getFormErrorLabelsProps } from './errorHandling'; import Validation from '../validationSchema'; import { InputFormField, TextareaFormField } from './FormFields'; -import TxButton from '@polkadot/joy-utils/TxButton'; +import TxButton from '@polkadot/joy-utils/react/components/TxButton'; import { SubmittableResult } from '@polkadot/api'; import { TxFailedCallback, TxCallback } from '@polkadot/react-components/Status/types'; -import { MyAccountProps, withOnlyMembers } from '@polkadot/joy-utils/MyAccount'; -import { withMulti } from '@polkadot/react-api/with'; +import { MyAccountProps } from '@polkadot/joy-utils/react/hocs/accounts'; +import { withOnlyMembers } from '@polkadot/joy-utils/react/hocs/guards'; +import { withMulti } from '@polkadot/react-api/hoc'; import { withCalls } from '@polkadot/react-api'; import { CallProps } from '@polkadot/react-api/types'; import { Balance, Event } from '@polkadot/types/interfaces'; @@ -16,8 +17,8 @@ import { RouteComponentProps } from 'react-router'; import { ProposalType } from '@polkadot/joy-utils/types/proposals'; import proposalsConsts from '@polkadot/joy-utils/consts/proposals'; import { formatBalance } from '@polkadot/util'; -import './forms.css'; import { ProposalId } from '@joystream/types/proposals'; +import styled from 'styled-components'; // Generic form values export type GenericFormValues = { @@ -74,6 +75,33 @@ export const genericFormDefaultOptions: GenericFormDefaultOptions = { } }; +const StyledGenericProposalForm = styled.div` + .proposal-form { + margin: 0 auto; + } + + .ui.form.proposal-form { + & label { + font-size: 1rem; + } + + & input[name="tokens"] { + max-width: 16rem; + } + } + + .form-buttons { + display: flex; + button { + margin-right: 0.5em; + } + } + + .ui.dropdown .ui.avatar.image { + width: 2em !important; + } +`; + // Generic proposal form with basic structure, "Title" and "Rationale" fields // Other fields can be passed as children export const GenericProposalForm: React.FunctionComponent = props => { @@ -162,7 +190,7 @@ export const GenericProposalForm: React.FunctionComponent proposalsConsts[proposalType].stake; return ( -
+
(p === '{STAKE}' ? requiredStake : p))} tx={`proposalsCodex.${txMethod}`} @@ -220,7 +247,7 @@ export const GenericProposalForm: React.FunctionComponent
-
+ ); }; diff --git a/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx b/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx index 4c228e15dd..3da45c7bb3 100644 --- a/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx @@ -11,10 +11,9 @@ import { import { FormField } from './FormFields'; import { ProposalType } from '@polkadot/joy-utils/types/proposals'; import { WorkingGroupKey, WorkingGroupDef } from '@joystream/types/common'; -import './forms.css'; import { Dropdown, Message } from 'semantic-ui-react'; import { usePromise, useTransport } from '@polkadot/joy-utils/react/hooks'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import { WorkerData } from '@polkadot/joy-utils/types/workingGroups'; import { LeadInfo } from '@polkadot/joy-utils/react/components/working-groups/LeadInfo'; @@ -70,7 +69,7 @@ export const GenericWorkingGroupProposalForm: React.FunctionComponent(errors, touched); return ( diff --git a/pioneer/packages/joy-proposals/src/forms/MintCapacityForm.tsx b/pioneer/packages/joy-proposals/src/forms/MintCapacityForm.tsx index 8c6c0296cc..25edcc8e5d 100644 --- a/pioneer/packages/joy-proposals/src/forms/MintCapacityForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/MintCapacityForm.tsx @@ -16,7 +16,6 @@ import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; import { ProposalType } from '@polkadot/joy-utils/types/proposals'; import { formatBalance } from '@polkadot/util'; -import './forms.css'; export type FormValues = GenericFormValues & { capacity: string; diff --git a/pioneer/packages/joy-proposals/src/forms/RuntimeUpgradeForm.tsx b/pioneer/packages/joy-proposals/src/forms/RuntimeUpgradeForm.tsx index ea16a093b7..9ed2ab19c0 100644 --- a/pioneer/packages/joy-proposals/src/forms/RuntimeUpgradeForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/RuntimeUpgradeForm.tsx @@ -13,7 +13,6 @@ import { } from './GenericProposalForm'; import Validation from '../validationSchema'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import FileDropdown from './FileDropdown'; export type FormValues = GenericFormValues & { diff --git a/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupLeadForm.tsx b/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupLeadForm.tsx index 17bb481874..7144166729 100644 --- a/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupLeadForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupLeadForm.tsx @@ -17,9 +17,8 @@ import { FormField } from './FormFields'; import { withFormContainer } from './FormContainer'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; import { Membership } from '@joystream/types/members'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; import _ from 'lodash'; -import './forms.css'; export type FormValues = GenericFormValues & { workingGroupLead: any; diff --git a/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupMintCapForm.tsx b/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupMintCapForm.tsx index be7f149cb1..a48d6a5676 100644 --- a/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupMintCapForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupMintCapForm.tsx @@ -2,7 +2,7 @@ import React from 'react'; import MintCapacityForm from './MintCapacityForm'; import { RouteComponentProps } from 'react-router'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; const ContentWorkingGroupMintCapForm = (props: RouteComponentProps) => { const transport = useTransport(); diff --git a/pioneer/packages/joy-proposals/src/forms/SetCouncilParamsForm.tsx b/pioneer/packages/joy-proposals/src/forms/SetCouncilParamsForm.tsx index 1cafa3f9c8..6f1a94313a 100644 --- a/pioneer/packages/joy-proposals/src/forms/SetCouncilParamsForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SetCouncilParamsForm.tsx @@ -15,12 +15,11 @@ import { import Validation from '../validationSchema'; import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; -import { createType } from '@polkadot/types'; -import './forms.css'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; import _ from 'lodash'; -import { ElectionParameters } from '@joystream/types/council'; -import { PromiseComponent } from '@polkadot/joy-utils/react/components'; +import PromiseComponent from '@polkadot/joy-utils/react/components/PromiseComponent'; +import { IElectionParameters } from '@joystream/types/src/council'; +import { SimplifiedTypeInterface } from '@polkadot/joy-utils/types/common'; export type FormValues = GenericFormValues & { announcingPeriod: string; @@ -50,17 +49,17 @@ type ExportComponentProps = ProposalFormExportProps; type FormInnerProps = ProposalFormInnerProps; -function createElectionParameters (values: FormValues): ElectionParameters { - return new ElectionParameters({ - announcing_period: createType('BlockNumber', parseInt(values.announcingPeriod)), - voting_period: createType('BlockNumber', parseInt(values.votingPeriod)), - revealing_period: createType('BlockNumber', parseInt(values.revealingPeriod)), - council_size: createType('u32', values.councilSize), - candidacy_limit: createType('u32', values.candidacyLimit), - new_term_duration: createType('BlockNumber', parseInt(values.newTermDuration)), - min_council_stake: createType('Balance', values.minCouncilStake), - min_voting_stake: createType('Balance', values.minVotingStake) - }); +function createElectionParameters (values: FormValues): SimplifiedTypeInterface { + return { + announcing_period: parseInt(values.announcingPeriod), + voting_period: parseInt(values.votingPeriod), + revealing_period: parseInt(values.revealingPeriod), + council_size: values.councilSize, + candidacy_limit: values.candidacyLimit, + new_term_duration: parseInt(values.newTermDuration), + min_council_stake: values.minCouncilStake, + min_voting_stake: values.minVotingStake + }; } const SetCouncilParamsForm: React.FunctionComponent = props => { @@ -69,7 +68,7 @@ const SetCouncilParamsForm: React.FunctionComponent = props => { const [placeholders, setPlaceholders] = useState<{ [k in keyof FormValues]: string }>(defaultValues); const transport = useTransport(); - const [councilParams, error, loading] = usePromise(() => transport.council.electionParameters(), null); + const [councilParams, error, loading] = usePromise(() => transport.council.electionParameters(), null); useEffect(() => { if (councilParams) { const fetchedPlaceholders = { ...placeholders }; diff --git a/pioneer/packages/joy-proposals/src/forms/SetMaxValidatorCountForm.tsx b/pioneer/packages/joy-proposals/src/forms/SetMaxValidatorCountForm.tsx index e274d2dff6..f32031b705 100644 --- a/pioneer/packages/joy-proposals/src/forms/SetMaxValidatorCountForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SetMaxValidatorCountForm.tsx @@ -15,7 +15,6 @@ import Validation from '../validationSchema'; import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks'; -import './forms.css'; export type FormValues = GenericFormValues & { maxValidatorCount: string; diff --git a/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupLeadRewardForm.tsx b/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupLeadRewardForm.tsx index 39f15b2a13..528692ed1f 100644 --- a/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupLeadRewardForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupLeadRewardForm.tsx @@ -15,7 +15,6 @@ import { } from './GenericWorkingGroupProposalForm'; import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import { Grid } from 'semantic-ui-react'; import { formatBalance } from '@polkadot/util'; import _ from 'lodash'; diff --git a/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupMintCapacityForm.tsx b/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupMintCapacityForm.tsx index a53006273f..9b4513383a 100644 --- a/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupMintCapacityForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SetWorkingGroupMintCapacityForm.tsx @@ -15,7 +15,6 @@ import { } from './GenericWorkingGroupProposalForm'; import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import { Grid } from 'semantic-ui-react'; import { formatBalance } from '@polkadot/util'; import _ from 'lodash'; diff --git a/pioneer/packages/joy-proposals/src/forms/SignalForm.tsx b/pioneer/packages/joy-proposals/src/forms/SignalForm.tsx index 1163346db8..b0c722febe 100644 --- a/pioneer/packages/joy-proposals/src/forms/SignalForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SignalForm.tsx @@ -14,7 +14,6 @@ import { import Validation from '../validationSchema'; import { TextareaFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; export type FormValues = GenericFormValues & { description: string; diff --git a/pioneer/packages/joy-proposals/src/forms/SlashWorkingGroupLeadStakeForm.tsx b/pioneer/packages/joy-proposals/src/forms/SlashWorkingGroupLeadStakeForm.tsx index c9e4692a62..ceaaf76375 100644 --- a/pioneer/packages/joy-proposals/src/forms/SlashWorkingGroupLeadStakeForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SlashWorkingGroupLeadStakeForm.tsx @@ -15,7 +15,6 @@ import { } from './GenericWorkingGroupProposalForm'; import { InputFormField } from './FormFields'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import { Grid } from 'semantic-ui-react'; import { formatBalance } from '@polkadot/util'; import _ from 'lodash'; diff --git a/pioneer/packages/joy-proposals/src/forms/SpendingProposalForm.tsx b/pioneer/packages/joy-proposals/src/forms/SpendingProposalForm.tsx index 125e2535d9..298af09cb1 100644 --- a/pioneer/packages/joy-proposals/src/forms/SpendingProposalForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/SpendingProposalForm.tsx @@ -17,7 +17,6 @@ import { InputFormField, FormField } from './FormFields'; import { withFormContainer } from './FormContainer'; import { InputAddress } from '@polkadot/react-components/index'; import { formatBalance } from '@polkadot/util'; -import './forms.css'; export type FormValues = GenericFormValues & { destinationAccount: any; diff --git a/pioneer/packages/joy-proposals/src/forms/TerminateWorkingGroupLeaderForm.tsx b/pioneer/packages/joy-proposals/src/forms/TerminateWorkingGroupLeaderForm.tsx index c44b225042..2fd5020364 100644 --- a/pioneer/packages/joy-proposals/src/forms/TerminateWorkingGroupLeaderForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/TerminateWorkingGroupLeaderForm.tsx @@ -13,20 +13,17 @@ import { defaultValues as wgFromDefaultValues } from './GenericWorkingGroupProposalForm'; import { withFormContainer } from './FormContainer'; -import './forms.css'; import _ from 'lodash'; import Validation from '../validationSchema'; import { WorkerData } from '@polkadot/joy-utils/types/workingGroups'; import { getFormErrorLabelsProps } from './errorHandling'; import FormField, { TextareaFormField } from './FormFields'; import { Checkbox } from 'semantic-ui-react'; -import { TerminateRoleParameters } from '@joystream/types/proposals'; -import { WorkerId } from '@joystream/types/working-group'; -import { Bytes } from '@polkadot/types'; -import { WorkingGroup, InputValidationLengthConstraint } from '@joystream/types/common'; -import { bool as Bool } from '@polkadot/types/primitive'; +import { InputValidationLengthConstraint } from '@joystream/types/common'; import { withCalls } from '@polkadot/react-api'; import { formatBalance } from '@polkadot/util'; +import { SimplifiedTypeInterface } from '@polkadot/joy-utils/types/common'; +import { ITerminateRoleParameters } from '@joystream/types/src/proposals'; export type FormValues = WGFormValues & { terminationRationale: string; @@ -46,13 +43,13 @@ type FormContainerProps = ProposalFormContainerProps & { }; type FormInnerProps = ProposalFormInnerProps; -const valuesToTerminateRoleParams = (values: FormValues, lead: WorkerData): TerminateRoleParameters => { - return new TerminateRoleParameters({ - worker_id: new WorkerId(lead.workerId), - rationale: new Bytes(values.terminationRationale), - slash: lead.stake ? new Bool(values.slashStake) : new Bool(false), - working_group: new WorkingGroup(values.workingGroup) - }); +const valuesToTerminateRoleParams = (values: FormValues, lead: WorkerData): SimplifiedTypeInterface => { + return { + worker_id: lead.workerId, + rationale: values.terminationRationale, + slash: lead.stake ? values.slashStake : false, + working_group: values.workingGroup + }; }; const TerminateWorkingGroupLeaderForm: React.FunctionComponent = props => { @@ -111,7 +108,7 @@ const FormContainer = withFormContainer({ validationSchema: (props: FormContainerProps) => Yup.object().shape({ ...genericFormDefaultOptions.validationSchema, ...Validation.TerminateWorkingGroupLeaderRole( - props.terminationRationaleConstraint || InputValidationLengthConstraint.createWithMaxAllowed() + props.terminationRationaleConstraint ) }), handleSubmit: genericFormDefaultOptions.handleSubmit, diff --git a/pioneer/packages/joy-proposals/src/forms/forms.css b/pioneer/packages/joy-proposals/src/forms/forms.css deleted file mode 100644 index d800c9c497..0000000000 --- a/pioneer/packages/joy-proposals/src/forms/forms.css +++ /dev/null @@ -1,23 +0,0 @@ -.Forms { - .proposal-form { - margin: 0 auto; - } - - .ui.form.proposal-form { - & label { - font-size: 1rem; - } - - & input[name="tokens"] { - max-width: 16rem; - } - } - - .form-buttons { - display: flex; - } - - .ui.dropdown .ui.avatar.image { - width: 2em !important; - } -} diff --git a/pioneer/packages/joy-proposals/src/index.css b/pioneer/packages/joy-proposals/src/index.css deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/pioneer/packages/joy-proposals/src/index.tsx b/pioneer/packages/joy-proposals/src/index.tsx index ffa06eae0a..ec3cd611ad 100644 --- a/pioneer/packages/joy-proposals/src/index.tsx +++ b/pioneer/packages/joy-proposals/src/index.tsx @@ -4,13 +4,10 @@ import { Link } from 'react-router-dom'; import styled from 'styled-components'; import { Breadcrumb } from 'semantic-ui-react'; -import { AppProps, I18nProps } from '@polkadot/react-components/types'; -import { TransportProvider } from '@polkadot/joy-utils/react/context'; +import { I18nProps } from '@polkadot/react-components/types'; import { ProposalPreviewList, ProposalFromId, ChooseProposalType } from './Proposal'; import _ from 'lodash'; -import './index.css'; - import translate from './translate'; import NotDone from './NotDone'; import { @@ -30,8 +27,12 @@ import { SetWorkingGroupLeadRewardForm, TerminateWorkingGroupLeaderForm } from './forms'; +import { RouteProps as AppMainRouteProps } from '@polkadot/apps-routing/types'; +import style from './style'; + +const ProposalsMain = styled.main`${style}`; -interface Props extends AppProps, I18nProps {} +interface Props extends AppMainRouteProps, I18nProps {} const StyledHeader = styled.header` text-align: left; @@ -46,59 +47,57 @@ function App (props: Props): React.ReactElement { const { basePath } = props; return ( - -
- - - - ( - <> - Proposals - - New proposal - - {_.startCase(props.match.params.type)} - - )} /> - + + + + + ( + <> Proposals - New proposal - - - Proposals - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
+ New proposal + + {_.startCase(props.match.params.type)} + + )} /> + + Proposals + + New proposal + + + Proposals + + + + + + + + + + + + + + + + + + + + + + + + + + + ); } diff --git a/pioneer/packages/joy-proposals/src/stories/data/ProposalDetails.mock.ts b/pioneer/packages/joy-proposals/src/stories/data/ProposalDetails.mock.ts index 474db8c862..e985cc160e 100644 --- a/pioneer/packages/joy-proposals/src/stories/data/ProposalDetails.mock.ts +++ b/pioneer/packages/joy-proposals/src/stories/data/ProposalDetails.mock.ts @@ -1,13 +1,13 @@ import { ParsedProposal } from '@polkadot/joy-utils/types/proposals'; -import { ProposalId } from '@joystream/types/proposals'; +import { createMock } from '@joystream/types'; const mockedProposal: ParsedProposal = { - id: new ProposalId(100), + id: createMock('ProposalId', 100), title: 'Awesome Proposal', description: 'Please send me some tokens for coffee', createdAtBlock: 36, type: 'Text', - details: ['Ciao'], + details: createMock('ProposalDetails', { Text: 'Ciao' }), parameters: { approvalQuorumPercentage: 66, approvalThresholdPercentage: 80, diff --git a/pioneer/packages/joy-proposals/src/Proposal/Proposal.css b/pioneer/packages/joy-proposals/src/style.ts similarity index 80% rename from pioneer/packages/joy-proposals/src/Proposal/Proposal.css rename to pioneer/packages/joy-proposals/src/style.ts index d3dd08ab20..3802a35c76 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/Proposal.css +++ b/pioneer/packages/joy-proposals/src/style.ts @@ -1,7 +1,7 @@ -.Proposal { - position: relative; +import { css } from 'styled-components'; - .description { +export default css` + .ui.card .description { word-wrap: break-word; word-break: break-word; } @@ -26,4 +26,4 @@ .ui.tabular.list-menu { margin-bottom: 2rem; } -} +`; diff --git a/pioneer/packages/joy-proposals/src/validationSchema.ts b/pioneer/packages/joy-proposals/src/validationSchema.ts index 7b3c68c28c..0507461755 100644 --- a/pioneer/packages/joy-proposals/src/validationSchema.ts +++ b/pioneer/packages/joy-proposals/src/validationSchema.ts @@ -152,9 +152,9 @@ type FormValuesByType = never; type ValidationSchemaFuncParamsByType = - T extends 'AddWorkingGroupLeaderOpening' ? [number, InputValidationLengthConstraint] : + T extends 'AddWorkingGroupLeaderOpening' ? [number, InputValidationLengthConstraint | undefined] : T extends 'FillWorkingGroupLeaderOpening' ? [number] : - T extends 'TerminateWorkingGroupLeaderRole' ? [InputValidationLengthConstraint] : + T extends 'TerminateWorkingGroupLeaderRole' ? [InputValidationLengthConstraint | undefined] : []; /* eslint-enable @typescript-eslint/indent */ @@ -178,6 +178,23 @@ function minMaxInt (min: number, max: number, fieldName: string) { .max(max, errorMessage(fieldName, min, max)); } +function minMaxStrFromConstraint(constraint: InputValidationLengthConstraint | undefined, fieldName: string) { + const schema = Yup.string().required(`${fieldName} is required!`); + return constraint + ? ( + schema + .min( + constraint.min.toNumber(), + `${fieldName} must be at least ${constraint.min.toNumber()} character(s) long` + ) + .max( + constraint.max.toNumber(), + `${fieldName} cannot be more than ${constraint.max.toNumber()} character(s) long` + ) + ) + : schema; +} + const Validation: ValidationType = { All: () => ({ title: Yup.string() @@ -303,7 +320,7 @@ const Validation: ValidationType = { errorMessage('The max validator count', MAX_VALIDATOR_COUNT_MIN, MAX_VALIDATOR_COUNT_MAX) ) }), - AddWorkingGroupLeaderOpening: (currentBlock: number, { min: HRTMin, max: HRTMax }: InputValidationLengthConstraint) => ({ + AddWorkingGroupLeaderOpening: (currentBlock: number, HRTConstraint?: InputValidationLengthConstraint) => ({ workingGroup: Yup.string(), activateAt: Yup.string().required(), activateAtBlock: Yup.number() @@ -346,8 +363,7 @@ const Validation: ValidationType = { LEAVE_ROLE_UNSTAKING_MAX, 'Leave role unstaking period' ), - humanReadableText: Yup.string() - .required() + humanReadableText: minMaxStrFromConstraint(HRTConstraint, 'human_readable_text') .test( 'schemaIsValid', 'Schema validation failed!', @@ -368,8 +384,6 @@ const Validation: ValidationType = { return true; } ) - .min(HRTMin.toNumber(), `human_readable_text must be at least ${HRTMin.toNumber()} character(s) long`) - .max(HRTMax.toNumber(), `human_readable_text cannot be more than ${HRTMax.toNumber()} character(s) long`) }), SetWorkingGroupMintCapacity: () => ({ workingGroup: Yup.string(), @@ -421,12 +435,9 @@ const Validation: ValidationType = { workingGroup: Yup.string(), amount: minMaxInt(MIN_REWARD_AMOUNT, MAX_REWARD_AMOUNT, 'Reward amount') }), - TerminateWorkingGroupLeaderRole: ({ min, max }: InputValidationLengthConstraint) => ({ + TerminateWorkingGroupLeaderRole: (rationaleConstraint?: InputValidationLengthConstraint) => ({ workingGroup: Yup.string(), - terminationRationale: Yup.string() - .required('Termination rationale is required') - .min(min.toNumber(), `Termination rationale must be at least ${min.toNumber()} character(s) long`) - .max(max.toNumber(), `Termination rationale cannot be more than ${max.toNumber()} character(s) long`), + terminationRationale: minMaxStrFromConstraint(rationaleConstraint, 'Termination rationale'), slashStake: Yup.boolean() }) }; diff --git a/pioneer/packages/joy-utils-old/src/consts/members.ts b/pioneer/packages/joy-utils/src/consts/members.ts similarity index 100% rename from pioneer/packages/joy-utils-old/src/consts/members.ts rename to pioneer/packages/joy-utils/src/consts/members.ts diff --git a/pioneer/packages/joy-utils-old/src/consts/proposals.ts b/pioneer/packages/joy-utils/src/consts/proposals.ts similarity index 100% rename from pioneer/packages/joy-utils-old/src/consts/proposals.ts rename to pioneer/packages/joy-utils/src/consts/proposals.ts diff --git a/pioneer/packages/joy-utils-old/src/consts/workingGroups.ts b/pioneer/packages/joy-utils/src/consts/workingGroups.ts similarity index 100% rename from pioneer/packages/joy-utils-old/src/consts/workingGroups.ts rename to pioneer/packages/joy-utils/src/consts/workingGroups.ts diff --git a/pioneer/packages/joy-utils/src/react/components/TxButton.tsx b/pioneer/packages/joy-utils/src/react/components/TxButton.tsx index 73eb3b3bbe..9ada4c4d8b 100644 --- a/pioneer/packages/joy-utils/src/react/components/TxButton.tsx +++ b/pioneer/packages/joy-utils/src/react/components/TxButton.tsx @@ -1,67 +1,55 @@ -import React from 'react'; -import { BareProps, ApiProps } from '@polkadot/react-api/types'; -import { QueueTxExtrinsicAdd, PartialQueueTxExtrinsic, TxFailedCallback, TxCallback } from '@polkadot/react-components/Status/types'; +import React, { useContext } from 'react'; +import { TxFailedCallback, TxCallback } from '@polkadot/react-components/Status/types'; import { Button } from '@polkadot/react-components/index'; -import { QueueConsumer } from '@polkadot/react-components/Status/Context'; -import { withApi } from '@polkadot/react-api/index'; +import QueueContext from '@polkadot/react-components/Status/Context'; import { assert } from '@polkadot/util'; -import { withMyAccount, MyAccountProps } from '../hocs/accounts'; -import { IconName } from '@fortawesome/fontawesome-svg-core'; - -type InjectedProps = { - queueExtrinsic: QueueTxExtrinsicAdd; -}; +import { ButtonProps as DefaultButtonProps } from '@polkadot/react-components/Button/types'; +import { StrictButtonProps as SemanticButtonStrictProps, Button as SemanticButton } from 'semantic-ui-react'; +import { useApi } from '@polkadot/react-hooks'; +import { useMyAccount } from '../hooks'; +import _ from 'lodash'; export type OnTxButtonClick = (sendTx: () => void) => void; -type BasicButtonProps = { +type TxButtonBaseProps = { accountId?: string; type?: 'submit' | 'button'; - isBasic?: boolean; - isDisabled?: boolean; - label?: React.ReactNode; params: Array; tx: string; - - className?: string; - style?: Record; - children?: React.ReactNode; - compact?: boolean; - icon?: IconName; - onClick?: OnTxButtonClick; txFailedCb?: TxFailedCallback; txSuccessCb?: TxCallback; txStartCb?: () => void; txUpdateCb?: TxCallback; -}; - -type PropsWithApi = BareProps & ApiProps & MyAccountProps & PartialQueueTxExtrinsic & BasicButtonProps - -class TxButtonInner extends React.PureComponent { - render () { - const { myAddress, accountId, isDisabled, icon = 'check', onClick } = this.props; - const origin = accountId || myAddress; - - return ( - - + { proposalsBatch && (<> { proposalsBatch.totalBatches > 1 && ( @@ -81,16 +81,16 @@ function ProposalPreviewList ({ bestNumber }: ProposalPreviewListProps) { /> ) } - { proposalsBatch.proposals.length - ? ( - - {proposalsBatch.proposals.map((prop: ParsedProposal, idx: number) => ( - - ))} - - ) - : `There are currently no ${activeFilter !== 'All' ? activeFilter.toLocaleLowerCase() : 'submitted'} proposals.` - } + { proposalsBatch.proposals.length + ? ( + + {proposalsBatch.proposals.map((prop: ParsedProposal, idx: number) => ( + + ))} + + ) + : `There are currently no ${activeFilter !== 'All' ? activeFilter.toLocaleLowerCase() : 'submitted'} proposals.` + } ) } diff --git a/pioneer/packages/joy-proposals/src/Proposal/ProposalTypePreview.tsx b/pioneer/packages/joy-proposals/src/Proposal/ProposalTypePreview.tsx index 092848a77b..fc10dbf01b 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/ProposalTypePreview.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/ProposalTypePreview.tsx @@ -62,9 +62,9 @@ type ProposalTypePreviewProps = { }; const ProposalTypeDetail = (props: { title: string; value: string }) => ( -
-
{ `${props.title}:` }
-
{ props.value }
+
+
{ `${props.title}:` }
+
{ props.value }
); @@ -90,7 +90,7 @@ export default function ProposalTypePreview (props: ProposalTypePreviewProps) { }; return ( - + {/* TODO: We can add it once we have the actual assets @@ -98,18 +98,18 @@ export default function ProposalTypePreview (props: ProposalTypePreviewProps) { {_.startCase(type)} {description} -
+
1 ? 's' : ''}` : 'NONE' } /> 1 ? 's' : ''}` : 'NONE' } />
@@ -139,10 +139,10 @@ export default function ProposalTypePreview (props: ProposalTypePreviewProps) { ) } -
- +
+ Create - +
diff --git a/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx b/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx index 42f9c5eec7..5186ff18c3 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/Votes.tsx @@ -24,20 +24,21 @@ export default function Votes ({ proposal: { id, votingResults } }: VotesProps) + message='Fetching the votes...'> { (votes && votes.votes.length > 0) ? ( <> -
+
All Votes: ({votes.votes.length}/{votes.councilMembersLength})
- +
{votes.votes.map((proposalVote, idx) => { const { vote, member } = proposalVote; const voteStr = (vote as VoteKind).type.toString() as VoteKindStr; const { icon, textColor } = useVoteStyles(voteStr); + return ( @@ -59,7 +60,7 @@ export default function Votes ({ proposal: { id, votingResults } }: VotesProps) ) : ( -
No votes have been submitted!
+
No votes have been submitted!
) } diff --git a/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx b/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx index 086dcd5d53..a18251bd91 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/VotingSection.tsx @@ -32,8 +32,10 @@ type VoteButtonProps = { proposalId: ProposalId; onSuccess: () => void; } + function VoteButton ({ voteKind, proposalId, memberId, onSuccess }: VoteButtonProps) { const { icon, color } = useVoteStyles(voteKind); + return ( sendTx() } + onClick={ (sendTx) => sendTx() } txFailedCb={ () => null } txSuccessCb={ onSuccess } color={color} @@ -87,7 +89,7 @@ export default function VotingSection ({ - You voted {`"${voteStr}"`} + You voted {`"${voteStr}"`} ); @@ -97,7 +99,7 @@ export default function VotingSection ({ return ( <> -
Sumbit your vote
+
Sumbit your vote
{ VoteKinds.map((voteKind) => diff --git a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx index 4869c5dac0..b1c26fdea5 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPost.tsx @@ -61,6 +61,7 @@ export default function DiscussionPost ({ authorId.toNumber() === memberId.toNumber() && editsCount < constraints.maxPostEdits ); + const onEditSuccess = () => { setEditing(false); refreshDiscussion(); @@ -98,9 +99,9 @@ export default function DiscussionPost ({ setEditing(true)} primary - size="tiny" + size='tiny' icon> - + ) } diff --git a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx index c19a25a4ee..b9161990bb 100644 --- a/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx +++ b/pioneer/packages/joy-proposals/src/Proposal/discussion/DiscussionPostForm.tsx @@ -76,7 +76,7 @@ const DiscussionPostFormInner = (props: InnerProps) => { }; return ( -
+ { { /> { isEditForm ? ( )} - diff --git a/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx b/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx index 3da45c7bb3..98bc9dfaa3 100644 --- a/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx +++ b/pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx @@ -1,13 +1,11 @@ import React from 'react'; import { getFormErrorLabelsProps } from './errorHandling'; -import { - GenericProposalForm, +import { GenericProposalForm, GenericFormValues, genericFormDefaultValues, ProposalFormExportProps, ProposalFormContainerProps, - ProposalFormInnerProps -} from './GenericProposalForm'; + ProposalFormInnerProps } from './GenericProposalForm'; import { FormField } from './FormFields'; import { ProposalType } from '@polkadot/joy-utils/types/proposals'; import { WorkingGroupKey, WorkingGroupDef } from '@joystream/types/common'; @@ -45,7 +43,7 @@ type ExportComponentProps = ProposalFormExportProps; export type FormInnerProps = ProposalFormInnerProps; -export const GenericWorkingGroupProposalForm: React.FunctionComponent = props => { +export const GenericWorkingGroupProposalForm: React.FunctionComponent = (props) => { const { handleChange, errors, @@ -72,17 +70,18 @@ export const GenericWorkingGroupProposalForm: React.FunctionComponent(errors, touched); + return ( ({ text: wgKey + ' Working Group', value: wgKey }))} + options={Object.keys(WorkingGroupDef).map((wgKey) => ({ text: wgKey + ' Working Group', value: wgKey }))} value={values.workingGroup} onChange={ handleChange } /> diff --git a/pioneer/packages/joy-proposals/src/forms/LabelWithHelp.tsx b/pioneer/packages/joy-proposals/src/forms/LabelWithHelp.tsx index d8880ba5bc..deb9be8c0d 100644 --- a/pioneer/packages/joy-proposals/src/forms/LabelWithHelp.tsx +++ b/pioneer/packages/joy-proposals/src/forms/LabelWithHelp.tsx @@ -5,6 +5,7 @@ type LabelWithHelpProps = { text: string; help: string }; export default function LabelWithHelp (props: LabelWithHelpProps) { const [open, setOpen] = useState(false); + return (
{[...props.transactionDetails].map((v, k) => ( @@ -934,7 +961,7 @@ export type DoneStageProps = { export function DoneStage (props: DoneStageProps) { return ( - +

Application submitted!

Your application is #. @@ -942,8 +969,8 @@ export function DoneStage (props: DoneStageProps) {

You can track the progress of your - application in the My roles and applications section. Note that your application is attached - to your role key (see below). If you have any issues, you can message the group lead in in the Forum or contact them directly. + application in the My roles and applications section. Note that your application is attached + to your role key (see below). If you have any issues, you can message the group lead in in the Forum or contact them directly.

Your new role key

@@ -953,7 +980,7 @@ export function DoneStage (props: DoneStageProps) {

{'We\'ve generated a new role key, '}{props.roleKeyName}, automatically. A copy of the backup file should have been downloaded, or you can - get a backup from the My account section. + get a backup from the My account section.

You can also switch your role key using the Accounts selector in the top right of the screen. It works like @@ -969,7 +996,7 @@ export function DoneStage (props: DoneStageProps) { This role key has been generated with no password! - We strongly recommend that you set a password for it in the My account section. + We strongly recommend that you set a password for it in the My account section. @@ -1014,7 +1041,7 @@ export const FlowModal = Loadable( 'keypairs', 'slots' ], - props => { + (props) => { const { applicationStake, setApplicationStake, roleStake, setRoleStake, @@ -1026,6 +1053,7 @@ export const FlowModal = Loadable( } = props; const accContext = useMyAccount(); + useEffect(() => { if (txKeyAddress.isEmpty) { setTxKeyAddress(createMock('AccountId', accContext.state.address)); @@ -1033,11 +1061,14 @@ export const FlowModal = Loadable( }, [txKeyAddress]); const history = useHistory(); + const cancel = () => { if (history.length > 1) { history.goBack(); + return; } + history.push('/working-groups/'); }; @@ -1092,56 +1123,56 @@ export const FlowModal = Loadable( const cancelText = complete ? 'Close' : 'Cancel application'; return ( - -

- - - + +
+ + + - + cancel()}> {cancelText} - - + + { activeStep === ProgressSteps.ConfirmStakes && ( + {...props} + nextTransition={enterApplicationDetailsState} + prevTransition={cancel} + {...setStakeProps} + /> ) } { activeStep === ProgressSteps.ApplicationDetails && ( { props.hasConfirmStep ? enterConfirmStakeState() : cancel(); }} - /> + setData={setAppDetails} + data={appDetails} + applicationDetails={props.role.application} + nextTransition={enterSubmitApplicationState} + prevTransition={() => { props.hasConfirmStep ? enterConfirmStakeState() : cancel(); }} + /> ) } { activeStep === ProgressSteps.SubmitApplication && ( - ) } + {...props} + nextTransition={enterDoneState} + prevTransition={enterApplicationDetailsState} + keyAddress={txKeyAddress} + setKeyAddress={setTxKeyAddress} + transactionDetails={props.transactionDetails} + totalStake={Add(applicationStake, roleStake)} + /> + ) } { activeStep === ProgressSteps.Done && () } - +
{props.role.headline}
-
{txInProgress && -
-
+
+
} diff --git a/pioneer/packages/joy-roles/src/tabs.stories.tsx b/pioneer/packages/joy-roles/src/tabs.stories.tsx index 03c5640628..fa6a546449 100644 --- a/pioneer/packages/joy-roles/src/tabs.stories.tsx +++ b/pioneer/packages/joy-roles/src/tabs.stories.tsx @@ -14,7 +14,7 @@ export default { export const RolesPage = () => { const tab = ( - + diff --git a/pioneer/packages/joy-roles/src/tabs/Admin.controller.tsx b/pioneer/packages/joy-roles/src/tabs/Admin.controller.tsx index 92f530f081..9e159c48db 100644 --- a/pioneer/packages/joy-roles/src/tabs/Admin.controller.tsx +++ b/pioneer/packages/joy-roles/src/tabs/Admin.controller.tsx @@ -11,8 +11,7 @@ import { View } from '@polkadot/joy-utils/react/hocs'; import { useMyAccount } from '@polkadot/joy-utils/react/hooks'; import { QueueTxExtrinsicAdd } from '@polkadot/react-components/Status/types'; -import { - Accordion, +import { Accordion, Button, Card, Checkbox, @@ -26,44 +25,33 @@ import { Message, Modal, Table, - TextArea -} from 'semantic-ui-react'; + TextArea } from 'semantic-ui-react'; import { ITransport } from '../transport'; -import { - Application, +import { Application, ApplicationStage, ActivateOpeningAt, Opening, OpeningStage, StakingPolicy, StakingAmountLimitModeKeys, - StakingAmountLimitMode -} from '@joystream/types/hiring'; + StakingAmountLimitMode } from '@joystream/types/hiring'; -import { - Membership, - MemberId -} from '@joystream/types/members'; +import { Membership, + MemberId } from '@joystream/types/members'; import { Stake, StakeId } from '@joystream/types/stake'; -import { - CuratorApplication, CuratorApplicationId, +import { CuratorApplication, CuratorApplicationId, CuratorOpening, - IOpeningPolicyCommitment, CuratorOpeningId -} from '@joystream/types/content-working-group'; + IOpeningPolicyCommitment, CuratorOpeningId } from '@joystream/types/content-working-group'; -import { - classifyOpeningStage, +import { classifyOpeningStage, OpeningStageClassification, - OpeningState -} from '../classifiers'; + OpeningState } from '../classifiers'; -import { - openingDescription -} from '../openingStateMarkup'; +import { openingDescription } from '../openingStateMarkup'; import { Add, Zero } from '../balances'; import { createMock } from '@joystream/types'; @@ -110,46 +98,46 @@ type State = { function newHRT (title: string): Text { return createMock('Text', JSON.stringify({ - version: 1, - headline: 'some headline', - job: { - title: title, - description: 'some job description' - }, - application: { - sections: [ - { - title: 'About you', - questions: [ - { - title: 'your name', - type: 'text' - } - ] - }, - { - title: 'Something else', - questions: [ - { - title: 'another thing', - type: 'text area' - } - ] - } - ] - }, - reward: '10 JOY per block', - creator: { - membership: { - handle: 'ben' + version: 1, + headline: 'some headline', + job: { + title: title, + description: 'some job description' + }, + application: { + sections: [ + { + title: 'About you', + questions: [ + { + title: 'your name', + type: 'text' + } + ] + }, + { + title: 'Something else', + questions: [ + { + title: 'another thing', + type: 'text area' + } + ] } - }, - process: { - details: [ - 'Some custom detail' - ] + ] + }, + reward: '10 JOY per block', + creator: { + membership: { + handle: 'ben' } - }) + }, + process: { + details: [ + 'Some custom detail' + ] + } + }) ); } @@ -379,15 +367,19 @@ export class AdminController extends Controller { startAcceptingApplications (accountId: string, id = 0) { const tx = this.api.tx.contentWorkingGroup.acceptCuratorApplications(id); + this.queueExtrinsic({ extrinsic: tx, txSuccessCb: this.onTxSuccess, accountId }); } async applyAsACurator (creatorAddress: string, openingId: number) { const membershipIds = (await this.api.query.members.memberIdsByControllerAccountId(creatorAddress)) as Vec; + if (membershipIds.length === 0) { console.error('No membship ID associated with this address'); + return; } + const tx = this.api.tx.contentWorkingGroup.applyOnCuratorOpening( membershipIds[0], openingId, @@ -396,11 +388,13 @@ export class AdminController extends Controller { 400, 'This is my application' ); + this.queueExtrinsic({ extrinsic: tx, txSuccessCb: this.onTxSuccess, accountId: creatorAddress }); } beginApplicantReview (accountId: string, openingId: number) { const tx = this.api.tx.contentWorkingGroup.beginCuratorApplicantReview(openingId); + this.queueExtrinsic({ extrinsic: tx, txSuccessCb: this.onTxSuccess, accountId }); } @@ -410,19 +404,23 @@ export class AdminController extends Controller { applications, null ); + this.queueExtrinsic({ extrinsic: tx, txSuccessCb: this.onTxSuccess, accountId }); } protected async profile (id: MemberId): Promise { const member = (await this.api.query.members.membershipById(id)) as Membership; + if (member.isEmpty) { throw new Error(`Expected member profile not found! (id: ${id.toString()}`); } + return member; } protected async stakeValue (stakeId: StakeId): Promise { const stake = await this.api.query.stake.stakes(stakeId) as Stake; + return stake.value; } @@ -446,6 +444,7 @@ export class AdminController extends Controller { this.state.openings = new Map(); const nextOpeningId = await this.api.query.contentWorkingGroup.nextCuratorOpeningId() as CuratorOpeningId; + for (let i = nextOpeningId.toNumber() - 1; i >= 0; i--) { const curatorOpening = await this.api.query.contentWorkingGroup.curatorOpeningById(i) as CuratorOpening; @@ -467,6 +466,7 @@ export class AdminController extends Controller { } const nextAppid = await this.api.query.contentWorkingGroup.nextCuratorApplicationId() as CuratorApplicationId; + for (let i = 0; i < nextAppid.toNumber(); i++) { const cApplication = await this.api.query.contentWorkingGroup.curatorApplicationById(i) as CuratorApplication; @@ -507,12 +507,14 @@ type AdminContainerProps = { state: State; controller: AdminController; } + const AdminContainer = ({ state, controller }: AdminContainerProps) => { const address = useMyAccount().state.address; const containerRef = useRef(null); + return (
- + @@ -544,7 +546,7 @@ const AdminContainer = ({ state, controller }: AdminContainerProps) => { { - [...state.openings.keys()].map(key => ) + [...state.openings.keys()].map((key) => ) }
@@ -606,6 +608,7 @@ const NewOpening = (props: NewOpeningProps) => { const onChangePolicyField = (fieldName: PolicyKey, value: policyDescriptor[PolicyKey]) => { const newState = { ...policy }; + newState[fieldName] = value; setPolicy(newState); }; @@ -642,14 +645,17 @@ const NewOpening = (props: NewOpeningProps) => { ) => { if (mode === '') { const policyField = policy[fieldName]; + mode = policyField && policyField.isSome ? (policyField.unwrap().amount_mode.type as StakingAmountLimitModeKeys) : StakingAmountLimitModeKeys.Exact; // Default } + const value = createStakingPolicyOpt( stakeValue, mode === StakingAmountLimitModeKeys.Exact ? STAKING_MODE_EXACT : STAKING_MODE_AT_LEAST ); + onChangePolicyField(fieldName, value); }; @@ -686,7 +692,7 @@ const NewOpening = (props: NewOpeningProps) => { /> {showExactBlock === true && @@ -696,7 +702,7 @@ const NewOpening = (props: NewOpeningProps) => { onChangePolicyField('max_review_period_length', createMock('u32', value))} /> @@ -704,7 +710,7 @@ const NewOpening = (props: NewOpeningProps) => { - onStakeModeCheckboxChange(setRequireAppStakingPolicy, 'application_staking_policy', checked, 0)} /> + onStakeModeCheckboxChange(setRequireAppStakingPolicy, 'application_staking_policy', checked, 0)} /> {requireAppStakingPolicy && ( @@ -717,7 +723,7 @@ const NewOpening = (props: NewOpeningProps) => { changeStakingMode('application_staking_policy', '', value)} /> @@ -727,7 +733,7 @@ const NewOpening = (props: NewOpeningProps) => { - onStakeModeCheckboxChange(setRequireRoleStakingPolicy, 'role_staking_policy', checked, 0)} /> + onStakeModeCheckboxChange(setRequireRoleStakingPolicy, 'role_staking_policy', checked, 0)} /> {requireRoleStakingPolicy && ( @@ -740,7 +746,7 @@ const NewOpening = (props: NewOpeningProps) => { changeStakingMode('role_staking_policy', '', value)} /> @@ -752,7 +758,7 @@ const NewOpening = (props: NewOpeningProps) => {