diff --git a/commander/src/bootstrapping/commands/base_ipc_client.ts b/commander/src/bootstrapping/commands/base_ipc_client.ts index 9c8a7bd178b..037eb074aac 100644 --- a/commander/src/bootstrapping/commands/base_ipc_client.ts +++ b/commander/src/bootstrapping/commands/base_ipc_client.ts @@ -15,7 +15,7 @@ import * as apiClient from '@liskhq/lisk-api-client'; import { Command } from '@oclif/core'; -import { RegisteredSchema, ModuleMetadataJSON } from 'lisk-framework'; +import { Types, Modules } from 'lisk-framework'; import { PromiseResolvedType } from '../../types'; import { isApplicationRunning } from '../../utils/application'; import { flagsWithParser } from '../../utils/flags'; @@ -34,8 +34,8 @@ export abstract class BaseIPCClientCommand extends Command { protected baseIPCClientFlags!: BaseIPCClientFlags; protected _client!: PromiseResolvedType> | undefined; - protected _schema!: RegisteredSchema; - protected _metadata!: ModuleMetadataJSON[]; + protected _schema!: Types.RegisteredSchema; + protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; async finally(): Promise { diff --git a/commander/src/bootstrapping/commands/config/show.ts b/commander/src/bootstrapping/commands/config/show.ts index 6d6ce91032c..0f7a2d05a36 100644 --- a/commander/src/bootstrapping/commands/config/show.ts +++ b/commander/src/bootstrapping/commands/config/show.ts @@ -15,7 +15,7 @@ import * as utils from '@liskhq/lisk-utils'; import { Command } from '@oclif/core'; import * as fs from 'fs-extra'; -import { ApplicationConfig } from 'lisk-framework'; +import { Types } from 'lisk-framework'; import { flagsWithParser } from '../../../utils/flags'; import { getConfigFilesPath, getDefaultPath } from '../../../utils/path'; @@ -46,11 +46,11 @@ export class ShowCommand extends Command { this.error(`Folder in ${dataPath} does not contain valid config`); } // Get config from network config or config specified - let config = (await fs.readJSON(configFilePath)) as ApplicationConfig; + let config = (await fs.readJSON(configFilePath)) as Types.ApplicationConfig; if (flags.config) { - const customConfig = (await fs.readJSON(flags.config)) as ApplicationConfig; - config = utils.objects.mergeDeep({}, config, customConfig) as ApplicationConfig; + const customConfig = (await fs.readJSON(flags.config)) as Types.ApplicationConfig; + config = utils.objects.mergeDeep({}, config, customConfig) as Types.ApplicationConfig; } config.system.dataPath = dataPath; diff --git a/commander/src/bootstrapping/commands/genesis-block/create.ts b/commander/src/bootstrapping/commands/genesis-block/create.ts index bd348abe670..c406c4d2ab6 100644 --- a/commander/src/bootstrapping/commands/genesis-block/create.ts +++ b/commander/src/bootstrapping/commands/genesis-block/create.ts @@ -14,7 +14,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { Application, PartialApplicationConfig } from 'lisk-framework'; +import { Application, Types } from 'lisk-framework'; import { objects } from '@liskhq/lisk-utils'; import { Command, Flags as flagParser } from '@oclif/core'; import * as fs from 'fs-extra'; @@ -141,6 +141,6 @@ export abstract class BaseGenesisBlockCommand extends Command { this.log(`Genesis block files saved at: ${configPath}`); } - abstract getApplication(config: PartialApplicationConfig): Application; + abstract getApplication(config: Types.PartialApplicationConfig): Application; abstract getApplicationConfigDir(): string; } diff --git a/commander/src/bootstrapping/commands/start.ts b/commander/src/bootstrapping/commands/start.ts index d1b7e9deff9..32403398890 100644 --- a/commander/src/bootstrapping/commands/start.ts +++ b/commander/src/bootstrapping/commands/start.ts @@ -18,7 +18,7 @@ import { Command, Flags as flagParser } from '@oclif/core'; import * as fs from 'fs-extra'; import { utils as cryptoUtils } from '@liskhq/lisk-cryptography'; -import { ApplicationConfig, Application, PartialApplicationConfig } from 'lisk-framework'; +import { Types, Application } from 'lisk-framework'; import * as utils from '@liskhq/lisk-utils'; import { flagsWithParser } from '../../utils/flags'; @@ -152,8 +152,8 @@ export abstract class StartCommand extends Command { let config = await fs.readJSON(configFilePath); if (flags.config) { - const customConfig: ApplicationConfig = await fs.readJSON(flags.config); - config = utils.objects.mergeDeep({}, config, customConfig) as ApplicationConfig; + const customConfig: Types.ApplicationConfig = await fs.readJSON(flags.config); + config = utils.objects.mergeDeep({}, config, customConfig) as Types.ApplicationConfig; } config.system.version = this.config.pjson.version; config.system.dataPath = dataPath; @@ -220,7 +220,7 @@ export abstract class StartCommand extends Command { } } - abstract getApplication(config: PartialApplicationConfig): Promise; + abstract getApplication(config: Types.PartialApplicationConfig): Promise; abstract getApplicationConfigDir(): string; } diff --git a/commander/src/bootstrapping/commands/transaction/create.ts b/commander/src/bootstrapping/commands/transaction/create.ts index f867b230613..4da3a685c65 100644 --- a/commander/src/bootstrapping/commands/transaction/create.ts +++ b/commander/src/bootstrapping/commands/transaction/create.ts @@ -22,12 +22,11 @@ import { validator } from '@liskhq/lisk-validator'; import { Command, Flags as flagParser } from '@oclif/core'; import { Application, - PartialApplicationConfig, - RegisteredSchema, + Types, blockHeaderSchema, blockSchema, transactionSchema, - ModuleMetadataJSON, + Modules, } from 'lisk-framework'; import { PromiseResolvedType } from '../../../types'; import { deriveKeypair } from '../../../utils/commons'; @@ -74,7 +73,11 @@ interface Transaction { signatures: never[]; } -const getParamsObject = async (metadata: ModuleMetadataJSON[], flags: CreateFlags, args: Args) => { +const getParamsObject = async ( + metadata: Modules.ModuleMetadataJSON[], + flags: CreateFlags, + args: Args, +) => { let params: Record; const paramsSchema = getParamsSchema(metadata, args.module, args.command); @@ -112,8 +115,8 @@ const getKeysFromFlags = async (flags: CreateFlags) => { const validateAndSignTransaction = ( transaction: Transaction, - schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + schema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], chainID: string, privateKey: Buffer, noSignature: boolean, @@ -145,8 +148,8 @@ const validateAndSignTransaction = ( const createTransactionOffline = async ( args: Args, flags: CreateFlags, - registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + registeredSchema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transaction: Transaction, ) => { const params = await getParamsObject(metadata, flags, args); @@ -169,8 +172,8 @@ const createTransactionOnline = async ( args: Args, flags: CreateFlags, client: apiClient.APIClient, - registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + registeredSchema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transaction: Transaction, ) => { const nodeInfo = await client.node.getNodeInfo(); @@ -275,8 +278,8 @@ export abstract class CreateCommand extends Command { }; protected _client!: PromiseResolvedType> | undefined; - protected _schema!: RegisteredSchema; - protected _metadata!: ModuleMetadataJSON[]; + protected _schema!: Types.RegisteredSchema; + protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; async run(): Promise { @@ -373,5 +376,5 @@ export abstract class CreateCommand extends Command { } } - abstract getApplication(config: PartialApplicationConfig): Application; + abstract getApplication(config: Types.PartialApplicationConfig): Application; } diff --git a/commander/src/bootstrapping/commands/transaction/sign.ts b/commander/src/bootstrapping/commands/transaction/sign.ts index 2be81949a98..04611294d01 100644 --- a/commander/src/bootstrapping/commands/transaction/sign.ts +++ b/commander/src/bootstrapping/commands/transaction/sign.ts @@ -18,9 +18,8 @@ import { Application, blockHeaderSchema, blockSchema, - ModuleMetadataJSON, - PartialApplicationConfig, - RegisteredSchema, + Modules, + Types, transactionSchema, } from 'lisk-framework'; import * as transactions from '@liskhq/lisk-transactions'; @@ -57,8 +56,8 @@ interface SignFlags { const signTransaction = async ( flags: SignFlags, - registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + registeredSchema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, chainID: string | undefined, keys: Keys, @@ -105,8 +104,8 @@ const signTransaction = async ( const signTransactionOffline = async ( flags: SignFlags, - registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + registeredSchema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ): Promise> => { const mandatoryKeys = flags['mandatory-keys']; @@ -132,8 +131,8 @@ const signTransactionOffline = async ( const signTransactionOnline = async ( flags: SignFlags, client: apiClient.APIClient, - registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + registeredSchema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ) => { const transactionObject = decodeTransaction(registeredSchema, metadata, transactionHexStr); @@ -190,8 +189,8 @@ export abstract class SignCommand extends Command { ]; protected _client: PromiseResolvedType> | undefined; - protected _schema!: RegisteredSchema; - protected _metadata!: ModuleMetadataJSON[]; + protected _schema!: Types.RegisteredSchema; + protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; async run(): Promise { @@ -261,5 +260,5 @@ export abstract class SignCommand extends Command { } } - abstract getApplication(config: PartialApplicationConfig): Application; + abstract getApplication(config: Types.PartialApplicationConfig): Application; } diff --git a/commander/src/utils/genesis_creation.ts b/commander/src/utils/genesis_creation.ts index 20a92d928d8..d47954897cc 100644 --- a/commander/src/utils/genesis_creation.ts +++ b/commander/src/utils/genesis_creation.ts @@ -15,14 +15,7 @@ */ import { Schema } from '@liskhq/lisk-codec'; import { address } from '@liskhq/lisk-cryptography'; -import { - genesisInteroperabilitySchema, - MODULE_NAME_INTEROPERABILITY, - posGenesisStoreSchema, - PoSModule, - tokenGenesisStoreSchema, - TokenModule, -} from 'lisk-framework'; +import { Modules } from 'lisk-framework'; export const genesisAssetsSchema = { $id: '/genesis/asset/0', @@ -91,7 +84,7 @@ export const generateGenesisBlockDefaultPoSAssets = (input: GenesisBlockDefaultA ); const genesisAssets = [ { - module: new TokenModule().name, + module: new Modules.Token.TokenModule().name, data: { userSubstore: input.keysList.map(a => ({ address: a.address, @@ -108,10 +101,10 @@ export const generateGenesisBlockDefaultPoSAssets = (input: GenesisBlockDefaultA escrowSubstore: [], supportedTokensSubstore: [], } as Record, - schema: tokenGenesisStoreSchema, + schema: Modules.Token.genesisTokenStoreSchema, }, { - module: new PoSModule().name, + module: new Modules.PoS.PoSModule().name, data: { validators: input.keysList.map((v, i) => ({ address: v.address, @@ -133,10 +126,10 @@ export const generateGenesisBlockDefaultPoSAssets = (input: GenesisBlockDefaultA initValidators: input.keysList.slice(0, input.numberOfValidators).map(v => v.address), }, } as Record, - schema: posGenesisStoreSchema, + schema: Modules.PoS.genesisStoreSchema, }, { - module: MODULE_NAME_INTEROPERABILITY, + module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, data: { ownChainName: '', ownChainNonce: 0, @@ -144,7 +137,7 @@ export const generateGenesisBlockDefaultPoSAssets = (input: GenesisBlockDefaultA terminatedStateAccounts: [], terminatedOutboxAccounts: [], }, - schema: genesisInteroperabilitySchema, + schema: Modules.Interoperability.genesisInteroperabilitySchema, }, ]; diff --git a/commander/src/utils/transaction.ts b/commander/src/utils/transaction.ts index a215bcda1a0..37a0dd115dd 100644 --- a/commander/src/utils/transaction.ts +++ b/commander/src/utils/transaction.ts @@ -16,14 +16,14 @@ import * as liskApiClient from '@liskhq/lisk-api-client'; import * as cryptography from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { TransactionJSON } from '@liskhq/lisk-chain'; -import { ModuleMetadataJSON, RegisteredSchema } from 'lisk-framework'; +import { Modules, Types } from 'lisk-framework'; import { Schema } from '../types'; import { getDefaultPath } from './path'; import { isApplicationRunning } from './application'; export const getParamsSchema = ( - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], module: string, command: string, ): Schema => { @@ -39,8 +39,8 @@ export const getParamsSchema = ( }; export const decodeTransaction = ( - schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + schema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ) => { const transactionBytes = Buffer.from(transactionHexStr, 'hex'); @@ -59,8 +59,8 @@ export const decodeTransaction = ( }; export const encodeTransaction = ( - schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + schema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, ): Buffer => { @@ -78,8 +78,8 @@ export const encodeTransaction = ( }; export const encodeTransactionJSON = ( - schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + schema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, ): Buffer => { @@ -100,8 +100,8 @@ export const encodeTransactionJSON = ( }; export const transactionToJSON = ( - schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + schema: Types.RegisteredSchema, + metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, ): Record => { diff --git a/commander/test/bootstrapping/commands/transaction/sign.spec.ts b/commander/test/bootstrapping/commands/transaction/sign.spec.ts index 66972451f5b..a5b02142488 100644 --- a/commander/test/bootstrapping/commands/transaction/sign.spec.ts +++ b/commander/test/bootstrapping/commands/transaction/sign.spec.ts @@ -15,7 +15,7 @@ import * as fs from 'fs-extra'; import { ed } from '@liskhq/lisk-cryptography'; -import { Application, IPCChannel, transactionSchema } from 'lisk-framework'; +import { Application, Controller, transactionSchema } from 'lisk-framework'; import * as apiClient from '@liskhq/lisk-api-client'; import { codec } from '@liskhq/lisk-codec'; import { TransactionAttrs } from '@liskhq/lisk-chain'; @@ -101,8 +101,8 @@ describe('transaction:sign command', () => { jest.spyOn(appUtils, 'isApplicationRunning').mockReturnValue(true); jest.spyOn(fs, 'existsSync').mockReturnValue(true); jest.spyOn(SignCommandExtended.prototype, 'printJSON').mockReturnValue(); - jest.spyOn(IPCChannel.prototype, 'startAndListen').mockResolvedValue(); - jest.spyOn(IPCChannel.prototype, 'invoke'); + jest.spyOn(Controller.IPCChannel.prototype, 'startAndListen').mockResolvedValue(); + jest.spyOn(Controller.IPCChannel.prototype, 'invoke'); jest.spyOn(readerUtils, 'getPassphraseFromPrompt').mockResolvedValue(senderPassphrase); jest .spyOn(apiClient, 'createIPCClient') diff --git a/examples/interop/pos-mainchain-fast/src/app/app.ts b/examples/interop/pos-mainchain-fast/src/app/app.ts index 3250d66e460..24342b37d88 100644 --- a/examples/interop/pos-mainchain-fast/src/app/app.ts +++ b/examples/interop/pos-mainchain-fast/src/app/app.ts @@ -1,12 +1,12 @@ -import { Application, PartialApplicationConfig, NFTModule } from 'lisk-sdk'; +import { Application, Types, Modules } from 'lisk-sdk'; import { TestNftModule } from './modules/testNft/module'; import { registerModules } from './modules'; import { registerPlugins } from './plugins'; -export const getApplication = (config: PartialApplicationConfig): Application => { +export const getApplication = (config: Types.PartialApplicationConfig): Application => { const { app, method } = Application.defaultApplication(config, true); - const nftModule = new NFTModule(); + const nftModule = new Modules.NFT.NFTModule(); const testNftModule = new TestNftModule(); const interoperabilityModule = app['_registeredModules'].find( mod => mod.name === 'interoperability', diff --git a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/destroy_nft.ts b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/destroy_nft.ts index 822ad1b174f..50e2c25f122 100644 --- a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/destroy_nft.ts +++ b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/destroy_nft.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCommand, CommandExecuteContext, NFTMethod } from 'lisk-sdk'; +import { StateMachine, Modules } from 'lisk-sdk'; import { destroyNftParamsSchema } from '../schema'; interface Params { @@ -20,15 +20,15 @@ interface Params { nftID: Buffer; } -export class DestroyNftCommand extends BaseCommand { - private _nftMethod!: NFTMethod; +export class DestroyNftCommand extends Modules.BaseCommand { + private _nftMethod!: Modules.NFT.NFTMethod; public schema = destroyNftParamsSchema; - public init(args: { nftMethod: NFTMethod }): void { + public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { const { params } = context; await this._nftMethod.destroy(context.getMethodContext(), params.address, params.nftID); diff --git a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/mint_nft.ts b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/mint_nft.ts index bc5638846d4..49741fc0a2c 100644 --- a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/mint_nft.ts +++ b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/commands/mint_nft.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCommand, CommandExecuteContext, NFTMethod } from 'lisk-sdk'; +import { StateMachine, Modules } from 'lisk-sdk'; import { NFTAttributes } from '../types'; import { mintNftParamsSchema } from '../schema'; @@ -22,15 +22,15 @@ interface Params { attributesArray: NFTAttributes[]; } -export class MintNftCommand extends BaseCommand { - private _nftMethod!: NFTMethod; +export class MintNftCommand extends Modules.BaseCommand { + private _nftMethod!: Modules.NFT.NFTMethod; public schema = mintNftParamsSchema; - public init(args: { nftMethod: NFTMethod }): void { + public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { const { params } = context; await this._nftMethod.create( diff --git a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/endpoint.ts b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/endpoint.ts index 1d091013741..5a94633bbfc 100644 --- a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/endpoint.ts +++ b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/endpoint.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseEndpoint } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class TestNftEndpoint extends BaseEndpoint {} +export class TestNftEndpoint extends Modules.BaseEndpoint {} diff --git a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/method.ts b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/method.ts index 5bab789e7f1..23f005c5f71 100644 --- a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/method.ts +++ b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/method.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class TestNftMethod extends BaseMethod {} +export class TestNftMethod extends Modules.BaseMethod {} diff --git a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/module.ts b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/module.ts index a228abff3af..3c9506c7930 100644 --- a/examples/interop/pos-mainchain-fast/src/app/modules/testNft/module.ts +++ b/examples/interop/pos-mainchain-fast/src/app/modules/testNft/module.ts @@ -12,26 +12,26 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseModule, ModuleInitArgs, ModuleMetadata, NFTMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; import { TestNftEndpoint } from './endpoint'; import { TestNftMethod } from './method'; import { MintNftCommand } from './commands/mint_nft'; import { DestroyNftCommand } from './commands/destroy_nft'; -export class TestNftModule extends BaseModule { +export class TestNftModule extends Modules.BaseModule { public endpoint = new TestNftEndpoint(this.stores, this.offchainStores); public method = new TestNftMethod(this.stores, this.events); public mintNftCommand = new MintNftCommand(this.stores, this.events); public destroyNftCommand = new DestroyNftCommand(this.stores, this.events); public commands = [this.mintNftCommand, this.destroyNftCommand]; - private _nftMethod!: NFTMethod; + private _nftMethod!: Modules.NFT.NFTMethod; - public addDependencies(nftMethod: NFTMethod) { + public addDependencies(nftMethod: Modules.NFT.NFTMethod) { this._nftMethod = nftMethod; } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { return { ...this.baseMetadata(), endpoints: [], @@ -45,7 +45,7 @@ export class TestNftModule extends BaseModule { } // eslint-disable-next-line @typescript-eslint/require-await - public async init(_args: ModuleInitArgs) { + public async init(_args: Modules.ModuleInitArgs) { this.mintNftCommand.init({ nftMethod: this._nftMethod, }); diff --git a/examples/interop/pos-mainchain-fast/src/commands/genesis-block/create.ts b/examples/interop/pos-mainchain-fast/src/commands/genesis-block/create.ts index ad2d13f7575..84c6244b5f1 100644 --- a/examples/interop/pos-mainchain-fast/src/commands/genesis-block/create.ts +++ b/examples/interop/pos-mainchain-fast/src/commands/genesis-block/create.ts @@ -1,10 +1,10 @@ import { BaseGenesisBlockCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { join } from 'path'; import { getApplication } from '../../app/app'; export class GenesisBlockCommand extends BaseGenesisBlockCommand { - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-mainchain-fast/src/commands/start.ts b/examples/interop/pos-mainchain-fast/src/commands/start.ts index 362671e0137..72661f6c6f5 100644 --- a/examples/interop/pos-mainchain-fast/src/commands/start.ts +++ b/examples/interop/pos-mainchain-fast/src/commands/start.ts @@ -5,7 +5,7 @@ import { Flags as flagParser } from '@oclif/core'; import { FlagInput } from '@oclif/core/lib/interfaces'; import { BaseStartCommand } from 'lisk-commander'; -import { Application, ApplicationConfig, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { ForgerPlugin } from '@liskhq/lisk-framework-forger-plugin'; import { MonitorPlugin } from '@liskhq/lisk-framework-monitor-plugin'; import { ReportMisbehaviorPlugin } from '@liskhq/lisk-framework-report-misbehavior-plugin'; @@ -19,7 +19,7 @@ interface Flags { [key: string]: string | number | boolean | undefined; } -const setPluginConfig = (config: ApplicationConfig, flags: Flags): void => { +const setPluginConfig = (config: Types.ApplicationConfig, flags: Flags): void => { if (flags['monitor-plugin-port'] !== undefined) { config.plugins[MonitorPlugin.name] = config.plugins[MonitorPlugin.name] ?? {}; config.plugins[MonitorPlugin.name].port = flags['monitor-plugin-port']; @@ -111,11 +111,11 @@ export class StartCommand extends BaseStartCommand { }), }; - public async getApplication(config: PartialApplicationConfig): Promise { + public async getApplication(config: Types.PartialApplicationConfig): Promise { /* eslint-disable @typescript-eslint/no-unsafe-call */ const { flags } = await this.parse(StartCommand); // Set Plugins Config - setPluginConfig(config as ApplicationConfig, flags); + setPluginConfig(config as Types.ApplicationConfig, flags); const app = getApplication(config); if (flags['enable-forger-plugin']) { diff --git a/examples/interop/pos-mainchain-fast/src/commands/transaction/create.ts b/examples/interop/pos-mainchain-fast/src/commands/transaction/create.ts index 4c7cbb76768..cf60661f9ff 100644 --- a/examples/interop/pos-mainchain-fast/src/commands/transaction/create.ts +++ b/examples/interop/pos-mainchain-fast/src/commands/transaction/create.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionCreateCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type CreateFlags = typeof TransactionCreateCommand.flags & { @@ -15,7 +15,7 @@ export class CreateCommand extends TransactionCreateCommand { static args = [...TransactionCreateCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-mainchain-fast/src/commands/transaction/sign.ts b/examples/interop/pos-mainchain-fast/src/commands/transaction/sign.ts index b55093102a7..139ed5ad7e9 100644 --- a/examples/interop/pos-mainchain-fast/src/commands/transaction/sign.ts +++ b/examples/interop/pos-mainchain-fast/src/commands/transaction/sign.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionSignCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type SignFlags = typeof TransactionSignCommand.flags & { [key: string]: Record }; @@ -13,7 +13,7 @@ export class SignCommand extends TransactionSignCommand { static args = [...TransactionSignCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-sidechain-example-one/src/app/app.ts b/examples/interop/pos-sidechain-example-one/src/app/app.ts index 20cf00b39c8..1114c958d5d 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/app.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/app.ts @@ -1,13 +1,13 @@ -import { Application, PartialApplicationConfig, NFTModule } from 'lisk-sdk'; +import { Application, Types, Modules } from 'lisk-sdk'; import { TestNftModule } from './modules/testNft/module'; import { registerModules } from './modules'; import { registerPlugins } from './plugins'; import { HelloModule } from './modules/hello/module'; -export const getApplication = (config: PartialApplicationConfig): Application => { +export const getApplication = (config: Types.PartialApplicationConfig): Application => { const { app, method } = Application.defaultApplication(config, false); - const nftModule = new NFTModule(); + const nftModule = new Modules.NFT.NFTModule(); const testNftModule = new TestNftModule(); const interoperabilityModule = app['_registeredModules'].find( mod => mod.name === 'interoperability', diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_cc_command.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_cc_command.ts index d7f0531e394..32e49a61b52 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_cc_command.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_cc_command.ts @@ -1,13 +1,13 @@ /* eslint-disable class-methods-use-this */ -import { BaseCCCommand, CrossChainMessageContext, codec, cryptography, db } from 'lisk-sdk'; +import { Modules, codec, cryptography, db } from 'lisk-sdk'; import { CCReactMessageParamsSchema } from '../schemas'; import { CCReactMessageParams } from '../types'; import { MAX_RESERVED_ERROR_STATUS, CROSS_CHAIN_COMMAND_REACT } from '../constants'; import { ReactionStore, ReactionStoreData } from '../stores/reaction'; import { MessageStore } from '../stores/message'; -export class ReactCCCommand extends BaseCCCommand { +export class ReactCCCommand extends Modules.Interoperability.BaseCCCommand { public schema = CCReactMessageParamsSchema; public get name(): string { @@ -15,7 +15,7 @@ export class ReactCCCommand extends BaseCCCommand { } // eslint-disable-next-line @typescript-eslint/require-await - public async verify(ctx: CrossChainMessageContext): Promise { + public async verify(ctx: Modules.Interoperability.CrossChainMessageContext): Promise { const { ccm } = ctx; if (ccm.status > MAX_RESERVED_ERROR_STATUS) { @@ -34,7 +34,7 @@ export class ReactCCCommand extends BaseCCCommand { } } - public async execute(ctx: CrossChainMessageContext): Promise { + public async execute(ctx: Modules.Interoperability.CrossChainMessageContext): Promise { const { ccm, logger, transaction } = ctx; logger.info('Executing React CCM'); diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_method.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_method.ts index f8535173f9a..8c3bc36183c 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_method.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_method.ts @@ -1,3 +1,3 @@ -import { BaseCCMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class HelloInteroperableMethod extends BaseCCMethod {} +export class HelloInteroperableMethod extends Modules.Interoperability.BaseCCMethod {} diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/commands/create_hello_command.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/commands/create_hello_command.ts index 36d21f17f63..c5b6da08e57 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/commands/create_hello_command.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/commands/create_hello_command.ts @@ -1,12 +1,6 @@ /* eslint-disable class-methods-use-this */ -import { - BaseCommand, - CommandVerifyContext, - CommandExecuteContext, - VerificationResult, - VerifyStatus, -} from 'lisk-sdk'; +import { Modules, StateMachine } from 'lisk-sdk'; import { createHelloSchema } from '../schemas'; import { MessageStore } from '../stores/message'; import { counterKey, CounterStore, CounterStoreData } from '../stores/counter'; @@ -17,7 +11,7 @@ interface Params { message: string; } -export class CreateHelloCommand extends BaseCommand { +export class CreateHelloCommand extends Modules.BaseCommand { public schema = createHelloSchema; private _blacklist!: string[]; @@ -32,8 +26,10 @@ export class CreateHelloCommand extends BaseCommand { } // eslint-disable-next-line @typescript-eslint/require-await - public async verify(context: CommandVerifyContext): Promise { - let validation: VerificationResult; + public async verify( + context: StateMachine.CommandVerifyContext, + ): Promise { + let validation: StateMachine.VerificationResult; const wordList = context.params.message.split(' '); const found = this._blacklist.filter(value => wordList.includes(value)); if (found.length > 0) { @@ -42,13 +38,13 @@ export class CreateHelloCommand extends BaseCommand { } else { context.logger.info('==== NOT FOUND: Message contains no blacklisted words ===='); validation = { - status: VerifyStatus.OK, + status: StateMachine.VerifyStatus.OK, }; } return validation; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { // 1. Get account data of the sender of the Hello transaction. const { senderAddress } = context.transaction; // 2. Get message and counter stores. diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/endpoint.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/endpoint.ts index af5cb5aa6b8..f8ba814eed8 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/endpoint.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/endpoint.ts @@ -1,10 +1,10 @@ -import { BaseEndpoint, ModuleEndpointContext, cryptography } from 'lisk-sdk'; +import { Modules, Types, cryptography } from 'lisk-sdk'; import { counterKey, CounterStore, CounterStoreData } from './stores/counter'; import { MessageStore, MessageStoreData } from './stores/message'; import { ReactionStore, ReactionStoreData } from './stores/reaction'; -export class HelloEndpoint extends BaseEndpoint { - public async getHelloCounter(ctx: ModuleEndpointContext): Promise { +export class HelloEndpoint extends Modules.BaseEndpoint { + public async getHelloCounter(ctx: Types.ModuleEndpointContext): Promise { const counterSubStore = this.stores.get(CounterStore); const helloCounter = await counterSubStore.get(ctx, counterKey); @@ -12,7 +12,7 @@ export class HelloEndpoint extends BaseEndpoint { return helloCounter; } - public async getReactions(ctx: ModuleEndpointContext): Promise { + public async getReactions(ctx: Types.ModuleEndpointContext): Promise { const reactionSubStore = this.stores.get(ReactionStore); const { address } = ctx.params; @@ -28,7 +28,7 @@ export class HelloEndpoint extends BaseEndpoint { return reactions; } - public async getHello(ctx: ModuleEndpointContext): Promise { + public async getHello(ctx: Types.ModuleEndpointContext): Promise { const messageSubStore = this.stores.get(MessageStore); const { address } = ctx.params; diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/events/new_hello.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/events/new_hello.ts index a613a9d18c0..a98921bd758 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/events/new_hello.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/events/new_hello.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BaseEvent } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; export const newHelloEventSchema = { $id: '/hello/events/new_hello', @@ -34,6 +34,6 @@ export interface NewHelloEventData { message: string; } -export class NewHelloEvent extends BaseEvent { +export class NewHelloEvent extends Modules.BaseEvent { public schema = newHelloEventSchema; } diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/method.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/method.ts index 0ce458081f6..aac55c32d55 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/method.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/method.ts @@ -1,9 +1,9 @@ -import { BaseMethod, ImmutableMethodContext } from 'lisk-sdk'; +import { Modules, StateMachine } from 'lisk-sdk'; import { MessageStore, MessageStoreData } from './stores/message'; -export class HelloMethod extends BaseMethod { +export class HelloMethod extends Modules.BaseMethod { public async getHello( - methodContext: ImmutableMethodContext, + methodContext: StateMachine.ImmutableMethodContext, address: Buffer, ): Promise { const messageSubStore = this.stores.get(MessageStore); diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/module.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/module.ts index 9c0219774d9..2601645a036 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/module.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/module.ts @@ -1,21 +1,6 @@ /* eslint-disable class-methods-use-this */ -import { - validator, - BaseInteroperableModule, - BlockAfterExecuteContext, - BlockExecuteContext, - BlockVerifyContext, - GenesisBlockExecuteContext, - InsertAssetContext, - ModuleInitArgs, - ModuleMetadata, - TransactionExecuteContext, - TransactionVerifyContext, - utils, - VerificationResult, - VerifyStatus, -} from 'lisk-sdk'; +import { validator, StateMachine, Modules, utils } from 'lisk-sdk'; import { CreateHelloCommand } from './commands/create_hello_command'; import { ReactCCCommand } from './cc_commands/react_cc_command'; import { HelloEndpoint } from './endpoint'; @@ -30,7 +15,7 @@ import { import { CounterStore } from './stores/counter'; import { MessageStore } from './stores/message'; import { ReactionStore, reactionStoreSchema } from './stores/reaction'; -import { ModuleConfigJSON } from './types'; +import { ModuleConfig } from './types'; import { HelloInteroperableMethod } from './cc_method'; export const defaultConfig = { @@ -39,7 +24,7 @@ export const defaultConfig = { blacklist: ['illegalWord1'], }; -export class HelloModule extends BaseInteroperableModule { +export class HelloModule extends Modules.Interoperability.BaseInteroperableModule { public endpoint = new HelloEndpoint(this.stores, this.offchainStores); public method = new HelloMethod(this.stores, this.events); public commands = [new CreateHelloCommand(this.stores, this.events)]; @@ -56,7 +41,7 @@ export class HelloModule extends BaseInteroperableModule { this.events.register(NewHelloEvent, new NewHelloEvent(this.name)); } - public metadata(): ModuleMetadata { + public metadata() { return { endpoints: [ { @@ -89,13 +74,17 @@ export class HelloModule extends BaseInteroperableModule { // Lifecycle hooks // eslint-disable-next-line @typescript-eslint/require-await - public async init(args: ModuleInitArgs): Promise { + public async init(args: Modules.ModuleInitArgs): Promise { // Get the module config defined in the config.json file const { moduleConfig } = args; // Overwrite the default module config with values from config.json, if set - const config = utils.objects.mergeDeep({}, defaultConfig, moduleConfig) as ModuleConfigJSON; + const config: ModuleConfig = utils.objects.mergeDeep( + {}, + defaultConfig, + moduleConfig, + ) as ModuleConfig; // Validate the provided config with the config schema - validator.validator.validate(configSchema, config); + validator.validator.validate(configSchema, config); // Call the command init() method with config values as parameters this.commands[0].init(config).catch(err => { // eslint-disable-next-line no-console @@ -103,39 +92,51 @@ export class HelloModule extends BaseInteroperableModule { }); } - public async insertAssets(_context: InsertAssetContext) { + public async insertAssets(_context: StateMachine.InsertAssetContext) { // initialize block generation, add asset } - public async verifyAssets(_context: BlockVerifyContext): Promise { + public async verifyAssets(_context: StateMachine.BlockVerifyContext): Promise { // verify block } // Lifecycle hooks // eslint-disable-next-line @typescript-eslint/require-await - public async verifyTransaction(_context: TransactionVerifyContext): Promise { + public async verifyTransaction( + _context: StateMachine.TransactionVerifyContext, + ): Promise { // verify transaction will be called multiple times in the transaction pool const result = { - status: VerifyStatus.OK, + status: StateMachine.VerifyStatus.OK, }; return result; } - // eslint-disable-next-line @typescript-eslint/no-empty-function - public async beforeCommandExecute(_context: TransactionExecuteContext): Promise {} + public async beforeCommandExecute( + _context: StateMachine.TransactionExecuteContext, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): Promise {} - // eslint-disable-next-line @typescript-eslint/no-empty-function - public async afterCommandExecute(_context: TransactionExecuteContext): Promise {} + public async afterCommandExecute( + _context: StateMachine.TransactionExecuteContext, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async initGenesisState(_context: GenesisBlockExecuteContext): Promise {} + public async initGenesisState(_context: StateMachine.GenesisBlockExecuteContext): Promise {} - // eslint-disable-next-line @typescript-eslint/no-empty-function - public async finalizeGenesisState(_context: GenesisBlockExecuteContext): Promise {} + public async finalizeGenesisState( + _context: StateMachine.GenesisBlockExecuteContext, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): Promise {} - // eslint-disable-next-line @typescript-eslint/no-empty-function - public async beforeTransactionsExecute(_context: BlockExecuteContext): Promise {} + public async beforeTransactionsExecute( + _context: StateMachine.BlockExecuteContext, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): Promise {} - // eslint-disable-next-line @typescript-eslint/no-empty-function - public async afterTransactionsExecute(_context: BlockAfterExecuteContext): Promise {} + public async afterTransactionsExecute( + _context: StateMachine.BlockAfterExecuteContext, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): Promise {} } diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/counter.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/counter.ts index 254e4976b68..4386e6f7a72 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/counter.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/counter.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BaseStore } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; export interface CounterStoreData { counter: number; @@ -31,6 +31,6 @@ export const counterStoreSchema = { }, }; -export class CounterStore extends BaseStore { +export class CounterStore extends Modules.BaseStore { public schema = counterStoreSchema; } diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/message.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/message.ts index 55e6af81051..e85679307ef 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/message.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/message.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BaseStore } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; export interface MessageStoreData { message: string; @@ -29,6 +29,6 @@ export const messageStoreSchema = { }, }; -export class MessageStore extends BaseStore { +export class MessageStore extends Modules.BaseStore { public schema = messageStoreSchema; } diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/reaction.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/reaction.ts index caac621fcc1..4180bc8da69 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/reaction.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/stores/reaction.ts @@ -1,4 +1,4 @@ -import { BaseStore } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; export interface ReactionStoreData { reactions: { @@ -27,6 +27,6 @@ export const reactionStoreSchema = { }, }; -export class ReactionStore extends BaseStore { +export class ReactionStore extends Modules.BaseStore { public schema = reactionStoreSchema; } diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/types.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/types.ts index 20b25cc1ba6..dc88f262ca7 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/types.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/types.ts @@ -1,4 +1,4 @@ -import { JSONObject } from 'lisk-sdk'; +import { Types } from 'lisk-sdk'; export interface ModuleConfig { maxMessageLength: number; @@ -6,7 +6,7 @@ export interface ModuleConfig { blacklist: string[]; } -export type ModuleConfigJSON = JSONObject; +export type ModuleConfigJSON = Types.JSONObject; export interface CreateHelloParams { message: string; diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/destroy_nft.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/destroy_nft.ts index 822ad1b174f..50e2c25f122 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/destroy_nft.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/destroy_nft.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCommand, CommandExecuteContext, NFTMethod } from 'lisk-sdk'; +import { StateMachine, Modules } from 'lisk-sdk'; import { destroyNftParamsSchema } from '../schema'; interface Params { @@ -20,15 +20,15 @@ interface Params { nftID: Buffer; } -export class DestroyNftCommand extends BaseCommand { - private _nftMethod!: NFTMethod; +export class DestroyNftCommand extends Modules.BaseCommand { + private _nftMethod!: Modules.NFT.NFTMethod; public schema = destroyNftParamsSchema; - public init(args: { nftMethod: NFTMethod }): void { + public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { const { params } = context; await this._nftMethod.destroy(context.getMethodContext(), params.address, params.nftID); diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/mint_nft.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/mint_nft.ts index bc5638846d4..fdc1133e233 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/mint_nft.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/mint_nft.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCommand, CommandExecuteContext, NFTMethod } from 'lisk-sdk'; +import { Modules, StateMachine } from 'lisk-sdk'; import { NFTAttributes } from '../types'; import { mintNftParamsSchema } from '../schema'; @@ -22,15 +22,15 @@ interface Params { attributesArray: NFTAttributes[]; } -export class MintNftCommand extends BaseCommand { - private _nftMethod!: NFTMethod; +export class MintNftCommand extends Modules.BaseCommand { + private _nftMethod!: Modules.NFT.NFTMethod; public schema = mintNftParamsSchema; - public init(args: { nftMethod: NFTMethod }): void { + public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { const { params } = context; await this._nftMethod.create( diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/endpoint.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/endpoint.ts index 1d091013741..5a94633bbfc 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/endpoint.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/endpoint.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseEndpoint } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class TestNftEndpoint extends BaseEndpoint {} +export class TestNftEndpoint extends Modules.BaseEndpoint {} diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/method.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/method.ts index 5bab789e7f1..23f005c5f71 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/method.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/method.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class TestNftMethod extends BaseMethod {} +export class TestNftMethod extends Modules.BaseMethod {} diff --git a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/module.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/module.ts index a228abff3af..3c9506c7930 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/module.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/module.ts @@ -12,26 +12,26 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseModule, ModuleInitArgs, ModuleMetadata, NFTMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; import { TestNftEndpoint } from './endpoint'; import { TestNftMethod } from './method'; import { MintNftCommand } from './commands/mint_nft'; import { DestroyNftCommand } from './commands/destroy_nft'; -export class TestNftModule extends BaseModule { +export class TestNftModule extends Modules.BaseModule { public endpoint = new TestNftEndpoint(this.stores, this.offchainStores); public method = new TestNftMethod(this.stores, this.events); public mintNftCommand = new MintNftCommand(this.stores, this.events); public destroyNftCommand = new DestroyNftCommand(this.stores, this.events); public commands = [this.mintNftCommand, this.destroyNftCommand]; - private _nftMethod!: NFTMethod; + private _nftMethod!: Modules.NFT.NFTMethod; - public addDependencies(nftMethod: NFTMethod) { + public addDependencies(nftMethod: Modules.NFT.NFTMethod) { this._nftMethod = nftMethod; } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { return { ...this.baseMetadata(), endpoints: [], @@ -45,7 +45,7 @@ export class TestNftModule extends BaseModule { } // eslint-disable-next-line @typescript-eslint/require-await - public async init(_args: ModuleInitArgs) { + public async init(_args: Modules.ModuleInitArgs) { this.mintNftCommand.init({ nftMethod: this._nftMethod, }); diff --git a/examples/interop/pos-sidechain-example-one/src/commands/genesis-block/create.ts b/examples/interop/pos-sidechain-example-one/src/commands/genesis-block/create.ts index ad2d13f7575..84c6244b5f1 100644 --- a/examples/interop/pos-sidechain-example-one/src/commands/genesis-block/create.ts +++ b/examples/interop/pos-sidechain-example-one/src/commands/genesis-block/create.ts @@ -1,10 +1,10 @@ import { BaseGenesisBlockCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { join } from 'path'; import { getApplication } from '../../app/app'; export class GenesisBlockCommand extends BaseGenesisBlockCommand { - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-sidechain-example-one/src/commands/start.ts b/examples/interop/pos-sidechain-example-one/src/commands/start.ts index 362671e0137..72661f6c6f5 100644 --- a/examples/interop/pos-sidechain-example-one/src/commands/start.ts +++ b/examples/interop/pos-sidechain-example-one/src/commands/start.ts @@ -5,7 +5,7 @@ import { Flags as flagParser } from '@oclif/core'; import { FlagInput } from '@oclif/core/lib/interfaces'; import { BaseStartCommand } from 'lisk-commander'; -import { Application, ApplicationConfig, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { ForgerPlugin } from '@liskhq/lisk-framework-forger-plugin'; import { MonitorPlugin } from '@liskhq/lisk-framework-monitor-plugin'; import { ReportMisbehaviorPlugin } from '@liskhq/lisk-framework-report-misbehavior-plugin'; @@ -19,7 +19,7 @@ interface Flags { [key: string]: string | number | boolean | undefined; } -const setPluginConfig = (config: ApplicationConfig, flags: Flags): void => { +const setPluginConfig = (config: Types.ApplicationConfig, flags: Flags): void => { if (flags['monitor-plugin-port'] !== undefined) { config.plugins[MonitorPlugin.name] = config.plugins[MonitorPlugin.name] ?? {}; config.plugins[MonitorPlugin.name].port = flags['monitor-plugin-port']; @@ -111,11 +111,11 @@ export class StartCommand extends BaseStartCommand { }), }; - public async getApplication(config: PartialApplicationConfig): Promise { + public async getApplication(config: Types.PartialApplicationConfig): Promise { /* eslint-disable @typescript-eslint/no-unsafe-call */ const { flags } = await this.parse(StartCommand); // Set Plugins Config - setPluginConfig(config as ApplicationConfig, flags); + setPluginConfig(config as Types.ApplicationConfig, flags); const app = getApplication(config); if (flags['enable-forger-plugin']) { diff --git a/examples/interop/pos-sidechain-example-one/src/commands/transaction/create.ts b/examples/interop/pos-sidechain-example-one/src/commands/transaction/create.ts index 4c7cbb76768..cf60661f9ff 100644 --- a/examples/interop/pos-sidechain-example-one/src/commands/transaction/create.ts +++ b/examples/interop/pos-sidechain-example-one/src/commands/transaction/create.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionCreateCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type CreateFlags = typeof TransactionCreateCommand.flags & { @@ -15,7 +15,7 @@ export class CreateCommand extends TransactionCreateCommand { static args = [...TransactionCreateCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-sidechain-example-one/src/commands/transaction/sign.ts b/examples/interop/pos-sidechain-example-one/src/commands/transaction/sign.ts index b55093102a7..139ed5ad7e9 100644 --- a/examples/interop/pos-sidechain-example-one/src/commands/transaction/sign.ts +++ b/examples/interop/pos-sidechain-example-one/src/commands/transaction/sign.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionSignCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type SignFlags = typeof TransactionSignCommand.flags & { [key: string]: Record }; @@ -13,7 +13,7 @@ export class SignCommand extends TransactionSignCommand { static args = [...TransactionSignCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-sidechain-example-two/src/app/app.ts b/examples/interop/pos-sidechain-example-two/src/app/app.ts index 62a607b9357..ad80fe3e252 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/app.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/app.ts @@ -1,9 +1,9 @@ -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { registerModules } from './modules'; import { registerPlugins } from './plugins'; import { ReactModule } from './modules/react/module'; -export const getApplication = (config: PartialApplicationConfig): Application => { +export const getApplication = (config: Types.PartialApplicationConfig): Application => { const { app, method } = Application.defaultApplication(config); const reactModule = new ReactModule(); app.registerModule(reactModule); diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/cc_method.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/cc_method.ts index b7a881b33db..c082e3085f3 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/cc_method.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/cc_method.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCCMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class ReactInteroperableMethod extends BaseCCMethod {} +export class ReactInteroperableMethod extends Modules.Interoperability.BaseCCMethod {} diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_cc_command.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_cc_command.ts index 08c178ed89c..22b66d09f5e 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_cc_command.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_cc_command.ts @@ -1,18 +1,11 @@ /* eslint-disable class-methods-use-this */ -import { - BaseCommand, - CommandVerifyContext, - CommandExecuteContext, - VerificationResult, - VerifyStatus, - codec, -} from 'lisk-sdk'; +import { Modules, StateMachine, codec } from 'lisk-sdk'; import { CROSS_CHAIN_COMMAND_REACT } from '../constants'; import { CCReactCommandParamsSchema, CCReactMessageParamsSchema } from '../schemas'; import { CCReactMessageParams, CCReactCommandParams, InteroperabilityMethod } from '../types'; -export class CrossChainReactCommand extends BaseCommand { +export class CrossChainReactCommand extends Modules.BaseCommand { private _interoperabilityMethod!: InteroperabilityMethod; public schema = CCReactCommandParamsSchema; @@ -26,8 +19,8 @@ export class CrossChainReactCommand extends BaseCommand { // eslint-disable-next-line @typescript-eslint/require-await public async verify( - context: CommandVerifyContext, - ): Promise { + context: StateMachine.CommandVerifyContext, + ): Promise { const { params, logger } = context; logger.info('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'); @@ -40,17 +33,19 @@ export class CrossChainReactCommand extends BaseCommand { } } catch (err) { return { - status: VerifyStatus.FAIL, + status: StateMachine.VerifyStatus.FAIL, error: err as Error, }; } return { - status: VerifyStatus.OK, + status: StateMachine.VerifyStatus.OK, }; } - public async execute(context: CommandExecuteContext): Promise { + public async execute( + context: StateMachine.CommandExecuteContext, + ): Promise { const { params, transaction: { senderAddress }, diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/endpoint.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/endpoint.ts index 160b0b59d92..daebf72e0f1 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/endpoint.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/endpoint.ts @@ -1,3 +1,3 @@ -import { BaseEndpoint } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class ReactEndpoint extends BaseEndpoint {} +export class ReactEndpoint extends Modules.BaseEndpoint {} diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/method.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/method.ts index 69f80f11e97..2f5518cf7e5 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/method.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/method.ts @@ -1,3 +1,3 @@ -import { BaseMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class ReactMethod extends BaseMethod {} +export class ReactMethod extends Modules.BaseMethod {} diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/module.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/module.ts index 4e30f4d5213..ee0ce575c5b 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/module.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/module.ts @@ -1,14 +1,14 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/member-ordering */ -import { BaseInteroperableModule, ModuleMetadata, ModuleInitArgs } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; import { CrossChainReactCommand } from './commands/react_cc_command'; import { ReactEndpoint } from './endpoint'; import { ReactMethod } from './method'; import { ReactInteroperableMethod } from './cc_method'; import { InteroperabilityMethod } from './types'; -export class ReactModule extends BaseInteroperableModule { +export class ReactModule extends Modules.Interoperability.BaseInteroperableModule { public endpoint = new ReactEndpoint(this.stores, this.offchainStores); public method = new ReactMethod(this.stores, this.events); public commands = [new CrossChainReactCommand(this.stores, this.events)]; @@ -21,7 +21,7 @@ export class ReactModule extends BaseInteroperableModule { this.stores.register(ReactionStore, new ReactionStore(this.name, 0)); } */ - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { return { ...this.baseMetadata(), endpoints: [], @@ -39,7 +39,7 @@ export class ReactModule extends BaseInteroperableModule { // Lifecycle hooks // eslint-disable-next-line @typescript-eslint/require-await - public async init(_args: ModuleInitArgs) { + public async init(_args: Modules.ModuleInitArgs) { this.commands[0].init({ interoperabilityMethod: this._interoperabilityMethod, }); diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/types.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/types.ts index cead8f9b88f..f201df69256 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/types.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/types.ts @@ -1,10 +1,4 @@ -import { - MethodContext, - ImmutableMethodContext, - CCMsg, - ChannelData, - OwnChainAccount, -} from 'lisk-sdk'; +import { StateMachine, Modules } from 'lisk-sdk'; export type TokenID = Buffer; // Parameters of the reactCrossChain CCM @@ -26,9 +20,11 @@ export interface CCReactCommandParams extends CCReactMessageParams { } export interface InteroperabilityMethod { - getOwnChainAccount(methodContext: ImmutableMethodContext): Promise; + getOwnChainAccount( + methodContext: StateMachine.ImmutableMethodContext, + ): Promise; send( - methodContext: MethodContext, + methodContext: StateMachine.MethodContext, feeAddress: Buffer, module: string, crossChainCommand: string, @@ -37,9 +33,22 @@ export interface InteroperabilityMethod { parameters: Buffer, timestamp?: number, ): Promise; - error(methodContext: MethodContext, ccm: CCMsg, code: number): Promise; - terminateChain(methodContext: MethodContext, chainID: Buffer): Promise; - getChannel(methodContext: MethodContext, chainID: Buffer): Promise; - getMessageFeeTokenID(methodContext: ImmutableMethodContext, chainID: Buffer): Promise; - getMessageFeeTokenIDFromCCM(methodContext: ImmutableMethodContext, ccm: CCMsg): Promise; + error( + methodContext: StateMachine.MethodContext, + ccm: Modules.Interoperability.CCMsg, + code: number, + ): Promise; + terminateChain(methodContext: StateMachine.MethodContext, chainID: Buffer): Promise; + getChannel( + methodContext: StateMachine.MethodContext, + chainID: Buffer, + ): Promise; + getMessageFeeTokenID( + methodContext: StateMachine.ImmutableMethodContext, + chainID: Buffer, + ): Promise; + getMessageFeeTokenIDFromCCM( + methodContext: StateMachine.ImmutableMethodContext, + ccm: Modules.Interoperability.CCMsg, + ): Promise; } diff --git a/examples/interop/pos-sidechain-example-two/src/commands/genesis-block/create.ts b/examples/interop/pos-sidechain-example-two/src/commands/genesis-block/create.ts index ad2d13f7575..84c6244b5f1 100644 --- a/examples/interop/pos-sidechain-example-two/src/commands/genesis-block/create.ts +++ b/examples/interop/pos-sidechain-example-two/src/commands/genesis-block/create.ts @@ -1,10 +1,10 @@ import { BaseGenesisBlockCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { join } from 'path'; import { getApplication } from '../../app/app'; export class GenesisBlockCommand extends BaseGenesisBlockCommand { - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-sidechain-example-two/src/commands/start.ts b/examples/interop/pos-sidechain-example-two/src/commands/start.ts index 362671e0137..72661f6c6f5 100644 --- a/examples/interop/pos-sidechain-example-two/src/commands/start.ts +++ b/examples/interop/pos-sidechain-example-two/src/commands/start.ts @@ -5,7 +5,7 @@ import { Flags as flagParser } from '@oclif/core'; import { FlagInput } from '@oclif/core/lib/interfaces'; import { BaseStartCommand } from 'lisk-commander'; -import { Application, ApplicationConfig, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { ForgerPlugin } from '@liskhq/lisk-framework-forger-plugin'; import { MonitorPlugin } from '@liskhq/lisk-framework-monitor-plugin'; import { ReportMisbehaviorPlugin } from '@liskhq/lisk-framework-report-misbehavior-plugin'; @@ -19,7 +19,7 @@ interface Flags { [key: string]: string | number | boolean | undefined; } -const setPluginConfig = (config: ApplicationConfig, flags: Flags): void => { +const setPluginConfig = (config: Types.ApplicationConfig, flags: Flags): void => { if (flags['monitor-plugin-port'] !== undefined) { config.plugins[MonitorPlugin.name] = config.plugins[MonitorPlugin.name] ?? {}; config.plugins[MonitorPlugin.name].port = flags['monitor-plugin-port']; @@ -111,11 +111,11 @@ export class StartCommand extends BaseStartCommand { }), }; - public async getApplication(config: PartialApplicationConfig): Promise { + public async getApplication(config: Types.PartialApplicationConfig): Promise { /* eslint-disable @typescript-eslint/no-unsafe-call */ const { flags } = await this.parse(StartCommand); // Set Plugins Config - setPluginConfig(config as ApplicationConfig, flags); + setPluginConfig(config as Types.ApplicationConfig, flags); const app = getApplication(config); if (flags['enable-forger-plugin']) { diff --git a/examples/interop/pos-sidechain-example-two/src/commands/transaction/create.ts b/examples/interop/pos-sidechain-example-two/src/commands/transaction/create.ts index 4c7cbb76768..cf60661f9ff 100644 --- a/examples/interop/pos-sidechain-example-two/src/commands/transaction/create.ts +++ b/examples/interop/pos-sidechain-example-two/src/commands/transaction/create.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionCreateCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type CreateFlags = typeof TransactionCreateCommand.flags & { @@ -15,7 +15,7 @@ export class CreateCommand extends TransactionCreateCommand { static args = [...TransactionCreateCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/interop/pos-sidechain-example-two/src/commands/transaction/sign.ts b/examples/interop/pos-sidechain-example-two/src/commands/transaction/sign.ts index b55093102a7..139ed5ad7e9 100644 --- a/examples/interop/pos-sidechain-example-two/src/commands/transaction/sign.ts +++ b/examples/interop/pos-sidechain-example-two/src/commands/transaction/sign.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionSignCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type SignFlags = typeof TransactionSignCommand.flags & { [key: string]: Record }; @@ -13,7 +13,7 @@ export class SignCommand extends TransactionSignCommand { static args = [...TransactionSignCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/poa-sidechain/src/app/app.ts b/examples/poa-sidechain/src/app/app.ts index 42f6724245f..651062468bb 100644 --- a/examples/poa-sidechain/src/app/app.ts +++ b/examples/poa-sidechain/src/app/app.ts @@ -1,8 +1,8 @@ -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { registerModules } from './modules'; import { registerPlugins } from './plugins'; -export const getApplication = (config: PartialApplicationConfig): Application => { +export const getApplication = (config: Types.PartialApplicationConfig): Application => { const app = registerModules(config); registerPlugins(app); diff --git a/examples/poa-sidechain/src/app/modules.ts b/examples/poa-sidechain/src/app/modules.ts index bc8306a7c45..8ea8c37d18f 100644 --- a/examples/poa-sidechain/src/app/modules.ts +++ b/examples/poa-sidechain/src/app/modules.ts @@ -1,27 +1,16 @@ -import { - Application, - AuthModule, - FeeModule, - PartialApplicationConfig, - PoAModule, - RandomModule, - RewardModule, - SidechainInteroperabilityModule, - TokenModule, - ValidatorsModule, -} from 'lisk-sdk'; +import { Application, Modules, Types } from 'lisk-sdk'; -export const registerModules = (config: PartialApplicationConfig): Application => { +export const registerModules = (config: Types.PartialApplicationConfig): Application => { const application = new Application(config); // create module instances - const authModule = new AuthModule(); - const tokenModule = new TokenModule(); - const feeModule = new FeeModule(); - const rewardModule = new RewardModule(); - const randomModule = new RandomModule(); - const validatorModule = new ValidatorsModule(); - const poaModule = new PoAModule(); - const interoperabilityModule = new SidechainInteroperabilityModule(); + const authModule = new Modules.Auth.AuthModule(); + const tokenModule = new Modules.Token.TokenModule(); + const feeModule = new Modules.Fee.FeeModule(); + const rewardModule = new Modules.Reward.RewardModule(); + const randomModule = new Modules.Random.RandomModule(); + const validatorModule = new Modules.Validators.ValidatorsModule(); + const poaModule = new Modules.PoA.PoAModule(); + const interoperabilityModule = new Modules.Interoperability.SidechainInteroperabilityModule(); interoperabilityModule.addDependencies(validatorModule.method, tokenModule.method); rewardModule.addDependencies(tokenModule.method, randomModule.method); diff --git a/examples/poa-sidechain/src/commands/genesis-block/create.ts b/examples/poa-sidechain/src/commands/genesis-block/create.ts index ad2d13f7575..84c6244b5f1 100644 --- a/examples/poa-sidechain/src/commands/genesis-block/create.ts +++ b/examples/poa-sidechain/src/commands/genesis-block/create.ts @@ -1,10 +1,10 @@ import { BaseGenesisBlockCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { join } from 'path'; import { getApplication } from '../../app/app'; export class GenesisBlockCommand extends BaseGenesisBlockCommand { - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/poa-sidechain/src/commands/start.ts b/examples/poa-sidechain/src/commands/start.ts index 0aefab8d5d3..cb50e242a7a 100644 --- a/examples/poa-sidechain/src/commands/start.ts +++ b/examples/poa-sidechain/src/commands/start.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { Flags as flagParser } from '@oclif/core'; import { BaseStartCommand } from 'lisk-commander'; -import { Application, ApplicationConfig, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { ForgerPlugin } from '@liskhq/lisk-framework-forger-plugin'; import { MonitorPlugin } from '@liskhq/lisk-framework-monitor-plugin'; import { ReportMisbehaviorPlugin } from '@liskhq/lisk-framework-report-misbehavior-plugin'; @@ -18,7 +18,7 @@ interface Flags { [key: string]: string | number | boolean | undefined; } -const setPluginConfig = (config: ApplicationConfig, flags: Flags): void => { +const setPluginConfig = (config: Types.ApplicationConfig, flags: Flags): void => { if (flags['monitor-plugin-port'] !== undefined) { config.plugins[MonitorPlugin.name] = config.plugins[MonitorPlugin.name] ?? {}; config.plugins[MonitorPlugin.name].port = flags['monitor-plugin-port']; @@ -101,11 +101,11 @@ export class StartCommand extends BaseStartCommand { }), }; - public async getApplication(config: PartialApplicationConfig): Promise { + public async getApplication(config: Types.PartialApplicationConfig): Promise { /* eslint-disable @typescript-eslint/no-unsafe-call */ const { flags } = await this.parse(StartCommand); // Set Plugins Config - setPluginConfig(config as ApplicationConfig, flags); + setPluginConfig(config as Types.ApplicationConfig, flags); const app = getApplication(config); if (flags['enable-forger-plugin']) { diff --git a/examples/poa-sidechain/src/commands/transaction/create.ts b/examples/poa-sidechain/src/commands/transaction/create.ts index 4c7cbb76768..cf60661f9ff 100644 --- a/examples/poa-sidechain/src/commands/transaction/create.ts +++ b/examples/poa-sidechain/src/commands/transaction/create.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionCreateCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type CreateFlags = typeof TransactionCreateCommand.flags & { @@ -15,7 +15,7 @@ export class CreateCommand extends TransactionCreateCommand { static args = [...TransactionCreateCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/poa-sidechain/src/commands/transaction/sign.ts b/examples/poa-sidechain/src/commands/transaction/sign.ts index b55093102a7..139ed5ad7e9 100644 --- a/examples/poa-sidechain/src/commands/transaction/sign.ts +++ b/examples/poa-sidechain/src/commands/transaction/sign.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionSignCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type SignFlags = typeof TransactionSignCommand.flags & { [key: string]: Record }; @@ -13,7 +13,7 @@ export class SignCommand extends TransactionSignCommand { static args = [...TransactionSignCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/pos-mainchain/src/app/app.ts b/examples/pos-mainchain/src/app/app.ts index 6a99bf61049..dbf6225dca7 100644 --- a/examples/pos-mainchain/src/app/app.ts +++ b/examples/pos-mainchain/src/app/app.ts @@ -1,9 +1,9 @@ -import { Application, PartialApplicationConfig, NFTModule } from 'lisk-sdk'; +import { Application, Types, Modules } from 'lisk-sdk'; import { TestNftModule } from './modules/testNft/module'; -export const getApplication = (config: PartialApplicationConfig): Application => { +export const getApplication = (config: Types.PartialApplicationConfig): Application => { const { app, method } = Application.defaultApplication(config, true); - const nftModule = new NFTModule(); + const nftModule = new Modules.NFT.NFTModule(); const testNftModule = new TestNftModule(); const interoperabilityModule = app['_registeredModules'].find( mod => mod.name === 'interoperability', diff --git a/examples/pos-mainchain/src/app/modules/testNft/commands/destroy_nft.ts b/examples/pos-mainchain/src/app/modules/testNft/commands/destroy_nft.ts index 822ad1b174f..50e2c25f122 100644 --- a/examples/pos-mainchain/src/app/modules/testNft/commands/destroy_nft.ts +++ b/examples/pos-mainchain/src/app/modules/testNft/commands/destroy_nft.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCommand, CommandExecuteContext, NFTMethod } from 'lisk-sdk'; +import { StateMachine, Modules } from 'lisk-sdk'; import { destroyNftParamsSchema } from '../schema'; interface Params { @@ -20,15 +20,15 @@ interface Params { nftID: Buffer; } -export class DestroyNftCommand extends BaseCommand { - private _nftMethod!: NFTMethod; +export class DestroyNftCommand extends Modules.BaseCommand { + private _nftMethod!: Modules.NFT.NFTMethod; public schema = destroyNftParamsSchema; - public init(args: { nftMethod: NFTMethod }): void { + public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { const { params } = context; await this._nftMethod.destroy(context.getMethodContext(), params.address, params.nftID); diff --git a/examples/pos-mainchain/src/app/modules/testNft/commands/mint_nft.ts b/examples/pos-mainchain/src/app/modules/testNft/commands/mint_nft.ts index bc5638846d4..fdc1133e233 100644 --- a/examples/pos-mainchain/src/app/modules/testNft/commands/mint_nft.ts +++ b/examples/pos-mainchain/src/app/modules/testNft/commands/mint_nft.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseCommand, CommandExecuteContext, NFTMethod } from 'lisk-sdk'; +import { Modules, StateMachine } from 'lisk-sdk'; import { NFTAttributes } from '../types'; import { mintNftParamsSchema } from '../schema'; @@ -22,15 +22,15 @@ interface Params { attributesArray: NFTAttributes[]; } -export class MintNftCommand extends BaseCommand { - private _nftMethod!: NFTMethod; +export class MintNftCommand extends Modules.BaseCommand { + private _nftMethod!: Modules.NFT.NFTMethod; public schema = mintNftParamsSchema; - public init(args: { nftMethod: NFTMethod }): void { + public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } - public async execute(context: CommandExecuteContext): Promise { + public async execute(context: StateMachine.CommandExecuteContext): Promise { const { params } = context; await this._nftMethod.create( diff --git a/examples/pos-mainchain/src/app/modules/testNft/endpoint.ts b/examples/pos-mainchain/src/app/modules/testNft/endpoint.ts index 1d091013741..5a94633bbfc 100644 --- a/examples/pos-mainchain/src/app/modules/testNft/endpoint.ts +++ b/examples/pos-mainchain/src/app/modules/testNft/endpoint.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseEndpoint } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class TestNftEndpoint extends BaseEndpoint {} +export class TestNftEndpoint extends Modules.BaseEndpoint {} diff --git a/examples/pos-mainchain/src/app/modules/testNft/method.ts b/examples/pos-mainchain/src/app/modules/testNft/method.ts index 5bab789e7f1..23f005c5f71 100644 --- a/examples/pos-mainchain/src/app/modules/testNft/method.ts +++ b/examples/pos-mainchain/src/app/modules/testNft/method.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export class TestNftMethod extends BaseMethod {} +export class TestNftMethod extends Modules.BaseMethod {} diff --git a/examples/pos-mainchain/src/app/modules/testNft/module.ts b/examples/pos-mainchain/src/app/modules/testNft/module.ts index a228abff3af..3c9506c7930 100644 --- a/examples/pos-mainchain/src/app/modules/testNft/module.ts +++ b/examples/pos-mainchain/src/app/modules/testNft/module.ts @@ -12,26 +12,26 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseModule, ModuleInitArgs, ModuleMetadata, NFTMethod } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; import { TestNftEndpoint } from './endpoint'; import { TestNftMethod } from './method'; import { MintNftCommand } from './commands/mint_nft'; import { DestroyNftCommand } from './commands/destroy_nft'; -export class TestNftModule extends BaseModule { +export class TestNftModule extends Modules.BaseModule { public endpoint = new TestNftEndpoint(this.stores, this.offchainStores); public method = new TestNftMethod(this.stores, this.events); public mintNftCommand = new MintNftCommand(this.stores, this.events); public destroyNftCommand = new DestroyNftCommand(this.stores, this.events); public commands = [this.mintNftCommand, this.destroyNftCommand]; - private _nftMethod!: NFTMethod; + private _nftMethod!: Modules.NFT.NFTMethod; - public addDependencies(nftMethod: NFTMethod) { + public addDependencies(nftMethod: Modules.NFT.NFTMethod) { this._nftMethod = nftMethod; } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { return { ...this.baseMetadata(), endpoints: [], @@ -45,7 +45,7 @@ export class TestNftModule extends BaseModule { } // eslint-disable-next-line @typescript-eslint/require-await - public async init(_args: ModuleInitArgs) { + public async init(_args: Modules.ModuleInitArgs) { this.mintNftCommand.init({ nftMethod: this._nftMethod, }); diff --git a/examples/pos-mainchain/src/commands/genesis-block/create.ts b/examples/pos-mainchain/src/commands/genesis-block/create.ts index ad2d13f7575..84c6244b5f1 100644 --- a/examples/pos-mainchain/src/commands/genesis-block/create.ts +++ b/examples/pos-mainchain/src/commands/genesis-block/create.ts @@ -1,10 +1,10 @@ import { BaseGenesisBlockCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { join } from 'path'; import { getApplication } from '../../app/app'; export class GenesisBlockCommand extends BaseGenesisBlockCommand { - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/pos-mainchain/src/commands/start.ts b/examples/pos-mainchain/src/commands/start.ts index 64455c30aab..ed650075ad3 100644 --- a/examples/pos-mainchain/src/commands/start.ts +++ b/examples/pos-mainchain/src/commands/start.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { Flags as flagParser } from '@oclif/core'; import { BaseStartCommand } from 'lisk-commander'; -import { Application, ApplicationConfig, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { ForgerPlugin } from '@liskhq/lisk-framework-forger-plugin'; import { MonitorPlugin } from '@liskhq/lisk-framework-monitor-plugin'; import { ReportMisbehaviorPlugin } from '@liskhq/lisk-framework-report-misbehavior-plugin'; @@ -17,7 +17,7 @@ interface Flags { [key: string]: string | number | boolean | undefined; } -const setPluginConfig = (config: ApplicationConfig, flags: Flags): void => { +const setPluginConfig = (config: Types.ApplicationConfig, flags: Flags): void => { if (flags['monitor-plugin-port'] !== undefined) { config.plugins[MonitorPlugin.name] = config.plugins[MonitorPlugin.name] ?? {}; config.plugins[MonitorPlugin.name].port = flags['monitor-plugin-port']; @@ -100,11 +100,11 @@ export class StartCommand extends BaseStartCommand { }), }; - public async getApplication(config: PartialApplicationConfig): Promise { + public async getApplication(config: Types.PartialApplicationConfig): Promise { /* eslint-disable @typescript-eslint/no-unsafe-call */ const { flags } = await this.parse(StartCommand); // Set Plugins Config - setPluginConfig(config as ApplicationConfig, flags); + setPluginConfig(config as Types.ApplicationConfig, flags); const app = getApplication(config); if (flags['enable-forger-plugin']) { diff --git a/examples/pos-mainchain/src/commands/transaction/create.ts b/examples/pos-mainchain/src/commands/transaction/create.ts index 4c7cbb76768..cf60661f9ff 100644 --- a/examples/pos-mainchain/src/commands/transaction/create.ts +++ b/examples/pos-mainchain/src/commands/transaction/create.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionCreateCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type CreateFlags = typeof TransactionCreateCommand.flags & { @@ -15,7 +15,7 @@ export class CreateCommand extends TransactionCreateCommand { static args = [...TransactionCreateCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/examples/pos-mainchain/src/commands/transaction/sign.ts b/examples/pos-mainchain/src/commands/transaction/sign.ts index b55093102a7..139ed5ad7e9 100644 --- a/examples/pos-mainchain/src/commands/transaction/sign.ts +++ b/examples/pos-mainchain/src/commands/transaction/sign.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { TransactionSignCommand } from 'lisk-commander'; -import { Application, PartialApplicationConfig } from 'lisk-sdk'; +import { Application, Types } from 'lisk-sdk'; import { getApplication } from '../../app/app'; type SignFlags = typeof TransactionSignCommand.flags & { [key: string]: Record }; @@ -13,7 +13,7 @@ export class SignCommand extends TransactionSignCommand { static args = [...TransactionSignCommand.args]; - public getApplication(config: PartialApplicationConfig): Application { + public getApplication(config: Types.PartialApplicationConfig): Application { const app = getApplication(config); return app; } diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/active_validators_update.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/active_validators_update.ts index 4bf2e7f5b7a..ab01f9f3d77 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/active_validators_update.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/active_validators_update.ts @@ -12,23 +12,20 @@ * Removal or modification of this copyright notice is prohibited. */ /* eslint-disable no-bitwise */ -import { - ActiveValidator, - Certificate, - LastCertificate, - utils, - ActiveValidatorsUpdate, -} from 'lisk-sdk'; +import { Modules, utils, Engine } from 'lisk-sdk'; import { ValidatorsData } from './types'; /** * @see https://github.com/LiskHQ/lips/blob/main/proposals/lip-0053.md#computing-the-validators-update */ export const calculateActiveValidatorsUpdate = ( - certificate: Certificate, + certificate: Engine.Certificate, validatorsHashPreimage: ValidatorsData[], - lastCertificate: LastCertificate, -): { activeValidatorsUpdate: ActiveValidatorsUpdate; certificateThreshold: bigint } => { + lastCertificate: Modules.Interoperability.LastCertificate, +): { + activeValidatorsUpdate: Modules.Interoperability.ActiveValidatorsUpdate; + certificateThreshold: bigint; +} => { let certificateThreshold; const validatorDataAtCertificate = validatorsHashPreimage.find(validatorsData => validatorsData.validatorsHash.equals(certificate.validatorsHash), @@ -68,17 +65,18 @@ export const calculateActiveValidatorsUpdate = ( * @see https://github.com/LiskHQ/lips/blob/main/proposals/lip-0053.md#computing-the-validators-update */ export const getActiveValidatorsUpdate = ( - currentValidators: ActiveValidator[], - newValidators: ActiveValidator[], -): ActiveValidatorsUpdate => { - const currentValidatorsMap = new utils.dataStructures.BufferMap(); + currentValidators: Modules.Interoperability.ActiveValidator[], + newValidators: Modules.Interoperability.ActiveValidator[], +): Modules.Interoperability.ActiveValidatorsUpdate => { + const currentValidatorsMap = + new utils.dataStructures.BufferMap(); const allBLSKeysSet = new utils.dataStructures.BufferSet(); for (const v of currentValidators) { currentValidatorsMap.set(v.blsKey, v); allBLSKeysSet.add(v.blsKey); } - const validatorsUpdate: ActiveValidator[] = []; + const validatorsUpdate: Modules.Interoperability.ActiveValidator[] = []; const blsKeysUpdate: Buffer[] = []; const newBLSKeys = new utils.dataStructures.BufferSet(); for (const v of newValidators) { diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/certificate_generation.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/certificate_generation.ts index da342b1a535..3eacb3cc1ba 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/certificate_generation.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/certificate_generation.ts @@ -12,23 +12,16 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - AggregateCommit, - BFTHeights, - Certificate, - chain, - computeUnsignedCertificateFromBlockHeader, - LastCertificate, -} from 'lisk-sdk'; +import { Engine, chain, Modules } from 'lisk-sdk'; import { BlockHeader, ValidatorsData } from './types'; /** * @see https://github.com/LiskHQ/lips/blob/main/proposals/lip-0061.md#getcertificatefromaggregatecommit */ export const getCertificateFromAggregateCommit = ( - aggregateCommit: AggregateCommit, + aggregateCommit: Engine.AggregateCommit, blockHeaders: BlockHeader[], -): Certificate => { +): Engine.Certificate => { const blockHeader = blockHeaders.find(header => header.height === aggregateCommit.height); if (!blockHeader) { @@ -38,7 +31,7 @@ export const getCertificateFromAggregateCommit = ( } return { - ...computeUnsignedCertificateFromBlockHeader(new chain.BlockHeader(blockHeader)), + ...Engine.computeUnsignedCertificateFromBlockHeader(new chain.BlockHeader(blockHeader)), aggregationBits: aggregateCommit.aggregationBits, signature: aggregateCommit.certificateSignature, }; @@ -51,7 +44,7 @@ export const checkChainOfTrust = ( lastValidatorsHash: Buffer, blsKeyToBFTWeight: Record, lastCertificateThreshold: bigint, - aggregateCommit: AggregateCommit, + aggregateCommit: Engine.AggregateCommit, blockHeaders: BlockHeader[], validatorsHashPreimage: ValidatorsData[], ): boolean => { @@ -101,11 +94,11 @@ export const checkChainOfTrust = ( */ export const getNextCertificateFromAggregateCommits = ( blockHeaders: BlockHeader[], - aggregateCommits: AggregateCommit[], + aggregateCommits: Engine.AggregateCommit[], validatorsHashPreimage: ValidatorsData[], - bftHeights: BFTHeights, - lastCertificate: LastCertificate, -): Certificate | undefined => { + bftHeights: Engine.BFTHeights, + lastCertificate: Modules.Interoperability.LastCertificate, +): Engine.Certificate | undefined => { const blockHeaderAtLastCertifiedHeight = blockHeaders.find( header => header.height === lastCertificate.height, ); diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/chain_connector_plugin.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/chain_connector_plugin.ts index 03d548f4c2c..cf5f37d62bc 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/chain_connector_plugin.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/chain_connector_plugin.ts @@ -13,30 +13,17 @@ */ import { - BasePlugin, - PluginInitContext, + Engine, + Plugins, apiClient, - BFTHeights, db as liskDB, codec, chain, - OutboxRootWitness, - JSONObject, + Modules, + Types, Schema, Transaction, - LastCertificate, - CcmSendSuccessEventData, - CcmProcessedEventData, - CCMProcessedResult, - CrossChainUpdateTransactionParams, - certificateSchema, - ccuParamsSchema, cryptography, - ChainAccountJSON, - ActiveValidatorsUpdate, - AggregateCommit, - ChannelDataJSON, - Certificate, transactions, } from 'lisk-sdk'; import { calculateActiveValidatorsUpdate } from './active_validators_update'; @@ -93,13 +80,13 @@ type ModulesMetadata = [ type FinalizedHeightInfo = { inboxSize: number; lastCertificateHeight: number }; -export class ChainConnectorPlugin extends BasePlugin { +export class ChainConnectorPlugin extends Plugins.BasePlugin { public endpoint = new Endpoint(); public configSchema = configSchema; private _chainConnectorPluginDB!: liskDB.Database; private _chainConnectorStore!: ChainConnectorStore; - private _lastCertificate!: LastCertificate; + private _lastCertificate!: Modules.Interoperability.LastCertificate; private _ccuFrequency!: number; private _maxCCUSize!: number; private _isSaveCCU!: boolean; @@ -118,7 +105,7 @@ export class ChainConnectorPlugin extends BasePlugin } // eslint-disable-next-line @typescript-eslint/require-await - public async init(context: PluginInitContext): Promise { + public async init(context: Plugins.PluginInitContext): Promise { await super.init(context); this._ccuFrequency = this.config.ccuFrequency ?? CCU_FREQUENCY; if (this.config.maxCCUSize > CCU_TOTAL_CCM_SIZE) { @@ -189,9 +176,13 @@ export class ChainConnectorPlugin extends BasePlugin } const ccuFee = BigInt(this.config.ccuFee ?? '0') + additionalFee; - const computedMinFee = transactions.computeMinFee(tx, ccuParamsSchema, { - additionalFee, - }); + const computedMinFee = transactions.computeMinFee( + tx, + Modules.Interoperability.ccuParamsSchema, + { + additionalFee, + }, + ); if (ccuFee > computedMinFee) { return ccuFee; @@ -205,17 +196,19 @@ export class ChainConnectorPlugin extends BasePlugin finalizedHeight: number; }>('system_getNodeInfo'); this._receivingChainFinalizedHeight = finalizedHeight; - const { inbox } = await this._receivingChainClient.invoke( - 'interoperability_getChannel', - { chainID: this._ownChainID.toString('hex') }, - ); + const { inbox } = + await this._receivingChainClient.invoke( + 'interoperability_getChannel', + { chainID: this._ownChainID.toString('hex') }, + ); if (!inbox) { throw new Error('No channel data available on receiving chain.'); } - const { lastCertificate } = await this._receivingChainClient.invoke( - 'interoperability_getChainAccount', - { chainID: this._ownChainID.toString('hex') }, - ); + const { lastCertificate } = + await this._receivingChainClient.invoke( + 'interoperability_getChainAccount', + { chainID: this._ownChainID.toString('hex') }, + ); if (!lastCertificate) { throw new Error('No chain data available on receiving chain.'); } @@ -244,16 +237,17 @@ export class ChainConnectorPlugin extends BasePlugin const { blockHeader: receivedBlock } = data as unknown as Data; const newBlockHeader = chain.BlockHeader.fromJSON(receivedBlock).toObject(); - let chainAccountJSON: ChainAccountJSON; + let chainAccountJSON: Modules.Interoperability.ChainAccountJSON; // Save blockHeader, aggregateCommit, validatorsData and cross chain messages if any. try { const nodeInfo = await this._sendingChainClient.node.getNodeInfo(); // Fetch last certificate from the receiving chain and update the _lastCertificate try { - chainAccountJSON = await this._receivingChainClient.invoke( - 'interoperability_getChainAccount', - { chainID: this._ownChainID.toString('hex') }, - ); + chainAccountJSON = + await this._receivingChainClient.invoke( + 'interoperability_getChainAccount', + { chainID: this._ownChainID.toString('hex') }, + ); // If sending chain is not registered with the receiving chain then only save data on new block and exit if (!chainAccountJSON || (chainAccountJSON && !chainAccountJSON.lastCertificate)) { this.logger.info( @@ -331,12 +325,12 @@ export class ChainConnectorPlugin extends BasePlugin private async _computeCCUParams( blockHeaders: BlockHeader[], - aggregateCommits: AggregateCommit[], + aggregateCommits: Engine.AggregateCommit[], validatorsHashPreimage: ValidatorsData[], ccmsFromEvents: CCMsFromEvents[], ): Promise< | { - ccuParams: CrossChainUpdateTransactionParams; + ccuParams: Modules.Interoperability.CrossChainUpdateTransactionParams; lastCCMToBeSent: LastSentCCMWithHeight | undefined; } | undefined @@ -360,7 +354,7 @@ export class ChainConnectorPlugin extends BasePlugin height: this._lastCertificate.height, }; - let activeValidatorsUpdate: ActiveValidatorsUpdate = { + let activeValidatorsUpdate: Modules.Interoperability.ActiveValidatorsUpdate = { blsKeysUpdate: [], bftWeightsUpdate: [], bftWeightsUpdateBitmap: EMPTY_BYTES, @@ -377,20 +371,22 @@ export class ChainConnectorPlugin extends BasePlugin record.height <= (newCertificate ? newCertificate.height : this._lastCertificate.height), ); // Calculate messageWitnessHashes for pending CCMs if any - const channelDataOnReceivingChain = await this._receivingChainClient.invoke( - 'interoperability_getChannel', - { chainID: this._ownChainID.toString('hex') }, - ); + const channelDataOnReceivingChain = + await this._receivingChainClient.invoke( + 'interoperability_getChannel', + { chainID: this._ownChainID.toString('hex') }, + ); if (!channelDataOnReceivingChain?.inbox) { this.logger.info('Receiving chain is not registered yet on the sending chain.'); return; } const inboxSizeOnReceivingChain = channelDataJSONToObj(channelDataOnReceivingChain).inbox.size; - const receivingChainChannelDataJSON = await this._sendingChainClient.invoke( - 'interoperability_getChannel', - { chainID: this._receivingChainID.toString('hex') }, - ); + const receivingChainChannelDataJSON = + await this._sendingChainClient.invoke( + 'interoperability_getChannel', + { chainID: this._receivingChainID.toString('hex') }, + ); if (!receivingChainChannelDataJSON?.outbox) { this.logger.info('Sending chain is not registered yet on the receiving chain.'); @@ -465,7 +461,7 @@ export class ChainConnectorPlugin extends BasePlugin outboxRootWitness = ccmsDataAtCertificateHeight?.inclusionProof; } - certificate = codec.encode(certificateSchema, newCertificate); + certificate = codec.encode(Engine.certificateSchema, newCertificate); } // eslint-disable-next-line consistent-return @@ -480,16 +476,16 @@ export class ChainConnectorPlugin extends BasePlugin messageWitnessHashes, outboxRootWitness, }, - } as CrossChainUpdateTransactionParams, + } as Modules.Interoperability.CrossChainUpdateTransactionParams, lastCCMToBeSent, }; } private async _findNextCertificate( - aggregateCommits: AggregateCommit[], + aggregateCommits: Engine.AggregateCommit[], blockHeaders: BlockHeader[], validatorsHashPreimage: ValidatorsData[], - ): Promise { + ): Promise { if (aggregateCommits.length === 0) { return undefined; } @@ -512,7 +508,9 @@ export class ChainConnectorPlugin extends BasePlugin return undefined; } - const bftHeights = await this._sendingChainClient.invoke('consensus_getBFTHeights'); + const bftHeights = await this._sendingChainClient.invoke( + 'consensus_getBFTHeights', + ); // Calculate certificate return getNextCertificateFromAggregateCommits( blockHeaders, @@ -540,7 +538,7 @@ export class ChainConnectorPlugin extends BasePlugin } // Check for events if any and store them - const events = await this._sendingChainClient.invoke>( + const events = await this._sendingChainClient.invoke>( 'chain_getEvents', { height: newBlockHeader.height }, ); @@ -586,7 +584,7 @@ export class ChainConnectorPlugin extends BasePlugin } for (const e of ccmSendSuccessEvents) { - const eventData = codec.decode( + const eventData = codec.decode( ccmSendSuccessEventInfo[0].data, Buffer.from(e.data, 'hex'), ); @@ -604,11 +602,11 @@ export class ChainConnectorPlugin extends BasePlugin } for (const e of ccmProcessedEvents) { - const eventData = codec.decode( + const eventData = codec.decode( ccmProcessedEventInfo[0].data, Buffer.from(e.data, 'hex'), ); - if (eventData.result === CCMProcessedResult.FORWARDED) { + if (eventData.result === Modules.Interoperability.CCMProcessedResult.FORWARDED) { ccmsFromEvents.push(eventData.ccm); } } @@ -632,17 +630,18 @@ export class ChainConnectorPlugin extends BasePlugin }, ); const proveResponseObj = proveResponseJSONToObj(proveResponseJSON); - const outboxRootWitness: OutboxRootWitness = { + const outboxRootWitness: Modules.Interoperability.OutboxRootWitness = { bitmap: proveResponseObj.proof.queries[0].bitmap, siblingHashes: proveResponseObj.proof.siblingHashes, }; const crossChainMessages = await this._chainConnectorStore.getCrossChainMessages(); let receivingChainOutboxSize = 0; try { - const receivingChainChannelDataJSON = await this._sendingChainClient.invoke( - 'interoperability_getChannel', - { chainID: this._receivingChainID.toString('hex') }, - ); + const receivingChainChannelDataJSON = + await this._sendingChainClient.invoke( + 'interoperability_getChannel', + { chainID: this._receivingChainID.toString('hex') }, + ); receivingChainOutboxSize = receivingChainChannelDataJSON.outbox.size; } catch (error) { this.logger.debug( @@ -844,7 +843,9 @@ export class ChainConnectorPlugin extends BasePlugin } } - private async _submitCCU(ccuParams: CrossChainUpdateTransactionParams): Promise { + private async _submitCCU( + ccuParams: Modules.Interoperability.CrossChainUpdateTransactionParams, + ): Promise { if (!this._chainConnectorStore.privateKey) { throw new Error('There is no key enabled to submit CCU'); } @@ -870,7 +871,7 @@ export class ChainConnectorPlugin extends BasePlugin command: targetCommand, nonce: BigInt(nonce), senderPublicKey: relayerPublicKey, - params: codec.encode(ccuParamsSchema, ccuParams), + params: codec.encode(Modules.Interoperability.ccuParamsSchema, ccuParams), signatures: [], }; diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/constants.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/constants.ts index a95cc836e1b..ddc44ff2754 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/constants.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/constants.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { MAX_CCM_SIZE } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; // LIP: https://github.com/LiskHQ/lips/blob/main/proposals/lip-0045.md#liveness-condition export const CCU_FREQUENCY = 1; // At each block @@ -46,4 +46,4 @@ export const DB_KEY_LIST_OF_CCU = Buffer.from([6]); * Max size of total CCMs that can be included in a CCU * CCU_TOTAL_CCM_SIZE */ -export const CCU_TOTAL_CCM_SIZE = MAX_CCM_SIZE; +export const CCU_TOTAL_CCM_SIZE = Modules.Interoperability.MAX_CCM_SIZE; diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/db.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/db.ts index 9c65068b077..2095731f236 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/db.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/db.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { codec, db as liskDB, AggregateCommit, chain, cryptography } from 'lisk-sdk'; +import { codec, db as liskDB, Engine, chain, cryptography } from 'lisk-sdk'; import * as os from 'os'; import { join } from 'path'; import { ensureDir } from 'fs-extra'; @@ -42,7 +42,7 @@ interface BlockHeadersInfo { } interface AggregateCommitsInfo { - aggregateCommits: AggregateCommit[]; + aggregateCommits: Engine.AggregateCommit[]; } interface ValidatorsHashPreimage { @@ -105,8 +105,8 @@ export class ChainConnectorStore { await this._db.set(DB_KEY_BLOCK_HEADERS, encodedInfo); } - public async getAggregateCommits(): Promise { - let aggregateCommits: AggregateCommit[] = []; + public async getAggregateCommits(): Promise { + let aggregateCommits: Engine.AggregateCommit[] = []; try { const encodedInfo = await this._db.get(DB_KEY_AGGREGATE_COMMITS); aggregateCommits = codec.decode( @@ -119,7 +119,7 @@ export class ChainConnectorStore { return aggregateCommits; } - public async setAggregateCommits(aggregateCommits: AggregateCommit[]) { + public async setAggregateCommits(aggregateCommits: Engine.AggregateCommit[]) { const encodedInfo = codec.encode(aggregateCommitsInfoSchema, { aggregateCommits }); await this._db.set(DB_KEY_AGGREGATE_COMMITS, encodedInfo); } diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/endpoint.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/endpoint.ts index 3aaf8b36455..ee0029d4496 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/endpoint.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/endpoint.ts @@ -12,14 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - BasePluginEndpoint, - PluginEndpointContext, - chain, - BlockHeader, - BlockHeaderJSON, - validator as liskValidator, -} from 'lisk-sdk'; +import { Plugins, Types, chain, BlockHeaderJSON, validator as liskValidator } from 'lisk-sdk'; import { ChainConnectorStore } from './db'; import { AggregateCommitJSON, @@ -36,7 +29,7 @@ import { authorizeRequestSchema } from './schemas'; // eslint-disable-next-line prefer-destructuring const validator: liskValidator.LiskValidator = liskValidator.validator; -export class Endpoint extends BasePluginEndpoint { +export class Endpoint extends Plugins.BasePluginEndpoint { private _chainConnectorStore!: ChainConnectorStore; private _config!: ChainConnectorPluginConfig; @@ -46,26 +39,26 @@ export class Endpoint extends BasePluginEndpoint { } // eslint-disable-next-line @typescript-eslint/require-await - public async getSentCCUs(_context: PluginEndpointContext): Promise { + public async getSentCCUs(_context: Types.PluginEndpointContext): Promise { const sentCCUs = await this._chainConnectorStore.getListOfCCUs(); return sentCCUs.map(transaction => new chain.Transaction(transaction).toJSON()); } public async getAggregateCommits( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { const aggregateCommits = await this._chainConnectorStore.getAggregateCommits(); return aggregateCommits.map(aggregateCommit => aggregateCommitToJSON(aggregateCommit)); } - public async getBlockHeaders(_context: PluginEndpointContext): Promise { + public async getBlockHeaders(_context: Types.PluginEndpointContext): Promise { const blockHeaders = await this._chainConnectorStore.getBlockHeaders(); - return blockHeaders.map(blockHeader => new BlockHeader(blockHeader).toJSON()); + return blockHeaders.map(blockHeader => new chain.BlockHeader(blockHeader).toJSON()); } public async getCrossChainMessages( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { const ccmsAndInclusionProofs = await this._chainConnectorStore.getCrossChainMessages(); return ccmsAndInclusionProofs.map(ccmsAndInclusionProof => @@ -73,7 +66,9 @@ export class Endpoint extends BasePluginEndpoint { ); } - public async getLastSentCCM(_context: PluginEndpointContext): Promise { + public async getLastSentCCM( + _context: Types.PluginEndpointContext, + ): Promise { const lastSentCCM = await this._chainConnectorStore.getLastSentCCM(); if (!lastSentCCM) { throw new Error('No CCM was sent so far.'); @@ -90,14 +85,14 @@ export class Endpoint extends BasePluginEndpoint { } public async getValidatorsInfoFromPreimage( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { const validatorsHashPreimage = await this._chainConnectorStore.getValidatorsHashPreimage(); return validatorsHashPreimagetoJSON(validatorsHashPreimage); } // eslint-disable-next-line @typescript-eslint/require-await - public async authorize(context: PluginEndpointContext): Promise<{ result: string }> { + public async authorize(context: Types.PluginEndpointContext): Promise<{ result: string }> { validator.validate<{ enable: boolean; password: string }>( authorizeRequestSchema, context.params, diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/inbox_update.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/inbox_update.ts index b01d920e742..da2c528ba1c 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/inbox_update.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/inbox_update.ts @@ -12,16 +12,16 @@ * Removal or modification of this copyright notice is prohibited. */ -import { ccmSchema, codec, tree } from 'lisk-sdk'; +import { Modules, codec, tree } from 'lisk-sdk'; import { CCMsFromEvents, LastSentCCMWithHeight } from './types'; /** * @see https://github.com/LiskHQ/lips/blob/main/proposals/lip-0053.md#messagewitnesshashes - * + * * Calculates messageWitnessHashes if there are any pending ccms as well as it filters out ccms * based on last sent ccm nonce. * Also, it checks whether a list of ccm can fit into a CCU based on maxCCUSize - * + * * @param sendingChainChannelInfo Channel info of the sendingChain stored on receivingChain * @param ccmsToBeIncluded Filtered list of CCMs that can be included for a given certificate * @param lastSentCCMInfo Last send CCM info which is used to filter out ccms @@ -60,7 +60,7 @@ export const calculateMessageWitnesses = ( } } if (inboxSizeOnReceivingChain < outboxSizeOnSendingChain) { - const ccmBytes = codec.encode(ccmSchema, ccm); + const ccmBytes = codec.encode(Modules.Interoperability.ccmSchema, ccm); totalSize += ccmBytes.length; if (totalSize < maxCCUSize) { includedSerializedCCMs.push(ccmBytes); diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/schemas.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/schemas.ts index b3c4418830a..36bcef071ad 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/schemas.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/schemas.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { chain, aggregateCommitSchema, ccmSchema } from 'lisk-sdk'; +import { chain, Engine, Modules } from 'lisk-sdk'; import { CCU_FREQUENCY, CCU_TOTAL_CCM_SIZE, @@ -129,7 +129,7 @@ export const aggregateCommitsInfoSchema = { type: 'array', fieldNumber: 1, items: { - ...aggregateCommitSchema, + ...Engine.aggregateCommitSchema, }, }, }, @@ -152,10 +152,13 @@ export const validatorsHashPreimageInfoSchema = { export const lastSentCCMWithHeight = { $id: `${pluginSchemaIDPrefix}/lastSentCCMWithHeight`, type: 'object', - required: [...ccmSchema.required, 'height'], + required: [...Modules.Interoperability.ccmSchema.required, 'height'], properties: { - ...ccmSchema.properties, - height: { dataType: 'uint32', fieldNumber: Object.keys(ccmSchema.properties).length + 1 }, + ...Modules.Interoperability.ccmSchema.properties, + height: { + dataType: 'uint32', + fieldNumber: Object.keys(Modules.Interoperability.ccmSchema.properties).length + 1, + }, }, }; @@ -188,7 +191,7 @@ export const ccmsFromEventsSchema = { type: 'array', fieldNumber: 1, items: { - ...ccmSchema, + ...Modules.Interoperability.ccmSchema, }, }, height: { dataType: 'uint32', fieldNumber: 2 }, diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/types.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/types.ts index a8ac15541c3..dc2580306d6 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/types.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/types.ts @@ -12,18 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - Transaction, - chain, - CCMsg, - OutboxRootWitness, - ActiveValidator, - AggregateCommit, - BFTParameters, - Proof, - ProveResponse, - BFTValidator, -} from 'lisk-sdk'; +import { Transaction, chain, Modules, Engine, Proof, ProveResponse, BFTValidator } from 'lisk-sdk'; export interface BlockHeader extends chain.BlockHeaderAttrs { validatorsHash: Buffer; @@ -45,7 +34,7 @@ export interface ChainConnectorPluginConfig { export type SentCCUs = Transaction[]; export type SentCCUsJSON = chain.TransactionJSON[]; -export interface ActiveValidatorWithAddress extends ActiveValidator { +export interface ActiveValidatorWithAddress extends Modules.Interoperability.ActiveValidator { address: Buffer; } @@ -55,14 +44,14 @@ export interface ValidatorsData { validatorsHash: Buffer; } -export interface LastSentCCMWithHeight extends CCMsg { +export interface LastSentCCMWithHeight extends Modules.Interoperability.CCMsg { height: number; } export interface CCMsFromEvents { - ccms: CCMsg[]; + ccms: Modules.Interoperability.CCMsg[]; height: number; - inclusionProof: OutboxRootWitness; + inclusionProof: Modules.Interoperability.OutboxRootWitness; outboxSize: number; } @@ -81,7 +70,7 @@ export type CCMsFromEventsJSON = JSONObject; export type LastSentCCMWithHeightJSON = JSONObject; -export type AggregateCommitJSON = JSONObject; +export type AggregateCommitJSON = JSONObject; export type BFTValidatorJSON = JSONObject; @@ -91,4 +80,4 @@ export type ProofJSON = JSONObject; export type ProveResponseJSON = JSONObject; -export type BFTParametersJSON = JSONObject; +export type BFTParametersJSON = JSONObject; diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/src/utils.ts b/framework-plugins/lisk-framework-chain-connector-plugin/src/utils.ts index 40b44c4db10..6b6c91c5c03 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/utils.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/utils.ts @@ -12,19 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - AggregateCommit, - ChainAccount, - ChainAccountJSON, - ChannelData, - ChannelDataJSON, - Inbox, - InboxJSON, - Outbox, - OutboxJSON, - BFTParameters, - ProveResponse, -} from 'lisk-sdk'; +import { Engine, Modules, ProveResponse } from 'lisk-sdk'; import { BFTParametersJSON, @@ -36,7 +24,7 @@ import { import { CHAIN_ID_LENGTH } from './constants'; -interface BFTParametersWithoutGeneratorKey extends Omit { +interface BFTParametersWithoutGeneratorKey extends Omit { validators: { address: Buffer; bftWeight: bigint; @@ -56,7 +44,7 @@ export const getTokenIDLSK = (chainID: Buffer): Buffer => { return Buffer.concat([networkID, Buffer.alloc(7, 0)]); }; -export const aggregateCommitToJSON = (aggregateCommit: AggregateCommit) => ({ +export const aggregateCommitToJSON = (aggregateCommit: Engine.AggregateCommit) => ({ height: aggregateCommit.height, aggregationBits: aggregateCommit.aggregationBits.toString('hex'), certificateSignature: aggregateCommit.certificateSignature.toString('hex'), @@ -96,16 +84,16 @@ export const validatorsHashPreimagetoJSON = (validatorsHashPreimage: ValidatorsD return validatorsHashPreimageJSON; }; -export const channelDataToJSON = (channelData: ChannelData) => { +export const channelDataToJSON = (channelData: Modules.Interoperability.ChannelData) => { const { inbox, messageFeeTokenID, outbox, partnerChainOutboxRoot, minReturnFeePerByte } = channelData; - const inboxJSON: InboxJSON = { + const inboxJSON: Modules.Interoperability.InboxJSON = { appendPath: inbox.appendPath.map(ap => ap.toString('hex')), root: inbox.root.toString('hex'), size: inbox.size, }; - const outboxJSON: OutboxJSON = { + const outboxJSON: Modules.Interoperability.OutboxJSON = { appendPath: outbox.appendPath.map(ap => ap.toString('hex')), root: outbox.root.toString('hex'), size: outbox.size, @@ -120,17 +108,19 @@ export const channelDataToJSON = (channelData: ChannelData) => { }; }; -export const channelDataJSONToObj = (channelData: ChannelDataJSON): ChannelData => { +export const channelDataJSONToObj = ( + channelData: Modules.Interoperability.ChannelDataJSON, +): Modules.Interoperability.ChannelData => { const { inbox, messageFeeTokenID, outbox, partnerChainOutboxRoot, minReturnFeePerByte } = channelData; - const inboxJSON: Inbox = { + const inboxJSON: Modules.Interoperability.Inbox = { appendPath: inbox.appendPath.map(ap => Buffer.from(ap, 'hex')), root: Buffer.from(inbox.root, 'hex'), size: inbox.size, }; - const outboxJSON: Outbox = { + const outboxJSON: Modules.Interoperability.Outbox = { appendPath: outbox.appendPath.map(ap => Buffer.from(ap, 'hex')), root: Buffer.from(outbox.root, 'hex'), size: outbox.size, @@ -145,7 +135,9 @@ export const channelDataJSONToObj = (channelData: ChannelDataJSON): ChannelData }; }; -export const chainAccountDataJSONToObj = (chainAccountJSON: ChainAccountJSON): ChainAccount => { +export const chainAccountDataJSONToObj = ( + chainAccountJSON: Modules.Interoperability.ChainAccountJSON, +): Modules.Interoperability.ChainAccount => { const { lastCertificate } = chainAccountJSON; return { ...chainAccountJSON, diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/certificate_generation.spec.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/certificate_generation.spec.ts index 60c6f7ec4a9..f38e528071e 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/certificate_generation.spec.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/certificate_generation.spec.ts @@ -12,13 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - BFTHeights, - chain, - computeUnsignedCertificateFromBlockHeader, - cryptography, - testing, -} from 'lisk-sdk'; +import { chain, Engine, cryptography, testing } from 'lisk-sdk'; import { checkChainOfTrust, getCertificateFromAggregateCommit, @@ -103,7 +97,7 @@ describe('certificate generation', () => { validatorsHash: cryptography.utils.getRandomBytes(HASH_LENGTH), }; - const bftHeights: BFTHeights = { + const bftHeights: Engine.BFTHeights = { maxHeightPrevoted: 5, maxHeightPrecommitted: 5, maxHeightCertified: 3, @@ -123,7 +117,7 @@ describe('certificate generation', () => { const firstBlockHeader = sampleBlockHeaders[0]; const { aggregateCommit } = firstBlockHeader; - const unsignedCertificate = computeUnsignedCertificateFromBlockHeader( + const unsignedCertificate = Engine.computeUnsignedCertificateFromBlockHeader( new chain.BlockHeader(firstBlockHeader), ); const expectedCertificate = { @@ -275,7 +269,7 @@ describe('certificate generation', () => { it('should return a valid certificate passing chainOfTrust check', () => { const secondBlockHeader = sampleBlockHeaders[1]; - const unsignedCertificate = computeUnsignedCertificateFromBlockHeader( + const unsignedCertificate = Engine.computeUnsignedCertificateFromBlockHeader( new chain.BlockHeader(secondBlockHeader), ); const expectedCertificate = { diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/db.spec.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/db.spec.ts index 38dea0d0b15..43f2925370f 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/db.spec.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/db.spec.ts @@ -12,16 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - AggregateCommit, - db, - testing, - cryptography, - chain, - SubmitMainchainCrossChainUpdateCommand, - CROSS_CHAIN_COMMAND_NAME_TRANSFER, - MODULE_NAME_INTEROPERABILITY, -} from 'lisk-sdk'; +import { Engine, db, testing, cryptography, chain, Modules } from 'lisk-sdk'; import * as fs from 'fs-extra'; import { homedir } from 'os'; import { join } from 'path'; @@ -99,7 +90,7 @@ describe('Plugins DB', () => { }); describe('aggregateCommits', () => { - let sampleAggregateCommits: AggregateCommit[]; + let sampleAggregateCommits: Engine.AggregateCommit[]; beforeEach(() => { sampleAggregateCommits = [ @@ -240,7 +231,7 @@ describe('Plugins DB', () => { beforeEach(() => { sampleLastSentCCM = { - crossChainCommand: CROSS_CHAIN_COMMAND_NAME_TRANSFER, + crossChainCommand: Modules.Token.CROSS_CHAIN_COMMAND_NAME_TRANSFER, fee: BigInt(1000), height: 1, module: 'token', @@ -270,8 +261,8 @@ describe('Plugins DB', () => { listOfCCUs = [ testing .createTransaction({ - commandClass: SubmitMainchainCrossChainUpdateCommand as any, - module: MODULE_NAME_INTEROPERABILITY, + commandClass: Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand as any, + module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, params: { activeValidatorsUpdate: { blsKeysUpdate: [], @@ -295,8 +286,8 @@ describe('Plugins DB', () => { .toObject(), testing .createTransaction({ - commandClass: SubmitMainchainCrossChainUpdateCommand as any, - module: MODULE_NAME_INTEROPERABILITY, + commandClass: Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand as any, + module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, params: { activeValidatorsUpdate: { blsKeysUpdate: [], diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/endpoint.spec.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/endpoint.spec.ts index b918a9d387d..0e5d7676843 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/endpoint.spec.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/endpoint.spec.ts @@ -14,14 +14,7 @@ import { removeSync } from 'fs-extra'; import { when } from 'jest-when'; -import { - ApplicationConfigForPlugin, - GenesisConfig, - testing, - cryptography, - apiClient, - db, -} from 'lisk-sdk'; +import { Types, testing, cryptography, apiClient, db } from 'lisk-sdk'; import { ChainConnectorPlugin } from '../../src/chain_connector_plugin'; import * as chainConnectorDB from '../../src/db'; import { CCMsFromEvents, CCMsFromEventsJSON, LastSentCCMWithHeightJSON } from '../../src/types'; @@ -29,11 +22,11 @@ import { ccmsFromEventsToJSON, getMainchainID } from '../../src/utils'; describe('endpoints', () => { const ownChainID = Buffer.from('10000000', 'hex'); - const appConfigForPlugin: ApplicationConfigForPlugin = { + const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, genesis: { chainID: ownChainID.toString('hex'), - } as GenesisConfig, + } as Types.GenesisConfig, generator: { keys: { fromFile: '', diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/inbox_update.spec.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/inbox_update.spec.ts index 4e68cead9a9..1b75727cd04 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/inbox_update.spec.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/inbox_update.spec.ts @@ -12,14 +12,14 @@ * Removal or modification of this copyright notice is prohibited. */ -import { CCMsg, tree } from 'lisk-sdk'; +import { Modules, tree } from 'lisk-sdk'; import { CCU_TOTAL_CCM_SIZE } from '../../src/constants'; import { CCMsFromEvents } from '../../src/types'; import { calculateMessageWitnesses } from '../../src/inbox_update'; import { getSampleCCM } from '../utils/sampleCCM'; describe('inboxUpdate', () => { - let sampleCCMs: CCMsg[]; + let sampleCCMs: Modules.Interoperability.CCMsg[]; let sampleCCMsFromEvents: CCMsFromEvents[]; beforeEach(() => { diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/plugin.spec.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/plugin.spec.ts index 3c592feeaea..75ceec21b95 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/plugin.spec.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/plugin.spec.ts @@ -16,22 +16,15 @@ import { cryptography, testing, apiClient, - ApplicationConfigForPlugin, + Types, codec, db, Block, - AggregateCommit, chain, - ccmSchema, - ChannelDataJSON, - CCMsg, - certificateSchema, + Modules, + Engine, tree, - CrossChainUpdateTransactionParams, - Certificate, - BFTHeights, transactions, - ccuParamsSchema, } from 'lisk-sdk'; import { when } from 'jest-when'; import { @@ -63,7 +56,7 @@ import { getSampleCCU } from '../utils/sampleCCU'; describe('ChainConnectorPlugin', () => { const BLS_SIGNATURE_LENGTH = 96; const ownChainID = Buffer.from('04000000', 'hex'); - const appConfigForPlugin: ApplicationConfigForPlugin = { + const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, genesis: { chainID: ownChainID.toString('hex'), @@ -90,10 +83,10 @@ describe('ChainConnectorPlugin', () => { properties: { ccm: { fieldNumber: 1, - type: ccmSchema.type, - required: [...ccmSchema.required], + type: Modules.Interoperability.ccmSchema.type, + required: [...Modules.Interoperability.ccmSchema.required], properties: { - ...ccmSchema.properties, + ...Modules.Interoperability.ccmSchema.properties, }, }, }, @@ -106,10 +99,10 @@ describe('ChainConnectorPlugin', () => { properties: { ccm: { fieldNumber: 1, - type: ccmSchema.type, - required: [...ccmSchema.required], + type: Modules.Interoperability.ccmSchema.type, + required: [...Modules.Interoperability.ccmSchema.required], properties: { - ...ccmSchema.properties, + ...Modules.Interoperability.ccmSchema.properties, }, }, result: { @@ -154,7 +147,7 @@ describe('ChainConnectorPlugin', () => { '6c5e2b24ff1cc99da7a49bd28420b93b2a91e2e2a3b0a0ce07676966b707d3c2859bbd02747cf8e26dab592c02155dfddd4a16b0fe83fd7e7ffaec0b5391f3f7'; const defaultPassword = '123'; const defaultCCUFee = '500000'; - const sampleCCUParams: CrossChainUpdateTransactionParams = { + const sampleCCUParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { sendingChainID: Buffer.from('04000001', 'hex'), activeValidatorsUpdate: { bftWeightsUpdate: [], @@ -199,7 +192,7 @@ describe('ChainConnectorPlugin', () => { let defaultEncryptedPrivateKey: string; let defaultConfig: ChainConnectorPluginConfig & Record; - let sampleBFTHeights: BFTHeights; + let sampleBFTHeights: Engine.BFTHeights; beforeEach(async () => { sampleBFTHeights = { @@ -467,7 +460,7 @@ describe('ChainConnectorPlugin', () => { let height = 0; return new Array(count).fill(0).map(() => { height += 1; - const aggregateCommit: AggregateCommit = { + const aggregateCommit: Engine.AggregateCommit = { height, aggregationBits: Buffer.from('00', 'hex'), certificateSignature: Buffer.alloc(0), @@ -571,7 +564,7 @@ describe('ChainConnectorPlugin', () => { describe('_newBlockHandler', () => { let block: Block; - let sampleNextCertificate: Certificate; + let sampleNextCertificate: Engine.Certificate; beforeEach(async () => { block = await testing.createBlock({ @@ -1078,9 +1071,13 @@ describe('ChainConnectorPlugin', () => { }); await expect(chainConnectorPlugin['_getCcuFee'](transactionTemplate)).resolves.toBe( - transactions.computeMinFee(transactionTemplate, ccuParamsSchema, { - additionalFee: initializationFees.userAccount, - }), + transactions.computeMinFee( + transactionTemplate, + Modules.Interoperability.ccuParamsSchema, + { + additionalFee: initializationFees.userAccount, + }, + ), ); }); }); @@ -1108,7 +1105,7 @@ describe('ChainConnectorPlugin', () => { }); await expect(chainConnectorPlugin['_getCcuFee'](transactionTemplate)).resolves.toBe( - transactions.computeMinFee(transactionTemplate, ccuParamsSchema), + transactions.computeMinFee(transactionTemplate, Modules.Interoperability.ccuParamsSchema), ); }); }); @@ -1116,9 +1113,9 @@ describe('ChainConnectorPlugin', () => { describe('_computeCCUParams', () => { let sampleCCMsWithEvents: CCMsFromEvents[]; let sampleBlockHeaders: BlockHeader[]; - let sampleAggregateCommits: AggregateCommit[]; + let sampleAggregateCommits: Engine.AggregateCommit[]; let sampleValidatorsHashPreimage: ValidatorsData[]; - let sampleChannelDataJSON: ChannelDataJSON; + let sampleChannelDataJSON: Modules.Interoperability.ChannelDataJSON; beforeEach(async () => { sampleBlockHeaders = new Array(10).fill(0).map((_, index) => { @@ -1341,14 +1338,14 @@ describe('ChainConnectorPlugin', () => { const lastSentCCMsFromEvents = sampleCCMsWithEvents[5]; const expectedCCMsToBeSent = sampleCCMsWithEvents .slice(5, 7) - .reduce((ccms: CCMsg[], record: CCMsFromEvents) => { + .reduce((ccms: Modules.Interoperability.CCMsg[], record: CCMsFromEvents) => { for (const ccm of record.ccms) { ccms.push(ccm); } return ccms; }, []) - .map(ccm => codec.encode(ccmSchema, ccm)); + .map(ccm => codec.encode(Modules.Interoperability.ccmSchema, ccm)); await chainConnectorPlugin['_chainConnectorStore'].setLastSentCCM({ ...lastSentCCMsFromEvents.ccms[0], height: lastSentCCMsFromEvents.height, @@ -1500,7 +1497,7 @@ describe('ChainConnectorPlugin', () => { validatorsData[0].certificateThreshold, ); expect(result?.ccuParams.certificate).toEqual( - codec.encode(certificateSchema, newCertificate), + codec.encode(Engine.certificateSchema, newCertificate), ); expect(result?.ccuParams.inboxUpdate.crossChainMessages).toEqual([]); expect(result?.ccuParams.inboxUpdate.messageWitnessHashes).toEqual([]); @@ -1580,7 +1577,7 @@ describe('ChainConnectorPlugin', () => { validatorsUpdateResult.certificateThreshold, ); expect(result?.ccuParams.certificate).toEqual( - codec.encode(certificateSchema, newCertificate), + codec.encode(Engine.certificateSchema, newCertificate), ); expect(result?.ccuParams.inboxUpdate.crossChainMessages.length).toEqual( @@ -1681,7 +1678,7 @@ describe('ChainConnectorPlugin', () => { validatorsUpdateResult.certificateThreshold, ); expect(result?.ccuParams.certificate).toEqual( - codec.encode(certificateSchema, newCertificate), + codec.encode(Engine.certificateSchema, newCertificate), ); expect(result?.ccuParams.inboxUpdate.crossChainMessages.length).toEqual( sampleCCMsWithEvents.slice(5, 8).length, @@ -1773,7 +1770,7 @@ describe('ChainConnectorPlugin', () => { validatorsUpdateResult.certificateThreshold, ); expect(result?.ccuParams.certificate).toEqual( - codec.encode(certificateSchema, newCertificate), + codec.encode(Engine.certificateSchema, newCertificate), ); expect(result?.ccuParams.inboxUpdate.crossChainMessages).toEqual([]); expect(result?.ccuParams.inboxUpdate.messageWitnessHashes).toEqual([]); diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/utils.spec.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/utils.spec.ts index 4e18d347c14..48e0e5e9660 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/utils.spec.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/unit/utils.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BLS_SIGNATURE_LENGTH, cryptography } from 'lisk-sdk'; +import { Modules, cryptography } from 'lisk-sdk'; import * as utils from '../../src/active_validators_update'; import { calculateActiveValidatorsUpdate, @@ -29,7 +29,7 @@ describe('calculateActiveValidatorsUpdate', () => { aggregationBits: Buffer.alloc(1), blockID: cryptography.utils.getRandomBytes(HASH_LENGTH), height: 10, - signature: cryptography.utils.getRandomBytes(BLS_SIGNATURE_LENGTH), + signature: cryptography.utils.getRandomBytes(Modules.Interoperability.BLS_SIGNATURE_LENGTH), stateRoot: cryptography.utils.getRandomBytes(HASH_LENGTH), timestamp: Date.now(), validatorsHash: certificateValidatorsHash, diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCM.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCM.ts index 57f369a4c4d..b1bb8fdf198 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCM.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCM.ts @@ -12,13 +12,16 @@ * Removal or modification of this copyright notice is prohibited. */ -import { CCMsg, MODULE_NAME_INTEROPERABILITY, CROSS_CHAIN_COMMAND_NAME_TRANSFER } from 'lisk-sdk'; +import { Modules } from 'lisk-sdk'; -export const getSampleCCM = (nonce = 1, ccmSizeInBytes?: number): CCMsg => { +export const getSampleCCM = ( + nonce = 1, + ccmSizeInBytes?: number, +): Modules.Interoperability.CCMsg => { return { nonce: BigInt(nonce), - module: MODULE_NAME_INTEROPERABILITY, - crossChainCommand: CROSS_CHAIN_COMMAND_NAME_TRANSFER, + module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, + crossChainCommand: Modules.Token.CROSS_CHAIN_COMMAND_NAME_TRANSFER, sendingChainID: Buffer.from([0, 0, 0, 3]), receivingChainID: Buffer.from('04000000', 'hex'), fee: BigInt(nonce), diff --git a/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCU.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCU.ts index cae194ca490..2a09991acea 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCU.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCU.ts @@ -12,17 +12,13 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - testing, - SubmitMainchainCrossChainUpdateCommand, - MODULE_NAME_INTEROPERABILITY, -} from 'lisk-sdk'; +import { testing, Modules } from 'lisk-sdk'; export const getSampleCCU = (txParams?: Record) => testing .createTransaction({ - commandClass: SubmitMainchainCrossChainUpdateCommand as any, - module: MODULE_NAME_INTEROPERABILITY, + commandClass: Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand as any, + module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, nonce: (txParams?.nonce as bigint) ?? BigInt(0), params: (txParams?.params as Record) ?? { activeValidatorsUpdate: { diff --git a/framework-plugins/lisk-framework-dashboard-plugin/src/plugin/dashboard_plugin.ts b/framework-plugins/lisk-framework-dashboard-plugin/src/plugin/dashboard_plugin.ts index c0a08dfa133..5f5b5dfa400 100644 --- a/framework-plugins/lisk-framework-dashboard-plugin/src/plugin/dashboard_plugin.ts +++ b/framework-plugins/lisk-framework-dashboard-plugin/src/plugin/dashboard_plugin.ts @@ -12,14 +12,14 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BasePlugin } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import * as express from 'express'; import { join } from 'path'; import { Server } from 'http'; import { configSchema } from './schemas'; import { DashboardPluginConfig } from './types'; -export class DashboardPlugin extends BasePlugin { +export class DashboardPlugin extends Plugins.BasePlugin { public configSchema = configSchema; private _server!: Server; diff --git a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts index e9aa771804f..90b57787b15 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts @@ -13,14 +13,7 @@ */ import axios from 'axios'; -import { - BasePluginEndpoint, - PluginEndpointContext, - validator as liskValidator, - cryptography, - transactions, - BasePlugin, -} from 'lisk-sdk'; +import { Plugins, Types, validator as liskValidator, cryptography, transactions } from 'lisk-sdk'; import { authorizeParamsSchema, fundParamsSchema } from './schemas'; import { FaucetPluginConfig, State } from './types'; @@ -28,18 +21,22 @@ import { FaucetPluginConfig, State } from './types'; // eslint-disable-next-line prefer-destructuring const validator: liskValidator.LiskValidator = liskValidator.validator; -export class Endpoint extends BasePluginEndpoint { +export class Endpoint extends Plugins.BasePluginEndpoint { private _state: State = { publicKey: undefined, privateKey: undefined, address: undefined }; - private _client!: BasePlugin['apiClient']; + private _client!: Plugins.BasePlugin['apiClient']; private _config!: FaucetPluginConfig; - public init(state: State, apiClient: BasePlugin['apiClient'], config: FaucetPluginConfig) { + public init( + state: State, + apiClient: Plugins.BasePlugin['apiClient'], + config: FaucetPluginConfig, + ) { this._state = state; this._client = apiClient; this._config = config; } // eslint-disable-next-line @typescript-eslint/require-await - public async authorize(context: PluginEndpointContext): Promise<{ result: string }> { + public async authorize(context: Types.PluginEndpointContext): Promise<{ result: string }> { validator.validate<{ enable: boolean; password: string }>( authorizeParamsSchema, context.params, @@ -76,7 +73,7 @@ export class Endpoint extends BasePluginEndpoint { } } - public async fundTokens(context: PluginEndpointContext): Promise<{ result: string }> { + public async fundTokens(context: Types.PluginEndpointContext): Promise<{ result: string }> { validator.validate(fundParamsSchema, context.params); const { address, token } = context.params; diff --git a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts index 431aaa07fc0..2ccf641e2dc 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BasePlugin, PluginInitContext } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import * as express from 'express'; import { join } from 'path'; import { Server } from 'http'; @@ -19,7 +19,7 @@ import { configSchema } from './schemas'; import { FaucetPluginConfig, State } from './types'; import { Endpoint } from './endpoint'; -export class FaucetPlugin extends BasePlugin { +export class FaucetPlugin extends Plugins.BasePlugin { public configSchema = configSchema; public endpoint = new Endpoint(); @@ -34,7 +34,7 @@ export class FaucetPlugin extends BasePlugin { return __filename; } - public async init(context: PluginInitContext): Promise { + public async init(context: Plugins.PluginInitContext): Promise { await super.init(context); this.endpoint.init(this._state, this.apiClient, this.config); } diff --git a/framework-plugins/lisk-framework-faucet-plugin/test/functional/faucet.spec.ts b/framework-plugins/lisk-framework-faucet-plugin/test/functional/faucet.spec.ts index 4854234981b..56ed37bf223 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/test/functional/faucet.spec.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/test/functional/faucet.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { testing, PartialApplicationConfig, BasePlugin } from 'lisk-sdk'; +import { testing, Types, Plugins } from 'lisk-sdk'; import { FaucetPlugin } from '../../src'; describe('faucet plugin', () => { @@ -31,11 +31,11 @@ describe('faucet plugin', () => { captchaSitekey: '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI', }, }, - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, - plugins: [new FaucetPlugin() as BasePlugin], + plugins: [new FaucetPlugin() as Plugins.BasePlugin], }); await appEnv.startApplication(); }); diff --git a/framework-plugins/lisk-framework-faucet-plugin/test/functional/fund.spec.ts b/framework-plugins/lisk-framework-faucet-plugin/test/functional/fund.spec.ts index 8c30dfbc536..2157a500116 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/test/functional/fund.spec.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/test/functional/fund.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import * as axios from 'axios'; -import { testing, PartialApplicationConfig, BasePlugin } from 'lisk-sdk'; +import { testing, Types, Plugins } from 'lisk-sdk'; import { FaucetPlugin } from '../../src/plugin'; describe('fund tokens action', () => { @@ -31,10 +31,10 @@ describe('fund tokens action', () => { captchaSitekey: '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI', }, }, - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, - plugins: [new FaucetPlugin() as BasePlugin], + plugins: [new FaucetPlugin() as Plugins.BasePlugin], }); await appEnv.startApplication(); await appEnv.ipcClient.invoke<{ result: string }>('faucet:authorize', { diff --git a/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/auth.spec.ts b/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/auth.spec.ts index a326b4aa50e..cdb5553e9d0 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/auth.spec.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/auth.spec.ts @@ -12,11 +12,11 @@ * Removal or modification of this copyright notice is prohibited. */ -import { ApplicationConfigForPlugin, testing } from 'lisk-sdk'; +import { Types, testing } from 'lisk-sdk'; import { FaucetPlugin } from '../../../src/plugin'; import { configSchema } from '../../../src/plugin/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/faucet_plugin.spec.ts b/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/faucet_plugin.spec.ts index 76e18803242..fb464b96313 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/faucet_plugin.spec.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/test/unit/plugin/faucet_plugin.spec.ts @@ -12,10 +12,10 @@ * Removal or modification of this copyright notice is prohibited. */ -import { ApplicationConfigForPlugin, testing } from 'lisk-sdk'; +import { Types, testing } from 'lisk-sdk'; import { FaucetPlugin } from '../../../src/plugin'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; const logger = testing.mocks.loggerMock; diff --git a/framework-plugins/lisk-framework-forger-plugin/src/endpoint.ts b/framework-plugins/lisk-framework-forger-plugin/src/endpoint.ts index d82ed0fa466..40957d65290 100644 --- a/framework-plugins/lisk-framework-forger-plugin/src/endpoint.ts +++ b/framework-plugins/lisk-framework-forger-plugin/src/endpoint.ts @@ -11,13 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { - BasePlugin, - BasePluginEndpoint, - PluginEndpointContext, - db as liskDB, - cryptography, -} from 'lisk-sdk'; +import { Plugins, Types, db as liskDB, cryptography } from 'lisk-sdk'; import { getForgerInfo } from './db'; import { Forger } from './types'; @@ -50,16 +44,16 @@ interface Validator { consecutiveMissedBlocks: number; } -export class Endpoint extends BasePluginEndpoint { - private _client!: BasePlugin['apiClient']; +export class Endpoint extends Plugins.BasePluginEndpoint { + private _client!: Plugins.BasePlugin['apiClient']; private _db!: liskDB.Database; - public init(db: liskDB.Database, apiClient: BasePlugin['apiClient']) { + public init(db: liskDB.Database, apiClient: Plugins.BasePlugin['apiClient']) { this._db = db; this._client = apiClient; } - public async getStakers(_context: PluginEndpointContext): Promise { + public async getStakers(_context: Types.PluginEndpointContext): Promise { const { status: forgersList } = await this._client.invoke<{ status: Forger[] }>( 'generator_getStatus', ); @@ -95,7 +89,7 @@ export class Endpoint extends BasePluginEndpoint { return result; } - public async getForgingInfo(_context: PluginEndpointContext): Promise { + public async getForgingInfo(_context: Types.PluginEndpointContext): Promise { const { status: forgersList } = await this._client.invoke<{ status: Forger[] }>( 'generator_getStatus', ); diff --git a/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts b/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts index 36f3f4383e0..e0b24594204 100644 --- a/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts +++ b/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts @@ -12,16 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - BasePlugin, - GenesisConfig, - utils, - codec, - chain, - db as liskDB, - cryptography, - PluginInitContext, -} from 'lisk-sdk'; +import { Plugins, Types, utils, codec, chain, db as liskDB, cryptography } from 'lisk-sdk'; import { getDBInstance, getForgerInfo, @@ -62,7 +53,7 @@ interface ForgerTransactionsInfo { interface NodeInfo { genesisHeight: number; - genesis: GenesisConfig; + genesis: Types.GenesisConfig; } interface MissedBlocksByAddress { @@ -77,7 +68,7 @@ const getBinaryAddress = (hexAddressStr: string) => Buffer.from(hexAddressStr, 'hex').toString('binary'); const getAddressBuffer = (hexAddressStr: string) => Buffer.from(hexAddressStr, 'hex'); -export class ForgerPlugin extends BasePlugin { +export class ForgerPlugin extends Plugins.BasePlugin { public endpoint = new Endpoint(); private _forgerPluginDB!: liskDB.Database; @@ -91,7 +82,7 @@ export class ForgerPlugin extends BasePlugin { return ['block:created', 'block:missed']; } - public async init(context: PluginInitContext): Promise { + public async init(context: Plugins.PluginInitContext): Promise { await super.init(context); this.endpoint.init(this._forgerPluginDB, this.apiClient); } diff --git a/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/event_track.spec.ts b/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/event_track.spec.ts index 784c5229978..05c18caa87b 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/event_track.spec.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/event_track.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { testing, PartialApplicationConfig } from 'lisk-sdk'; +import { testing, Types } from 'lisk-sdk'; import { getForgerInfoByAddress, getForgerPlugin, waitTill } from '../../utils/application'; import { getRandomAccount } from '../../utils/accounts'; import { createTransferTransaction, createStakeTransaction } from '../../utils/transactions'; @@ -28,7 +28,7 @@ describe('Forger Info', () => { const config = { rootPath, label: 'event_track_functional', - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, diff --git a/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/forger_info_sync.spec.ts b/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/forger_info_sync.spec.ts index 93d2d166e6a..dfaeb7a5add 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/forger_info_sync.spec.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/functional/forger_info/forger_info_sync.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { testing, PartialApplicationConfig } from 'lisk-sdk'; +import { testing, Types } from 'lisk-sdk'; import { getForgerInfoByAddress, getForgerPlugin, waitTill } from '../../utils/application'; import { getRandomAccount } from '../../utils/accounts'; import { createTransferTransaction } from '../../utils/transactions'; @@ -28,7 +28,7 @@ describe('Forger Info Sync', () => { const config = { rootPath, label: 'forger_info_sync_functional', - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, diff --git a/framework-plugins/lisk-framework-forger-plugin/test/functional/forging_info.spec.ts b/framework-plugins/lisk-framework-forger-plugin/test/functional/forging_info.spec.ts index 96d91c57e57..81a54604b78 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/functional/forging_info.spec.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/functional/forging_info.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { testing, PartialApplicationConfig } from 'lisk-sdk'; +import { testing, Types } from 'lisk-sdk'; import { getForgerInfoByAddress, getForgerPlugin } from '../utils/application'; import { ForgerPlugin } from '../../src'; @@ -24,7 +24,7 @@ describe('forger:getForgingInfo action', () => { const config = { rootPath, label: 'forging_info_functional', - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, diff --git a/framework-plugins/lisk-framework-forger-plugin/test/functional/voters.spec.ts b/framework-plugins/lisk-framework-forger-plugin/test/functional/voters.spec.ts index d1105d7b5a6..822f4378aea 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/functional/voters.spec.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/functional/voters.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { testing, PartialApplicationConfig } from 'lisk-sdk'; +import { testing, Types } from 'lisk-sdk'; import { waitTill } from '../utils/application'; import { createStakeTransaction } from '../utils/transactions'; import { ForgerPlugin } from '../../src'; @@ -27,7 +27,7 @@ describe('forger:getStakers action', () => { const config = { rootPath, label: 'stakers_functional', - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, diff --git a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/blocks.ts b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/blocks.ts index be82446ec53..a9481abb602 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/blocks.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/blocks.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BasePlugin } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import { BlockPropagationStats, PeerInfo, SharedState } from '../types'; export interface BlockStats { @@ -31,7 +31,7 @@ const getAverageReceivedBlocks = (blocks: { [key: string]: BlockPropagationStats }; export const getBlockStats = async ( - client: BasePlugin['apiClient'], + client: Plugins.BasePlugin['apiClient'], state: SharedState, ): Promise => { const connectedPeers = await client.invoke>('network_getConnectedPeers'); diff --git a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/network.ts b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/network.ts index d67bfd57e59..470cf6f251c 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/network.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/network.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BasePlugin } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import { PeerInfo } from '../types'; export interface NetworkStats { @@ -36,7 +36,9 @@ const getMajorityHeight = (peers: PeerInfo[]): { height: number; count: number } return majority; }; -export const getNetworkStats = async (client: BasePlugin['apiClient']): Promise => { +export const getNetworkStats = async ( + client: Plugins.BasePlugin['apiClient'], +): Promise => { const networkStats = await client.invoke('network_getStats'); const connectedPeers = await client.invoke('network_getConnectedPeers'); const disconnectedPeers = await client.invoke('network_getDisconnectedPeers'); diff --git a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/prometheus.ts b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/prometheus.ts index 3ff71cb152a..156bbe5a580 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/prometheus.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/prometheus.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { Request, Response, NextFunction } from 'express'; -import { BasePlugin } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import { SharedState, PeerInfo } from '../types'; import { getBlockStats } from './blocks'; import { getTransactionStats } from './transactions'; @@ -56,7 +56,7 @@ const prometheusExporter = (data: PrometheusData[]) => { }; export const getData = - (client: BasePlugin['apiClient'], state: SharedState) => + (client: Plugins.BasePlugin['apiClient'], state: SharedState) => async (_req: Request, res: Response, next: NextFunction): Promise => { try { const connectedPeers: PeerInfo[] = await client.invoke('network_getConnectedPeers'); diff --git a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/transactions.ts b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/transactions.ts index af3f211320b..5bed06b7588 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/src/controllers/transactions.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/src/controllers/transactions.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BasePlugin } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import { PeerInfo, SharedState, TransactionPropagationStats } from '../types'; export interface TransactionStats { @@ -33,7 +33,7 @@ const getAverage = (transactions: Record): }; export const getTransactionStats = async ( - client: BasePlugin['apiClient'], + client: Plugins.BasePlugin['apiClient'], state: SharedState, ): Promise => ({ transactions: state.transactions, diff --git a/framework-plugins/lisk-framework-monitor-plugin/src/endpoint.ts b/framework-plugins/lisk-framework-monitor-plugin/src/endpoint.ts index e846fb58c85..35fc89cfc23 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/src/endpoint.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/src/endpoint.ts @@ -11,39 +11,41 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { BasePlugin, BasePluginEndpoint, PluginEndpointContext } from 'lisk-sdk'; +import { Plugins, Types } from 'lisk-sdk'; import { SharedState } from './types'; import * as controllers from './controllers'; -export class Endpoint extends BasePluginEndpoint { +export class Endpoint extends Plugins.BasePluginEndpoint { private _state!: SharedState; - private _client!: BasePlugin['apiClient']; + private _client!: Plugins.BasePlugin['apiClient']; - public init(state: SharedState, apiClient: BasePlugin['apiClient']) { + public init(state: SharedState, apiClient: Plugins.BasePlugin['apiClient']) { this._state = state; this._client = apiClient; } public async getTransactionStats( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { return controllers.transactions.getTransactionStats(this._client, this._state); } public async getBlockStats( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { return controllers.blocks.getBlockStats(this._client, this._state); } public async getNetworkStats( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { return controllers.network.getNetworkStats(this._client); } // eslint-disable-next-line @typescript-eslint/require-await - public async getForkStats(_context: PluginEndpointContext): Promise { + public async getForkStats( + _context: Types.PluginEndpointContext, + ): Promise { return controllers.forks.getForkStats(this._state); } } diff --git a/framework-plugins/lisk-framework-monitor-plugin/src/monitor_plugin.ts b/framework-plugins/lisk-framework-monitor-plugin/src/monitor_plugin.ts index 597119c6c0e..6bbb705cad6 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/src/monitor_plugin.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/src/monitor_plugin.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { Server } from 'http'; -import { BasePlugin, PluginInitContext } from 'lisk-sdk'; +import { Plugins } from 'lisk-sdk'; import * as express from 'express'; import type { Express } from 'express'; import * as cors from 'cors'; @@ -31,7 +31,7 @@ interface BlockData { }; } -export class MonitorPlugin extends BasePlugin { +export class MonitorPlugin extends Plugins.BasePlugin { public configSchema = configSchema; public endpoint = new Endpoint(); @@ -43,7 +43,7 @@ export class MonitorPlugin extends BasePlugin { return __filename; } - public async init(context: PluginInitContext): Promise { + public async init(context: Plugins.PluginInitContext): Promise { await super.init(context); this._state = { forks: { diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts index 585ef1a6d52..4d87cbe0545 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts @@ -11,12 +11,12 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { testing, ApplicationConfigForPlugin, chain, cryptography } from 'lisk-sdk'; +import { testing, Types, chain, cryptography } from 'lisk-sdk'; import { when } from 'jest-when'; import { MonitorPlugin } from '../../src'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts index d87d38b1f23..0b415e31661 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts @@ -12,11 +12,11 @@ * Removal or modification of this copyright notice is prohibited. */ -import { chain, cryptography, testing, ApplicationConfigForPlugin } from 'lisk-sdk'; +import { chain, cryptography, testing, Types } from 'lisk-sdk'; import { MonitorPlugin } from '../../src/monitor_plugin'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; const validPluginOptions = configSchema.default; diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/network.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/network.spec.ts index 95939e6ad7e..fe0969dc398 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/network.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/network.spec.ts @@ -12,13 +12,13 @@ * Removal or modification of this copyright notice is prohibited. */ -import { ApplicationConfigForPlugin, testing } from 'lisk-sdk'; +import { Types, testing } from 'lisk-sdk'; import { when } from 'jest-when'; import { PeerInfo } from '../../src/types'; import { MonitorPlugin } from '../../src'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/subscribe_event.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/subscribe_event.spec.ts index 42eabfff587..c774a8db2c7 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/subscribe_event.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/subscribe_event.spec.ts @@ -11,11 +11,11 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { testing, ApplicationConfigForPlugin } from 'lisk-sdk'; +import { testing, Types } from 'lisk-sdk'; import { MonitorPlugin } from '../../src'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/transaction.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/transaction.spec.ts index c4b995bc883..767d3fb38fc 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/transaction.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/transaction.spec.ts @@ -13,11 +13,11 @@ */ import { randomBytes } from 'crypto'; -import { testing, ApplicationConfigForPlugin } from 'lisk-sdk'; +import { testing, Types } from 'lisk-sdk'; import { MonitorPlugin } from '../../src/monitor_plugin'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts index ca9df7e1391..012f1916a57 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts @@ -15,13 +15,7 @@ import * as os from 'os'; import { join } from 'path'; import { ensureDir } from 'fs-extra'; -import { - cryptography, - codec, - chain, - db as liskDB, - areDistinctHeadersContradicting, -} from 'lisk-sdk'; +import { cryptography, codec, chain, db as liskDB, Engine } from 'lisk-sdk'; const { BlockHeader } = chain; const { utils } = cryptography; @@ -129,7 +123,7 @@ export const getContradictingBlockHeader = async ( continue; } - const isContradicting = areDistinctHeadersContradicting(header, blockHeader); + const isContradicting = Engine.areDistinctHeadersContradicting(header, blockHeader); if (isContradicting) { return header; diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts index af4ee3235af..18fb00ec63c 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts @@ -11,12 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { - BasePluginEndpoint, - PluginEndpointContext, - validator as liskValidator, - cryptography, -} from 'lisk-sdk'; +import { Plugins, Types, validator as liskValidator, cryptography } from 'lisk-sdk'; import { actionParamsSchema } from './schemas'; import { ReportMisbehaviorPluginConfig, State } from './types'; @@ -26,7 +21,7 @@ const validator: liskValidator.LiskValidator = liskValidator.validator; const { encrypt, ed } = cryptography; -export class Endpoint extends BasePluginEndpoint { +export class Endpoint extends Plugins.BasePluginEndpoint { private _state!: State; private _config!: ReportMisbehaviorPluginConfig; @@ -36,7 +31,7 @@ export class Endpoint extends BasePluginEndpoint { } // eslint-disable-next-line @typescript-eslint/require-await - public async authorize(context: PluginEndpointContext): Promise<{ result: string }> { + public async authorize(context: Types.PluginEndpointContext): Promise<{ result: string }> { validator.validate<{ enable: boolean; password: string }>(actionParamsSchema, context.params); const { enable, password } = context.params; diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts index 5f5c6b546b2..89b16bf40a4 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts @@ -11,15 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { - BasePlugin, - PluginInitContext, - db as liskDB, - codec, - chain, - cryptography, - blockHeaderSchema, -} from 'lisk-sdk'; +import { Plugins, db as liskDB, codec, chain, cryptography, blockHeaderSchema } from 'lisk-sdk'; import { getDBInstance, saveBlockHeaders, @@ -33,7 +25,7 @@ import { Endpoint } from './endpoint'; const { address, ed } = cryptography; const { BlockHeader, Transaction, TAG_TRANSACTION } = chain; -export class ReportMisbehaviorPlugin extends BasePlugin { +export class ReportMisbehaviorPlugin extends Plugins.BasePlugin { public configSchema = configSchema; public endpoint = new Endpoint(); @@ -45,7 +37,7 @@ export class ReportMisbehaviorPlugin extends BasePlugin { + public async init(context: Plugins.PluginInitContext): Promise { await super.init(context); this.endpoint.init(this._state, this.config); } diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/functional/save_new_block.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/functional/save_new_block.spec.ts index dfac002c4cb..f406e3388ae 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/functional/save_new_block.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/functional/save_new_block.spec.ts @@ -12,14 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - testing, - RegisteredSchema, - PartialApplicationConfig, - chain, - db as liskDB, - codec, -} from 'lisk-sdk'; +import { testing, Types, chain, db as liskDB, codec } from 'lisk-sdk'; import { rmdirSync, existsSync } from 'fs'; import { homedir } from 'os'; import { join } from 'path'; @@ -49,7 +42,7 @@ describe('save block header', () => { const rootPath = join(homedir(), '.lisk', 'report-misbehavior-plugin'); const apiPort = 5002; - const encodeBlockHeader = (schemas: RegisteredSchema, newHeader: chain.BlockHeader) => + const encodeBlockHeader = (schemas: Types.RegisteredSchema, newHeader: chain.BlockHeader) => codec.encode(schemas.blockHeader, newHeader); beforeAll(async () => { @@ -65,7 +58,7 @@ describe('save block header', () => { encryptedPassphrase: testing.fixtures.defaultFaucetAccount.encryptedPassphrase, }, }, - } as PartialApplicationConfig; + } as Types.PartialApplicationConfig; appEnv = testing.createDefaultApplicationEnv({ config, diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/integration/cleanup_job.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/integration/cleanup_job.spec.ts index d5e8b77f864..3eabddddce4 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/integration/cleanup_job.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/integration/cleanup_job.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { utils } from '@liskhq/lisk-cryptography'; -import { ApplicationConfigForPlugin, GenesisConfig, testing, chain, codec } from 'lisk-sdk'; +import { Types, testing, chain, codec } from 'lisk-sdk'; import * as fs from 'fs-extra'; import { ReportMisbehaviorPlugin } from '../../src'; @@ -21,7 +21,7 @@ import { blockHeadersSchema } from '../../src/db'; import { configSchema } from '../../src/schemas'; import { waitTill } from '../utils/application'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { system: { dataPath: '~/.lisk/my-app', keepEventsForHeights: -1, @@ -35,7 +35,7 @@ const appConfigForPlugin: ApplicationConfigForPlugin = { port: 7887, host: '127.0.0.1', }, - genesis: {} as GenesisConfig, + genesis: {} as Types.GenesisConfig, network: { version: '1.0', seedPeers: [], diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/auth.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/auth.spec.ts index 4dbf1a31c7c..cf2678f7439 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/auth.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/auth.spec.ts @@ -12,11 +12,11 @@ * Removal or modification of this copyright notice is prohibited. */ -import { ApplicationConfigForPlugin, testing } from 'lisk-sdk'; +import { Types, testing } from 'lisk-sdk'; import { ReportMisbehaviorPlugin } from '../../src'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/db.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/db.spec.ts index a0ab3f3c307..c2fd7cafedf 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/db.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/db.spec.ts @@ -13,7 +13,7 @@ */ import { rmSync } from 'fs-extra'; -import * as sdk from 'lisk-sdk'; +import { Engine } from 'lisk-sdk'; import { chain, db as liskDB, blockHeaderSchema, codec, BlockHeader } from 'lisk-sdk'; import { getContradictingBlockHeader, saveBlockHeaders } from '../../src/db'; @@ -100,13 +100,13 @@ describe('db', () => { }); it('should return undefined if block headers are not contradicting', async () => { - jest.spyOn(sdk, 'areDistinctHeadersContradicting').mockImplementation(() => false); + jest.spyOn(Engine, 'areDistinctHeadersContradicting').mockImplementation(() => false); await expect(getContradictingBlockHeader(db, header2)).resolves.toBeUndefined(); }); it('should return the block in plugin db if blocks are contradicting', async () => { - jest.spyOn(sdk, 'areDistinctHeadersContradicting').mockImplementation(() => true); + jest.spyOn(Engine, 'areDistinctHeadersContradicting').mockImplementation(() => true); await expect(getContradictingBlockHeader(db, header2)).resolves.toEqual(headerClone); }); diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts index c2286d1d67b..fad3952c880 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts @@ -11,13 +11,13 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { testing, chain, ApplicationConfigForPlugin } from 'lisk-sdk'; +import { testing, chain, Types } from 'lisk-sdk'; import { when } from 'jest-when'; import { ReportMisbehaviorPlugin } from '../../src'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/subscribe_event.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/subscribe_event.spec.ts index fe0aef005aa..85216da86b3 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/subscribe_event.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/subscribe_event.spec.ts @@ -12,11 +12,11 @@ * Removal or modification of this copyright notice is prohibited. */ -import { ApplicationConfigForPlugin, testing } from 'lisk-sdk'; +import { Types, testing } from 'lisk-sdk'; import { ReportMisbehaviorPlugin } from '../../src'; import { configSchema } from '../../src/schemas'; -const appConfigForPlugin: ApplicationConfigForPlugin = { +const appConfigForPlugin: Types.ApplicationConfigForPlugin = { ...testing.fixtures.defaultConfig, }; diff --git a/framework/src/engine/bft/index.ts b/framework/src/engine/bft/index.ts index ca140154aee..4f328824f19 100644 --- a/framework/src/engine/bft/index.ts +++ b/framework/src/engine/bft/index.ts @@ -14,5 +14,6 @@ export { BFTModule } from './module'; export type { BFTMethod } from './method'; +export { bftParametersSchema, BFTParameters } from './schemas'; +export { BFTHeights } from './types'; export { computeValidatorsHash, areDistinctHeadersContradicting } from './utils'; -export { BFTParameters } from './schemas'; diff --git a/framework/src/engine/consensus/index.ts b/framework/src/engine/consensus/index.ts index f64a1f227a1..2c6ca5e9eba 100644 --- a/framework/src/engine/consensus/index.ts +++ b/framework/src/engine/consensus/index.ts @@ -13,13 +13,8 @@ */ export { Consensus } from './consensus'; -export { - CONSENSUS_EVENT_BLOCK_BROADCAST, - CONSENSUS_EVENT_FORK_DETECTED, - CONSENSUS_EVENT_BLOCK_DELETE, - CONSENSUS_EVENT_BLOCK_NEW, -} from './constants'; -export { BFTHeights } from '../bft/types'; +export { CONSENSUS_EVENT_BLOCK_DELETE, CONSENSUS_EVENT_BLOCK_NEW } from './constants'; +export { BFTHeader, ActiveValidator, AggregateCommit } from './types'; export { isEmptyConsensusUpdate } from './utils'; export { computeUnsignedCertificateFromBlockHeader, diff --git a/framework/src/engine/index.ts b/framework/src/engine/index.ts index e0e4a7c1cbf..fb9eb6e70d8 100644 --- a/framework/src/engine/index.ts +++ b/framework/src/engine/index.ts @@ -13,4 +13,5 @@ */ export { Engine } from './engine'; -export { computeValidatorsHash, areDistinctHeadersContradicting, BFTParameters } from './bft'; +export * from './bft'; +export * from './consensus'; diff --git a/framework/src/index.ts b/framework/src/index.ts index b11e5c002fc..8ce96b4bd9b 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -11,7 +11,6 @@ * * Removal or modification of this copyright notice is prohibited. */ - export { Transaction, TransactionJSON, @@ -26,174 +25,22 @@ export { BlockAssetJSON, standardEventDataSchema, } from '@liskhq/lisk-chain'; -export { - BaseModule, - BaseMethod, - BaseCommand, - BaseEndpoint, - BaseEvent, - BaseOffchainStore, - BaseStore, - EventQueuer, - ImmutableOffchainStoreGetter, - ImmutableStoreGetter, - OffchainStoreGetter, - StoreGetter, - ModuleMetadata, - ModuleMetadataJSON, - ModuleInitArgs, - BaseInternalMethod, -} from './modules'; export { Application } from './application'; export { systemDirs } from './system_dirs'; -export { BasePlugin, PluginInitContext } from './plugins/base_plugin'; -export { BasePluginEndpoint } from './plugins/base_plugin_endpoint'; -export { IPCChannel } from './controller/channels'; -export type { BaseChannel } from './controller/channels'; -export type { EventsDefinition, EventCallback } from './controller/event'; +export * as Plugins from './plugins'; +export * as Logger from './logger'; +export * as Controller from './controller'; export * as testing from './testing'; -export * from './types'; -export { ValidatorsMethod, ValidatorsModule } from './modules/validators'; -export { - AuthMethod, - AuthModule, - multisigRegMsgSchema, - genesisAuthStoreSchema as authGenesisStoreSchema, -} from './modules/auth'; -export { - TokenMethod, - TokenModule, - TransferCommand, - TransferCrossChainCommand, - CrossChainTransferCommand, - TokenInteroperableMethod, - TokenEndpoint, - TransferParams, - CCTransferParams, - genesisTokenStoreSchema as tokenGenesisStoreSchema, - CROSS_CHAIN_COMMAND_NAME_TRANSFER, - LOCAL_ID_LENGTH, - TOKEN_ID_LENGTH, - MAX_DATA_LENGTH, -} from './modules/token'; -export { NFTModule, NFTMethod } from './modules/nft'; -export { - PoSMethod, - PoSModule, - ValidatorRegistrationCommand, - ReportMisbehaviorCommand, - UnlockCommand, - UpdateGeneratorKeyCommand, - StakeCommand, - genesisStoreSchema as posGenesisStoreSchema, -} from './modules/pos'; -export { - SubmitMainchainCrossChainUpdateCommand, - MainchainInteroperabilityMethod, - MainchainInteroperabilityModule, - RecoverMessageCommand, - RegisterMainchainCommand, - SubmitSidechainCrossChainUpdateCommand, - SidechainInteroperabilityMethod, - SidechainInteroperabilityModule, - RegisterSidechainCommand, - InitializeStateRecoveryCommand, - RecoverStateCommand, - TerminateSidechainForLivenessCommand, - CCMsg, - ChainAccount, - ChainAccountJSON, - ChannelData, - ChannelDataJSON, - Inbox, - InboxJSON, - Outbox, - OutboxJSON, - InboxUpdate, - CrossChainUpdateTransactionParams, - ActiveValidator, - ActiveValidatorsUpdate, - OutboxRootWitness, - LIVENESS_LIMIT, - MESSAGE_TAG_CERTIFICATE, - MODULE_NAME_INTEROPERABILITY, - MAX_CCM_SIZE, - EMPTY_BYTES, - ChainStatus, - ccmSchema, - OwnChainAccount, - OwnChainAccountJSON, - LastCertificate, - LastCertificateJSON, - CcmProcessedEventData, - CcmSendSuccessEventData, - CCMProcessedCode, - CCMProcessedResult, - ccuParamsSchema, - sidechainRegParams, - mainchainRegParams, - messageRecoveryParamsSchema, - messageRecoveryInitializationParamsSchema, - registrationCCMParamsSchema, - sidechainTerminatedCCMParamsSchema, - validatorsHashInputSchema, - registrationSignatureMessageSchema, - stateRecoveryParamsSchema, - stateRecoveryInitParamsSchema, - terminateSidechainForLivenessParamsSchema, - genesisInteroperabilitySchema, - BaseCCCommand, - BaseCCMethod, - BaseInteroperableModule, - CrossChainMessageContext, - CCCommandExecuteContext, - ImmutableCrossChainMessageContext, - getMainchainID, - RecoverContext, -} from './modules/interoperability'; -export { RewardMethod, RewardModule } from './modules/reward'; -export { DynamicRewardMethod, DynamicRewardModule } from './modules/dynamic_reward'; -export { FeeMethod, FeeModule } from './modules/fee'; -export { RandomMethod, RandomModule } from './modules/random'; -export { PoAModule, PoAMethod } from './modules/poa'; -export { NamedRegistry } from './modules/named_registry'; -export { - GenesisBlockExecuteContext, - InsertAssetContext, - MethodContext, - ImmutableMethodContext, - CommandExecuteContext, - CommandVerifyContext, - VerificationResult, - VerifyStatus, - TransactionVerifyContext, - TransactionExecuteContext, - BlockVerifyContext, - BlockExecuteContext, - BlockAfterExecuteContext, -} from './state_machine/types'; -export { TransactionExecutionResult, TransactionVerifyResult } from './abi/constants'; -export { AggregateCommit } from './engine/consensus/types'; -export { BFTHeights } from './engine/bft/types'; -export { BFTParameters } from './engine/bft/schemas'; -export { - computeUnsignedCertificateFromBlockHeader, - Certificate, - UnsignedCertificate, - aggregateCommitSchema, - certificateSchema, - unsignedCertificateSchema, -} from './engine/consensus'; +export * as Modules from './modules'; +export * as StateMachine from './state_machine'; +export * as Engine from './engine'; +export * as Types from './types'; export { applicationConfigSchema } from './schema'; export { - BLS_PUBLIC_KEY_LENGTH, - BLS_SIGNATURE_LENGTH, - NUMBER_ACTIVE_VALIDATORS_MAINCHAIN, - MESSAGE_TAG_CHAIN_REG, - MIN_CHAIN_NAME_LENGTH, - MAX_CHAIN_NAME_LENGTH, - MAX_NUM_VALIDATORS, - CHAIN_ID_LENGTH, -} from './modules/interoperability/constants'; -export { Proof, QueryProof, ProveResponse, Validator as BFTValidator } from './abi/abi'; -export { areDistinctHeadersContradicting } from './engine/bft'; + TransactionExecutionResult, + TransactionVerifyResult, + Proof, + QueryProof, + ProveResponse, + Validator as BFTValidator, +} from './abi'; diff --git a/framework/src/logger/logger.ts b/framework/src/logger/logger.ts index 9bba17c1242..8e1de1fa0fb 100644 --- a/framework/src/logger/logger.ts +++ b/framework/src/logger/logger.ts @@ -113,6 +113,7 @@ interface LoggerInput { readonly name: string; } +/** Logger interface, to create log messages. */ export interface Logger { readonly trace: (data?: Record | unknown, message?: string) => void; readonly debug: (data?: Record | unknown, message?: string) => void; diff --git a/framework/src/modules/auth/commands/register_multisignature.ts b/framework/src/modules/auth/commands/register_multisignature.ts index a0ffbfafe26..c22d9572c0c 100644 --- a/framework/src/modules/auth/commands/register_multisignature.ts +++ b/framework/src/modules/auth/commands/register_multisignature.ts @@ -15,7 +15,7 @@ import { codec } from '@liskhq/lisk-codec'; import { objects as objectUtils } from '@liskhq/lisk-utils'; import * as cryptography from '@liskhq/lisk-cryptography'; -import { BaseCommand } from '../..'; +import { BaseCommand } from '../../base_command'; import { CommandExecuteContext, CommandVerifyContext, diff --git a/framework/src/modules/base_command.ts b/framework/src/modules/base_command.ts index 6761609b7ea..0b55b2576d7 100644 --- a/framework/src/modules/base_command.ts +++ b/framework/src/modules/base_command.ts @@ -14,7 +14,11 @@ /* eslint-disable class-methods-use-this */ import { Schema, emptySchema } from '@liskhq/lisk-codec'; -import { CommandVerifyContext, CommandExecuteContext, VerificationResult } from '../state_machine'; +import { + CommandVerifyContext, + CommandExecuteContext, + VerificationResult, +} from '../state_machine/types'; import { NamedRegistry } from './named_registry'; /** diff --git a/framework/src/modules/base_event.ts b/framework/src/modules/base_event.ts index 027630f5ae2..1db21c7ab63 100644 --- a/framework/src/modules/base_event.ts +++ b/framework/src/modules/base_event.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { codec, emptySchema, Schema } from '@liskhq/lisk-codec'; -import { EventQueue } from '../state_machine'; +import { EventQueue } from '../state_machine/event_queue'; export interface EventQueuer { eventQueue: EventQueue; diff --git a/framework/src/modules/base_method.ts b/framework/src/modules/base_method.ts index 6bb8f4d023c..762a6f510a3 100644 --- a/framework/src/modules/base_method.ts +++ b/framework/src/modules/base_method.ts @@ -13,6 +13,9 @@ */ import { NamedRegistry } from './named_registry'; +/** + * The `BaseMethod` provides a generic interface for module methods. + */ export abstract class BaseMethod { // eslint-disable-next-line no-useless-constructor public constructor(protected stores: NamedRegistry, protected events: NamedRegistry) {} diff --git a/framework/src/modules/base_module.ts b/framework/src/modules/base_module.ts index 83abe9f969f..26f57bdf490 100644 --- a/framework/src/modules/base_module.ts +++ b/framework/src/modules/base_module.ts @@ -15,7 +15,11 @@ import { Schema } from '@liskhq/lisk-codec'; import { GenesisConfig } from '../types'; +import { BaseCommand } from './base_command'; +import { BaseEndpoint } from './base_endpoint'; +import { BaseMethod } from './base_method'; import { + InsertAssetContext, BlockAfterExecuteContext, BlockExecuteContext, GenesisBlockExecuteContext, @@ -23,38 +27,55 @@ import { TransactionVerifyContext, BlockVerifyContext, VerificationResult, -} from '../state_machine'; -import { BaseCommand } from './base_command'; -import { BaseEndpoint } from './base_endpoint'; -import { BaseMethod } from './base_method'; -import { InsertAssetContext } from '../state_machine/types'; +} from '../state_machine/types'; import { NamedRegistry } from './named_registry'; +/** + * Arguments used during module initialization. + */ export interface ModuleInitArgs { + /** Genesis config options */ genesisConfig: Omit; + /** Module-specific config options */ moduleConfig: Record; } export interface ModuleMetadata { + /** A list of Endpoints of the respective module. */ endpoints: { + // The name of the endpoint. name: string; + // Required parameters for the endpoint. request?: Schema; + // A schema of the expected response to a request, sent to the endpoint. response?: Schema; }[]; + /** A list of Blockchain Events that are emitted by the module. */ events: { + // The event name. name: string; + // The event data. data: Schema; }[]; + /** The list of Commands belonging to the module. */ commands: { + // The command name. name: string; + // The parameters of the command. params: Schema; }[]; + /** The schemas to decode block assets that are relevant to the module. */ assets: { + // The block version. version: number; + // The asset schema. data: Schema; }[]; + /** The data stores of the module. */ stores: { + // The store key. key: string; + // The store schema. data?: Schema; }[]; } @@ -65,30 +86,86 @@ export type ModuleMetadataJSON = ModuleMetadata & { name: string }; * The `BaseModule` represents Lisk modules by providing a generic interface, from which each module extends from. */ export abstract class BaseModule { + /** + * A command is a group of state-transition logic triggered by a transaction and is identified by the module and command name of the transaction. + */ public commands: BaseCommand[] = []; + /** + * Blockchain events, or module events, are logs of events that occur in the blockchain network during block execution. + * Events occur per block, and are stored in the respective block header, from where they can be queried. + */ public events: NamedRegistry = new NamedRegistry(); + /** + * A module can define one or multiple on-chain stores, to store data in the blockchain, i.e. to include it in the blockchain state. + * + * For example, data such as account balances, validator’s names, and multisignature keys are values that are stored in the on-chain module store. + */ public stores: NamedRegistry = new NamedRegistry(); + /** + * In a module, the off-chain store is available in: insertAssets & Endpoints. + * + * It complements the on-chain module store, by allowing to store various additional data in the blockchain client, that does not need to be included in the on-chain store. + * + * The data stored in the off-chain store is not part of the blockchain protocol, and it may differ from machine to machine. + */ public offchainStores: NamedRegistry = new NamedRegistry(); + /** + * The module name is the unique identifier for the module. + * + * The module name is automatically calculated from the class name of the module: + * The `Module` suffix of the class name is removed, and the first character is converted to lowercase. + */ public get name(): string { const name = this.constructor.name.replace('Module', ''); return name.charAt(0).toLowerCase() + name.substr(1); } + /** + * An endpoint is an interface between a module and an external system. Lisk endpoints support RPC communication. + * The module-specific RPC endpoints can be invoked by external services, like UIs, to get relevant data from the application. + * + * Endpoints allow us to conveniently get data from the blockchain. + * It is never possible to set data / mutate the state via module endpoints. + */ public abstract endpoint: BaseEndpoint; + + /** + * A method is an interface for module-to-module communication, and can perform state mutations on the blockchain. + * + * To get or set module-specific data in the blockchain, methods are either called by other modules or by the module itself. + * For example, the `transfer()` method from the Token module is called by a module, if it needs to transfer tokens from one account to the other. + */ public abstract method: BaseMethod; + /** + * If a module needs to access certain configuration options, it is required to validate and cache the respective configurations in the `init()` method of a module. + * + * The init() function is called for every registered module once, when the client is started. + * + * @param args + */ public async init?(args: ModuleInitArgs): Promise; public async insertAssets?(context: InsertAssetContext): Promise; public async verifyAssets?(context: BlockVerifyContext): Promise; public async verifyTransaction?(context: TransactionVerifyContext): Promise; public async beforeCommandExecute?(context: TransactionExecuteContext): Promise; public async afterCommandExecute?(context: TransactionExecuteContext): Promise; + + /** + * The hook `initGenesisState()` is called at the beginning of the genesis block execution. + * Each module must initialize its state using an associated block asset. + * + * @param context + */ public async initGenesisState?(context: GenesisBlockExecuteContext): Promise; public async finalizeGenesisState?(context: GenesisBlockExecuteContext): Promise; public async beforeTransactionsExecute?(context: BlockExecuteContext): Promise; public async afterTransactionsExecute?(context: BlockAfterExecuteContext): Promise; + /** + * The metadata of a module provides information about the module to external services like UIs. + */ public abstract metadata(): ModuleMetadata; protected baseMetadata() { diff --git a/framework/src/modules/index.ts b/framework/src/modules/index.ts index 7dca1cf8234..8fc25f7824b 100644 --- a/framework/src/modules/index.ts +++ b/framework/src/modules/index.ts @@ -12,15 +12,23 @@ * Removal or modification of this copyright notice is prohibited. */ -export { BaseInternalMethod } from './BaseInternalMethod'; -export { BaseModule, ModuleMetadata, ModuleMetadataJSON, ModuleInitArgs } from './base_module'; -export { BaseCommand } from './base_command'; -export { BaseMethod } from './base_method'; -export { BaseEndpoint } from './base_endpoint'; -export { BaseStore, StoreGetter, ImmutableStoreGetter } from './base_store'; -export { - BaseOffchainStore, - OffchainStoreGetter, - ImmutableOffchainStoreGetter, -} from './base_offchain_store'; -export { BaseEvent, EventQueuer } from './base_event'; +export * from './BaseInternalMethod'; +export * from './base_module'; +export * from './base_command'; +export * from './base_method'; +export * from './base_endpoint'; +export * from './base_store'; +export * from './base_offchain_store'; +export * from './named_registry'; +export * from './base_event'; +export * as Fee from './fee'; +export * as Token from './token'; +export * as NFT from './nft'; +export * as Interoperability from './interoperability'; +export * as PoS from './pos'; +export * as Reward from './reward'; +export * as DynamicReward from './dynamic_reward'; +export * as Random from './random'; +export * as PoA from './poa'; +export * as Validators from './validators'; +export * as Auth from './auth'; diff --git a/framework/src/modules/interoperability/base_cc_method.ts b/framework/src/modules/interoperability/base_cc_method.ts index 098b3a5db0a..01889374721 100644 --- a/framework/src/modules/interoperability/base_cc_method.ts +++ b/framework/src/modules/interoperability/base_cc_method.ts @@ -12,9 +12,12 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseMethod } from '..'; +import { BaseMethod } from '../base_method'; import { BeforeCCMForwardingContext, CrossChainMessageContext, RecoverContext } from './types'; +/** + * The BaseCCMethod represents Lisk module methods with cross-chain relations. + */ export abstract class BaseCCMethod extends BaseMethod { public beforeRecoverCCM?(ctx: CrossChainMessageContext): Promise; public recover?(ctx: RecoverContext): Promise; diff --git a/framework/src/modules/interoperability/base_interoperable_module.ts b/framework/src/modules/interoperability/base_interoperable_module.ts index 86bfb960d16..76c0b9ba6f2 100644 --- a/framework/src/modules/interoperability/base_interoperable_module.ts +++ b/framework/src/modules/interoperability/base_interoperable_module.ts @@ -16,7 +16,12 @@ import { BaseModule } from '../base_module'; import { BaseCCCommand } from './base_cc_command'; import { BaseCCMethod } from './base_cc_method'; +/** + * The BaseInteroperableModule represents Lisk modules with cross-chain commands by providing a generic interface, from which each interoperable module extends from. + */ export abstract class BaseInteroperableModule extends BaseModule { + /** A list of the cross-chain commands of the module */ public crossChainCommand: BaseCCCommand[] = []; + /** Methods related to cross-chain communication */ public abstract crossChainMethod: BaseCCMethod; } diff --git a/framework/src/modules/interoperability/index.ts b/framework/src/modules/interoperability/index.ts index 1dcb67c856d..a5d1275851f 100644 --- a/framework/src/modules/interoperability/index.ts +++ b/framework/src/modules/interoperability/index.ts @@ -14,8 +14,10 @@ export { BaseCCCommand } from './base_cc_command'; export { BaseInteroperableModule } from './base_interoperable_module'; +export { BaseInteroperabilityModule } from './base_interoperability_module'; +export { BaseInteroperabilityMethod } from './base_interoperability_method'; export { BaseCCMethod } from './base_cc_method'; -export { getMainchainID } from './utils'; +export { getMainchainID, validateFormat } from './utils'; // Mainchain export { MainchainInteroperabilityModule } from './mainchain/module'; @@ -50,13 +52,7 @@ export { RecoverContext, } from './types'; // Common -export { - LIVENESS_LIMIT, - MESSAGE_TAG_CERTIFICATE, - MODULE_NAME_INTEROPERABILITY, - MAX_CCM_SIZE, - EMPTY_BYTES, -} from './constants'; +export * from './constants'; export { ChainStatus } from './stores/chain_account'; export { ccmSchema, diff --git a/framework/src/modules/nft/cc_commands/cc_transfer.ts b/framework/src/modules/nft/cc_commands/cc_transfer.ts index ae4884b76fd..03a9bfbdada 100644 --- a/framework/src/modules/nft/cc_commands/cc_transfer.ts +++ b/framework/src/modules/nft/cc_commands/cc_transfer.ts @@ -31,6 +31,9 @@ import { FeeMethod } from '../types'; import { EscrowStore } from '../stores/escrow'; import { CcmTransferEvent } from '../events/ccm_transfer'; +/** + * Accepts CCMs created by the {@link CrossChainTransferCommand} and executes the cross-chain transfer on the receiving chain. + */ export class CrossChainTransferCommand extends BaseCCCommand { public schema = crossChainNFTTransferMessageParamsSchema; private _method!: NFTMethod; diff --git a/framework/src/modules/nft/commands/transfer.ts b/framework/src/modules/nft/commands/transfer.ts index bd5ae39d2c8..dcb3ec4a1b9 100644 --- a/framework/src/modules/nft/commands/transfer.ts +++ b/framework/src/modules/nft/commands/transfer.ts @@ -28,6 +28,19 @@ export interface TransferParams { data: string; } +/** + * The Transfer command transfers an NFT from one account to another. + * + * ## Parameters + * - `nftID`: number (16 byte long) + * - `recipientAddress`: string (Lisk32 address) + * - `data`: string (Optional transfer message) + * + * @example + * ```sh + * lisk-core transaction:create nft transfer 10000000 --params='{"nftID":"01000000000000010000000000000001","recipientAddress":"lskycz7hvr8yfu74bcwxy2n4mopfmjancgdvxq8xz","data":"Congratulations on completing the course!"}' + * ``` + */ export class TransferCommand extends BaseCommand { public schema = transferParamsSchema; private _internalMethod!: InternalMethod; diff --git a/framework/src/modules/nft/commands/transfer_cross_chain.ts b/framework/src/modules/nft/commands/transfer_cross_chain.ts index 062919f3830..5b37949d51f 100644 --- a/framework/src/modules/nft/commands/transfer_cross_chain.ts +++ b/framework/src/modules/nft/commands/transfer_cross_chain.ts @@ -33,6 +33,25 @@ export interface TransferCrossChainParams { includeAttributes: boolean; } +/** + * The TransferCrossChain command transfers an NFT from one account to another across chains. + * + * ## Name + * - `transferCrossChain` + * + * ## Parameters + * - `nftID` (number) : 16 byte long + * - `recipientAddress` (string) : Lisk32 address + * - `data` (string) : Optional transfer message + * - `receivingChainID` (string) : The {@link https://lisk.com/documentation/understand-blockchain/interoperability/index.html#chain-identifiers | Chain ID} of the network receiving the NFT. + * - `messageFee` (string): Fee for the execution of the CCM in Beddows + * - `includeAttributes` (boolean) : Boolean, if NFT attributes should be inlcuded in the cross-chain transfer, or not. + * + * @example + * ```sh + * lisk-core transaction:create nft transferCrossChain 10000000 --params='{"nftID":"01000000000000010000000000000001","recipientAddress":"lskycz7hvr8yfu74bcwxy2n4mopfmjancgdvxq8xz","data":"Congratulations on completing the course!","receivingChainID":"04000002","messageFee":"10000000","includeAttributes":true}' + * ``` + */ export class TransferCrossChainCommand extends BaseCommand { public schema = crossChainTransferParamsSchema; diff --git a/framework/src/modules/nft/endpoint.ts b/framework/src/modules/nft/endpoint.ts index 01cea421482..6df2ae4b7fe 100644 --- a/framework/src/modules/nft/endpoint.ts +++ b/framework/src/modules/nft/endpoint.ts @@ -38,6 +38,18 @@ export class NFTEndpoint extends BaseEndpoint { this._nftMethod = nftMethod; } + /** + * Gets all NFT owned by a specific account. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_getNFTs '{ "address": "lsk24cd35u4jdq8szo3pnsqe5dsxwrnazyqqqg5eu" }' --pretty + * ``` + * + * @param context + * + * @returns A list of all NFT owned by the specified account. + */ public async getNFTs( context: ModuleEndpointContext, ): Promise<{ nfts: JSONObject & { id: string }>[] }> { @@ -77,6 +89,18 @@ export class NFTEndpoint extends BaseEndpoint { return { nfts }; } + /** + * Checks whether an account owns a specific NFT or not. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_hasNFT '{ "address": "lsk24cd35u4jdq8szo3pnsqe5dsxwrnazyqqqg5eu", "id":"04000000000000010000000000000001" }' --pretty + * ``` + * + * @param context + * + * @returns `true` if the account owns the NFT, `false` if not. + */ public async hasNFT(context: ModuleEndpointContext): Promise<{ hasNFT: boolean }> { const { params } = context; validator.validate<{ address: string; id: string }>(hasNFTRequestSchema, params); @@ -96,6 +120,18 @@ export class NFTEndpoint extends BaseEndpoint { return { hasNFT: nftData.owner.equals(owner) }; } + /** + * Gets a specific NFT. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_getNFT '{ "id":"04000000000000010000000000000001" }' --pretty + * ``` + * + * @param context + * + * @returns The NFT with the specified {@link NFTModule | "NFT ID"}. + */ public async getNFT(context: ModuleEndpointContext): Promise> { const { params } = context; validator.validate<{ id: string }>(getNFTRequestSchema, params); @@ -142,6 +178,18 @@ export class NFTEndpoint extends BaseEndpoint { }; } + /** + * Returns all supported NFT collections of the network. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_getSupportedCollectionIDs --pretty + * ``` + * + * @param context + * + * @returns A list of all NFT collection IDs that are supported by the network. + */ public async getSupportedCollectionIDs( context: ModuleEndpointContext, ): Promise<{ supportedCollectionIDs: string[] }> { @@ -170,6 +218,18 @@ export class NFTEndpoint extends BaseEndpoint { return { supportedCollectionIDs }; } + /** + * Checks whether a specific NFT collection ID is supported by the network. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_isCollectionIDSupported '{ "chainID":"04000001","collectionID":"00000001" }' --pretty + * ``` + * + * @param context + * + * @returns `true` if the specified NFT collection is supported, `false` if not. + */ public async isCollectionIDSupported( context: ModuleEndpointContext, ): Promise<{ isCollectionIDSupported: boolean }> { @@ -207,6 +267,18 @@ export class NFTEndpoint extends BaseEndpoint { }; } + /** + * Gets all escrowed NFTs for a specific chain ID. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_getEscrowedNFTIDs '{ "chainID":"04000001" }' --pretty + * ``` + * + * @param context + * + * @returns A list of escrowed NFT for the specified chain ID. + */ public async getEscrowedNFTIDs( context: ModuleEndpointContext, ): Promise<{ escrowedNFTIDs: string[] }> { @@ -230,6 +302,18 @@ export class NFTEndpoint extends BaseEndpoint { }; } + /** + * Checks whether a specific NFT is supported by the network. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_isNFTSupported '{ "nftID":"04000000000000010000000000000001" }' --pretty + * ``` + * + * @param context + * + * @returns `true` if the NFT is supported, `false` if not. + */ public async isNFTSupported( context: ModuleEndpointContext, ): Promise<{ isNFTSupported: boolean }> { @@ -252,6 +336,18 @@ export class NFTEndpoint extends BaseEndpoint { return { isNFTSupported }; } + /** + * Returns all NFT supported by the network. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_getSupportedNFTs --pretty + * ``` + * + * @param context + * + * @returns A list of all supported NFT IDs + */ public async getSupportedNFTs( context: ModuleEndpointContext, ): Promise<{ supportedNFTs: string[] }> { diff --git a/framework/src/modules/nft/index.ts b/framework/src/modules/nft/index.ts index 14063d827fe..b5c2c758979 100644 --- a/framework/src/modules/nft/index.ts +++ b/framework/src/modules/nft/index.ts @@ -13,4 +13,23 @@ */ export { NFTModule } from './module'; +export { TransferParams, TransferCommand } from './commands/transfer'; +export { + TransferCrossChainParams, + TransferCrossChainCommand, +} from './commands/transfer_cross_chain'; +export { CrossChainTransferCommand } from './cc_commands/cc_transfer'; +export { NFTInteroperableMethod } from './cc_method'; export { NFTMethod } from './method'; +export { NFTEndpoint } from './endpoint'; +export { InternalMethod } from './internal_method'; +export { NFTAttributes } from './stores/nft'; +export { NFT, InteroperabilityMethod } from './types'; +export { + LENGTH_COLLECTION_ID, + LENGTH_NFT_ID, + LENGTH_INDEX, + MODULE_NAME_NFT, + FEE_CREATE_NFT, + NftEventResult, +} from './constants'; diff --git a/framework/src/modules/nft/method.ts b/framework/src/modules/nft/method.ts index 9695cfedd99..6303286958a 100644 --- a/framework/src/modules/nft/method.ts +++ b/framework/src/modules/nft/method.ts @@ -11,7 +11,6 @@ * * Removal or modification of this copyright notice is prohibited. */ - import { validator } from '@liskhq/lisk-validator'; import { codec } from '@liskhq/lisk-codec'; import { BaseMethod } from '../base_method'; @@ -49,6 +48,9 @@ import { SetAttributesEvent } from './events/set_attributes'; import { NotFoundError } from './error'; import { UnlockEvent } from './events/unlock'; +/** + * Methods of the NFT Module. + */ export class NFTMethod extends BaseMethod { private _config!: ModuleConfig; private _internalMethod!: InternalMethod; @@ -58,11 +60,29 @@ export class NFTMethod extends BaseMethod { this._config = config; } + /** + * Adds dependencies from other module methods. + * + * @param internalMethod + * @param feeMethod {@link Modules.Fee.FeeMethod} + */ public addDependencies(internalMethod: InternalMethod, feeMethod: FeeMethod) { this._internalMethod = internalMethod; this._feeMethod = feeMethod; } + /** + * Gets the chain ID of an NFT. + * + * @example + * ```ts + * getChainID(nftID); + * ``` + * + * @param nftID Unique identifier of the NFT + * + * @returns The ID of the chain the NFT belongs to. + */ public getChainID(nftID: Buffer): Buffer { if (nftID.length !== LENGTH_NFT_ID) { throw new Error(`NFT ID must have length ${LENGTH_NFT_ID}`); @@ -71,10 +91,34 @@ export class NFTMethod extends BaseMethod { return nftID.subarray(0, LENGTH_CHAIN_ID); } + /** + * Checks whether a provided NFT is escrowed, e.g. the NFT is a native NFT that has been sent cross-chain to a foreign chain. + * + * @example + * ```ts + * isNFTEscrowed(nft); + * ``` + * + * @param nft The NFT to be checked + * + * @returns `true`, if the NFT is escrowed, `false` if not. + */ public isNFTEscrowed(nft: NFT): boolean { return nft.owner.length !== LENGTH_ADDRESS; } + /** + * Checks whether a provided NFT is {@link lock | locked} or not. + * + * @example + * ```ts + * isNFTLocked(nft); + * ``` + * + * @param nft The NFT to be checked + * + * @returns `true` if the NFT is locked, `false` if not. + */ public isNFTLocked(nft: NFT): boolean { if (!nft.lockingModule) { return false; @@ -83,6 +127,19 @@ export class NFTMethod extends BaseMethod { return nft.lockingModule !== NFT_NOT_LOCKED; } + /** + * Gets a specific NFT. + * + * @example + * ```ts + * getNFT(methodContext,nftID); + * ``` + * + * @param methodContext immutable method context + * @param nftID ID of the NFT + * + * @returns The requested {@link NFT}. + */ public async getNFT(methodContext: ImmutableMethodContext, nftID: Buffer): Promise { const nftStore = this.stores.get(NFTStore); const nftExists = await nftStore.has(methodContext, nftID); @@ -107,6 +164,20 @@ export class NFTMethod extends BaseMethod { return data; } + /** + * Destroys the specified NFT. + * The NFT will be removed from the NFT substore and cannot be retrieved, except in the case of destroying NFT on a foreign chain: + * the information about the NFT (e.g., the attributes) will still be available in the corresponding escrow entry of the NFT substore in the native chain. + * + * @example + * ```ts + * destroy(methodContext,address,nftID); + * ``` + * + * @param methodContext method context + * @param address Address of the account who initiated the destruction + * @param nftID ID of the NFT to be destroyed + */ public async destroy( methodContext: MethodContext, address: Buffer, @@ -181,10 +252,36 @@ export class NFTMethod extends BaseMethod { }); } + /** + * Gets the ID of the collection of an NFT. + * + * @example + * ```ts + * getCollectionID(nftID); + * ``` + * + * @param nftID ID of an NFT + * + * @returns The collection ID of the NFT. + */ public getCollectionID(nftID: Buffer): Buffer { return nftID.subarray(LENGTH_CHAIN_ID, LENGTH_CHAIN_ID + LENGTH_COLLECTION_ID); } + /** + * Checks whether the NFT is supported by the network, or not. + * + * @example + * ```ts + * isNFTSupported(methodContext,nftID); + * ``` + * + * @param methodContext Immutable method context + * @param nftID ID of an NFT + * + * @returns `true` if the NFT is supported, `false` if not. + */ + public async isNFTSupported( methodContext: ImmutableMethodContext, nftID: Buffer, @@ -222,6 +319,19 @@ export class NFTMethod extends BaseMethod { return false; } + /** + * Returns the next free index inside an NFT collection. + * + * @example + * ```ts + * getNextAvailableIndex(methodContext,collectionID); + * ``` + * + * @param methodContext method context + * @param collectionID ID of an NFT collection + * + * @returns Index of the next free slot inside an NFT collection. + */ public async getNextAvailableIndex( methodContext: MethodContext, collectionID: Buffer, @@ -249,6 +359,20 @@ export class NFTMethod extends BaseMethod { return index + BigInt(1); } + /** + * Mints a new NFT. + * The NFT will always be native to the chain creating it. + * + * @example + * ```ts + * create(methodContext,address,collectionID,attributesArray); + * ``` + * + * @param methodContext Method context + * @param address Address of the NFT owner + * @param collectionID ID of the collection the NFT belongs to + * @param attributesArray Attributes of the NFT + */ public async create( methodContext: MethodContext, address: Buffer, @@ -272,6 +396,22 @@ export class NFTMethod extends BaseMethod { }); } + /** + * This function locks an NFT to a given module. + * A locked NFT cannot be transferred (within the chain or across chains). + * This can be useful, for example, when the NFT is used as a deposit for a service. + * Module is specified both when locking and unlocking the NFT, thus preventing NFTs being accidentally locked and unlocked by different modules. + * Note that an NFT can not be locked to the NFT module. + * + * @example + * ```ts + * lock(methodContext,module,nftID); + * ``` + * + * @param methodContext Method context + * @param module The module locking the NFT + * @param nftID ID of the NFT to be locked + */ public async lock(methodContext: MethodContext, module: string, nftID: Buffer): Promise { if (module === NFT_NOT_LOCKED) { throw new Error('Cannot be locked by NFT module'); @@ -333,6 +473,18 @@ export class NFTMethod extends BaseMethod { }); } + /** + * This function is used to unlock an NFT that was {@link lock | locked} to a module. + * + * @example + * ```ts + * unlock(methodContext,module,nftID); + * ``` + * + * @param methodContext Method context + * @param module The module unlocking the NFT + * @param nftID ID of the NFT to be unlocked + */ public async unlock(methodContext: MethodContext, module: string, nftID: Buffer): Promise { let nft; try { @@ -394,6 +546,19 @@ export class NFTMethod extends BaseMethod { }); } + /** + * This function is used to transfer ownership of NFTs within one chain. + * + * @example + * ```ts + * transfer(methodContext,senderAddress,recipientAddress,nftID); + * ``` + * + * @param methodContext Method context + * @param senderAddress Address of the current owner of the NFT + * @param recipientAddress Address of the new owner of the NFT + * @param nftID ID of the NFT to be transferred + */ public async transfer( methodContext: MethodContext, senderAddress: Buffer, @@ -421,6 +586,23 @@ export class NFTMethod extends BaseMethod { await this._internalMethod.transfer(methodContext, recipientAddress, nftID); } + /** + * This function is used to transfer ownership of NFTs across chains in the Lisk ecosystem. + * + * @example + * ```ts + * transferCrossChain(methodContext,senderAddress,recipientAddress,nftID,receivingChainID,messageFee,data,includeAttributes); + * ``` + * + * @param methodContext Method context + * @param senderAddress Address of the current owner of the NFT + * @param recipientAddress Address of the new owner of the NFT + * @param nftID ID of the NFT to be transferred + * @param receivingChainID ID of the chain where the NFT is being transferred to + * @param messageFee Fee for the CCM + * @param data Message field + * @param includeAttributes Boolean, if the attributes of the NFT should be included in the transfer + */ public async transferCrossChain( methodContext: MethodContext, senderAddress: Buffer, @@ -471,6 +653,16 @@ export class NFTMethod extends BaseMethod { ); } + /** + * This function updates the supported NFTs substore to support all NFTs of the Lisk ecosystem. + * + * @example + * ```ts + * supportAllNFTs(methodContext); + * ``` + * + * @param methodContext + */ public async supportAllNFTs(methodContext: MethodContext): Promise { const supportedNFTsStore = this.stores.get(SupportedNFTsStore); @@ -493,6 +685,16 @@ export class NFTMethod extends BaseMethod { this.events.get(AllNFTsSupportedEvent).log(methodContext); } + /** + * This function removes support for all non-native NFTs. + * + * @example + * ```ts + * removeSupportAllNFTs(methodContext); + * ``` + * + * @param methodContext + */ public async removeSupportAllNFTs(methodContext: MethodContext): Promise { const supportedNFTsStore = this.stores.get(SupportedNFTsStore); @@ -507,6 +709,17 @@ export class NFTMethod extends BaseMethod { this.events.get(AllNFTsSupportRemovedEvent).log(methodContext); } + /** + * This function updates the supported NFTs substore to support all non-native NFTs of a specified foreign chain. + * + * @example + * ```ts + * supportAllNFTsFromChain(methodContext,chainID); + * ``` + * + * @param methodContext Method context + * @param chainID ID of a chain + */ public async supportAllNFTsFromChain( methodContext: MethodContext, chainID: Buffer, @@ -539,6 +752,17 @@ export class NFTMethod extends BaseMethod { this.events.get(AllNFTsFromChainSupportedEvent).log(methodContext, chainID); } + /** + * This function removes support for all non-native NFTs of a specified foreign chain. + * + * @example + * ```ts + * removeSupportAllNFTsFromChain(methodContext,chainID); + * ``` + * + * @param methodContext + * @param chainID ID of a chain + */ public async removeSupportAllNFTsFromChain( methodContext: MethodContext, chainID: Buffer, @@ -566,6 +790,18 @@ export class NFTMethod extends BaseMethod { this.events.get(AllNFTsFromChainSupportRemovedEvent).log(methodContext, chainID); } + /** + * This function updates the supported NFTs substore to support all non-native NFTs of a specified collection. + * + * @example + * ```ts + * supportAllNFTsFromCollection(methodContext,chainID,collectionID); + * ``` + * + * @param methodContext Method context + * @param chainID The chain ID the NFT collection belongs to + * @param collectionID The NFT collection to be supported + */ public async supportAllNFTsFromCollection( methodContext: MethodContext, chainID: Buffer, @@ -626,6 +862,18 @@ export class NFTMethod extends BaseMethod { }); } + /** + * This function removes support for all non-native NFTs of a specified collection. + * + * @example + * ```ts + * removeSupportAllNFTsFromCollection(methodContext,chainID,collectionID); + * ``` + * + * @param methodContext Method context + * @param chainID The chain ID the NFT collection belongs to + * @param collectionID The NFT collection to be un-supported + */ public async removeSupportAllNFTsFromCollection( methodContext: MethodContext, chainID: Buffer, @@ -679,6 +927,21 @@ export class NFTMethod extends BaseMethod { }); } + /** + * This function recovers an NFT escrowed to a terminated chain. + * It should only be called by the {@link Modules.Interoperability.BaseInteroperabilityModule | Interoperability module} to trigger the recovery of NFTs escrowed to terminated chains. + * + * @example + * ```ts + * recover(methodContext,terminatedChainID,substorePrefix,nftID,nft); + * ``` + * + * @param methodContext Method context + * @param terminatedChainID ID of the terminated chain + * @param substorePrefix Prefix of the NFT substore + * @param nftID ID of the nft to recover + * @param nft The NFT to recover + */ public async recover( methodContext: MethodContext, terminatedChainID: Buffer, @@ -796,6 +1059,21 @@ export class NFTMethod extends BaseMethod { }); } + /** + * This function is used to modify the attributes of NFTs. + * Each custom module can define the rules surrounding modifying NFT attributes and should call this function. + * This function will be executed even if the NFT is locked. + * + * @example + * ```ts + * setAttributes(methodContext,module,nftID,attributes); + * ``` + * + * @param methodContext Method context + * @param module Name of the module updating the NFT attributes + * @param nftID ID of an NFT + * @param attributes Attributes to add to the NFT + */ public async setAttributes( methodContext: MethodContext, module: string, diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 7521b750b36..4059629e16d 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -68,6 +68,41 @@ import { MODULE_NAME_NFT, } from './constants'; +/** + * ## Description + * The `NFTModule` is used for creating, destroying NFTs (non-fungible tokens), and transferring them in the Lisk ecosystem. + * + * ## Not a stand-alone module + * The NFT module is not intended to be used as a stand-alone module. + * Instead, it should be used inside other modules, that intend to implement features related to NFTs. + * Other modules can use the provided {@link method | methods} of the NFT module, to implement custom commands for minting and destroying NFTs in the network. + * This allows to define the specific details about how NFTs are created, and who is allowed to mint them. + * + * ## NFT Identifier + * To identify NFTs in the Lisk ecosystem, we introduce the `nftID`, a unique NFT identifier in the ecosystem. + * It is a 16 bytes long concatenation of the 4 bytes long `chainID`, the chain ID of the chain creating the NFT, the 4 bytes long `collectionID`, chosen when the NFT is created, and an 8 bytes long serialization of an index integer, automatically assigned at the NFT creation. + * + * This allows chains to define multiple sets of NFTs, each identified by their respective collection. Each collection can then easily have its own attributes schema and custom logic. + * For example, an art NFT exchange could have a different collection per artist, the index being a unique integer associated with each art piece of this artist. + * + * ## Attributes + * Each NFT is stored with an array of attributes specified by various modules, with each attribute property being a byte sequence that is not deserialized by the NFT module. + * Each custom module using NFTs should define schemas to serialize and deserialize their attributes property of NFTs. + * + * Note that the attributes properties are not limited in size by default, which can potentially cause the CCM {@link Modules.Interoperability.validateFormat} failure during the cross-chain NFT transfer. + * + * When an NFT is sent to another chain, the `attributes` properties of the NFT can be modified according to specifications set on the receiving chain. + * When the NFT is received back on its native chain, the returned modified attributes are disregarded and the original attributes are restored, as currently defined by {@link https://github.com/LiskHQ/lips/blob/main/proposals/lip-0052.md#getnewattributes | getNewAttributes} function. + * If needed, custom modules can implement a more fine-grained approach towards the attributes that are modified cross-chain. + * + * ## NFT cross-chain transfers + * As is the case with fungible tokens, all NFTs are escrowed in the native chain. + * Technically, this means that when a token is sent from its native chain to another, the NFT is not erased, but the owner of the NFT now becomes the receiving chain. + * When an NFT is returned, the native chain can then check that the NFT is indeed coming from the chain it was sent to and was not maliciously created and transferred from another chain. + * This implies that NFTs can only be transferred to and from their native chain. + * + * @see [LIP 0052 - Introduce NFT module](https://github.com/LiskHQ/lips/blob/main/proposals/lip-0052.md) + */ export class NFTModule extends BaseInteroperableModule { public method = new NFTMethod(this.stores, this.events); public endpoint = new NFTEndpoint(this.stores, this.offchainStores); @@ -84,6 +119,9 @@ export class NFTModule extends BaseInteroperableModule { public commands = [this._transferCommand, this._ccTransferCommand]; + /** + * Blockchain {@link events | Events} and {@link stores | Stores} of the module are registered in the constructor of a module, for later use in the module. + */ public constructor() { super(); this.events.register(TransferEvent, new TransferEvent(this.name)); @@ -120,10 +158,22 @@ export class NFTModule extends BaseInteroperableModule { this.stores.register(SupportedNFTsStore, new SupportedNFTsStore(this.name, 3)); } + /** + * @returns {@link MODULE_NAME_NFT} + */ public get name(): string { return MODULE_NAME_NFT; } + /** + * Adds dependencies from other modules. + * + * This method should be called where the module is registered to the app (generally in the `app.ts` or `modules.ts` file). + * + * @param interoperabilityMethod {@link InteroperabilityMethod} + * @param feeMethod {@link Modules.Fee.FeeMethod} + * @param tokenMethod {@link Modules.Token.TokenMethod} + */ public addDependencies( interoperabilityMethod: InteroperabilityMethod, feeMethod: FeeMethod, diff --git a/framework/src/modules/nft/types.ts b/framework/src/modules/nft/types.ts index 080089ccc0a..c9d9dbfcdd1 100644 --- a/framework/src/modules/nft/types.ts +++ b/framework/src/modules/nft/types.ts @@ -61,9 +61,13 @@ export interface NFTAttributes { attributes: Buffer; } +/** Interface for NFTs */ export interface NFT { + // Owner of the NFT owner: Buffer; + // NFT Attributes attributesArray: NFTAttributes[]; + // Name of the module locking the NFT (if locked). lockingModule?: string; } diff --git a/framework/src/plugins/index.ts b/framework/src/plugins/index.ts new file mode 100644 index 00000000000..0a7b36120ce --- /dev/null +++ b/framework/src/plugins/index.ts @@ -0,0 +1,2 @@ +export { BasePlugin, PluginInitContext } from './base_plugin'; +export { BasePluginEndpoint } from './base_plugin_endpoint'; diff --git a/framework/src/state_machine/event_queue.ts b/framework/src/state_machine/event_queue.ts index 2e3408307c6..cf73c6e85fa 100644 --- a/framework/src/state_machine/event_queue.ts +++ b/framework/src/state_machine/event_queue.ts @@ -19,6 +19,7 @@ interface RevertibleEvent { noRevert: boolean; } +/** Event interface to add blockchain events to the event queue. */ export class EventQueue { private readonly _height: number; private readonly _events: RevertibleEvent[]; diff --git a/framework/src/state_machine/index.ts b/framework/src/state_machine/index.ts index 470ac14d7e3..8f53215f332 100644 --- a/framework/src/state_machine/index.ts +++ b/framework/src/state_machine/index.ts @@ -21,24 +21,7 @@ export { BlockContext } from './block_context'; export { GenesisBlockContext } from './genesis_block_context'; export { EventQueue } from './event_queue'; export { createMethodContext, createImmutableMethodContext } from './method_context'; -export { - MethodContext, - BlockHeader, - BlockAssets, - VerifyStatus, - ImmutableSubStore, - ImmutableMethodContext, - BlockExecuteContext, - BlockAfterExecuteContext, - BlockVerifyContext, - InsertAssetContext, - GenesisBlockExecuteContext, - TransactionExecuteContext, - TransactionVerifyContext, - VerificationResult, - CommandVerifyContext, - CommandExecuteContext, -} from './types'; +export * from './types'; export { StateMachine } from './state_machine'; diff --git a/framework/src/state_machine/types.ts b/framework/src/state_machine/types.ts index 32849dd0979..0cecb260f82 100644 --- a/framework/src/state_machine/types.ts +++ b/framework/src/state_machine/types.ts @@ -39,17 +39,27 @@ export interface ImmutableStateStore { getStore: (moduleID: Buffer, storePrefix: Buffer) => ImmutableSubStore; } +/** State store interface. */ export interface StateStore { getStore: (moduleID: Buffer, storePrefix: Buffer) => SubStore; createSnapshot(): number; restoreSnapshot(snapshotID: number): void; } +/** Context for immutable methods */ export interface ImmutableMethodContext { getStore: (moduleID: Buffer, storePrefix: Buffer) => ImmutableSubStore; } +/** Context for methods */ export interface MethodContext { + /** + * Returns a module store based on module ID and store prefix + * @param moduleID The ID of a module + * @param storePrefix The prefix of a module store + * + * @returns The requested module store. + */ getStore: (moduleID: Buffer, storePrefix: Buffer) => SubStore; eventQueue: EventQueue; contextStore: Map; @@ -61,6 +71,7 @@ export enum VerifyStatus { PENDING = TransactionVerifyResult.PENDING, } +/** The block header. */ export interface BlockHeader { version: number; height: number; @@ -77,6 +88,7 @@ export interface BlockHeader { }; } +/** The block assets. */ export interface BlockAssets { getAsset: (module: string) => Buffer | undefined; } @@ -151,19 +163,31 @@ export interface CommandExecuteContext { getStore: (moduleID: Buffer, storePrefix: Buffer) => SubStore; } +/** + * Context for the genesis block execution hook. + */ export interface GenesisBlockExecuteContext { logger: Logger; eventQueue: EventQueue; stateStore: StateStore; getMethodContext: () => MethodContext; + /** State store interface to get data from the module stores. */ getStore: (moduleID: Buffer, storePrefix: Buffer) => SubStore; header: BlockHeader; assets: BlockAssets; + /** + * Sets the next active validators to generate blocks after the genesis block. + * + * @param preCommitThreshold + * @param certificateThreshold + * @param validators + */ setNextValidators: ( preCommitThreshold: bigint, certificateThreshold: bigint, validators: Validator[], ) => void; + /** The identifier of the blockchain, the genesis block belongs to. */ chainID: Buffer; } diff --git a/framework/test/integration/controller/ipc_channel.spec.ts b/framework/test/integration/controller/ipc_channel.spec.ts index 9ee82cc50e5..37cde3afe33 100644 --- a/framework/test/integration/controller/ipc_channel.spec.ts +++ b/framework/test/integration/controller/ipc_channel.spec.ts @@ -18,7 +18,7 @@ import { resolve as pathResolve } from 'path'; import { IPCChannel, InMemoryChannel } from '../../../src/controller/channels'; import { Bus } from '../../../src/controller/bus'; import { IPCServer } from '../../../src/controller/ipc/ipc_server'; -import { EndpointHandlers } from '../../../src'; +import { Types } from '../../../src'; // TODO: ZeroMQ tests are unstable with jest https://github.com/zeromq/zeromq.js/issues/416 // eslint-disable-next-line jest/no-disabled-tests @@ -52,7 +52,7 @@ describe.skip('IPCChannel', () => { endpoints: { multiplyByTwo: (params: any) => params.val * 2, multiplyByThree: (params: any) => params.val * 3, - } as unknown as EndpointHandlers, + } as unknown as Types.EndpointHandlers, }; const beta = { @@ -68,7 +68,7 @@ describe.skip('IPCChannel', () => { } return 0; }, - } as unknown as EndpointHandlers, + } as unknown as Types.EndpointHandlers, }; describe('after registering itself to the bus', () => { diff --git a/framework/test/integration/node/genesis_block.spec.ts b/framework/test/integration/node/genesis_block.spec.ts index 08e71e6ef94..169eba5b166 100644 --- a/framework/test/integration/node/genesis_block.spec.ts +++ b/framework/test/integration/node/genesis_block.spec.ts @@ -16,7 +16,7 @@ import { Chain } from '@liskhq/lisk-chain'; import { address } from '@liskhq/lisk-cryptography'; import * as testing from '../../../src/testing'; import { createTransferTransaction, defaultTokenID } from '../../utils/mocks/transaction'; -import { TokenModule } from '../../../src'; +import { Modules } from '../../../src'; import { genesisTokenStoreSchema } from '../../../src/modules/token'; import { GenesisTokenStore } from '../../../src/modules/token/types'; import { Consensus } from '../../../src/engine/consensus'; @@ -53,7 +53,9 @@ describe('genesis block', () => { it('should save accounts from genesis block assets', async () => { // Get genesis accounts - const tokenAsset = processEnv.getGenesisBlock().assets.getAsset(new TokenModule().name); + const tokenAsset = processEnv + .getGenesisBlock() + .assets.getAsset(new Modules.Token.TokenModule().name); const decoded = codec.decode( genesisTokenStoreSchema, tokenAsset as Buffer, @@ -96,7 +98,9 @@ describe('genesis block', () => { let recipientAddress: Buffer; beforeEach(async () => { - const tokenAsset = processEnv.getGenesisBlock().assets.getAsset(new TokenModule().name); + const tokenAsset = processEnv + .getGenesisBlock() + .assets.getAsset(new Modules.Token.TokenModule().name); const decoded = codec.decode( genesisTokenStoreSchema, tokenAsset as Buffer, diff --git a/framework/test/unit/abi_handler/abi_handler.spec.ts b/framework/test/unit/abi_handler/abi_handler.spec.ts index 8d3439b5c9b..c4c7ad13518 100644 --- a/framework/test/unit/abi_handler/abi_handler.spec.ts +++ b/framework/test/unit/abi_handler/abi_handler.spec.ts @@ -16,7 +16,7 @@ import { Block, BlockAssets, Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { utils } from '@liskhq/lisk-cryptography'; import { StateDB } from '@liskhq/lisk-db'; -import { BaseModule, TokenModule } from '../../../src'; +import { Modules } from '../../../src'; import { ABIHandler } from '../../../src/abi_handler/abi_handler'; import { transferParamsSchema } from '../../../src/modules/token/schemas'; import { StateMachine } from '../../../src/state_machine'; @@ -48,10 +48,10 @@ describe('abi handler', () => { commit: jest.fn().mockResolvedValue(utils.getRandomBytes(32)), } as never; const stateMachine = new StateMachine(); - const mod = new TokenModule(); + const mod = new Modules.Token.TokenModule(); const mod2 = new AuthModule(); jest.spyOn(mod.commands[0], 'execute').mockResolvedValue(); - stateMachine.registerModule(mod as BaseModule); + stateMachine.registerModule(mod as Modules.BaseModule); abiHandler = new ABIHandler({ logger: fakeLogger, channel: channelMock, @@ -78,9 +78,9 @@ describe('abi handler', () => { describe('init', () => { it('should not revert state and cache chainID if state is correct', async () => { const stateMachine = new StateMachine(); - const mod = new TokenModule(); + const mod = new Modules.Token.TokenModule(); jest.spyOn(mod.commands[0], 'execute').mockResolvedValue(); - stateMachine.registerModule(mod as BaseModule); + stateMachine.registerModule(mod as Modules.BaseModule); abiHandler = new ABIHandler({ logger: fakeLogger, channel: channelMock, diff --git a/framework/test/unit/application.spec.ts b/framework/test/unit/application.spec.ts index 1149a1e70f8..6ee045c731d 100644 --- a/framework/test/unit/application.spec.ts +++ b/framework/test/unit/application.spec.ts @@ -18,17 +18,7 @@ import * as childProcess from 'child_process'; import * as fs from 'fs-extra'; import * as os from 'os'; import { join } from 'path'; -import { - BaseCCMethod, - BaseEndpoint, - BaseInteroperableModule, - BaseMethod, - BaseModule, - BasePlugin, - MODULE_NAME_INTEROPERABILITY, - ModuleMetadata, - SidechainInteroperabilityModule, -} from '../../src'; +import { Modules, Plugins } from '../../src'; import { Application } from '../../src/application'; import { Bus } from '../../src/controller/bus'; import { WSServer } from '../../src/controller/ws/ws_server'; @@ -56,7 +46,7 @@ jest.mock('zeromq', () => { jest.mock('@liskhq/lisk-db'); jest.mock('../../src/logger'); -class TestPlugin extends BasePlugin { +class TestPlugin extends Plugins.BasePlugin { public get nodeModulePath(): string { return __filename; } @@ -70,10 +60,10 @@ class TestPlugin extends BasePlugin { public async unload(): Promise {} } -class TestModule extends BaseModule { +class TestModule extends Modules.BaseModule { public commands = []; - public endpoint: BaseEndpoint = {} as BaseEndpoint; - public method: BaseMethod = {} as BaseMethod; + public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint; + public method: Modules.BaseMethod = {} as Modules.BaseMethod; public verifyAssets = jest.fn(); public beforeTransactionsExecute = jest.fn(); @@ -82,16 +72,19 @@ class TestModule extends BaseModule { public get name() { return 'test-module'; } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { throw new Error('Method not implemented.'); } } -class TestInteroperableModule extends BaseInteroperableModule { - public crossChainMethod = { stores: {}, events: {} } as unknown as BaseCCMethod; +class TestInteroperableModule extends Modules.Interoperability.BaseInteroperableModule { + public crossChainMethod = { + stores: {}, + events: {}, + } as unknown as Modules.Interoperability.BaseCCMethod; public commands = []; - public endpoint: BaseEndpoint = {} as BaseEndpoint; - public method: BaseMethod = {} as BaseMethod; + public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint; + public method: Modules.BaseMethod = {} as Modules.BaseMethod; public verifyAssets = jest.fn(); public beforeTransactionsExecute = jest.fn(); @@ -101,7 +94,7 @@ class TestInteroperableModule extends BaseInteroperableModule { return 'test-interoperable-module'; } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { throw new Error('Method not implemented.'); } } @@ -280,7 +273,7 @@ describe('Application', () => { const interoperabilityModule = app['_registeredModules'].find( module => module.name === 'interoperability', - ) as SidechainInteroperabilityModule; + ) as Modules.Interoperability.SidechainInteroperabilityModule; expect( interoperabilityModule['interoperableCCCommands'].has(testInteroperableModule.name), @@ -295,7 +288,7 @@ describe('Application', () => { const { app } = Application.defaultApplication(config); const index = app['_registeredModules'].findIndex( - module => module.name === MODULE_NAME_INTEROPERABILITY, + module => module.name === Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, ); app['_registeredModules'][index] = new TestModule(); @@ -303,7 +296,7 @@ describe('Application', () => { const testInteroperableModule = new TestInteroperableModule(); expect(() => app.registerInteroperableModule(testInteroperableModule)).toThrow( - `${MODULE_NAME_INTEROPERABILITY} module is not registered.`, + `${Modules.Interoperability.MODULE_NAME_INTEROPERABILITY} module is not registered.`, ); }); }); diff --git a/framework/test/unit/controller/bus.spec.ts b/framework/test/unit/controller/bus.spec.ts index 661e59e8527..7c11b33b116 100644 --- a/framework/test/unit/controller/bus.spec.ts +++ b/framework/test/unit/controller/bus.spec.ts @@ -17,7 +17,7 @@ import * as fs from 'fs-extra'; import { Bus } from '../../../src/controller/bus'; import { Request } from '../../../src/controller/request'; import { IPCServer } from '../../../src/controller/ipc/ipc_server'; -import { EndpointInfo } from '../../../src'; +import { Types } from '../../../src'; import { InvokeRequest } from '../../../src/controller/channels/base_channel'; jest.mock('ws'); @@ -136,7 +136,7 @@ describe('Bus', () => { it('should register actions.', async () => { // Arrange const moduleName = 'name'; - const endpointInfo: { [key: string]: EndpointInfo } = { + const endpointInfo: { [key: string]: Types.EndpointInfo } = { action1: { namespace: 'name', method: 'action1', @@ -160,7 +160,7 @@ describe('Bus', () => { it('should throw error when trying to register duplicate actions.', async () => { // Arrange const moduleName = 'name'; - const endpointInfo: { [key: string]: EndpointInfo } = { + const endpointInfo: { [key: string]: Types.EndpointInfo } = { action1: { namespace: 'name', method: 'action1', @@ -179,7 +179,7 @@ describe('Bus', () => { it('should invoke the action on the channel.', async () => { // Arrange const moduleName = 'name'; - const endpointInfo: { [key: string]: EndpointInfo } = { + const endpointInfo: { [key: string]: Types.EndpointInfo } = { action1: { namespace: 'name', method: 'action1', @@ -196,7 +196,7 @@ describe('Bus', () => { it('should throw error when invoking an action on the channel with an invalid context.', async () => { // Arrange const moduleName = 'name'; - const endpointInfo: { [key: string]: EndpointInfo } = { + const endpointInfo: { [key: string]: Types.EndpointInfo } = { action1: { namespace: 'name', method: 'action1', @@ -244,7 +244,7 @@ describe('Bus', () => { it('should return a result of undefined when an empty context and action params are passed to a registered channel', async () => { const moduleName = 'name'; - const endpointInfo: { [key: string]: EndpointInfo } = { + const endpointInfo: { [key: string]: Types.EndpointInfo } = { action1: { namespace: 'name', method: 'action1', @@ -395,7 +395,7 @@ describe('Bus', () => { it('should return the registered actions', async () => { // Arrange const moduleName = 'name'; - const endpointInfo: { [key: string]: EndpointInfo } = { + const endpointInfo: { [key: string]: Types.EndpointInfo } = { action1: { namespace: 'name', method: 'action1', diff --git a/framework/test/unit/controller/controller.spec.ts b/framework/test/unit/controller/controller.spec.ts index c9161dfa3dd..4be7631dc93 100644 --- a/framework/test/unit/controller/controller.spec.ts +++ b/framework/test/unit/controller/controller.spec.ts @@ -22,7 +22,7 @@ import { Controller } from '../../../src/controller/controller'; import { Bus } from '../../../src/controller/bus'; import { InMemoryChannel } from '../../../src/controller/channels'; import * as basePluginModule from '../../../src/plugins/base_plugin'; -import { ApplicationConfigForPlugin, EndpointHandlers, testing } from '../../../src'; +import { Types, testing } from '../../../src'; jest.mock('zeromq'); @@ -93,7 +93,7 @@ describe('Controller Class', () => { ...testing.fixtures.defaultConfig.system, dataPath: '/user/.lisk/#LABEL', }, - } as ApplicationConfigForPlugin; + } as Types.ApplicationConfigForPlugin; const pluginConfigs = {}; const params = { @@ -107,7 +107,7 @@ describe('Controller Class', () => { moduleDB: new InMemoryDatabase() as unknown as Database, logger: loggerMock, events: ['app_start', 'app_blockNew'], - endpoints: new Map([['getBlockByID', jest.fn()]]) as EndpointHandlers, + endpoints: new Map([['getBlockByID', jest.fn()]]) as Types.EndpointHandlers, chainID: Buffer.alloc(0), }; diff --git a/framework/test/unit/controller/http/http_server.spec.ts b/framework/test/unit/controller/http/http_server.spec.ts index 45f0da2b970..e132abe8da4 100644 --- a/framework/test/unit/controller/http/http_server.spec.ts +++ b/framework/test/unit/controller/http/http_server.spec.ts @@ -48,7 +48,11 @@ describe('HTTPServer', () => { it('should setup event handlers', () => { // Assert - expect(httpServerInstance.server.eventNames()).toEqual(['request', 'connection', 'error']); + expect(httpServerInstance.server.eventNames()).toIncludeAllPartialMembers([ + 'request', + 'connection', + 'error', + ]); }); }); diff --git a/framework/test/unit/engine/endpoint/txpool.spec.ts b/framework/test/unit/engine/endpoint/txpool.spec.ts index 0f9a0f1ab1c..fa078eda379 100644 --- a/framework/test/unit/engine/endpoint/txpool.spec.ts +++ b/framework/test/unit/engine/endpoint/txpool.spec.ts @@ -22,7 +22,7 @@ import { Broadcaster } from '../../../../src/engine/generator/broadcaster'; import { InvalidTransactionError } from '../../../../src/engine/generator/errors'; import { fakeLogger } from '../../../utils/mocks'; import { TxpoolEndpoint } from '../../../../src/engine/endpoint/txpool'; -import { VerifyStatus } from '../../../../src'; +import { StateMachine } from '../../../../src'; import { ED25519_PUBLIC_KEY_LENGTH } from '../../../../src/engine/bft/constants'; const ED25519_SIGNATURE_LENGTH = 64; @@ -445,7 +445,7 @@ describe('txpool endpoint', () => { chainID, }), ).resolves.toEqual({ - result: VerifyStatus.OK, + result: StateMachine.VerifyStatus.OK, events: eventsJson, }); }); diff --git a/framework/test/unit/engine/engine.spec.ts b/framework/test/unit/engine/engine.spec.ts index f50c0708f17..b321ad5e7d1 100644 --- a/framework/test/unit/engine/engine.spec.ts +++ b/framework/test/unit/engine/engine.spec.ts @@ -14,13 +14,7 @@ */ import { Block, BlockAssets, Chain } from '@liskhq/lisk-chain'; import { jobHandlers } from '@liskhq/lisk-utils'; -import { Engine } from '../../../src/engine/engine'; -import { - Consensus, - CONSENSUS_EVENT_BLOCK_DELETE, - CONSENSUS_EVENT_BLOCK_NEW, - CONSENSUS_EVENT_FORK_DETECTED, -} from '../../../src/engine/consensus'; +import { Engine, Consensus } from '../../../src/engine'; import { ABI } from '../../../src/abi'; import * as logger from '../../../src/logger'; import { fakeLogger } from '../../utils/mocks'; @@ -29,8 +23,11 @@ import { Network } from '../../../src/engine/network'; import { Generator } from '../../../src/engine/generator'; import { RPCServer } from '../../../src/engine/rpc/rpc_server'; import { + CONSENSUS_EVENT_BLOCK_DELETE, + CONSENSUS_EVENT_BLOCK_NEW, CONSENSUS_EVENT_NETWORK_BLOCK_NEW, CONSENSUS_EVENT_VALIDATORS_CHANGED, + CONSENSUS_EVENT_FORK_DETECTED, } from '../../../src/engine/consensus/constants'; import { defaultConfig } from '../../../src/testing/fixtures'; import { createFakeBlockHeader } from '../../fixtures'; diff --git a/framework/test/unit/engine/legacy/legacy_chain_handler.spec.ts b/framework/test/unit/engine/legacy/legacy_chain_handler.spec.ts index c82dcf092de..b6bcf440941 100644 --- a/framework/test/unit/engine/legacy/legacy_chain_handler.spec.ts +++ b/framework/test/unit/engine/legacy/legacy_chain_handler.spec.ts @@ -16,7 +16,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { InMemoryDatabase } from '@liskhq/lisk-db'; -import { LegacyConfig } from '../../../../src'; +import { Types } from '../../../../src'; import { LegacyChainHandler } from '../../../../src/engine/legacy/legacy_chain_handler'; import { Network } from '../../../../src/engine/network'; import { encodeBlock } from '../../../../src/engine/legacy/codec'; @@ -30,7 +30,7 @@ const expectedSnapshotBlockID = utils.getRandomBytes(20); describe('Legacy Chain Handler', () => { let legacyChainHandler: LegacyChainHandler; - let legacyConfig: LegacyConfig; + let legacyConfig: Types.LegacyConfig; let peers: Peer[]; let network: Network; let legacyBlock16270316: LegacyBlock; diff --git a/framework/test/unit/modules/auth/stores/auth_account.spec.ts b/framework/test/unit/modules/auth/stores/auth_account.spec.ts index 5d36ecdd2e4..cdd320f8e89 100644 --- a/framework/test/unit/modules/auth/stores/auth_account.spec.ts +++ b/framework/test/unit/modules/auth/stores/auth_account.spec.ts @@ -13,7 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { StoreGetter } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { AuthAccount, AuthAccountStore } from '../../../../../src/modules/auth/stores/auth_account'; import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefixed_state_read_writer'; import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_prefixed_state'; @@ -29,7 +29,7 @@ describe('AuthAccountStore', () => { }; let authAccountStore: AuthAccountStore; - let context: StoreGetter; + let context: Modules.StoreGetter; beforeEach(async () => { authAccountStore = new AuthAccountStore('auth', 0); diff --git a/framework/test/unit/modules/base_store.spec.ts b/framework/test/unit/modules/base_store.spec.ts index a32b8c5a6e4..24e3bb2b7b4 100644 --- a/framework/test/unit/modules/base_store.spec.ts +++ b/framework/test/unit/modules/base_store.spec.ts @@ -13,7 +13,7 @@ */ import { Schema } from '@liskhq/lisk-codec'; -import { MethodContext } from '../../../src'; +import { StateMachine } from '../../../src'; import { BaseStore, computeSubstorePrefix } from '../../../src/modules/base_store'; import { createTransientMethodContext } from '../../../src/testing'; @@ -35,7 +35,7 @@ describe('BaseStore', () => { const key = Buffer.from([1, 2]); let store: SampleStore; - let context: MethodContext; + let context: StateMachine.MethodContext; beforeEach(() => { store = new SampleStore('sample', 0); diff --git a/framework/test/unit/modules/dynamic_reward/module.spec.ts b/framework/test/unit/modules/dynamic_reward/module.spec.ts index 001b7971325..94ddbc214c1 100644 --- a/framework/test/unit/modules/dynamic_reward/module.spec.ts +++ b/framework/test/unit/modules/dynamic_reward/module.spec.ts @@ -35,11 +35,7 @@ import { defaultConfig, EMPTY_BYTES, } from '../../../../src/modules/dynamic_reward/constants'; -import { - BlockAfterExecuteContext, - BlockExecuteContext, - GenesisBlockExecuteContext, -} from '../../../../src'; +import { StateMachine } from '../../../../src'; import { PrefixedStateReadWriter } from '../../../../src/state_machine/prefixed_state_read_writer'; import { EndOfRoundTimestampStore } from '../../../../src/modules/dynamic_reward/stores/end_of_round_timestamp'; import { @@ -139,7 +135,7 @@ describe('DynamicRewardModule', () => { }); describe('initGenesisState', () => { - let blockExecuteContext: GenesisBlockExecuteContext; + let blockExecuteContext: StateMachine.GenesisBlockExecuteContext; beforeEach(() => { stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); @@ -161,7 +157,7 @@ describe('DynamicRewardModule', () => { }); describe('beforeTransactionsExecute', () => { - let blockExecuteContext: BlockExecuteContext; + let blockExecuteContext: StateMachine.BlockExecuteContext; beforeEach(async () => { generatorAddress = utils.getRandomBytes(20); @@ -315,7 +311,7 @@ describe('DynamicRewardModule', () => { }); describe('afterTransactionsExecute', () => { - let blockExecuteContext: BlockAfterExecuteContext; + let blockExecuteContext: StateMachine.BlockAfterExecuteContext; let contextStore: Map; beforeEach(async () => { diff --git a/framework/test/unit/modules/fee/cc_method.spec.ts b/framework/test/unit/modules/fee/cc_method.spec.ts index 31b54218930..4805a6d269b 100644 --- a/framework/test/unit/modules/fee/cc_method.spec.ts +++ b/framework/test/unit/modules/fee/cc_method.spec.ts @@ -13,7 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { FeeModule } from '../../../../src'; +import { Modules } from '../../../../src'; import { FeeInteroperableMethod } from '../../../../src/modules/fee/cc_method'; import { CONTEXT_STORE_KEY_AVAILABLE_CCM_FEE } from '../../../../src/modules/fee/constants'; import { createCrossChainMessageContext } from '../../../../src/testing'; @@ -21,7 +21,7 @@ import { CrossChainMessageContext } from '../../../../src/modules/interoperabili import { RelayerFeeProcessedEvent } from '../../../../src/modules/fee/events/relayer_fee_processed'; describe('FeeInteroperableMethod', () => { - const feeModule = new FeeModule(); + const feeModule = new Modules.Fee.FeeModule(); const ccm = { module: 'token', crossChainCommand: 'crossChainTransfer', diff --git a/framework/test/unit/modules/fee/endpoint.spec.ts b/framework/test/unit/modules/fee/endpoint.spec.ts index 3384240bae5..f9eb7c3ebaf 100644 --- a/framework/test/unit/modules/fee/endpoint.spec.ts +++ b/framework/test/unit/modules/fee/endpoint.spec.ts @@ -13,14 +13,14 @@ */ import { InMemoryPrefixedStateDB } from '../../../../src/testing/in_memory_prefixed_state'; import { PrefixedStateReadWriter } from '../../../../src/state_machine/prefixed_state_read_writer'; -import { FeeModule } from '../../../../src'; +import { Modules } from '../../../../src'; import { createTransientModuleEndpointContext } from '../../../../src/testing'; import { FeeEndpoint } from '../../../../src/modules/fee/endpoint'; import { ModuleConfig } from '../../../../src/modules/fee/types'; import { defaultConfig } from '../../../../src/modules/fee/constants'; describe('FeeModuleEndpoint', () => { - const fee = new FeeModule(); + const fee = new Modules.Fee.FeeModule(); const config: ModuleConfig = { ...defaultConfig, feeTokenID: Buffer.from('1000000000000002', 'hex'), diff --git a/framework/test/unit/modules/fee/method.spec.ts b/framework/test/unit/modules/fee/method.spec.ts index a45492fd7f1..4bb5b5bd3d2 100644 --- a/framework/test/unit/modules/fee/method.spec.ts +++ b/framework/test/unit/modules/fee/method.spec.ts @@ -14,7 +14,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { createMethodContext, MethodContext } from '../../../../src/state_machine/method_context'; -import { FeeMethod, FeeModule } from '../../../../src'; +import { Modules } from '../../../../src'; import { ModuleConfig } from '../../../../src/modules/fee/types'; import { CONTEXT_STORE_KEY_AVAILABLE_CCM_FEE, @@ -27,18 +27,18 @@ import { EventQueue } from '../../../../src/state_machine'; import { PrefixedStateReadWriter } from '../../../../src/state_machine/prefixed_state_read_writer'; describe('FeeMethod', () => { - const fee = new FeeModule(); + const fee = new Modules.Fee.FeeModule(); const config: ModuleConfig = { ...defaultConfig, feeTokenID: Buffer.from('1000000000000002', 'hex'), minFeePerByte: 1234, }; - let feeMethod: FeeMethod; + let feeMethod: Modules.Fee.FeeMethod; let methodContext: MethodContext; beforeEach(() => { - feeMethod = new FeeMethod(fee.stores, fee.events); + feeMethod = new Modules.Fee.FeeMethod(fee.stores, fee.events); feeMethod.init(config); methodContext = createMethodContext({ contextStore: new Map(), diff --git a/framework/test/unit/modules/interoperability/base_cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/base_cc_commands/channel_terminated.spec.ts index 8d989c64437..c27d881ce03 100644 --- a/framework/test/unit/modules/interoperability/base_cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/base_cc_commands/channel_terminated.spec.ts @@ -13,7 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { ChainStatus, MainchainInteroperabilityModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { CCMStatusCode, CHAIN_ID_LENGTH, @@ -33,7 +33,7 @@ import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefix import { CCCommandExecuteContext } from '../../../../../src/modules/interoperability/types'; describe('BaseCCChannelTerminatedCommand', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const createTerminatedStateAccountMock = jest.fn(); let sampleExecuteContext: CCCommandExecuteContext; @@ -80,7 +80,7 @@ describe('BaseCCChannelTerminatedCommand', () => { timestamp: 100, validatorsHash: utils.getRandomBytes(32), }, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, }; beforeEach(() => { diff --git a/framework/test/unit/modules/interoperability/base_cc_commands/registration.spec.ts b/framework/test/unit/modules/interoperability/base_cc_commands/registration.spec.ts index 2bba2592d13..d8d66ea6889 100644 --- a/framework/test/unit/modules/interoperability/base_cc_commands/registration.spec.ts +++ b/framework/test/unit/modules/interoperability/base_cc_commands/registration.spec.ts @@ -14,7 +14,7 @@ import { codec } from '@liskhq/lisk-codec'; import { utils } from '@liskhq/lisk-cryptography'; -import { MainchainInteroperabilityModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { CCMStatusCode, CROSS_CHAIN_COMMAND_REGISTRATION, @@ -36,7 +36,7 @@ import { CHAIN_ID_LENGTH } from '../../../../../src/modules/token/constants'; import { ChainAccountUpdatedEvent } from '../../../../../src/modules/interoperability/events/chain_account_updated'; describe('BaseCCRegistrationCommand', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const objGetSetHas = () => ({ get: jest.fn(), diff --git a/framework/test/unit/modules/interoperability/base_cross_chain_update_command.spec.ts b/framework/test/unit/modules/interoperability/base_cross_chain_update_command.spec.ts index 414178d3433..584f58ecce3 100644 --- a/framework/test/unit/modules/interoperability/base_cross_chain_update_command.spec.ts +++ b/framework/test/unit/modules/interoperability/base_cross_chain_update_command.spec.ts @@ -16,13 +16,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { EMPTY_BUFFER } from '@liskhq/lisk-chain/dist-node/constants'; import { validator } from '@liskhq/lisk-validator'; -import { - CommandExecuteContext, - MainchainInteroperabilityModule, - Transaction, - CommandVerifyContext, - ChainAccount, -} from '../../../../src'; +import { StateMachine, Modules, Transaction } from '../../../../src'; import { BaseCCCommand } from '../../../../src/modules/interoperability/base_cc_command'; import { BaseCrossChainUpdateCommand } from '../../../../src/modules/interoperability/base_cross_chain_update_command'; import { BaseCCMethod } from '../../../../src/modules/interoperability/base_cc_method'; @@ -78,15 +72,15 @@ import { TransactionContext } from '../../../../src/state_machine'; class CrossChainUpdateCommand extends BaseCrossChainUpdateCommand { // eslint-disable-next-line @typescript-eslint/require-await - public async execute(_context: CommandExecuteContext): Promise { + public async execute(_context: StateMachine.CommandExecuteContext): Promise { throw new Error('Method not implemented.'); } } describe('BaseCrossChainUpdateCommand', () => { - let executeContext: CommandExecuteContext; + let executeContext: StateMachine.CommandExecuteContext; let stateStore: PrefixedStateReadWriter; - const interopsModule = new MainchainInteroperabilityModule(); + const interopsModule = new Modules.Interoperability.MainchainInteroperabilityModule(); const senderPublicKey = utils.getRandomBytes(32); const messageFeeTokenID = Buffer.alloc(8, 0); const chainID = Buffer.alloc(4, 0); @@ -215,7 +209,7 @@ describe('BaseCrossChainUpdateCommand', () => { let internalMethod: MainchainInteroperabilityInternalMethod; beforeEach(() => { - const interopModule = new MainchainInteroperabilityModule(); + const interopModule = new Modules.Interoperability.MainchainInteroperabilityModule(); stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); ccMethods = new Map(); ccMethods.set( @@ -283,7 +277,7 @@ describe('BaseCrossChainUpdateCommand', () => { }); describe('verifyCommon', () => { - let verifyContext: CommandVerifyContext; + let verifyContext: StateMachine.CommandVerifyContext; const ownChainAccount: OwnChainAccount = { chainID: EMPTY_BUFFER, @@ -291,7 +285,7 @@ describe('BaseCrossChainUpdateCommand', () => { nonce: BigInt(1), }; - const chainAccount: ChainAccount = { + const chainAccount: Modules.Interoperability.ChainAccount = { status: ChainStatus.REGISTERED, name: 'chain123', lastCertificate: { diff --git a/framework/test/unit/modules/interoperability/base_interoperability_module.spec.ts b/framework/test/unit/modules/interoperability/base_interoperability_module.spec.ts index 863f80f6d73..08d51315ad3 100644 --- a/framework/test/unit/modules/interoperability/base_interoperability_module.spec.ts +++ b/framework/test/unit/modules/interoperability/base_interoperability_module.spec.ts @@ -14,12 +14,7 @@ import { terminatedStateAccount, mainchainID, } from './interopFixtures'; -import { - ActiveValidator, - ChainStatus, - EMPTY_BYTES, - MainchainInteroperabilityModule, -} from '../../../../src'; +import { Engine, Modules } from '../../../../src'; import { MAX_NUM_VALIDATORS, MIN_RETURN_FEE_PER_BYTE_BEDDOWS, @@ -49,7 +44,7 @@ describe('initGenesisState Common Tests', () => { const chainID = Buffer.from([0, 0, 0, 0]); let stateStore: PrefixedStateReadWriter; - let interopMod: MainchainInteroperabilityModule; + let interopMod: Modules.Interoperability.MainchainInteroperabilityModule; let certificateThreshold = BigInt(0); let params: CreateGenesisBlockContextParams; let ownChainAccountStore: OwnChainAccountStore; @@ -62,7 +57,7 @@ describe('initGenesisState Common Tests', () => { beforeEach(() => { stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); - interopMod = new MainchainInteroperabilityModule(); + interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); params = { stateStore, chainID, @@ -172,7 +167,7 @@ describe('initGenesisState Common Tests', () => { }); it(`should throw error if activeValidators have more than MAX_NUM_VALIDATORS elements`, async () => { - const activeValidatorsTemp: ActiveValidator[] = []; + const activeValidatorsTemp: Engine.ActiveValidator[] = []; const max = MAX_NUM_VALIDATORS + 10; for (let i = 1; i < max; i += 1) { activeValidatorsTemp.push({ @@ -495,7 +490,7 @@ must NOT have more than ${MAX_NUM_VALIDATORS} items`, ...chainInfo, chainData: { ...chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -545,7 +540,7 @@ must NOT have more than ${MAX_NUM_VALIDATORS} items`, chainID: Buffer.from([0, 0, 0, 2]), chainData: { ...chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -609,11 +604,15 @@ must NOT have more than ${MAX_NUM_VALIDATORS} items`, await expect(interopMod.initGenesisState(context)).resolves.not.toThrow(); expect(ownChainAccountStore.set).toHaveBeenCalledTimes(1); - expect(ownChainAccountStore.set).toHaveBeenCalledWith(context, EMPTY_BYTES, { - name: genesisInteroperability.ownChainName, - chainID: context.chainID, - nonce: genesisInteroperability.ownChainNonce, - }); + expect(ownChainAccountStore.set).toHaveBeenCalledWith( + context, + Modules.Interoperability.EMPTY_BYTES, + { + name: genesisInteroperability.ownChainName, + chainID: context.chainID, + nonce: genesisInteroperability.ownChainNonce, + }, + ); }); it('should not throw error If for each entry in chainInfos, we add valid substore entries', async () => { @@ -684,7 +683,7 @@ must NOT have more than ${MAX_NUM_VALIDATORS} items`, ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), }, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, }, chainValidators: { activeValidators, @@ -736,7 +735,7 @@ must NOT have more than ${MAX_NUM_VALIDATORS} items`, ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), }, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, }, chainValidators: { activeValidators, diff --git a/framework/test/unit/modules/interoperability/base_state_recovery.spec.ts b/framework/test/unit/modules/interoperability/base_state_recovery.spec.ts index c6e6d6607e1..587cfa5ab15 100644 --- a/framework/test/unit/modules/interoperability/base_state_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/base_state_recovery.spec.ts @@ -16,11 +16,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { utils } from '@liskhq/lisk-cryptography'; import { SparseMerkleTree } from '@liskhq/lisk-db'; -import { - CommandExecuteContext, - CommandVerifyContext, - MainchainInteroperabilityModule, -} from '../../../../src'; +import { StateMachine, Modules } from '../../../../src'; import { BaseCCCommand } from '../../../../src/modules/interoperability/base_cc_command'; import { BaseCCMethod } from '../../../../src/modules/interoperability/base_cc_method'; import { @@ -45,12 +41,12 @@ import { computeStorePrefix } from '../../../../src/modules/base_store'; describe('RecoverStateCommand', () => { // Since the code is same for both mainchain and sidechain, using mainchain will be enough to test both - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const moduleName = 'fooModule'; let chainIDAsBuffer: Buffer; let stateRecoveryCommand: RecoverStateCommand; - let commandVerifyContext: CommandVerifyContext; - let commandExecuteContext: CommandExecuteContext; + let commandVerifyContext: StateMachine.CommandVerifyContext; + let commandExecuteContext: StateMachine.CommandExecuteContext; let interoperableCCMethods: Map; let interoperableMethod: any; let ccCommands: Map; diff --git a/framework/test/unit/modules/interoperability/endpoint.spec.ts b/framework/test/unit/modules/interoperability/endpoint.spec.ts index f6f89301111..df721fc3acf 100644 --- a/framework/test/unit/modules/interoperability/endpoint.spec.ts +++ b/framework/test/unit/modules/interoperability/endpoint.spec.ts @@ -14,7 +14,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; -import { ModuleEndpointContext, SidechainInteroperabilityModule } from '../../../../src'; +import { Types, Modules } from '../../../../src'; import { BaseInteroperabilityEndpoint } from '../../../../src/modules/interoperability/base_interoperability_endpoint'; import { BLS_PUBLIC_KEY_LENGTH, @@ -55,7 +55,7 @@ import { class TestEndpoint extends BaseInteroperabilityEndpoint {} describe('Test interoperability endpoint', () => { - const interopMod = new SidechainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); const chainID = utils.intToBuffer(1, 4); const chainAccountStoreMock = { get: jest.fn(), @@ -90,7 +90,7 @@ describe('Test interoperability endpoint', () => { has: jest.fn(), }; - let moduleContext: ModuleEndpointContext; + let moduleContext: Types.ModuleEndpointContext; const chainAccount: ChainAccount = { lastCertificate: { diff --git a/framework/test/unit/modules/interoperability/internal_method.spec.ts b/framework/test/unit/modules/interoperability/internal_method.spec.ts index 7719564558f..d5edfc415c1 100644 --- a/framework/test/unit/modules/interoperability/internal_method.spec.ts +++ b/framework/test/unit/modules/interoperability/internal_method.spec.ts @@ -36,15 +36,8 @@ import { } from '../../../../src/modules/interoperability/constants'; import { MainchainInteroperabilityInternalMethod } from '../../../../src/modules/interoperability/mainchain/internal_method'; import * as utils from '../../../../src/modules/interoperability/utils'; -import { - CrossChainUpdateTransactionParams, - MainchainInteroperabilityModule, - Transaction, - testing, - CCMsg, - OwnChainAccount, - ChainStatus, -} from '../../../../src'; +import { Modules, Transaction, testing } from '../../../../src'; + import { PrefixedStateReadWriter } from '../../../../src/state_machine/prefixed_state_read_writer'; import { InMemoryPrefixedStateDB } from '../../../../src/testing/in_memory_prefixed_state'; import { ChannelDataStore } from '../../../../src/modules/interoperability/stores/channel_data'; @@ -83,7 +76,7 @@ import { InvalidSMTVerificationEvent } from '../../../../src/modules/interoperab import { CCM_STATUS_OK } from '../../../../src/modules/token/constants'; describe('Base interoperability internal method', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainID = Buffer.from('01', 'hex'); const appendData = Buffer.from( '0c4c839c0fd8155fd0d52efc7dd29d2a71919dee517d50967cd26f4db2e0d1c5b', @@ -182,7 +175,7 @@ describe('Base interoperability internal method', () => { let ownChainAccountSubstore: OwnChainAccountStore; let methodContext: MethodContext; let storeContext: StoreGetter; - let ownChainAccount: OwnChainAccount; + let ownChainAccount: Modules.Interoperability.OwnChainAccount; beforeEach(async () => { ownChainAccount = { @@ -394,7 +387,7 @@ describe('Base interoperability internal method', () => { expect(chainDataSubstore.set).toHaveBeenCalledWith(crossChainMessageContext, chainId, { ...chainAccount, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, }); expect(outboxRootSubstore.del).toHaveBeenCalledWith(crossChainMessageContext, chainId); }); @@ -420,7 +413,7 @@ describe('Base interoperability internal method', () => { expect(chainDataSubstore.set).toHaveBeenCalledWith(crossChainMessageContext, chainId, { ...chainAccount, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, }); expect(outboxRootSubstore.del).toHaveBeenCalledWith(crossChainMessageContext, chainId); @@ -1318,7 +1311,7 @@ describe('Base interoperability internal method', () => { }); describe('verifyCertificate', () => { - const txParams: CrossChainUpdateTransactionParams = { + const txParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { certificate: Buffer.alloc(0), activeValidatorsUpdate: { blsKeysUpdate: [], @@ -1524,7 +1517,7 @@ describe('Base interoperability internal method', () => { const { aggregationBits, signature, ...unsignedCertificate } = defaultCertificate; const encodedCertificate = codec.encode(certificateSchema, defaultCertificate); const encodedUnsignedCertificate = codec.encode(unsignedCertificateSchema, unsignedCertificate); - const txParams: CrossChainUpdateTransactionParams = { + const txParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { certificate: encodedCertificate, activeValidatorsUpdate, certificateThreshold: BigInt(10), @@ -1621,7 +1614,7 @@ describe('Base interoperability internal method', () => { describe('verifyOutboxRootWitness', () => { const encodedCertificate = codec.encode(certificateSchema, defaultCertificate); - const txParams: CrossChainUpdateTransactionParams = { + const txParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { certificate: encodedCertificate, activeValidatorsUpdate: { blsKeysUpdate: [], @@ -1732,7 +1725,7 @@ describe('Base interoperability internal method', () => { const encodedDefaultCertificate = codec.encode(certificateSchema, { ...certificate, }); - // const txParams: CrossChainUpdateTransactionParams = { + // const txParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { // certificate: encodedDefaultCertificate, // activeValidatorsUpdate: { // blsKeysUpdate: [], @@ -1762,7 +1755,7 @@ describe('Base interoperability internal method', () => { const defaultSendingChainID = 20; const defaultSendingChainIDBuffer = cryptoUtils.intToBuffer(defaultSendingChainID, 4); - const defaultCCMs: CCMsg[] = [ + const defaultCCMs: Modules.Interoperability.CCMsg[] = [ { crossChainCommand: CROSS_CHAIN_COMMAND_REGISTRATION, fee: BigInt(0), @@ -1785,7 +1778,7 @@ describe('Base interoperability internal method', () => { }; let commandExecuteContext: CommandExecuteContext; - let crossChainUpdateParams: CrossChainUpdateTransactionParams; + let crossChainUpdateParams: Modules.Interoperability.CrossChainUpdateTransactionParams; beforeEach(async () => { crossChainUpdateParams = { diff --git a/framework/test/unit/modules/interoperability/interopFixtures.ts b/framework/test/unit/modules/interoperability/interopFixtures.ts index dae45f12cff..e87c0b6b144 100644 --- a/framework/test/unit/modules/interoperability/interopFixtures.ts +++ b/framework/test/unit/modules/interoperability/interopFixtures.ts @@ -1,12 +1,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { BlockAssets } from '@liskhq/lisk-chain'; -import { - ChainStatus, - GenesisBlockExecuteContext, - genesisInteroperabilitySchema, - MODULE_NAME_INTEROPERABILITY, -} from '../../../../src'; +import { Modules, StateMachine } from '../../../../src'; import { HASH_LENGTH, MIN_RETURN_FEE_PER_BYTE_BEDDOWS, @@ -68,7 +63,7 @@ export const lastCertificate = { export const chainData = { name: 'dummy', lastCertificate, - status: ChainStatus.REGISTERED, + status: Modules.Interoperability.ChainStatus.REGISTERED, }; export const chainInfo = { @@ -101,12 +96,17 @@ export const genesisInteroperability: GenesisInteroperability = { export const createInitGenesisStateContext = ( genesisInterop: GenesisInteroperability, params: CreateGenesisBlockContextParams, -): GenesisBlockExecuteContext => { - const encodedAsset = codec.encode(genesisInteroperabilitySchema, genesisInterop); +): StateMachine.GenesisBlockExecuteContext => { + const encodedAsset = codec.encode( + Modules.Interoperability.genesisInteroperabilitySchema, + genesisInterop, + ); return createGenesisBlockContext({ ...params, - assets: new BlockAssets([{ module: MODULE_NAME_INTEROPERABILITY, data: encodedAsset }]), + assets: new BlockAssets([ + { module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, data: encodedAsset }, + ]), }).createInitGenesisStateContext(); }; diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/initialize_message_recovery.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/initialize_message_recovery.spec.ts index e2e769f541a..875e58992f6 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/initialize_message_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/initialize_message_recovery.spec.ts @@ -15,14 +15,7 @@ import { codec } from '@liskhq/lisk-codec'; import { utils } from '@liskhq/lisk-cryptography'; import { SparseMerkleTree } from '@liskhq/lisk-db'; -import { - CommandExecuteContext, - CommandVerifyContext, - MainchainInteroperabilityModule, - Transaction, - VerifyStatus, - messageRecoveryInitializationParamsSchema, -} from '../../../../../../src'; +import { StateMachine, Modules, Transaction } from '../../../../../../src'; import { EMPTY_BYTES, EMPTY_HASH, @@ -49,7 +42,7 @@ import { createTransactionContext, InMemoryPrefixedStateDB } from '../../../../. import { InvalidSMTVerificationEvent } from '../../../../../../src/modules/interoperability/events/invalid_smt_verification'; describe('InitializeMessageRecoveryCommand', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const targetChainID = Buffer.from([0, 0, 3, 0]); const ownChainAccount: OwnChainAccount = { chainID: Buffer.from([0, 0, 2, 0]), @@ -139,7 +132,7 @@ describe('InitializeMessageRecoveryCommand', () => { }); describe('verify', () => { - let defaultContext: CommandVerifyContext; + let defaultContext: StateMachine.CommandVerifyContext; beforeEach(() => { defaultContext = createTransactionContext({ @@ -160,7 +153,7 @@ describe('InitializeMessageRecoveryCommand', () => { channel: Buffer.alloc(0), }; const encodedTransactionParams = codec.encode( - messageRecoveryInitializationParamsSchema, + Modules.Interoperability.messageRecoveryInitializationParamsSchema, transactionParams, ); const context = createTransactionContext({ @@ -189,7 +182,7 @@ describe('InitializeMessageRecoveryCommand', () => { }).createCommandVerifyContext(command.schema); const result = await command.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Chain ID is not valid.`); }); @@ -207,7 +200,7 @@ describe('InitializeMessageRecoveryCommand', () => { }).createCommandVerifyContext(command.schema); const result = await command.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Chain ID is not valid.`); }); @@ -216,7 +209,7 @@ describe('InitializeMessageRecoveryCommand', () => { const result = await command.verify(defaultContext); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Chain is not registered`); }); @@ -225,7 +218,7 @@ describe('InitializeMessageRecoveryCommand', () => { const result = await command.verify(defaultContext); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`not present`); }); @@ -238,7 +231,7 @@ describe('InitializeMessageRecoveryCommand', () => { const result = await command.verify(defaultContext); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Terminated outbox account already exists.`); }); @@ -247,16 +240,20 @@ describe('InitializeMessageRecoveryCommand', () => { .get(OwnChainAccountStore) .set(stateStore, EMPTY_BYTES, { ...ownChainAccount, chainID: Buffer.from([2, 2, 2, 2]) }); - await expect(command.verify(defaultContext)).resolves.toEqual({ status: VerifyStatus.OK }); + await expect(command.verify(defaultContext)).resolves.toEqual({ + status: StateMachine.VerifyStatus.OK, + }); }); it('should resolve when params is valid', async () => { - await expect(command.verify(defaultContext)).resolves.toEqual({ status: VerifyStatus.OK }); + await expect(command.verify(defaultContext)).resolves.toEqual({ + status: StateMachine.VerifyStatus.OK, + }); }); }); describe('execute', () => { - let executeContext: CommandExecuteContext; + let executeContext: StateMachine.CommandExecuteContext; beforeEach(() => { executeContext = createTransactionContext({ stateStore, diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/recover_message.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/recover_message.spec.ts index 2bd7b295e7c..4be6dcd7317 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/recover_message.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/recover_message.spec.ts @@ -18,11 +18,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { utils } from '@liskhq/lisk-cryptography'; import { MerkleTree, regularMerkleTree } from '@liskhq/lisk-tree'; import { Proof } from '@liskhq/lisk-tree/dist-node/merkle_tree/types'; -import { - CROSS_CHAIN_COMMAND_NAME_TRANSFER, - CommandExecuteContext, - MainchainInteroperabilityModule, -} from '../../../../../../src'; +import { Modules, StateMachine } from '../../../../../../src'; import { BaseCCCommand } from '../../../../../../src/modules/interoperability/base_cc_command'; import { BaseCCMethod } from '../../../../../../src/modules/interoperability/base_cc_method'; import { @@ -64,7 +60,7 @@ import { CcmSendSuccessEvent } from '../../../../../../src/modules/interoperabil import { InvalidRMTVerificationEvent } from '../../../../../../src/modules/interoperability/events/invalid_rmt_verification'; describe('MessageRecoveryCommand', () => { - const interopModule = new MainchainInteroperabilityModule(); + const interopModule = new Modules.Interoperability.MainchainInteroperabilityModule(); const leafPrefix = Buffer.from([0]); const appendPrecedingToIndices = (indices: number[], terminatedChainOutboxSize: number) => @@ -136,7 +132,7 @@ describe('MessageRecoveryCommand', () => { { nonce: BigInt(1), module: MODULE_NAME_INTEROPERABILITY, - crossChainCommand: CROSS_CHAIN_COMMAND_NAME_TRANSFER, + crossChainCommand: Modules.Token.CROSS_CHAIN_COMMAND_NAME_TRANSFER, sendingChainID: getMainchainID(chainID), receivingChainID: chainID, fee: BigInt(0), @@ -516,7 +512,7 @@ describe('MessageRecoveryCommand', () => { }); describe('Mainchain execute', () => { - let commandExecuteContext: CommandExecuteContext; + let commandExecuteContext: StateMachine.CommandExecuteContext; beforeEach(async () => { commandExecuteContext = createTransactionContext({ diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/register_sidechain.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/register_sidechain.spec.ts index 79098e423e0..a7772783dde 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/register_sidechain.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/register_sidechain.spec.ts @@ -51,7 +51,7 @@ import { } from '../../../../../../src/modules/interoperability/utils'; import { PrefixedStateReadWriter } from '../../../../../../src/state_machine/prefixed_state_read_writer'; import { InMemoryPrefixedStateDB } from '../../../../../../src/testing/in_memory_prefixed_state'; -import { MainchainInteroperabilityModule, TokenMethod, MethodContext } from '../../../../../../src'; +import { Modules, StateMachine } from '../../../../../../src'; import { RegisteredNamesStore } from '../../../../../../src/modules/interoperability/stores/registered_names'; import { createStoreGetter } from '../../../../../../src/testing/utils'; import { ChannelDataStore } from '../../../../../../src/modules/interoperability/stores/channel_data'; @@ -69,7 +69,7 @@ import { CcmSendSuccessEvent } from '../../../../../../src/modules/interoperabil import { InvalidNameError } from '../../../../../../src/modules/interoperability/errors'; describe('RegisterSidechainCommand', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainID = Buffer.from([0, 0, 0, 0]); const newChainID = utils.intToBuffer(2, 4); const existingChainID = utils.intToBuffer(1, 4); @@ -130,14 +130,14 @@ describe('RegisterSidechainCommand', () => { let chainValidatorsSubstore: ChainValidatorsStore; let registeredNamesSubstore: RegisteredNamesStore; let verifyContext: CommandVerifyContext; - const tokenMethod: TokenMethod = new TokenMethod( + const tokenMethod: Modules.Token.TokenMethod = new Modules.Token.TokenMethod( interopMod.stores, interopMod.events, interopMod.name, ); let initializeEscrowAmountMock: jest.SpyInstance< Promise, - [methodContext: MethodContext, chainID: Buffer, tokenID: Buffer] + [methodContext: StateMachine.MethodContext, chainID: Buffer, tokenID: Buffer] >; beforeEach(async () => { diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/submit_mainchain_cross_chain_update.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/submit_mainchain_cross_chain_update.spec.ts index 4b8cc0e0bce..d1caa07fb01 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/submit_mainchain_cross_chain_update.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/submit_mainchain_cross_chain_update.spec.ts @@ -18,16 +18,7 @@ import { bls, utils } from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; import { codec } from '@liskhq/lisk-codec'; import { EMPTY_BUFFER } from '@liskhq/lisk-chain/dist-node/constants'; -import { - CommandExecuteContext, - CommandVerifyContext, - VerifyStatus, - SubmitMainchainCrossChainUpdateCommand, - MainchainInteroperabilityModule, - Transaction, - BLS_SIGNATURE_LENGTH, - EMPTY_BYTES, -} from '../../../../../../src'; +import { StateMachine, Transaction, Modules } from '../../../../../../src'; import { ActiveValidator, ActiveValidatorsUpdate, @@ -91,7 +82,7 @@ import { } from '../../../../../../src/modules/interoperability/stores/own_chain_account'; describe('SubmitMainchainCrossChainUpdateCommand', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainID = Buffer.alloc(4, 0); const senderPublicKey = utils.getRandomBytes(32); const messageFeeTokenID = Buffer.alloc(8, 0); @@ -102,7 +93,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { stateRoot: utils.getRandomBytes(HASH_LENGTH), validatorsHash: cryptography.utils.getRandomBytes(HASH_LENGTH), aggregationBits: cryptography.utils.getRandomBytes(1), - signature: cryptography.utils.getRandomBytes(BLS_SIGNATURE_LENGTH), + signature: cryptography.utils.getRandomBytes(Modules.Interoperability.BLS_SIGNATURE_LENGTH), }; const defaultNewCertificateThreshold = BigInt(20); @@ -175,9 +166,9 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { let encodedDefaultCertificate: Buffer; let partnerChainAccount: ChainAccount; let partnerChannelAccount: ChannelData; - let verifyContext: CommandVerifyContext; - let executeContext: CommandExecuteContext; - let mainchainCCUUpdateCommand: SubmitMainchainCrossChainUpdateCommand; + let verifyContext: StateMachine.CommandVerifyContext; + let executeContext: StateMachine.CommandExecuteContext; + let mainchainCCUUpdateCommand: Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand; let params: CrossChainUpdateTransactionParams; let activeValidatorsUpdate: ActiveValidator[]; let sortedActiveValidatorsUpdate: ActiveValidatorsUpdate; @@ -186,7 +177,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { let partnerValidatorStore: ChainValidatorsStore; beforeEach(async () => { - mainchainCCUUpdateCommand = new SubmitMainchainCrossChainUpdateCommand( + mainchainCCUUpdateCommand = new Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand( interopMod.stores, interopMod.events, new Map(), @@ -402,7 +393,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { await mainchainCCUUpdateCommand['stores'] .get(OwnChainAccountStore) - .set(stateStore, EMPTY_BYTES, { + .set(stateStore, Modules.Interoperability.EMPTY_BYTES, { ...ownChainAccount, }); @@ -418,7 +409,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { jest.spyOn(mainchainCCUUpdateCommand, 'verifyCommon' as any); await expect(mainchainCCUUpdateCommand.verify(verifyContext)).resolves.toEqual({ - status: VerifyStatus.OK, + status: StateMachine.VerifyStatus.OK, }); expect(mainchainCCUUpdateCommand['verifyCommon']).toHaveBeenCalledWith(verifyContext, true); @@ -432,7 +423,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { ...verifyContext, params: { ...params } as any, }), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); expect(mainchainCCUUpdateCommand['internalMethod'].isLive).toHaveBeenCalledWith( verifyContext, @@ -462,7 +453,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { }, }, }), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); expect(interopUtils.verifyLivenessConditionForRegisteredChains).not.toHaveBeenCalled(); }); @@ -482,7 +473,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { }, }, }), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); expect(interopUtils.verifyLivenessConditionForRegisteredChains).toHaveBeenCalled(); expect(validator.validate).toHaveBeenCalledWith( @@ -507,7 +498,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { }, }, }), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); }); }); @@ -731,12 +722,12 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { params: Buffer.alloc(0), }; let context: CrossChainMessageContext; - let command: SubmitMainchainCrossChainUpdateCommand; + let command: Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand; let ccMethods: Map; let ccCommands: Map; beforeEach(async () => { - const interopModule = new MainchainInteroperabilityModule(); + const interopModule = new Modules.Interoperability.MainchainInteroperabilityModule(); ccMethods = new Map(); ccMethods.set( 'token', @@ -753,7 +744,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { public execute = jest.fn(); })(interopModule.stores, interopModule.events), ]); - command = new SubmitMainchainCrossChainUpdateCommand( + command = new Modules.Interoperability.SubmitMainchainCrossChainUpdateCommand( interopModule.stores, interopModule.events, ccMethods, diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/terminate_sidechain_for_liveness.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/terminate_sidechain_for_liveness.spec.ts index 5dc0146673a..e96f19490d7 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/terminate_sidechain_for_liveness.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/terminate_sidechain_for_liveness.spec.ts @@ -16,7 +16,7 @@ import { codec } from '@liskhq/lisk-codec'; import { Transaction } from '@liskhq/lisk-chain'; import { utils } from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; -import { CommandExecuteContext, MainchainInteroperabilityModule } from '../../../../../../src'; +import { StateMachine, Modules } from '../../../../../../src'; import { BaseCCCommand } from '../../../../../../src/modules/interoperability/base_cc_command'; import { BaseCCMethod } from '../../../../../../src/modules/interoperability/base_cc_method'; import { @@ -39,7 +39,7 @@ import { TerminateSidechainForLivenessCommand } from '../../../../../../src/modu import { CHAIN_ID_LENGTH } from '../../../../../../src/modules/token/constants'; describe('TerminateSidechainForLivenessCommand', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); let livenessTerminationCommand: TerminateSidechainForLivenessCommand; let commandVerifyContext: CommandVerifyContext; let interoperableCCMethods: Map; @@ -165,7 +165,7 @@ describe('TerminateSidechainForLivenessCommand', () => { }); describe('execute', () => { - let commandExecuteContext: CommandExecuteContext; + let commandExecuteContext: StateMachine.CommandExecuteContext; let transactionContext: TransactionContext; beforeEach(() => { diff --git a/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts index 949601335e3..46577f7d441 100644 --- a/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts @@ -12,12 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - MainchainInteroperabilityModule, - ModuleEndpointContext, - MAX_CHAIN_NAME_LENGTH, - MIN_CHAIN_NAME_LENGTH, -} from '../../../../../src'; +import { Modules, Types } from '../../../../../src'; import { CHAIN_REGISTRATION_FEE, MIN_RETURN_FEE_PER_BYTE_BEDDOWS, @@ -56,9 +51,9 @@ describe('MainchainInteroperabilityEndpoint', () => { }); describe('isChainNameAvailable', () => { - const nameMinLengthErrMsg = `Property '.name' must NOT have fewer than ${MIN_CHAIN_NAME_LENGTH} characters`; - const nameMaxLengthErrMsg = `Property '.name' must NOT have more than ${MAX_CHAIN_NAME_LENGTH} characters`; - const interopMod = new MainchainInteroperabilityModule(); + const nameMinLengthErrMsg = `Property '.name' must NOT have fewer than ${Modules.Interoperability.MIN_CHAIN_NAME_LENGTH} characters`; + const nameMaxLengthErrMsg = `Property '.name' must NOT have more than ${Modules.Interoperability.MAX_CHAIN_NAME_LENGTH} characters`; + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const registeredNamesStore = { has: jest.fn(), }; @@ -91,7 +86,7 @@ describe('MainchainInteroperabilityEndpoint', () => { await expect(endpoint.isChainNameAvailable(context)).rejects.toThrow(nameMinLengthErrMsg); }); - it(`should not throw error if name length equals ${MIN_CHAIN_NAME_LENGTH}`, () => { + it(`should not throw error if name length equals ${Modules.Interoperability.MIN_CHAIN_NAME_LENGTH}`, () => { const context = createTransientModuleEndpointContext({ params: { name: 'a', @@ -102,20 +97,20 @@ describe('MainchainInteroperabilityEndpoint', () => { expect(async () => endpoint.isChainNameAvailable(context)).not.toThrow(nameMinLengthErrMsg); }); - it(`should not throw error if name length equals ${MAX_CHAIN_NAME_LENGTH}`, () => { + it(`should not throw error if name length equals ${Modules.Interoperability.MAX_CHAIN_NAME_LENGTH}`, () => { const context = createTransientModuleEndpointContext({ params: { - name: 'a'.repeat(MAX_CHAIN_NAME_LENGTH), + name: 'a'.repeat(Modules.Interoperability.MAX_CHAIN_NAME_LENGTH), }, }); // eslint-disable-next-line @typescript-eslint/require-await expect(async () => endpoint.isChainNameAvailable(context)).not.toThrow(nameMaxLengthErrMsg); }); - it(`should throw error if name length exceeds ${MAX_CHAIN_NAME_LENGTH}`, async () => { + it(`should throw error if name length exceeds ${Modules.Interoperability.MAX_CHAIN_NAME_LENGTH}`, async () => { const context = createTransientModuleEndpointContext({ params: { - name: 'a'.repeat(MAX_CHAIN_NAME_LENGTH + 1), + name: 'a'.repeat(Modules.Interoperability.MAX_CHAIN_NAME_LENGTH + 1), }, }); await expect(endpoint.isChainNameAvailable(context)).rejects.toThrow(nameMaxLengthErrMsg); @@ -155,14 +150,14 @@ describe('MainchainInteroperabilityEndpoint', () => { }); describe('isChainIDAvailable', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainAccountStore = { has: jest.fn(), }; const ownChainAccountStore = { get: jest.fn().mockResolvedValue({ chainID: Buffer.from('00000000', 'hex') }), }; - let context: ModuleEndpointContext; + let context: Types.ModuleEndpointContext; beforeEach(() => { interopMod.stores.register(ChainAccountStore, chainAccountStore as never); diff --git a/framework/test/unit/modules/interoperability/mainchain/internal_method.spec.ts b/framework/test/unit/modules/interoperability/mainchain/internal_method.spec.ts index e6530f7a545..a0bab9a9088 100644 --- a/framework/test/unit/modules/interoperability/mainchain/internal_method.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/internal_method.spec.ts @@ -14,7 +14,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; -import { MainchainInteroperabilityModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { StoreGetter } from '../../../../../src/modules/base_store'; import { LIVENESS_LIMIT, EMPTY_BYTES } from '../../../../../src/modules/interoperability/constants'; import { MainchainInteroperabilityInternalMethod } from '../../../../../src/modules/interoperability/mainchain/internal_method'; @@ -28,7 +28,7 @@ import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_pr import { createStoreGetter } from '../../../../../src/testing/utils'; describe('Mainchain interoperability internal method', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const ownChainAccountStoreMock = { get: jest.fn(), set: jest.fn(), diff --git a/framework/test/unit/modules/interoperability/mainchain/method.spec.ts b/framework/test/unit/modules/interoperability/mainchain/method.spec.ts index 386d9a90847..23cf308b158 100644 --- a/framework/test/unit/modules/interoperability/mainchain/method.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/method.spec.ts @@ -13,10 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { - MainchainInteroperabilityMethod, - MainchainInteroperabilityModule, -} from '../../../../../src'; +import { Modules } from '../../../../../src'; import { createTransientMethodContext } from '../../../../../src/testing'; import { EventQueue, MethodContext } from '../../../../../src/state_machine'; import { @@ -27,7 +24,7 @@ import { import { OwnChainAccountStore } from '../../../../../src/modules/interoperability/stores/own_chain_account'; describe('Mainchain Method', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainID = utils.intToBuffer(1, 4); const chainAccountStoreMock = { get: jest.fn(), @@ -39,7 +36,7 @@ describe('Mainchain Method', () => { const interoperableCCMethods = new Map(); const defaultEventQueue = new EventQueue(0, [], [utils.hash(utils.getRandomBytes(32))]); const timestamp = Date.now(); - let mainchainInteroperabilityMethod: MainchainInteroperabilityMethod; + let mainchainInteroperabilityMethod: Modules.Interoperability.MainchainInteroperabilityMethod; let methodContext: MethodContext; let chainAccount: ChainAccount; @@ -47,7 +44,7 @@ describe('Mainchain Method', () => { methodContext = createTransientMethodContext({ eventQueue: defaultEventQueue }); interopMod.stores.register(ChainAccountStore, chainAccountStoreMock as never); interopMod.stores.register(OwnChainAccountStore, ownchainAccountStoreMock as never); - mainchainInteroperabilityMethod = new MainchainInteroperabilityMethod( + mainchainInteroperabilityMethod = new Modules.Interoperability.MainchainInteroperabilityMethod( interopMod.stores, interopMod.events, interoperableCCMethods, diff --git a/framework/test/unit/modules/interoperability/mainchain/module.spec.ts b/framework/test/unit/modules/interoperability/mainchain/module.spec.ts index 84b6d333a21..e824937d024 100644 --- a/framework/test/unit/modules/interoperability/mainchain/module.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/module.spec.ts @@ -21,11 +21,7 @@ import { EMPTY_HASH, MODULE_NAME_INTEROPERABILITY, } from '../../../../../src/modules/interoperability/constants'; -import { - ChainStatus, - MainchainInteroperabilityModule, - genesisInteroperabilitySchema, -} from '../../../../../src'; +import { Modules } from '../../../../../src'; import { ChainInfo, GenesisInteroperability, @@ -59,7 +55,7 @@ import { BaseInteroperabilityModule } from '../../../../../src/modules/interoper describe('initGenesisState', () => { const chainID = Buffer.from([0, 0, 0, 0]); let stateStore: PrefixedStateReadWriter; - let interopMod: MainchainInteroperabilityModule; + let interopMod: Modules.Interoperability.MainchainInteroperabilityModule; let certificateThreshold = BigInt(0); let params: CreateGenesisBlockContextParams; let validChainInfos: ChainInfo[]; @@ -67,7 +63,7 @@ describe('initGenesisState', () => { beforeEach(() => { stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); - interopMod = new MainchainInteroperabilityModule(); + interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); params = { stateStore, chainID, @@ -78,7 +74,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -316,9 +312,9 @@ describe('initGenesisState', () => { ); await expect(interopMod.initGenesisState(context)).rejects.toThrow( `chainData.status must be one of ${[ - ChainStatus.REGISTERED, - ChainStatus.ACTIVE, - ChainStatus.TERMINATED, + Modules.Interoperability.ChainStatus.REGISTERED, + Modules.Interoperability.ChainStatus.ACTIVE, + Modules.Interoperability.ChainStatus.TERMINATED, ].join(', ')}`, ); }); @@ -332,7 +328,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -424,7 +420,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -461,7 +457,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -496,7 +492,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.ACTIVE, + status: Modules.Interoperability.ChainStatus.ACTIVE, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -678,7 +674,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.ACTIVE, + status: Modules.Interoperability.ChainStatus.ACTIVE, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -707,7 +703,7 @@ describe('initGenesisState', () => { ...chainInfo, chainData: { ...chainData, - status: ChainStatus.ACTIVE, + status: Modules.Interoperability.ChainStatus.ACTIVE, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -743,7 +739,7 @@ describe('initGenesisState', () => { { ...chainInfo, chainData: { - ...chainData, // status: ChainStatus.REGISTERED, + ...chainData, // status: Modules.Interoperability.ChainStatus.REGISTERED, lastCertificate: { ...lastCertificate, validatorsHash: computeValidatorsHash(activeValidators, certificateThreshold), @@ -925,7 +921,7 @@ describe('initGenesisState', () => { // let's go with dynamic fixtures, so that if chainInfos length will change inside contextWithValidValidatorsHash, // we wouldn't have to refactor this part of tests const genesisInteroperabilityLocal = codec.decode( - genesisInteroperabilitySchema, + Modules.Interoperability.genesisInteroperabilitySchema, contextWithValidValidatorsHash.assets.getAsset(MODULE_NAME_INTEROPERABILITY) as Buffer, // not undefined at this point ); diff --git a/framework/test/unit/modules/interoperability/method.spec.ts b/framework/test/unit/modules/interoperability/method.spec.ts index 993fe117e96..6264e90d3d0 100644 --- a/framework/test/unit/modules/interoperability/method.spec.ts +++ b/framework/test/unit/modules/interoperability/method.spec.ts @@ -13,7 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { MainchainInteroperabilityModule, TokenMethod, ChannelData } from '../../../../src'; +import { Modules } from '../../../../src'; import { BaseInteroperabilityMethod } from '../../../../src/modules/interoperability/base_interoperability_method'; import { CCMStatusCode, @@ -45,7 +45,7 @@ import { getMainchainID, getEncodedCCMAndID } from '../../../../src/modules/inte class SampleInteroperabilityMethod extends BaseInteroperabilityMethod {} describe('Sample Method', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainID = utils.intToBuffer(1, 4); const interoperableCCMethods = new Map(); const chainAccountStoreMock = { @@ -76,10 +76,10 @@ describe('Sample Method', () => { }; let sampleInteroperabilityMethod: SampleInteroperabilityMethod; let methodContext: MethodContext; - let tokenMethodMock: TokenMethod; + let tokenMethodMock: Modules.Token.TokenMethod; let ccmSendFailEventMock: CcmSentFailedEvent; let ccmSendSuccessEventMock: CcmSendSuccessEvent; - let sampleChannelData: ChannelData; + let sampleChannelData: Modules.Interoperability.ChannelData; beforeEach(() => { sampleChannelData = { diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts index 2374c95577e..3ebb9cc8e39 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts @@ -27,14 +27,14 @@ import { createCrossChainMessageContext, InMemoryPrefixedStateDB, } from '../../../../../../src/testing'; -import { SidechainInteroperabilityModule } from '../../../../../../src'; +import { Modules } from '../../../../../../src'; import { SidechainInteroperabilityInternalMethod } from '../../../../../../src/modules/interoperability/sidechain/internal_method'; import { TerminatedStateStore } from '../../../../../../src/modules/interoperability/stores/terminated_state'; import { PrefixedStateReadWriter } from '../../../../../../src/state_machine/prefixed_state_read_writer'; import { createStoreGetter } from '../../../../../../src/testing/utils'; describe('SidechainCCSidechainTerminatedCommand', () => { - const interopMod = new SidechainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); const chainID = Buffer.from([0, 0, 1, 0]); diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/initialize_state_recovery.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/initialize_state_recovery.spec.ts index ee8b5d20264..8e05a60cb06 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/initialize_state_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/initialize_state_recovery.spec.ts @@ -31,7 +31,7 @@ import { OwnChainAccount, StateRecoveryInitParams, } from '../../../../../../src/modules/interoperability/types'; -import { CommandExecuteContext, SidechainInteroperabilityModule } from '../../../../../../src'; +import { StateMachine, Modules } from '../../../../../../src'; import { TransactionContext } from '../../../../../../src/state_machine'; import { stateRecoveryInitParamsSchema } from '../../../../../../src/modules/interoperability/schemas'; import { createTransactionContext } from '../../../../../../src/testing'; @@ -53,7 +53,7 @@ import { getMainchainID } from '../../../../../../src/modules/interoperability/u import { InvalidSMTVerificationEvent } from '../../../../../../src/modules/interoperability/events/invalid_smt_verification'; describe('Sidechain InitializeStateRecoveryCommand', () => { - const interopMod = new SidechainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); type StoreMock = Mocked; const getSetHas = () => ({ get: jest.fn(), @@ -67,7 +67,7 @@ describe('Sidechain InitializeStateRecoveryCommand', () => { const ownChainAccountStoreMock = getSetHas(); const terminatedStateAccountMock = getSetHas(); let stateRecoveryInitCommand: InitializeStateRecoveryCommand; - let commandExecuteContext: CommandExecuteContext; + let commandExecuteContext: StateMachine.CommandExecuteContext; let transaction: Transaction; let transactionParams: StateRecoveryInitParams; let encodedTransactionParams: Buffer; diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/register_mainchain.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/register_mainchain.spec.ts index 36d98665d9b..62b720fb027 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/register_mainchain.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/register_mainchain.spec.ts @@ -54,7 +54,7 @@ import { computeValidatorsHash, sortValidatorsByBLSKey, } from '../../../../../../src/modules/interoperability/utils'; -import { SidechainInteroperabilityModule } from '../../../../../../src'; +import { Modules } from '../../../../../../src'; import { OwnChainAccountStore } from '../../../../../../src/modules/interoperability/stores/own_chain_account'; import { ChannelDataStore } from '../../../../../../src/modules/interoperability/stores/channel_data'; import { OutboxRootStore } from '../../../../../../src/modules/interoperability/stores/outbox_root'; @@ -76,7 +76,7 @@ jest.mock('@liskhq/lisk-cryptography', () => ({ })); describe('RegisterMainchainCommand', () => { - const interopMod = new SidechainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); interopMod['internalMethod'] = { addToOutbox: jest.fn() } as any; const unsortedMainchainValidators: ActiveValidators[] = []; for (let i = 0; i < NUMBER_ACTIVE_VALIDATORS_MAINCHAIN; i += 1) { diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/submit_sidechain_cross_chain_update.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/submit_sidechain_cross_chain_update.spec.ts index 29a33db6007..ccbff6bece4 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/submit_sidechain_cross_chain_update.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/submit_sidechain_cross_chain_update.spec.ts @@ -16,13 +16,7 @@ import { bls, utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { Transaction } from '@liskhq/lisk-chain'; import { EMPTY_BUFFER } from '@liskhq/lisk-chain/dist-node/constants'; -import { - CommandExecuteContext, - CommandVerifyContext, - SidechainInteroperabilityModule, - EMPTY_BYTES, - VerifyStatus, -} from '../../../../../../src'; +import { StateMachine, Modules } from '../../../../../../src'; import { ActiveValidator, ActiveValidatorsUpdate, @@ -69,7 +63,7 @@ import { } from '../../../../../../src/modules/interoperability/stores/own_chain_account'; describe('SubmitSidechainCrossChainUpdateCommand', () => { - const interopMod = new SidechainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); const senderPublicKey = utils.getRandomBytes(32); const messageFeeTokenID = Buffer.alloc(8, 0); @@ -153,8 +147,8 @@ describe('SubmitSidechainCrossChainUpdateCommand', () => { let encodedDefaultCertificate: Buffer; let partnerChainAccount: ChainAccount; let partnerChannelAccount: ChannelData; - let verifyContext: CommandVerifyContext; - let executeContext: CommandExecuteContext; + let verifyContext: StateMachine.CommandVerifyContext; + let executeContext: StateMachine.CommandExecuteContext; let sidechainCCUUpdateCommand: SubmitSidechainCrossChainUpdateCommand; let params: CrossChainUpdateTransactionParams; let activeValidatorsUpdate: ActiveValidator[]; @@ -297,7 +291,7 @@ describe('SubmitSidechainCrossChainUpdateCommand', () => { await sidechainCCUUpdateCommand['stores'] .get(OwnChainAccountStore) - .set(stateStore, EMPTY_BYTES, { + .set(stateStore, Modules.Interoperability.EMPTY_BYTES, { ...ownChainAccount, }); @@ -308,7 +302,7 @@ describe('SubmitSidechainCrossChainUpdateCommand', () => { jest.spyOn(sidechainCCUUpdateCommand, 'verifyCommon' as any); await expect(sidechainCCUUpdateCommand.verify(verifyContext)).resolves.toEqual({ - status: VerifyStatus.OK, + status: StateMachine.VerifyStatus.OK, }); expect(sidechainCCUUpdateCommand['verifyCommon']).toHaveBeenCalledWith(verifyContext, false); @@ -322,7 +316,7 @@ describe('SubmitSidechainCrossChainUpdateCommand', () => { ...verifyContext, params: { ...params } as any, }), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); expect(sidechainCCUUpdateCommand['internalMethod'].isLive).not.toHaveBeenCalledWith( verifyContext, diff --git a/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts b/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts index 0ea8396b867..38473999655 100644 --- a/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts @@ -14,7 +14,7 @@ import { createTransientModuleEndpointContext } from '../../../../../src/testing'; import { SidechainInteroperabilityEndpoint } from '../../../../../src/modules/interoperability/sidechain/endpoint'; -import { ModuleEndpointContext } from '../../../../../src'; +import { Types } from '../../../../../src'; describe('SidechainInteroperabilityEndpoint', () => { let endpoint: SidechainInteroperabilityEndpoint; @@ -27,7 +27,7 @@ describe('SidechainInteroperabilityEndpoint', () => { }); describe('getMainchainID', () => { - let context: ModuleEndpointContext; + let context: Types.ModuleEndpointContext; it('should throw error for chainID having less than 8 chars', () => { context = createTransientModuleEndpointContext({ diff --git a/framework/test/unit/modules/interoperability/sidechain/internal_method.spec.ts b/framework/test/unit/modules/interoperability/sidechain/internal_method.spec.ts index 1b40e992e7f..20c04483e2a 100644 --- a/framework/test/unit/modules/interoperability/sidechain/internal_method.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/internal_method.spec.ts @@ -13,7 +13,7 @@ */ import { SidechainInteroperabilityInternalMethod } from '../../../../../src/modules/interoperability/sidechain/internal_method'; -import { SidechainInteroperabilityModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefixed_state_read_writer'; import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_prefixed_state'; import { @@ -28,7 +28,7 @@ import { OwnChainAccountStore } from '../../../../../src/modules/interoperabilit import { EMPTY_BYTES } from '../../../../../src/modules/interoperability/constants'; describe('Sidechain interoperability store', () => { - const sidechainInterops = new SidechainInteroperabilityModule(); + const sidechainInterops = new Modules.Interoperability.SidechainInteroperabilityModule(); const ownChainAccountStoreMock = { get: jest.fn(), set: jest.fn(), diff --git a/framework/test/unit/modules/interoperability/sidechain/method.spec.ts b/framework/test/unit/modules/interoperability/sidechain/method.spec.ts index a9af1a1cd41..024ca4f9b9c 100644 --- a/framework/test/unit/modules/interoperability/sidechain/method.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/method.spec.ts @@ -13,11 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { - SidechainInteroperabilityMethod, - SidechainInteroperabilityModule, - getMainchainID, -} from '../../../../../src'; +import { Modules } from '../../../../../src'; import { createTransientMethodContext } from '../../../../../src/testing'; import { EventQueue, MethodContext } from '../../../../../src/state_machine'; import { @@ -29,9 +25,9 @@ import { OwnChainAccountStore } from '../../../../../src/modules/interoperabilit import { TerminatedStateStore } from '../../../../../src/modules/interoperability/stores/terminated_state'; describe('Sidechain Method', () => { - const interopMod = new SidechainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); const chainID = utils.intToBuffer(1, 4); - const mainchainID = getMainchainID(chainID); + const mainchainID = Modules.Interoperability.getMainchainID(chainID); const chainAccountStoreMock = { get: jest.fn(), has: jest.fn(), @@ -44,7 +40,7 @@ describe('Sidechain Method', () => { }; const interoperableCCMethods = new Map(); const defaultEventQueue = new EventQueue(0, [], [utils.hash(utils.getRandomBytes(32))]); - let sidechainInteroperabilityMethod: SidechainInteroperabilityMethod; + let sidechainInteroperabilityMethod: Modules.Interoperability.SidechainInteroperabilityMethod; let methodContext: MethodContext; let chainAccount: ChainAccount; @@ -53,7 +49,7 @@ describe('Sidechain Method', () => { interopMod.stores.register(ChainAccountStore, chainAccountStoreMock as never); interopMod.stores.register(OwnChainAccountStore, ownchainAccountStoreMock as never); interopMod.stores.register(TerminatedStateStore, terminatedStateStoreMock as never); - sidechainInteroperabilityMethod = new SidechainInteroperabilityMethod( + sidechainInteroperabilityMethod = new Modules.Interoperability.SidechainInteroperabilityMethod( interopMod.stores, interopMod.events, interoperableCCMethods, diff --git a/framework/test/unit/modules/interoperability/sidechain/module.spec.ts b/framework/test/unit/modules/interoperability/sidechain/module.spec.ts index 1207637c682..dddf5ca23f7 100644 --- a/framework/test/unit/modules/interoperability/sidechain/module.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/module.spec.ts @@ -17,7 +17,7 @@ import { CreateGenesisBlockContextParams, InMemoryPrefixedStateDB, } from '../../../../../src/testing'; -import { ChainStatus, SidechainInteroperabilityModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { activeValidator, chainData, @@ -50,7 +50,7 @@ describe('initGenesisState', () => { const chainID = Buffer.from([1, 2, 3, 4]); let params: CreateGenesisBlockContextParams; let stateStore: PrefixedStateReadWriter; - let interopMod: SidechainInteroperabilityModule; + let interopMod: Modules.Interoperability.SidechainInteroperabilityModule; const activeValidators = [ { @@ -100,7 +100,7 @@ describe('initGenesisState', () => { beforeEach(() => { stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); - interopMod = new SidechainInteroperabilityModule(); + interopMod = new Modules.Interoperability.SidechainInteroperabilityModule(); params = { stateStore, chainID, @@ -340,7 +340,7 @@ describe('initGenesisState', () => { ...defaultData.chainInfos[0], chainData: { ...defaultData.chainInfos[0].chainData, - status: ChainStatus.TERMINATED, + status: Modules.Interoperability.ChainStatus.TERMINATED, }, }, ], @@ -348,7 +348,10 @@ describe('initGenesisState', () => { params, ); - const validStatuses = [ChainStatus.REGISTERED, ChainStatus.ACTIVE]; + const validStatuses = [ + Modules.Interoperability.ChainStatus.REGISTERED, + Modules.Interoperability.ChainStatus.ACTIVE, + ]; await expect(interopMod.initGenesisState(context)).rejects.toThrow( `chainData.status must be one of ${validStatuses.join(', ')}.`, ); diff --git a/framework/test/unit/modules/interoperability/stores/chain_account.spec.ts b/framework/test/unit/modules/interoperability/stores/chain_account.spec.ts index edb019befd0..8213c0b80fa 100644 --- a/framework/test/unit/modules/interoperability/stores/chain_account.spec.ts +++ b/framework/test/unit/modules/interoperability/stores/chain_account.spec.ts @@ -13,7 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { StoreGetter } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { HASH_LENGTH, MODULE_NAME_INTEROPERABILITY, @@ -24,7 +24,7 @@ import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_pr import { createStoreGetter } from '../../../../../src/testing/utils'; describe('ChainAccountStore', () => { - let context: StoreGetter; + let context: Modules.StoreGetter; let chainAccountStore: ChainAccountStore; const chainIDs = [ diff --git a/framework/test/unit/modules/interoperability/utils.spec.ts b/framework/test/unit/modules/interoperability/utils.spec.ts index b7be77d65fb..85d8d3f3b66 100644 --- a/framework/test/unit/modules/interoperability/utils.spec.ts +++ b/framework/test/unit/modules/interoperability/utils.spec.ts @@ -16,7 +16,7 @@ import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import * as cryptography from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; -import { BLS_SIGNATURE_LENGTH, VerifyStatus } from '../../../../src'; +import { Modules, StateMachine } from '../../../../src'; import { CCMStatusCode, CROSS_CHAIN_COMMAND_SIDECHAIN_TERMINATED, @@ -55,7 +55,7 @@ describe('Utils', () => { timestamp: Math.floor(Date.now() / 1000), validatorsHash: cryptography.utils.getRandomBytes(HASH_LENGTH), aggregationBits: cryptography.utils.getRandomBytes(1), - signature: cryptography.utils.getRandomBytes(BLS_SIGNATURE_LENGTH), + signature: cryptography.utils.getRandomBytes(Modules.Interoperability.BLS_SIGNATURE_LENGTH), }; beforeEach(() => { @@ -81,7 +81,7 @@ describe('Utils', () => { partnerChainAccount as ChainAccount, txParamsEmptyCertificate as CrossChainUpdateTransactionParams, ); - expect(result.status).toEqual(VerifyStatus.FAIL); + expect(result.status).toEqual(StateMachine.VerifyStatus.FAIL); }); it(`should return status VerifyStatus.OK status when chain status ${ChainStatus.REGISTERED} && certificate is non-empty`, () => { @@ -89,7 +89,7 @@ describe('Utils', () => { partnerChainAccount as ChainAccount, txParamsNonEmptyCertificate as CrossChainUpdateTransactionParams, ); - expect(result.status).toEqual(VerifyStatus.OK); + expect(result.status).toEqual(StateMachine.VerifyStatus.OK); }); }); diff --git a/framework/test/unit/modules/nft/cc_comands/cc_transfer.spec.ts b/framework/test/unit/modules/nft/cc_comands/cc_transfer.spec.ts index c422e16e890..9d7b7cddb32 100644 --- a/framework/test/unit/modules/nft/cc_comands/cc_transfer.spec.ts +++ b/framework/test/unit/modules/nft/cc_comands/cc_transfer.spec.ts @@ -26,7 +26,7 @@ import { NftEventResult, } from '../../../../../src/modules/nft/constants'; import { NFTStore } from '../../../../../src/modules/nft/stores/nft'; -import { CCMsg, CrossChainMessageContext, ccuParamsSchema } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { InternalMethod } from '../../../../../src/modules/nft/internal_method'; import { NFTMethod } from '../../../../../src/modules/nft/method'; import { EventQueue, MethodContext, createMethodContext } from '../../../../../src/state_machine'; @@ -98,7 +98,7 @@ describe('CrossChain Transfer Command', () => { height: 0, timestamp: 0, }; - const defaultEncodedCCUParams = codec.encode(ccuParamsSchema, { + const defaultEncodedCCUParams = codec.encode(Modules.Interoperability.ccuParamsSchema, { activeValidatorsUpdate: { blsKeysUpdate: [], bftWeightsUpdate: [], @@ -122,11 +122,11 @@ describe('CrossChain Transfer Command', () => { params: defaultEncodedCCUParams, }; let params: Buffer; - let ccm: CCMsg; + let ccm: Modules.Interoperability.CCMsg; let command: CrossChainTransferCommand; let methodContext: MethodContext; let stateStore: PrefixedStateReadWriter; - let context: CrossChainMessageContext; + let context: Modules.Interoperability.CrossChainMessageContext; let nftStore: NFTStore; let escrowStore: EscrowStore; let userStore: UserStore; diff --git a/framework/test/unit/modules/nft/commands/transfer.spec.ts b/framework/test/unit/modules/nft/commands/transfer.spec.ts index 12ea04e93e8..061ecfec9df 100644 --- a/framework/test/unit/modules/nft/commands/transfer.spec.ts +++ b/framework/test/unit/modules/nft/commands/transfer.spec.ts @@ -27,7 +27,7 @@ import { } from '../../../../../src/modules/nft/constants'; import { NFTAttributes, NFTStore } from '../../../../../src/modules/nft/stores/nft'; import { createStoreGetter } from '../../../../../src/testing/utils'; -import { NFTMethod, VerifyStatus } from '../../../../../src'; +import { Modules, StateMachine } from '../../../../../src'; import { InternalMethod } from '../../../../../src/modules/nft/internal_method'; import { UserStore } from '../../../../../src/modules/nft/stores/user'; import { EventQueue } from '../../../../../src/state_machine'; @@ -36,7 +36,7 @@ import { InteroperabilityMethod, TokenMethod } from '../../../../../src/modules/ describe('Transfer command', () => { const module = new NFTModule(); - const nftMethod = new NFTMethod(module.stores, module.events); + const nftMethod = new Modules.NFT.NFTMethod(module.stores, module.events); let interoperabilityMethod!: InteroperabilityMethod; let tokenMethod!: TokenMethod; const internalMethod = new InternalMethod(module.stores, module.events); @@ -111,7 +111,7 @@ describe('Transfer command', () => { const nftIDNotExistingVerification = await command.verify( nftIDNotExistingContext.createCommandVerifyContext(transferParamsSchema), ); - expect(nftIDNotExistingVerification.status).toBe(VerifyStatus.FAIL); + expect(nftIDNotExistingVerification.status).toBe(StateMachine.VerifyStatus.FAIL); expect(nftIDNotExistingVerification.error?.message).toBe('NFT does not exist'); }); @@ -128,7 +128,7 @@ describe('Transfer command', () => { const nftEscrowedVerification = await command.verify( nftEscrowedContext.createCommandVerifyContext(transferParamsSchema), ); - expect(nftEscrowedVerification.status).toBe(VerifyStatus.FAIL); + expect(nftEscrowedVerification.status).toBe(StateMachine.VerifyStatus.FAIL); expect(nftEscrowedVerification.error?.message).toBe('NFT is escrowed to another chain'); }); @@ -153,7 +153,7 @@ describe('Transfer command', () => { const nftIncorrectOwnerVerification = await command.verify( nftIncorrectOwnerContext.createCommandVerifyContext(transferParamsSchema), ); - expect(nftIncorrectOwnerVerification.status).toBe(VerifyStatus.FAIL); + expect(nftIncorrectOwnerVerification.status).toBe(StateMachine.VerifyStatus.FAIL); expect(nftIncorrectOwnerVerification.error?.message).toBe( 'Transfer not initiated by the NFT owner', ); @@ -181,7 +181,7 @@ describe('Transfer command', () => { const lockedNFTVerification = await command.verify( lockedNFTContext.createCommandVerifyContext(transferParamsSchema), ); - expect(lockedNFTVerification.status).toBe(VerifyStatus.FAIL); + expect(lockedNFTVerification.status).toBe(StateMachine.VerifyStatus.FAIL); expect(lockedNFTVerification.error?.message).toBe('Locked NFTs cannot be transferred'); }); @@ -206,7 +206,7 @@ describe('Transfer command', () => { await expect( command.verify(validContext.createCommandVerifyContext(transferParamsSchema)), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); }); }); diff --git a/framework/test/unit/modules/nft/commands/transfer_cross_chain.spec.ts b/framework/test/unit/modules/nft/commands/transfer_cross_chain.spec.ts index 1256d05a18e..20e0d8afff2 100644 --- a/framework/test/unit/modules/nft/commands/transfer_cross_chain.spec.ts +++ b/framework/test/unit/modules/nft/commands/transfer_cross_chain.spec.ts @@ -31,7 +31,7 @@ import { import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_prefixed_state'; import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefixed_state_read_writer'; import { EventQueue, VerifyStatus, createMethodContext } from '../../../../../src/state_machine'; -import { TokenMethod } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { MethodContext } from '../../../../../src/state_machine/method_context'; import { NFTStore } from '../../../../../src/modules/nft/stores/nft'; import { UserStore } from '../../../../../src/modules/nft/stores/user'; @@ -54,7 +54,7 @@ describe('TransferCrossChainComand', () => { const command = new TransferCrossChainCommand(module.stores, module.events); const nftMethod = new NFTMethod(module.stores, module.events); - const tokenMethod = new TokenMethod(module.stores, module.events, module.name); + const tokenMethod = new Modules.Token.TokenMethod(module.stores, module.events, module.name); const internalMethod = new InternalMethod(module.stores, module.events); let interoperabilityMethod!: InteroperabilityMethod; diff --git a/framework/test/unit/modules/nft/endpoint.spec.ts b/framework/test/unit/modules/nft/endpoint.spec.ts index 6bf141958fa..bea9745d3a2 100644 --- a/framework/test/unit/modules/nft/endpoint.spec.ts +++ b/framework/test/unit/modules/nft/endpoint.spec.ts @@ -35,7 +35,7 @@ import { NFT_NOT_LOCKED, } from '../../../../src/modules/nft/constants'; import { NFT } from '../../../../src/modules/nft/types'; -import { JSONObject } from '../../../../src'; +import { Types } from '../../../../src'; import { SupportedNFTsStore } from '../../../../src/modules/nft/stores/supported_nfts'; import { isCollectionIDSupportedResponseSchema, @@ -180,7 +180,7 @@ describe('NFTEndpoint', () => { }, }); - const expectedNFT: JSONObject = { + const expectedNFT: Types.JSONObject = { owner: escrowChainID.toString('hex'), attributesArray: [], }; @@ -344,7 +344,7 @@ describe('NFTEndpoint', () => { }, }); - const expectedNFT: JSONObject = { + const expectedNFT: Types.JSONObject = { owner: owner.toString('hex'), attributesArray: attributesArray.map(attribute => ({ module: attribute.module, diff --git a/framework/test/unit/modules/nft/stores/nft.spec.ts b/framework/test/unit/modules/nft/stores/nft.spec.ts index 7142bd787e1..5d824715e6f 100644 --- a/framework/test/unit/modules/nft/stores/nft.spec.ts +++ b/framework/test/unit/modules/nft/stores/nft.spec.ts @@ -17,11 +17,11 @@ import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefix import { InMemoryPrefixedStateDB } from '../../../../../src/testing'; import { createStoreGetter } from '../../../../../src/testing/utils'; import { LENGTH_NFT_ID } from '../../../../../src/modules/nft/constants'; -import { StoreGetter } from '../../../../../src'; +import { Modules } from '../../../../../src'; describe('NFTStore', () => { let store: NFTStore; - let context: StoreGetter; + let context: Modules.StoreGetter; beforeEach(() => { store = new NFTStore('NFT', 5); diff --git a/framework/test/unit/modules/nft/stores/supported_nfts.spec.ts b/framework/test/unit/modules/nft/stores/supported_nfts.spec.ts index 054ad566eaa..78ac8606e18 100644 --- a/framework/test/unit/modules/nft/stores/supported_nfts.spec.ts +++ b/framework/test/unit/modules/nft/stores/supported_nfts.spec.ts @@ -18,11 +18,11 @@ import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefix import { InMemoryPrefixedStateDB } from '../../../../../src/testing'; import { createStoreGetter } from '../../../../../src/testing/utils'; import { LENGTH_CHAIN_ID, LENGTH_COLLECTION_ID } from '../../../../../src/modules/nft/constants'; -import { CHAIN_ID_LENGTH, StoreGetter } from '../../../../../src'; +import { Modules } from '../../../../../src'; describe('NFTStore', () => { let store: SupportedNFTsStore; - let context: StoreGetter; + let context: Modules.StoreGetter; beforeEach(() => { store = new SupportedNFTsStore('NFT', 5); @@ -35,7 +35,7 @@ describe('NFTStore', () => { describe('save', () => { it('should order supported NFT collection of a chain', async () => { - const chainID = Buffer.alloc(CHAIN_ID_LENGTH, 0); + const chainID = Buffer.alloc(Modules.Interoperability.CHAIN_ID_LENGTH, 0); const unsortedSupportedCollections = [ { diff --git a/framework/test/unit/modules/poa/commands/register_authority.spec.ts b/framework/test/unit/modules/poa/commands/register_authority.spec.ts index 5e5eff50e41..dfa21b508f0 100644 --- a/framework/test/unit/modules/poa/commands/register_authority.spec.ts +++ b/framework/test/unit/modules/poa/commands/register_authority.spec.ts @@ -17,13 +17,7 @@ import { address, utils } from '@liskhq/lisk-cryptography'; import { TransactionAttrs } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import * as testing from '../../../../../src/testing'; -import { - CommandExecuteContext, - CommandVerifyContext, - Transaction, - VerifyStatus, - PoAModule, -} from '../../../../../src'; +import { Transaction, StateMachine, Modules } from '../../../../../src'; import { RegisterAuthorityCommand } from '../../../../../src/modules/poa/commands/register_authority'; import { COMMAND_REGISTER_AUTHORITY, @@ -46,7 +40,7 @@ import { InMemoryPrefixedStateDB } from '../../../../../src/testing'; import { ED25519_PUBLIC_KEY_LENGTH } from '../../../../../src/modules/validators/constants'; describe('RegisterAuthority', () => { - const poaModule = new PoAModule(); + const poaModule = new Modules.PoA.PoAModule(); let registerAuthorityCommand: RegisterAuthorityCommand; let mockValidatorsMethod: ValidatorsMethod; let mockFeeMethod: any; @@ -169,7 +163,7 @@ describe('RegisterAuthority', () => { }); describe('verify', () => { - let context: CommandVerifyContext; + let context: StateMachine.CommandVerifyContext; beforeEach(() => { context = testing .createTransactionContext({ @@ -230,12 +224,12 @@ describe('RegisterAuthority', () => { it('should return OK when transaction is valid', async () => { const result = await registerAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.OK); + expect(result.status).toBe(StateMachine.VerifyStatus.OK); }); }); describe('execute', () => { - let context: CommandExecuteContext; + let context: StateMachine.CommandExecuteContext; beforeEach(() => { context = testing .createTransactionContext({ diff --git a/framework/test/unit/modules/poa/commands/update_authority.spec.ts b/framework/test/unit/modules/poa/commands/update_authority.spec.ts index 36a57ff7bd9..1963b0e912c 100644 --- a/framework/test/unit/modules/poa/commands/update_authority.spec.ts +++ b/framework/test/unit/modules/poa/commands/update_authority.spec.ts @@ -2,14 +2,7 @@ import { bls, utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { TransactionAttrs } from '@liskhq/lisk-chain'; import { MAX_UINT64, validator } from '@liskhq/lisk-validator'; -import { - CommandExecuteContext, - CommandVerifyContext, - MAX_NUM_VALIDATORS, - PoAModule, - Transaction, - VerifyStatus, -} from '../../../../../src'; +import { StateMachine, Modules, Transaction } from '../../../../../src'; import { UpdateAuthorityCommand } from '../../../../../src/modules/poa/commands/update_authority'; import { UpdateAuthorityParams, ValidatorsMethod } from '../../../../../src/modules/poa/types'; import { @@ -36,7 +29,7 @@ import { EventQueue } from '../../../../../src/state_machine'; import { ED25519_PUBLIC_KEY_LENGTH } from '../../../../../src/modules/validators/constants'; describe('UpdateAuthority', () => { - const poaModule = new PoAModule(); + const poaModule = new Modules.PoA.PoAModule(); let updateAuthorityCommand: UpdateAuthorityCommand; let mockValidatorsMethod: ValidatorsMethod; let stateStore: PrefixedStateReadWriter; @@ -134,17 +127,19 @@ describe('UpdateAuthority', () => { expect(() => validator.validate(updateAuthorityCommand.schema, { ...updateAuthorityValidatorParams, - newValidators: Array.from(Array(MAX_NUM_VALIDATORS + 1).keys()).map(_ => ({ + newValidators: Array.from( + Array(Modules.Interoperability.MAX_NUM_VALIDATORS + 1).keys(), + ).map(_ => ({ address: utils.getRandomBytes(20), weight: BigInt(1), })), }), - ).toThrow(`must NOT have more than ${MAX_NUM_VALIDATORS} items`); + ).toThrow(`must NOT have more than ${Modules.Interoperability.MAX_NUM_VALIDATORS} items`); }); }); describe('verify', () => { - let context: CommandVerifyContext; + let context: StateMachine.CommandVerifyContext; beforeEach(() => { context = testing .createTransactionContext({ @@ -179,7 +174,7 @@ describe('UpdateAuthority', () => { const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude( `Addresses in newValidators are not lexicographically ordered.`, ); @@ -212,7 +207,7 @@ describe('UpdateAuthority', () => { .createCommandVerifyContext(updateAuthoritySchema); const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Addresses in newValidators are not unique.`); }); @@ -236,7 +231,7 @@ describe('UpdateAuthority', () => { .createCommandVerifyContext(updateAuthoritySchema); const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude( `No validator found for given address ${address2.toString('hex')}.`, ); @@ -265,7 +260,7 @@ describe('UpdateAuthority', () => { .createCommandVerifyContext(updateAuthoritySchema); const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Validator weight cannot be zero.`); }); @@ -292,7 +287,7 @@ describe('UpdateAuthority', () => { .createCommandVerifyContext(updateAuthoritySchema); const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Validator weight cannot be zero.`); }); @@ -319,7 +314,7 @@ describe('UpdateAuthority', () => { .createCommandVerifyContext(updateAuthoritySchema); const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(`Validators total weight exceeds ${MAX_UINT64}`); }); @@ -344,7 +339,7 @@ describe('UpdateAuthority', () => { const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude( `Threshold must be between ${minThreshold} and ${totalWeight} (inclusive).`, ); @@ -371,7 +366,7 @@ describe('UpdateAuthority', () => { const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude( `Threshold must be between ${minThreshold} and ${totalWeight}`, ); @@ -394,7 +389,7 @@ describe('UpdateAuthority', () => { const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.FAIL); + expect(result.status).toBe(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude( `validatorsUpdateNonce must be equal to ${chainProperties.validatorsUpdateNonce}.`, ); @@ -403,12 +398,12 @@ describe('UpdateAuthority', () => { it('should return OK when transaction is valid', async () => { const result = await updateAuthorityCommand.verify(context); - expect(result.status).toBe(VerifyStatus.OK); + expect(result.status).toBe(StateMachine.VerifyStatus.OK); }); }); describe('execute', () => { - let context: CommandExecuteContext; + let context: StateMachine.CommandExecuteContext; const checkEventResult = ( eventQueue: EventQueue, diff --git a/framework/test/unit/modules/poa/commands/update_generator_key.spec.ts b/framework/test/unit/modules/poa/commands/update_generator_key.spec.ts index a435a7c2d47..c1ec0f6fc71 100644 --- a/framework/test/unit/modules/poa/commands/update_generator_key.spec.ts +++ b/framework/test/unit/modules/poa/commands/update_generator_key.spec.ts @@ -17,13 +17,7 @@ import { codec } from '@liskhq/lisk-codec'; import { TransactionAttrs } from '@liskhq/lisk-chain'; import { utils, address } from '@liskhq/lisk-cryptography'; -import { - PoAModule, - Transaction, - CommandVerifyContext, - CommandExecuteContext, - VerifyStatus, -} from '../../../../../src'; +import { Modules, Transaction, StateMachine } from '../../../../../src'; import { UpdateGeneratorKeyParams, ValidatorsMethod } from '../../../../../src/modules/poa/types'; import { ValidatorStore } from '../../../../../src/modules/poa/stores'; import { @@ -40,7 +34,7 @@ import { UpdateGeneratorKeyCommand } from '../../../../../src/modules/poa/comman import { createStoreGetter } from '../../../../../src/testing/utils'; describe('UpdateGeneratorKey', () => { - const poaModule = new PoAModule(); + const poaModule = new Modules.PoA.PoAModule(); let updateGeneratorKeyCommand: UpdateGeneratorKeyCommand; let stateStore: PrefixedStateReadWriter; let mockValidatorsMethod: ValidatorsMethod; @@ -109,7 +103,7 @@ describe('UpdateGeneratorKey', () => { }); describe('verify', () => { - let context: CommandVerifyContext; + let context: StateMachine.CommandVerifyContext; beforeEach(() => { context = testing .createTransactionContext({ @@ -134,12 +128,12 @@ describe('UpdateGeneratorKey', () => { it('should return OK when transaction is valid', async () => { const result = await updateGeneratorKeyCommand.verify(context); - expect(result.status).toBe(VerifyStatus.OK); + expect(result.status).toBe(StateMachine.VerifyStatus.OK); }); }); describe('execute', () => { - let context: CommandExecuteContext; + let context: StateMachine.CommandExecuteContext; beforeEach(async () => { context = testing .createTransactionContext({ diff --git a/framework/test/unit/modules/poa/endpoint.spec.ts b/framework/test/unit/modules/poa/endpoint.spec.ts index 01af8feba6a..22e64bc159b 100644 --- a/framework/test/unit/modules/poa/endpoint.spec.ts +++ b/framework/test/unit/modules/poa/endpoint.spec.ts @@ -13,7 +13,7 @@ */ import { address as cryptoAddress, utils } from '@liskhq/lisk-cryptography'; -import { PoAModule } from '../../../../src'; +import { Modules } from '../../../../src'; import { PoAEndpoint } from '../../../../src/modules/poa/endpoint'; import { PrefixedStateReadWriter } from '../../../../src/state_machine/prefixed_state_read_writer'; import { SnapshotStore, ValidatorStore } from '../../../../src/modules/poa/stores'; @@ -25,7 +25,7 @@ import { createStoreGetter } from '../../../../src/testing/utils'; import { AUTHORITY_REGISTRATION_FEE, KEY_SNAPSHOT_0 } from '../../../../src/modules/poa/constants'; describe('PoAModuleEndpoint', () => { - const poa = new PoAModule(); + const poa = new Modules.PoA.PoAModule(); let poaEndpoint: PoAEndpoint; let stateStore: PrefixedStateReadWriter; diff --git a/framework/test/unit/modules/pos/commands/change_commission.spec.ts b/framework/test/unit/modules/pos/commands/change_commission.spec.ts index d19f9fd96f4..3ce2e389e59 100644 --- a/framework/test/unit/modules/pos/commands/change_commission.spec.ts +++ b/framework/test/unit/modules/pos/commands/change_commission.spec.ts @@ -24,7 +24,7 @@ import { EventQueue, VerifyStatus } from '../../../../../src/state_machine'; import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefixed_state_read_writer'; import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_prefixed_state'; import { ValidatorStore } from '../../../../../src/modules/pos/stores/validator'; -import { PoSModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { createStoreGetter } from '../../../../../src/testing/utils'; import { COMMISSION_INCREASE_PERIOD, @@ -35,7 +35,7 @@ import { createFakeBlockHeader } from '../../../../../src/testing'; import { CommissionChangeEvent } from '../../../../../src/modules/pos/events/commission_change'; describe('Change Commission command', () => { - const pos = new PoSModule(); + const pos = new Modules.PoS.PoSModule(); const changeCommissionCommand = new ChangeCommissionCommand(pos.stores, pos.events); changeCommissionCommand.init({ commissionIncreasePeriod: COMMISSION_INCREASE_PERIOD, diff --git a/framework/test/unit/modules/pos/commands/register_validator.spec.ts b/framework/test/unit/modules/pos/commands/register_validator.spec.ts index f5bd045833c..e0f6eee62e3 100644 --- a/framework/test/unit/modules/pos/commands/register_validator.spec.ts +++ b/framework/test/unit/modules/pos/commands/register_validator.spec.ts @@ -29,7 +29,7 @@ import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefix import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_prefixed_state'; import { ValidatorStore } from '../../../../../src/modules/pos/stores/validator'; import { NameStore } from '../../../../../src/modules/pos/stores/name'; -import { PoSModule } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { createStoreGetter } from '../../../../../src/testing/utils'; import { COMMISSION, @@ -39,7 +39,7 @@ import { import { ValidatorRegisteredEvent } from '../../../../../src/modules/pos/events/validator_registered'; describe('Validator registration command', () => { - const pos = new PoSModule(); + const pos = new Modules.PoS.PoSModule(); let validatorRegistrationCommand: RegisterValidatorCommand; let validatorRegisteredEvent: ValidatorRegisteredEvent; let stateStore: PrefixedStateReadWriter; diff --git a/framework/test/unit/modules/pos/commands/report_misbehavior.spec.ts b/framework/test/unit/modules/pos/commands/report_misbehavior.spec.ts index d720ad32674..d9630c74106 100644 --- a/framework/test/unit/modules/pos/commands/report_misbehavior.spec.ts +++ b/framework/test/unit/modules/pos/commands/report_misbehavior.spec.ts @@ -17,7 +17,7 @@ import { objects } from '@liskhq/lisk-utils'; import { address, utils, legacy } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { Status } from '@liskhq/lisk-transaction-pool/dist-node/types'; -import { ReportMisbehaviorCommand, VerifyStatus, PoSModule } from '../../../../../src'; +import { StateMachine, Modules } from '../../../../../src'; import * as testing from '../../../../../src/testing'; import { defaultConfig, @@ -42,8 +42,8 @@ import { liskToBeddows } from '../../../../utils/assets'; import { getModuleConfig, getValidatorWeight } from '../../../../../src/modules/pos/utils'; describe('ReportMisbehaviorCommand', () => { - const pos = new PoSModule(); - let pomCommand: ReportMisbehaviorCommand; + const pos = new Modules.PoS.PoSModule(); + let pomCommand: Modules.PoS.ReportMisbehaviorCommand; let stateStore: PrefixedStateReadWriter; let validatorSubstore: ValidatorStore; let stakerSubStore: StakerStore; @@ -85,7 +85,7 @@ describe('ReportMisbehaviorCommand', () => { beforeEach(async () => { pos.stores.get(EligibleValidatorsStore).init(config); - pomCommand = new ReportMisbehaviorCommand(pos.stores, pos.events); + pomCommand = new Modules.PoS.ReportMisbehaviorCommand(pos.stores, pos.events); mockTokenMethod = { lock: jest.fn(), unlock: jest.fn(), @@ -412,7 +412,10 @@ describe('ReportMisbehaviorCommand', () => { 'error.message', 'BlockHeaders are not contradicting as per BFT violation rules.', ); - await expect(pomCommand.verify(context)).resolves.toHaveProperty('status', VerifyStatus.FAIL); + await expect(pomCommand.verify(context)).resolves.toHaveProperty( + 'status', + StateMachine.VerifyStatus.FAIL, + ); }); it('should resolve without error when headers are valid, can be decoded and are contradicting', async () => { @@ -434,7 +437,10 @@ describe('ReportMisbehaviorCommand', () => { jest.spyOn(BlockHeader.prototype, 'validateSignature').mockReturnValue(undefined); jest.spyOn(bftUtil, 'areDistinctHeadersContradicting').mockReturnValue(true); - await expect(pomCommand.verify(context)).resolves.toHaveProperty('status', VerifyStatus.OK); + await expect(pomCommand.verify(context)).resolves.toHaveProperty( + 'status', + StateMachine.VerifyStatus.OK, + ); }); it('should not throw error when first height is equal to second height but equal maxHeightPrestaked', async () => { @@ -457,7 +463,10 @@ describe('ReportMisbehaviorCommand', () => { jest.spyOn(BlockHeader.prototype, 'validateSignature').mockReturnValue(undefined); - await expect(pomCommand.verify(context)).resolves.toHaveProperty('status', VerifyStatus.OK); + await expect(pomCommand.verify(context)).resolves.toHaveProperty( + 'status', + StateMachine.VerifyStatus.OK, + ); }); it('should not throw error when first height is greater than the second height but equal maxHeightPrestaked', async () => { diff --git a/framework/test/unit/modules/pos/commands/stake.spec.ts b/framework/test/unit/modules/pos/commands/stake.spec.ts index 120a9179937..b10eab9535d 100644 --- a/framework/test/unit/modules/pos/commands/stake.spec.ts +++ b/framework/test/unit/modules/pos/commands/stake.spec.ts @@ -16,7 +16,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { address, utils } from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; -import { StakeCommand, VerifyStatus, PoSModule } from '../../../../../src'; +import { StateMachine, Modules } from '../../../../../src'; import { defaultConfig, MODULE_NAME_POS, @@ -43,7 +43,7 @@ import { liskToBeddows } from '../../../../utils/assets'; import { DEFAULT_LOCAL_ID } from '../../../../utils/mocks/transaction'; describe('StakeCommand', () => { - const pos = new PoSModule(); + const pos = new Modules.PoS.PoSModule(); const checkEventResult = ( eventQueue: EventQueue, length: number, @@ -81,7 +81,7 @@ describe('StakeCommand', () => { let validatorStore: ValidatorStore; let context: any; let transaction: any; - let command: StakeCommand; + let command: Modules.PoS.StakeCommand; let transactionParamsDecoded: any; let stateStore: PrefixedStateReadWriter; let tokenLockMock: jest.Mock; @@ -120,7 +120,7 @@ describe('StakeCommand', () => { internalMethod = new InternalMethod(pos.stores, pos.events, pos.name); internalMethod.addDependencies(tokenMethod); mockAssignStakeRewards = jest.spyOn(internalMethod, 'assignStakeRewards').mockResolvedValue(); - command = new StakeCommand(pos.stores, pos.events); + command = new Modules.PoS.StakeCommand(pos.stores, pos.events); command.addDependencies({ tokenMethod, internalMethod, @@ -276,7 +276,10 @@ describe('StakeCommand', () => { transaction, }).createCommandVerifyContext(command.schema); - await expect(command.verify(context)).resolves.toHaveProperty('status', VerifyStatus.OK); + await expect(command.verify(context)).resolves.toHaveProperty( + 'status', + StateMachine.VerifyStatus.OK, + ); }); it('should not throw errors with valid downstake cast', async () => { @@ -288,7 +291,10 @@ describe('StakeCommand', () => { transaction, }).createCommandVerifyContext(command.schema); - await expect(command.verify(context)).resolves.toHaveProperty('status', VerifyStatus.OK); + await expect(command.verify(context)).resolves.toHaveProperty( + 'status', + StateMachine.VerifyStatus.OK, + ); }); it('should not throw errors with valid mixed stakes case', async () => { @@ -303,7 +309,10 @@ describe('StakeCommand', () => { transaction, }).createCommandVerifyContext(command.schema); - await expect(command.verify(context)).resolves.toHaveProperty('status', VerifyStatus.OK); + await expect(command.verify(context)).resolves.toHaveProperty( + 'status', + StateMachine.VerifyStatus.OK, + ); }); }); diff --git a/framework/test/unit/modules/pos/commands/unlock.spec.ts b/framework/test/unit/modules/pos/commands/unlock.spec.ts index 1d09db0c2ca..f3daae78bc2 100644 --- a/framework/test/unit/modules/pos/commands/unlock.spec.ts +++ b/framework/test/unit/modules/pos/commands/unlock.spec.ts @@ -15,7 +15,7 @@ import { BlockHeader, Transaction } from '@liskhq/lisk-chain'; import { utils } from '@liskhq/lisk-cryptography'; import * as testing from '../../../../../src/testing'; -import { UnlockCommand, CommandExecuteContext, PoSModule } from '../../../../../src'; +import { Modules, StateMachine } from '../../../../../src'; import { defaultConfig, EMPTY_KEY, @@ -37,9 +37,9 @@ import { GenesisDataStore } from '../../../../../src/modules/pos/stores/genesis' import { getModuleConfig } from '../../../../../src/modules/pos/utils'; describe('UnlockCommand', () => { - const pos = new PoSModule(); + const pos = new Modules.PoS.PoSModule(); - let unlockCommand: UnlockCommand; + let unlockCommand: Modules.PoS.UnlockCommand; let stateStore: PrefixedStateReadWriter; let validatorSubstore: ValidatorStore; let stakerSubstore: StakerStore; @@ -51,7 +51,7 @@ describe('UnlockCommand', () => { let unlockableObject2: UnlockingObject; let unlockableObject3: UnlockingObject; let nonUnlockableObject: UnlockingObject; - let context: CommandExecuteContext; + let context: StateMachine.CommandExecuteContext; let storedData: StakerData; const validator1 = { name: 'validator1', @@ -111,7 +111,7 @@ describe('UnlockCommand', () => { }; beforeEach(() => { - unlockCommand = new UnlockCommand(pos.stores, pos.events); + unlockCommand = new Modules.PoS.UnlockCommand(pos.stores, pos.events); mockTokenMethod = { lock: jest.fn(), unlock: jest.fn(), diff --git a/framework/test/unit/modules/pos/endpoint.spec.ts b/framework/test/unit/modules/pos/endpoint.spec.ts index 5b9c53cd701..90e8f3532b0 100644 --- a/framework/test/unit/modules/pos/endpoint.spec.ts +++ b/framework/test/unit/modules/pos/endpoint.spec.ts @@ -24,7 +24,7 @@ import { StakerData, StakeSharingCoefficient, } from '../../../../src/modules/pos/types'; -import { PoSModule } from '../../../../src'; +import { Modules } from '../../../../src'; import { StakerStore, stakerStoreSchema } from '../../../../src/modules/pos/stores/staker'; import { ValidatorStore } from '../../../../src/modules/pos/stores/validator'; import { createStoreGetter } from '../../../../src/testing/utils'; @@ -39,7 +39,7 @@ import { calculateStakeRewards, getModuleConfig } from '../../../../src/modules/ const { q96 } = math; describe('PosModuleEndpoint', () => { - const pos = new PoSModule(); + const pos = new Modules.PoS.PoSModule(); let posEndpoint: PoSEndpoint; let stateStore: PrefixedStateReadWriter; diff --git a/framework/test/unit/modules/pos/internal_method.spec.ts b/framework/test/unit/modules/pos/internal_method.spec.ts index ebcad6bc0e2..8325d61e75d 100644 --- a/framework/test/unit/modules/pos/internal_method.spec.ts +++ b/framework/test/unit/modules/pos/internal_method.spec.ts @@ -19,7 +19,7 @@ import { InternalMethod } from '../../../../src/modules/pos/internal_method'; import { createNewMethodContext } from '../../../../src/state_machine/method_context'; import { InMemoryPrefixedStateDB } from '../../../../src/testing'; import * as utils from '../../../../src/modules/pos/utils'; -import { MethodContext, PoSModule, TokenMethod } from '../../../../src'; +import { StateMachine, Modules } from '../../../../src'; import { ValidatorAccount } from '../../../../src/modules/pos/stores/validator'; import { StakeObject, @@ -48,10 +48,14 @@ describe('InternalMethod', () => { expect(eventData).toEqual(expectedResult); }; - const pos = new PoSModule(); + const pos = new Modules.PoS.PoSModule(); const moduleName = 'pos'; const internalMethod: InternalMethod = new InternalMethod(pos.stores, pos.events, moduleName); - const tokenMethod: TokenMethod = new TokenMethod(pos.stores, pos.events, moduleName); + const tokenMethod: Modules.Token.TokenMethod = new Modules.Token.TokenMethod( + pos.stores, + pos.events, + moduleName, + ); const chainID = Buffer.from([0, 0, 0, 0]); const localTokenID1 = Buffer.from([0, 0, 0, 1]); const localTokenID2 = Buffer.from([0, 0, 1, 0]); @@ -67,7 +71,7 @@ describe('InternalMethod', () => { internalMethod.addDependencies(tokenMethod); - let methodContext: MethodContext; + let methodContext: StateMachine.MethodContext; let stakerData: StakerData; let validatorData: ValidatorAccount; let calculateStakeRewardsMock: jest.SpyInstance< @@ -80,12 +84,18 @@ describe('InternalMethod', () => { >; let unlockMock: jest.SpyInstance< Promise, - [methodContext: MethodContext, address: Buffer, module: string, tokenID: Buffer, amount: bigint] + [ + methodContext: StateMachine.MethodContext, + address: Buffer, + module: string, + tokenID: Buffer, + amount: bigint, + ] >; let transferMock: jest.SpyInstance< Promise, [ - methodContext: MethodContext, + methodContext: StateMachine.MethodContext, senderAddress: Buffer, recipientAddress: Buffer, tokenID: Buffer, diff --git a/framework/test/unit/modules/random/endpoint.spec.ts b/framework/test/unit/modules/random/endpoint.spec.ts index 5a61c63f91e..4fb2a2ed979 100644 --- a/framework/test/unit/modules/random/endpoint.spec.ts +++ b/framework/test/unit/modules/random/endpoint.spec.ts @@ -13,7 +13,7 @@ */ import * as cryptography from '@liskhq/lisk-cryptography'; -import { ModuleEndpointContext, RandomModule } from '../../../../src'; +import { Types, Modules } from '../../../../src'; import { RandomEndpoint } from '../../../../src/modules/random/endpoint'; import { HashOnionStore } from '../../../../src/modules/random/stores/hash_onion'; import { @@ -29,7 +29,7 @@ import { MAX_HASH_COMPUTATION } from '../../../../src/modules/random/constants'; describe('RandomModuleEndpoint', () => { let randomEndpoint: RandomEndpoint; - let context: ModuleEndpointContext; + let context: Types.ModuleEndpointContext; const validatorsData = [ { @@ -77,7 +77,7 @@ describe('RandomModuleEndpoint', () => { }; beforeEach(async () => { - const randomModule = new RandomModule(); + const randomModule = new Modules.Random.RandomModule(); randomEndpoint = new RandomEndpoint(randomModule.stores, randomModule.offchainStores); const stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); context = createTransientModuleEndpointContext({ diff --git a/framework/test/unit/modules/random/module.spec.ts b/framework/test/unit/modules/random/module.spec.ts index c91ff170430..e73ee4781b3 100644 --- a/framework/test/unit/modules/random/module.spec.ts +++ b/framework/test/unit/modules/random/module.spec.ts @@ -27,7 +27,7 @@ import { import { EMPTY_KEY } from '../../../../src/modules/random/constants'; import { blockHeaderAssetRandomModule } from '../../../../src/modules/random/schemas'; import { defaultChainID } from '../../../fixtures'; -import { GenesisConfig, testing } from '../../../../src'; +import { Types, testing } from '../../../../src'; import { createBlockContext, createBlockHeaderWithDefaults, @@ -77,7 +77,7 @@ describe('RandomModule', () => { it('should initialize config with default value when module config is empty', async () => { await expect( randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }), ).toResolve(); @@ -87,7 +87,7 @@ describe('RandomModule', () => { it('should assign config values', async () => { await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: { maxLengthReveals: 20 }, }); @@ -286,7 +286,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); await randomModule.insertAssets(blockGenerateContext); @@ -355,7 +355,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); await randomModule.insertAssets(blockGenerateContext); @@ -424,7 +424,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); await randomModule.insertAssets(blockGenerateContext); @@ -501,7 +501,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); await randomModule.insertAssets(blockGenerateContext); @@ -546,7 +546,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); await randomModule.insertAssets(blockGenerateContext); @@ -613,7 +613,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); await randomModule.insertAssets(blockGenerateContext); @@ -651,7 +651,7 @@ describe('RandomModule', () => { // Act await randomModule.init({ - genesisConfig: {} as GenesisConfig, + genesisConfig: {} as Types.GenesisConfig, moduleConfig: {}, }); diff --git a/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts b/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts index 6b6c660f018..2b8a3fb4035 100644 --- a/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts +++ b/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts @@ -15,7 +15,7 @@ import { codec } from '@liskhq/lisk-codec'; import { utils } from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; -import { TokenModule, TokenMethod, ccuParamsSchema } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { CrossChainTransferCommand } from '../../../../../src/modules/token/cc_commands/cc_transfer'; import { CCM_STATUS_OK, @@ -41,7 +41,7 @@ import { InternalMethod } from '../../../../../src/modules/token/internal_method import { InteroperabilityMethod } from '../../../../../src/modules/token/types'; describe('CrossChain Transfer Command', () => { - const tokenModule = new TokenModule(); + const tokenModule = new Modules.Token.TokenModule(); const internalMethod = new InternalMethod(tokenModule.stores, tokenModule.events); const defaultAddress = utils.getRandomBytes(20); const randomAddress = utils.getRandomBytes(20); @@ -61,7 +61,7 @@ describe('CrossChain Transfer Command', () => { }; const defaultEscrowAmount = BigInt('100000000000'); const sendingChainID = Buffer.from([3, 0, 0, 0]); - const defaultEncodedCCUParams = codec.encode(ccuParamsSchema, { + const defaultEncodedCCUParams = codec.encode(Modules.Interoperability.ccuParamsSchema, { activeValidatorsUpdate: { blsKeysUpdate: [], bftWeightsUpdate: [], @@ -81,7 +81,7 @@ describe('CrossChain Transfer Command', () => { }); let command: CrossChainTransferCommand; - let method: TokenMethod; + let method: Modules.Token.TokenMethod; let interopMethod: InteroperabilityMethod; let stateStore: PrefixedStateReadWriter; let methodContext: MethodContext; @@ -143,7 +143,11 @@ describe('CrossChain Transfer Command', () => { }; beforeEach(async () => { - method = new TokenMethod(tokenModule.stores, tokenModule.events, tokenModule.name); + method = new Modules.Token.TokenMethod( + tokenModule.stores, + tokenModule.events, + tokenModule.name, + ); command = new CrossChainTransferCommand(tokenModule.stores, tokenModule.events); interopMethod = { getOwnChainAccount: jest.fn().mockResolvedValue({ chainID: Buffer.from([0, 0, 0, 1]) }), diff --git a/framework/test/unit/modules/token/cc_method.spec.ts b/framework/test/unit/modules/token/cc_method.spec.ts index 90ad6491dd0..25cf122d595 100644 --- a/framework/test/unit/modules/token/cc_method.spec.ts +++ b/framework/test/unit/modules/token/cc_method.spec.ts @@ -39,7 +39,7 @@ import { CCMStatusCode, CROSS_CHAIN_COMMAND_REGISTRATION, } from '../../../../src/modules/interoperability/constants'; -import { ccuParamsSchema } from '../../../../src'; +import { Modules } from '../../../../src'; import { InternalMethod } from '../../../../src/modules/token/internal_method'; import { InitializeUserAccountEvent } from '../../../../src/modules/token/events/initialize_user_account'; @@ -67,7 +67,7 @@ describe('TokenInteroperableMethod', () => { const defaultTotalSupply = BigInt('100000000000000'); const defaultEscrowAmount = BigInt('100000000000'); const sendingChainID = Buffer.from([3, 0, 0, 0]); - const defaultEncodedCCUParams = codec.encode(ccuParamsSchema, { + const defaultEncodedCCUParams = codec.encode(Modules.Interoperability.ccuParamsSchema, { activeValidatorsUpdate: { blsKeysUpdate: [], bftWeightsUpdate: [], diff --git a/framework/test/unit/modules/token/commands/transfer.spec.ts b/framework/test/unit/modules/token/commands/transfer.spec.ts index 7dbedfee1a9..849bf1ac02e 100644 --- a/framework/test/unit/modules/token/commands/transfer.spec.ts +++ b/framework/test/unit/modules/token/commands/transfer.spec.ts @@ -16,7 +16,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { utils } from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; -import { TokenModule, VerifyStatus } from '../../../../../src'; +import { Modules, StateMachine } from '../../../../../src'; import { TokenMethod } from '../../../../../src/modules/token/method'; import { TransferCommand } from '../../../../../src/modules/token/commands/transfer'; import { transferParamsSchema } from '../../../../../src/modules/token/schemas'; @@ -36,7 +36,7 @@ interface Params { } describe('Transfer command', () => { - const tokenModule = new TokenModule(); + const tokenModule = new Modules.Token.TokenModule(); const ownChainID = Buffer.from([0, 0, 0, 1]); const defaultUserAccountInitFee = BigInt('50000000'); const defaultEscrowAccountInitFee = BigInt('50000000'); @@ -153,7 +153,7 @@ describe('Transfer command', () => { }); const result = await command.verify(context.createCommandVerifyContext(transferParamsSchema)); - expect(result.status).toEqual(VerifyStatus.OK); + expect(result.status).toEqual(StateMachine.VerifyStatus.OK); }); it('should fail if balance for the provided tokenID is insufficient', async () => { @@ -204,7 +204,7 @@ describe('Transfer command', () => { }), }); const result = await command.verify(context.createCommandVerifyContext(transferParamsSchema)); - expect(result.status).toEqual(VerifyStatus.OK); + expect(result.status).toEqual(StateMachine.VerifyStatus.OK); }); }); diff --git a/framework/test/unit/modules/token/commands/transfer_cross_chain.spec.ts b/framework/test/unit/modules/token/commands/transfer_cross_chain.spec.ts index 146bcbba4c0..df8530bbf03 100644 --- a/framework/test/unit/modules/token/commands/transfer_cross_chain.spec.ts +++ b/framework/test/unit/modules/token/commands/transfer_cross_chain.spec.ts @@ -17,13 +17,7 @@ import { codec } from '@liskhq/lisk-codec'; import * as cryptography from '@liskhq/lisk-cryptography'; import { validator } from '@liskhq/lisk-validator'; import { utils } from '@liskhq/lisk-cryptography'; -import { - TokenMethod, - TokenModule, - Transaction, - VerificationResult, - VerifyStatus, -} from '../../../../../src'; +import { Modules, Transaction, StateMachine } from '../../../../../src'; import { TransferCrossChainCommand } from '../../../../../src/modules/token/commands/transfer_cross_chain'; import { CROSS_CHAIN_COMMAND_NAME_TRANSFER } from '../../../../../src/modules/token/constants'; import { @@ -51,8 +45,8 @@ interface Params { describe('CCTransfer command', () => { let command: TransferCrossChainCommand; - const module = new TokenModule(); - const method = new TokenMethod(module.stores, module.events, module.name); + const module = new Modules.Token.TokenModule(); + const method = new Modules.Token.TokenMethod(module.stores, module.events, module.name); const internalMethod = new InternalMethod(module.stores, module.events); const defaultOwnChainID = Buffer.from([0, 0, 0, 1]); @@ -223,8 +217,8 @@ describe('CCTransfer command', () => { }); describe('verify', () => { - const expectVerifyErrorError = (result: VerificationResult, message: string) => { - expect(result.status).toEqual(VerifyStatus.FAIL); + const expectVerifyErrorError = (result: StateMachine.VerificationResult, message: string) => { + expect(result.status).toEqual(StateMachine.VerifyStatus.FAIL); expect(result.error?.message).toInclude(message); }; diff --git a/framework/test/unit/modules/token/endpoint.spec.ts b/framework/test/unit/modules/token/endpoint.spec.ts index 01e0ef89543..3dc5d293574 100644 --- a/framework/test/unit/modules/token/endpoint.spec.ts +++ b/framework/test/unit/modules/token/endpoint.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { address, utils } from '@liskhq/lisk-cryptography'; -import { TokenMethod, TokenModule, MethodContext } from '../../../../src'; +import { Modules, StateMachine } from '../../../../src'; import { USER_ACCOUNT_INITIALIZATION_FEE, ESCROW_ACCOUNT_INITIALIZATION_FEE, @@ -32,7 +32,7 @@ import { ModuleConfig } from '../../../../src/modules/token/types'; import { InternalMethod } from '../../../../src/modules/token/internal_method'; describe('token endpoint', () => { - const tokenModule = new TokenModule(); + const tokenModule = new Modules.Token.TokenModule(); const addr = utils.getRandomBytes(20); const mainChainID = Buffer.from([1, 0, 0, 0]); const mainChainTokenID = Buffer.concat([mainChainID, Buffer.from([0, 0, 0, 0])]); @@ -63,10 +63,14 @@ describe('token endpoint', () => { let endpoint: TokenEndpoint; let stateStore: PrefixedStateReadWriter; - let methodContext: MethodContext; + let methodContext: StateMachine.MethodContext; beforeEach(async () => { - const method = new TokenMethod(tokenModule.stores, tokenModule.events, tokenModule.name); + const method = new Modules.Token.TokenMethod( + tokenModule.stores, + tokenModule.events, + tokenModule.name, + ); const internalMethod = new InternalMethod(tokenModule.stores, tokenModule.events); endpoint = new TokenEndpoint(tokenModule.stores, tokenModule.offchainStores); const config: ModuleConfig = { diff --git a/framework/test/unit/modules/token/stores/supported_tokens.spec.ts b/framework/test/unit/modules/token/stores/supported_tokens.spec.ts index 908476ee0b8..13737ff3cda 100644 --- a/framework/test/unit/modules/token/stores/supported_tokens.spec.ts +++ b/framework/test/unit/modules/token/stores/supported_tokens.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { StoreGetter } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { ALL_SUPPORTED_TOKENS_KEY, SupportedTokensStore, @@ -25,7 +25,7 @@ describe('SupportedTokensStore', () => { const ownChainID = Buffer.from([1, 0, 0, 1]); let store: SupportedTokensStore; - let context: StoreGetter; + let context: Modules.StoreGetter; beforeEach(() => { store = new SupportedTokensStore('token', 3); diff --git a/framework/test/unit/modules/token/stores/user.spec.ts b/framework/test/unit/modules/token/stores/user.spec.ts index b620a5b6ebd..37289c191aa 100644 --- a/framework/test/unit/modules/token/stores/user.spec.ts +++ b/framework/test/unit/modules/token/stores/user.spec.ts @@ -13,7 +13,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { StoreGetter } from '../../../../../src'; +import { Modules } from '../../../../../src'; import { UserStore } from '../../../../../src/modules/token/stores/user'; import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefixed_state_read_writer'; import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_prefixed_state'; @@ -29,7 +29,7 @@ describe('UserStore', () => { }; let store: UserStore; - let context: StoreGetter; + let context: Modules.StoreGetter; beforeEach(async () => { store = new UserStore('token', 0); diff --git a/framework/test/unit/modules/token/token_module.spec.ts b/framework/test/unit/modules/token/token_module.spec.ts index 8c0f8fe35f8..70a9b31a2d7 100644 --- a/framework/test/unit/modules/token/token_module.spec.ts +++ b/framework/test/unit/modules/token/token_module.spec.ts @@ -21,7 +21,7 @@ import { UserStore } from '../../../../src/modules/token/stores/user'; import { createGenesisBlockContext } from '../../../../src/testing'; import { invalidGenesisAssets, validGenesisAssets } from './init_genesis_state_fixture'; import { SupportedTokensStore } from '../../../../src/modules/token/stores/supported_tokens'; -import { EMPTY_BYTES } from '../../../../src'; +import { Modules } from '../../../../src'; describe('token module', () => { let tokenModule: TokenModule; @@ -108,7 +108,7 @@ describe('token module', () => { // When all the tokens are supported if ( input.supportedTokensSubstore.length === 1 && - input.supportedTokensSubstore[0].chainID.equals(EMPTY_BYTES) + input.supportedTokensSubstore[0].chainID.equals(Modules.Interoperability.EMPTY_BYTES) ) { expect(allSupported).toBeTrue(); } else { diff --git a/framework/test/unit/modules/validators/endpoint.spec.ts b/framework/test/unit/modules/validators/endpoint.spec.ts index b61339acf42..f1423d80801 100644 --- a/framework/test/unit/modules/validators/endpoint.spec.ts +++ b/framework/test/unit/modules/validators/endpoint.spec.ts @@ -13,7 +13,7 @@ */ import { utils, address as cryptoAddress } from '@liskhq/lisk-cryptography'; -import { ModuleEndpointContext } from '../../../../src'; +import { Types } from '../../../../src'; import { ValidatorsModule } from '../../../../src/modules/validators'; import { BLSKeyStore } from '../../../../src/modules/validators/stores/bls_keys'; import { ValidatorKeysStore } from '../../../../src/modules/validators/stores/validator_keys'; @@ -170,7 +170,7 @@ describe('ValidatorsModuleEndpoint', () => { }); describe('getValidator', () => { - let context: ModuleEndpointContext; + let context: Types.ModuleEndpointContext; beforeEach(() => { context = createTransientModuleEndpointContext({ stateStore, diff --git a/framework/test/unit/plugins/base_plugin.spec.ts b/framework/test/unit/plugins/base_plugin.spec.ts index ec8a12819b4..8acb0dee534 100644 --- a/framework/test/unit/plugins/base_plugin.spec.ts +++ b/framework/test/unit/plugins/base_plugin.spec.ts @@ -14,12 +14,12 @@ */ import * as apiClient from '@liskhq/lisk-api-client'; -import { BasePlugin, GenesisConfig, systemDirs, testing } from '../../../src'; +import { Plugins, Types, systemDirs, testing } from '../../../src'; import * as loggerModule from '../../../src/logger'; import { getPluginExportPath } from '../../../src/plugins/base_plugin'; import { fakeLogger } from '../../utils/mocks'; -class MyPlugin extends BasePlugin { +class MyPlugin extends Plugins.BasePlugin { public configSchema = { $id: '/myPlugin/schema', type: 'object', @@ -90,7 +90,7 @@ describe('base_plugin', () => { plugin.init({ appConfig: { ...testing.fixtures.defaultConfig, - genesis: {} as unknown as GenesisConfig, + genesis: {} as unknown as Types.GenesisConfig, }, logger: fakeLogger, config: { diff --git a/framework/test/unit/state_machine/custom_modules.ts b/framework/test/unit/state_machine/custom_modules.ts index 7e2302d69db..275642a797a 100644 --- a/framework/test/unit/state_machine/custom_modules.ts +++ b/framework/test/unit/state_machine/custom_modules.ts @@ -13,20 +13,9 @@ */ /* eslint-disable max-classes-per-file */ -import { - BaseMethod, - BaseCommand, - BaseEndpoint, - BaseModule, - TransactionVerifyResult, - BlockAfterExecuteContext, - BlockExecuteContext, - GenesisBlockExecuteContext, - TransactionExecuteContext, - ModuleMetadata, -} from '../../../src'; - -export class CustomCommand0 extends BaseCommand { +import { TransactionVerifyResult, StateMachine, Modules } from '../../../src'; + +export class CustomCommand0 extends Modules.BaseCommand { public schema = { $id: '/lisk/customCommand0', type: 'object', @@ -46,12 +35,12 @@ export class CustomCommand0 extends BaseCommand { public execute = jest.fn(); } -export class CustomModule0 extends BaseModule { +export class CustomModule0 extends Modules.BaseModule { public commands = [new CustomCommand0(this.stores, this.events)]; public method = { testing: jest.fn(), - } as unknown as BaseMethod; - public endpoint: BaseEndpoint = {} as BaseEndpoint; + } as unknown as Modules.BaseMethod; + public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint; public get name() { return 'customModule0'; @@ -64,15 +53,15 @@ export class CustomModule0 extends BaseModule { public verifyTransaction = jest.fn().mockResolvedValue({ status: 1 }); public beforeCommandExecute = jest.fn(); public afterCommandExecute = jest.fn(); - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { throw new Error('Method not implemented.'); } } -export class CustomModule1 extends BaseModule { +export class CustomModule1 extends Modules.BaseModule { public commands = []; - public endpoint: BaseEndpoint = {} as BaseEndpoint; - public method: BaseMethod = {} as BaseMethod; + public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint; + public method: Modules.BaseMethod = {} as Modules.BaseMethod; public verifyAssets = jest.fn(); public beforeTransactionsExecute = jest.fn(); @@ -81,12 +70,12 @@ export class CustomModule1 extends BaseModule { public get name() { return 'customModule1'; } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { throw new Error('Method not implemented.'); } } -export class CustomCommand2 extends BaseCommand { +export class CustomCommand2 extends Modules.BaseCommand { public schema = { $id: '/lisk/customCommand2', type: 'object', @@ -105,14 +94,14 @@ export class CustomCommand2 extends BaseCommand { public verify = jest.fn().mockResolvedValue({ status: TransactionVerifyResult.INVALID }); // eslint-disable-next-line @typescript-eslint/require-await - public async execute(ctx: TransactionExecuteContext): Promise { + public async execute(ctx: StateMachine.TransactionExecuteContext): Promise { ctx.eventQueue.add('customModule1', 'customModule1 Name', Buffer.from([0, 0, 2])); } } -export class CustomModule2 extends BaseModule { - public endpoint: BaseEndpoint = {} as BaseEndpoint; - public method: BaseMethod = {} as BaseMethod; +export class CustomModule2 extends Modules.BaseModule { + public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint; + public method: Modules.BaseMethod = {} as Modules.BaseMethod; public commands = [new CustomCommand2(this.stores, this.events)]; public get name() { @@ -124,31 +113,31 @@ export class CustomModule2 extends BaseModule { .mockResolvedValue({ status: TransactionVerifyResult.INVALID }); // eslint-disable-next-line @typescript-eslint/require-await - public async initGenesisState(ctx: GenesisBlockExecuteContext): Promise { + public async initGenesisState(ctx: StateMachine.GenesisBlockExecuteContext): Promise { ctx.eventQueue.add(this.name, this.name, Buffer.from([0, 0, 2])); } // eslint-disable-next-line @typescript-eslint/require-await - public async finalizeGenesisState(ctx: GenesisBlockExecuteContext): Promise { + public async finalizeGenesisState(ctx: StateMachine.GenesisBlockExecuteContext): Promise { ctx.eventQueue.add(this.name, this.name, Buffer.from([0, 0, 2])); } // eslint-disable-next-line @typescript-eslint/require-await - public async beforeTransactionsExecute(ctx: BlockExecuteContext): Promise { + public async beforeTransactionsExecute(ctx: StateMachine.BlockExecuteContext): Promise { ctx.eventQueue.add(this.name, this.name, Buffer.from([0, 0, 2])); } // eslint-disable-next-line @typescript-eslint/require-await - public async afterTransactionsExecute(ctx: BlockAfterExecuteContext): Promise { + public async afterTransactionsExecute(ctx: StateMachine.BlockAfterExecuteContext): Promise { ctx.eventQueue.add(this.name, this.name, Buffer.from([0, 0, 2])); } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { throw new Error('Method not implemented.'); } } -export class CustomCommand3 extends BaseCommand { +export class CustomCommand3 extends Modules.BaseCommand { public schema = { $id: '/lisk/customCommand3', type: 'object', @@ -168,12 +157,12 @@ export class CustomCommand3 extends BaseCommand { public execute = jest.fn().mockRejectedValue('Command execution failed'); } -export class CustomModule3 extends BaseModule { +export class CustomModule3 extends Modules.BaseModule { public commands = [new CustomCommand3(this.stores, this.events)]; public method = { testing: jest.fn(), - } as unknown as BaseMethod; - public endpoint: BaseEndpoint = {} as BaseEndpoint; + } as unknown as Modules.BaseMethod; + public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint; public get name() { return 'customModule3'; @@ -186,7 +175,7 @@ export class CustomModule3 extends BaseModule { public verifyTransaction = jest.fn().mockResolvedValue({ status: 1 }); public beforeCommandExecute = jest.fn(); public afterCommandExecute = jest.fn(); - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { throw new Error('Method not implemented.'); } } diff --git a/framework/test/utils/mocks/endpoint.ts b/framework/test/utils/mocks/endpoint.ts index cbeef63697e..2338f3cf367 100644 --- a/framework/test/utils/mocks/endpoint.ts +++ b/framework/test/utils/mocks/endpoint.ts @@ -14,7 +14,7 @@ */ import { utils } from '@liskhq/lisk-cryptography'; -import { ModuleEndpointContext } from '../../../src'; +import { Types } from '../../../src'; import { RequestContext } from '../../../src/engine/rpc/rpc_server'; import { PrefixedStateReadWriter } from '../../../src/state_machine/prefixed_state_read_writer'; import { createTransientModuleEndpointContext } from '../../../src/testing'; @@ -23,7 +23,7 @@ import { fakeLogger } from './logger'; export const createContext = ( stateStore: PrefixedStateReadWriter, params: Record, -): ModuleEndpointContext => +): Types.ModuleEndpointContext => createTransientModuleEndpointContext({ stateStore, params, diff --git a/framework/test/utils/mocks/transaction.ts b/framework/test/utils/mocks/transaction.ts index 409af774843..bb36879b1bf 100644 --- a/framework/test/utils/mocks/transaction.ts +++ b/framework/test/utils/mocks/transaction.ts @@ -17,7 +17,7 @@ import { Transaction, BlockHeader, TAG_TRANSACTION } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { ed, address } from '@liskhq/lisk-cryptography'; import { signMultiSignatureTransaction } from '@liskhq/lisk-transactions'; -import { TokenModule } from '../../../src'; +import { Modules } from '../../../src'; import { MESSAGE_TAG_MULTISIG_REG } from '../../../src/modules/auth/constants'; import { multisigRegMsgSchema, @@ -257,7 +257,7 @@ export const createMultisignatureTransferTransaction = (input: { senderPublicKey: Buffer; privateKeys: Buffer[]; }): Transaction => { - const mod = new TokenModule(); + const mod = new Modules.Token.TokenModule(); const command = new TransferCommand(mod.stores, mod.events); const params = { tokenID: defaultTokenID(input.chainID),