From b5511eff27de84ac8e2e9e94bd53dbd3b56db43e Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 24 Nov 2023 15:28:51 +0100 Subject: [PATCH 01/53] Add module typdocs --- framework/src/logger/logger.ts | 1 + framework/src/modules/base_method.ts | 3 ++ framework/src/modules/base_module.ts | 51 ++++++++++++++++++++++ framework/src/modules/nft/method.ts | 32 ++++++++++++++ framework/src/modules/nft/module.ts | 22 ++++++++++ framework/src/modules/nft/types.ts | 4 ++ framework/src/state_machine/event_queue.ts | 1 + framework/src/state_machine/types.ts | 24 ++++++++++ 8 files changed, 138 insertions(+) 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/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..e576ccba9ee 100644 --- a/framework/src/modules/base_module.ts +++ b/framework/src/modules/base_module.ts @@ -30,31 +30,52 @@ import { BaseMethod } from './base_method'; import { InsertAssetContext } 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 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; }[]; } @@ -70,25 +91,55 @@ export abstract class BaseModule { public stores: NamedRegistry = new NamedRegistry(); 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); } 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/nft/method.ts b/framework/src/modules/nft/method.ts index 9695cfedd99..e932c02e595 100644 --- a/framework/src/modules/nft/method.ts +++ b/framework/src/modules/nft/method.ts @@ -49,6 +49,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; @@ -63,6 +66,13 @@ export class NFTMethod extends BaseMethod { this._feeMethod = feeMethod; } + /** + * Gets the chain ID of an NFT. + * + * @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 +81,24 @@ 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. + * + * @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. + * + * @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 +107,14 @@ export class NFTMethod extends BaseMethod { return nft.lockingModule !== NFT_NOT_LOCKED; } + /** + * Gets a specific NFT. + * + * @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); diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 7521b750b36..bafd841934e 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -68,6 +68,9 @@ import { MODULE_NAME_NFT, } from './constants'; +/** + * The `NFTModule` is used in the Lisk ecosystem for creating, destroying NFTs (non-fungible token), and transferring them in the ecosystem. + */ export class NFTModule extends BaseInteroperableModule { public method = new NFTMethod(this.stores, this.events); public endpoint = new NFTEndpoint(this.stores, this.offchainStores); @@ -84,6 +87,9 @@ export class NFTModule extends BaseInteroperableModule { public commands = [this._transferCommand, this._ccTransferCommand]; + /** + * Blockchain {@link this.events | Events} and 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)); @@ -124,6 +130,15 @@ export class NFTModule extends BaseInteroperableModule { 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 SidechainInteroperabilityMethod} + * @param feeMethod + * @param tokenMethod + */ public addDependencies( interoperabilityMethod: InteroperabilityMethod, feeMethod: FeeMethod, @@ -181,6 +196,13 @@ export class NFTModule extends BaseInteroperableModule { }; } + /** + * Provides the genesis and module specific config options. + * + * Called during the lifecycle of the module once per node start up. + * + * @param args + */ // eslint-disable-next-line @typescript-eslint/require-await public async init(args: ModuleInitArgs) { const ownChainID = Buffer.from(args.genesisConfig.chainID, 'hex'); 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/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/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; } From a277f26bd75bdd3b12d712c9d7d1143455df2e6d Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 24 Nov 2023 17:09:22 +0100 Subject: [PATCH 02/53] Add module typdocs --- framework/src/index.ts | 3 ++- framework/src/modules/base_module.ts | 26 +++++++++++++++++++ .../src/modules/interoperability/index.ts | 1 + framework/src/modules/nft/index.ts | 1 + framework/src/modules/nft/method.ts | 10 +++++++ framework/src/modules/nft/module.ts | 8 +++--- 6 files changed, 44 insertions(+), 5 deletions(-) diff --git a/framework/src/index.ts b/framework/src/index.ts index b11e5c002fc..b30f813b4a9 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -76,7 +76,7 @@ export { TOKEN_ID_LENGTH, MAX_DATA_LENGTH, } from './modules/token'; -export { NFTModule, NFTMethod } from './modules/nft'; +export { NFTModule, NFTMethod, NFT, InteroperabilityMethod } from './modules/nft'; export { PoSMethod, PoSModule, @@ -145,6 +145,7 @@ export { BaseCCCommand, BaseCCMethod, BaseInteroperableModule, + BaseInteroperabilityMethod, CrossChainMessageContext, CCCommandExecuteContext, ImmutableCrossChainMessageContext, diff --git a/framework/src/modules/base_module.ts b/framework/src/modules/base_module.ts index e576ccba9ee..313b062ca4c 100644 --- a/framework/src/modules/base_module.ts +++ b/framework/src/modules/base_module.ts @@ -86,9 +86,28 @@ 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(); /** @@ -102,6 +121,13 @@ export abstract class BaseModule { 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; /** diff --git a/framework/src/modules/interoperability/index.ts b/framework/src/modules/interoperability/index.ts index 1dcb67c856d..d6776cc90d0 100644 --- a/framework/src/modules/interoperability/index.ts +++ b/framework/src/modules/interoperability/index.ts @@ -14,6 +14,7 @@ export { BaseCCCommand } from './base_cc_command'; export { BaseInteroperableModule } from './base_interoperable_module'; +export { BaseInteroperabilityMethod } from './base_interoperability_method'; export { BaseCCMethod } from './base_cc_method'; export { getMainchainID } from './utils'; diff --git a/framework/src/modules/nft/index.ts b/framework/src/modules/nft/index.ts index 14063d827fe..f8fadeda659 100644 --- a/framework/src/modules/nft/index.ts +++ b/framework/src/modules/nft/index.ts @@ -14,3 +14,4 @@ export { NFTModule } from './module'; export { NFTMethod } from './method'; +export { NFT, InteroperabilityMethod } from './types'; diff --git a/framework/src/modules/nft/method.ts b/framework/src/modules/nft/method.ts index e932c02e595..58652af1f3e 100644 --- a/framework/src/modules/nft/method.ts +++ b/framework/src/modules/nft/method.ts @@ -69,6 +69,11 @@ export class NFTMethod extends BaseMethod { /** * 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. @@ -84,6 +89,11 @@ export class NFTMethod extends BaseMethod { /** * 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. diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index bafd841934e..36f727e0e83 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -88,7 +88,7 @@ export class NFTModule extends BaseInteroperableModule { public commands = [this._transferCommand, this._ccTransferCommand]; /** - * Blockchain {@link this.events | Events} and Stores of the module are registered in the constructor of a module, for later use in the module. + * Blockchain {@link events | Events} and Stores of the module are registered in the constructor of a module, for later use in the module. */ public constructor() { super(); @@ -135,9 +135,9 @@ export class NFTModule extends BaseInteroperableModule { * * 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 SidechainInteroperabilityMethod} - * @param feeMethod - * @param tokenMethod + * @param interoperabilityMethod {@link InteroperabilityMethod} + * @param feeMethod {@link FeeMethod} + * @param tokenMethod {@link TokenMethod} */ public addDependencies( interoperabilityMethod: InteroperabilityMethod, From b63cb7c6859a286ec701c04e18cc4ab0ccae4c54 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 24 Nov 2023 17:25:03 +0100 Subject: [PATCH 03/53] Fix comment format --- framework/src/modules/base_module.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/framework/src/modules/base_module.ts b/framework/src/modules/base_module.ts index 313b062ca4c..c66c25484ae 100644 --- a/framework/src/modules/base_module.ts +++ b/framework/src/modules/base_module.ts @@ -34,14 +34,14 @@ import { NamedRegistry } from './named_registry'; * Arguments used during module initialization. */ export interface ModuleInitArgs { - // Genesis config options + /** Genesis config options */ genesisConfig: Omit; - // Module-specific config options + /** Module-specific config options */ moduleConfig: Record; } export interface ModuleMetadata { - // A list of Endpoints of the respective module. + /** A list of Endpoints of the respective module. */ endpoints: { // The name of the endpoint. name: string; @@ -50,28 +50,28 @@ export interface ModuleMetadata { // A schema of the expected response to a request to the endpoint. response?: Schema; }[]; - // A list of Blockchain Events that are emitted by the module. + /** 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. + /** 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. + /** 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. + /** The data stores of the module. */ stores: { // The store key. key: string; From 80806ab98f2fede445f61c0670b1e4c66ccda3a5 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 27 Nov 2023 15:51:48 +0100 Subject: [PATCH 04/53] Add typedocs for nft methods --- .../interoperability/base_cc_method.ts | 3 + .../base_interoperable_module.ts | 5 + framework/src/modules/nft/index.ts | 6 + framework/src/modules/nft/method.ts | 105 ++++++++++++++++++ framework/src/modules/nft/module.ts | 11 +- 5 files changed, 122 insertions(+), 8 deletions(-) diff --git a/framework/src/modules/interoperability/base_cc_method.ts b/framework/src/modules/interoperability/base_cc_method.ts index 098b3a5db0a..7878c969d5b 100644 --- a/framework/src/modules/interoperability/base_cc_method.ts +++ b/framework/src/modules/interoperability/base_cc_method.ts @@ -15,6 +15,9 @@ import { BaseMethod } from '..'; 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/nft/index.ts b/framework/src/modules/nft/index.ts index f8fadeda659..51aad2cff3f 100644 --- a/framework/src/modules/nft/index.ts +++ b/framework/src/modules/nft/index.ts @@ -13,5 +13,11 @@ */ 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 { NFTMethod } from './method'; export { NFT, InteroperabilityMethod } from './types'; diff --git a/framework/src/modules/nft/method.ts b/framework/src/modules/nft/method.ts index 58652af1f3e..cbcd9979962 100644 --- a/framework/src/modules/nft/method.ts +++ b/framework/src/modules/nft/method.ts @@ -105,6 +105,11 @@ export class NFTMethod extends BaseMethod { /** * 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. @@ -120,6 +125,11 @@ export class NFTMethod extends BaseMethod { /** * Gets a specific NFT. * + * @example + * ```ts + * getNFT(methodContext,nftID); + * ``` + * * @param methodContext immutable method context * @param nftID ID of the NFT * @@ -149,6 +159,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, @@ -223,10 +247,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, @@ -264,6 +314,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, @@ -291,6 +354,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, @@ -314,6 +391,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'); @@ -375,6 +468,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 { diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 36f727e0e83..fc759c1a55e 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -69,7 +69,9 @@ import { } from './constants'; /** - * The `NFTModule` is used in the Lisk ecosystem for creating, destroying NFTs (non-fungible token), and transferring them in the ecosystem. + * The `NFTModule` is used for creating, destroying NFTs (non-fungible tokens), and transferring them in the Lisk ecosystem. + * + * @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); @@ -196,13 +198,6 @@ export class NFTModule extends BaseInteroperableModule { }; } - /** - * Provides the genesis and module specific config options. - * - * Called during the lifecycle of the module once per node start up. - * - * @param args - */ // eslint-disable-next-line @typescript-eslint/require-await public async init(args: ModuleInitArgs) { const ownChainID = Buffer.from(args.genesisConfig.chainID, 'hex'); From 214f92777e7f259ea53371655d7a56d28a521c81 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 27 Nov 2023 16:57:28 +0100 Subject: [PATCH 05/53] Add typedocs for nft methods --- framework/src/index.ts | 10 +- .../src/modules/interoperability/index.ts | 1 + framework/src/modules/nft/index.ts | 2 + framework/src/modules/nft/method.ts | 133 +++++++++++++++++- 4 files changed, 144 insertions(+), 2 deletions(-) diff --git a/framework/src/index.ts b/framework/src/index.ts index b30f813b4a9..3d7dcf02e1e 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -76,7 +76,14 @@ export { TOKEN_ID_LENGTH, MAX_DATA_LENGTH, } from './modules/token'; -export { NFTModule, NFTMethod, NFT, InteroperabilityMethod } from './modules/nft'; +export { + NFTModule, + NFTMethod, + NFT, + NFTAttributes, + InternalMethod, + InteroperabilityMethod, +} from './modules/nft'; export { PoSMethod, PoSModule, @@ -145,6 +152,7 @@ export { BaseCCCommand, BaseCCMethod, BaseInteroperableModule, + BaseInteroperabilityModule, BaseInteroperabilityMethod, CrossChainMessageContext, CCCommandExecuteContext, diff --git a/framework/src/modules/interoperability/index.ts b/framework/src/modules/interoperability/index.ts index d6776cc90d0..c96aff40dcd 100644 --- a/framework/src/modules/interoperability/index.ts +++ b/framework/src/modules/interoperability/index.ts @@ -14,6 +14,7 @@ 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'; diff --git a/framework/src/modules/nft/index.ts b/framework/src/modules/nft/index.ts index 51aad2cff3f..e2e47246ce8 100644 --- a/framework/src/modules/nft/index.ts +++ b/framework/src/modules/nft/index.ts @@ -20,4 +20,6 @@ export { } from './commands/transfer_cross_chain'; export { CrossChainTransferCommand } from './cc_commands/cc_transfer'; export { NFTMethod } from './method'; +export { InternalMethod } from './internal_method'; +export { NFTAttributes } from './stores/nft'; export { NFT, InteroperabilityMethod } from './types'; diff --git a/framework/src/modules/nft/method.ts b/framework/src/modules/nft/method.ts index cbcd9979962..d15247e12fc 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'; @@ -61,6 +60,12 @@ export class NFTMethod extends BaseMethod { this._config = config; } + /** + * Adds dependencies from other module methods. + * + * @param internalMethod + * @param feeMethod {@link FeeMethod} + */ public addDependencies(internalMethod: InternalMethod, feeMethod: FeeMethod) { this._internalMethod = internalMethod; this._feeMethod = feeMethod; @@ -541,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, @@ -568,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, @@ -618,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); @@ -640,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); @@ -654,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, @@ -686,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, @@ -713,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, @@ -773,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, @@ -826,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 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, @@ -943,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, From 924d47e828fa67ac5a16d271082f7835d6884937 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 27 Nov 2023 17:17:36 +0100 Subject: [PATCH 06/53] Export constants --- framework/src/index.ts | 6 ++++++ framework/src/modules/nft/index.ts | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/framework/src/index.ts b/framework/src/index.ts index 3d7dcf02e1e..995c89095e5 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -83,6 +83,12 @@ export { NFTAttributes, InternalMethod, InteroperabilityMethod, + LENGTH_COLLECTION_ID, + LENGTH_NFT_ID, + LENGTH_INDEX, + MODULE_NAME_NFT, + FEE_CREATE_NFT, + NftEventResult, } from './modules/nft'; export { PoSMethod, diff --git a/framework/src/modules/nft/index.ts b/framework/src/modules/nft/index.ts index e2e47246ce8..ac2dd57d3ec 100644 --- a/framework/src/modules/nft/index.ts +++ b/framework/src/modules/nft/index.ts @@ -23,3 +23,11 @@ export { NFTMethod } from './method'; 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'; From 6987b666178bac5917d33875ceecb0c1c31e8e54 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 27 Nov 2023 17:42:19 +0100 Subject: [PATCH 07/53] Update typedoc.json to include exports of the NFT module --- framework/src/index.ts | 1 + framework/typedoc.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/src/index.ts b/framework/src/index.ts index 995c89095e5..68cad132618 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -81,6 +81,7 @@ export { NFTMethod, NFT, NFTAttributes, + TransferCrossChainParams, InternalMethod, InteroperabilityMethod, LENGTH_COLLECTION_ID, diff --git a/framework/typedoc.json b/framework/typedoc.json index bf8ab39eb2e..dcc7da854df 100644 --- a/framework/typedoc.json +++ b/framework/typedoc.json @@ -1,7 +1,7 @@ { "$schema": "https://typedoc.org/schema.json", "includeVersion": true, - "entryPoints": ["src/index.ts"], + "entryPoints": ["src/index.ts", "src/modules/nft/index.ts"], "readme": "./README.md", "tsconfig": "./tsconfig.json" } From b1f6d2e9b6ad2d92d4926a599c0c57fbd325c2eb Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 30 Nov 2023 13:46:29 +0100 Subject: [PATCH 08/53] Restructure module exports --- framework/src/index.ts | 150 +----------------- framework/src/modules/index.ts | 12 ++ .../interoperability/base_cc_method.ts | 2 +- .../src/modules/interoperability/index.ts | 8 +- .../src/modules/nft/commands/transfer.ts | 4 + framework/src/modules/nft/index.ts | 2 + framework/src/modules/nft/module.ts | 5 +- framework/typedoc.json | 2 +- 8 files changed, 26 insertions(+), 159 deletions(-) diff --git a/framework/src/index.ts b/framework/src/index.ts index 68cad132618..29e6a46d5d6 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,24 +25,6 @@ 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'; @@ -53,126 +34,7 @@ export type { BaseChannel } from './controller/channels'; export type { EventsDefinition, EventCallback } from './controller/event'; 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, - NFT, - NFTAttributes, - TransferCrossChainParams, - InternalMethod, - InteroperabilityMethod, - LENGTH_COLLECTION_ID, - LENGTH_NFT_ID, - LENGTH_INDEX, - MODULE_NAME_NFT, - FEE_CREATE_NFT, - NftEventResult, -} 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, - BaseInteroperabilityModule, - BaseInteroperabilityMethod, - 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 * as Modules from './modules'; export { GenesisBlockExecuteContext, InsertAssetContext, @@ -201,15 +63,5 @@ export { unsignedCertificateSchema, } from './engine/consensus'; 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'; diff --git a/framework/src/modules/index.ts b/framework/src/modules/index.ts index 7dca1cf8234..10177849001 100644 --- a/framework/src/modules/index.ts +++ b/framework/src/modules/index.ts @@ -24,3 +24,15 @@ export { ImmutableOffchainStoreGetter, } from './base_offchain_store'; export { BaseEvent, EventQueuer } 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 NamedRegistry from './named_registry'; +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 7878c969d5b..01889374721 100644 --- a/framework/src/modules/interoperability/base_cc_method.ts +++ b/framework/src/modules/interoperability/base_cc_method.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { BaseMethod } from '..'; +import { BaseMethod } from '../base_method'; import { BeforeCCMForwardingContext, CrossChainMessageContext, RecoverContext } from './types'; /** diff --git a/framework/src/modules/interoperability/index.ts b/framework/src/modules/interoperability/index.ts index c96aff40dcd..11b7012a830 100644 --- a/framework/src/modules/interoperability/index.ts +++ b/framework/src/modules/interoperability/index.ts @@ -52,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/commands/transfer.ts b/framework/src/modules/nft/commands/transfer.ts index bd5ae39d2c8..8fecd5f4285 100644 --- a/framework/src/modules/nft/commands/transfer.ts +++ b/framework/src/modules/nft/commands/transfer.ts @@ -28,6 +28,10 @@ export interface TransferParams { data: string; } +/** + * The Transfer command of the NFT modules transfers an NFT from one account to another. + * + */ export class TransferCommand extends BaseCommand { public schema = transferParamsSchema; private _internalMethod!: InternalMethod; diff --git a/framework/src/modules/nft/index.ts b/framework/src/modules/nft/index.ts index ac2dd57d3ec..b5c2c758979 100644 --- a/framework/src/modules/nft/index.ts +++ b/framework/src/modules/nft/index.ts @@ -19,7 +19,9 @@ export { 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'; diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index fc759c1a55e..3d0069704b3 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -90,7 +90,7 @@ export class NFTModule extends BaseInteroperableModule { public commands = [this._transferCommand, this._ccTransferCommand]; /** - * Blockchain {@link events | Events} and Stores of the module are registered in the constructor of a module, for later use in the module. + * 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(); @@ -128,6 +128,9 @@ 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; } diff --git a/framework/typedoc.json b/framework/typedoc.json index dcc7da854df..bf8ab39eb2e 100644 --- a/framework/typedoc.json +++ b/framework/typedoc.json @@ -1,7 +1,7 @@ { "$schema": "https://typedoc.org/schema.json", "includeVersion": true, - "entryPoints": ["src/index.ts", "src/modules/nft/index.ts"], + "entryPoints": ["src/index.ts"], "readme": "./README.md", "tsconfig": "./tsconfig.json" } From af860b422e7674d68602b913ee6b4b215521ba3e Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 30 Nov 2023 15:51:13 +0100 Subject: [PATCH 09/53] Restructure framework exports --- framework/src/controller/index.ts | 5 ++- framework/src/engine/bft/index.ts | 4 +- framework/src/engine/consensus/index.ts | 15 +++++--- framework/src/engine/endpoint/index.ts | 19 ++++++++++ framework/src/engine/index.ts | 6 ++- framework/src/index.ts | 49 +++++++------------------ framework/src/modules/base_command.ts | 6 ++- framework/src/modules/base_event.ts | 2 +- framework/src/modules/base_module.ts | 10 ++--- framework/src/modules/index.ts | 22 +++++------ framework/src/plugins/index.ts | 2 + framework/src/state_machine/index.ts | 19 +--------- 12 files changed, 74 insertions(+), 85 deletions(-) create mode 100644 framework/src/engine/endpoint/index.ts create mode 100644 framework/src/plugins/index.ts diff --git a/framework/src/controller/index.ts b/framework/src/controller/index.ts index 0a64a9a6e89..bc5f23b58f9 100644 --- a/framework/src/controller/index.ts +++ b/framework/src/controller/index.ts @@ -12,5 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -export { Controller } from './controller'; -export { InMemoryChannel, IPCChannel } from './channels'; +export * from './controller'; +export * from './channels'; +export * from './event'; diff --git a/framework/src/engine/bft/index.ts b/framework/src/engine/bft/index.ts index ca140154aee..7cc0a18ca67 100644 --- a/framework/src/engine/bft/index.ts +++ b/framework/src/engine/bft/index.ts @@ -12,7 +12,9 @@ * Removal or modification of this copyright notice is prohibited. */ +export * from './constants'; export { BFTModule } from './module'; export type { BFTMethod } from './method'; +export * 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..fccb8d29ae1 100644 --- a/framework/src/engine/consensus/index.ts +++ b/framework/src/engine/consensus/index.ts @@ -13,13 +13,16 @@ */ export { Consensus } from './consensus'; +export * from './constants'; export { - CONSENSUS_EVENT_BLOCK_BROADCAST, - CONSENSUS_EVENT_FORK_DETECTED, - CONSENSUS_EVENT_BLOCK_DELETE, - CONSENSUS_EVENT_BLOCK_NEW, -} from './constants'; -export { BFTHeights } from '../bft/types'; + BFTHeader, + ActiveValidator, + PkSigPair, + AggregateCommit, + CommitPool, + ValidatorUpdate, +} from './types'; +export * from './schema'; export { isEmptyConsensusUpdate } from './utils'; export { computeUnsignedCertificateFromBlockHeader, diff --git a/framework/src/engine/endpoint/index.ts b/framework/src/engine/endpoint/index.ts new file mode 100644 index 00000000000..5567d35ba47 --- /dev/null +++ b/framework/src/engine/endpoint/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright © 2021 Lisk Foundation + * + * See the LICENSE file at the top-level directory of this distribution + * for licensing information. + * + * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, + * no part of this software, including this file, may be copied, modified, + * propagated, or distributed except according to the terms contained in the + * LICENSE file. + * + * Removal or modification of this copyright notice is prohibited. + */ + +export * from './chain'; +export * from './consensus'; +export * from './state'; +export * from './system'; +export * from './txpool'; diff --git a/framework/src/engine/index.ts b/framework/src/engine/index.ts index e0e4a7c1cbf..5ca956d4f6c 100644 --- a/framework/src/engine/index.ts +++ b/framework/src/engine/index.ts @@ -12,5 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -export { Engine } from './engine'; -export { computeValidatorsHash, areDistinctHeadersContradicting, BFTParameters } from './bft'; +export * from './engine'; +export * from './bft'; +export * from './consensus'; +export * from './endpoint'; diff --git a/framework/src/index.ts b/framework/src/index.ts index 29e6a46d5d6..344529c234e 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -20,48 +20,25 @@ export { signingBlockHeaderSchema, Block, BlockJSON, - BlockHeader, BlockHeaderJSON, BlockAssetJSON, standardEventDataSchema, } from '@liskhq/lisk-chain'; 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 * from './plugins'; +export * as Controller from './controller'; export * as testing from './testing'; -export * from './types'; export * as Modules from './modules'; -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 StateMachine from './state_machine'; +export * as Engine from './engine'; +export * from './types'; export { applicationConfigSchema } from './schema'; -export { Proof, QueryProof, ProveResponse, Validator as BFTValidator } from './abi/abi'; -export { areDistinctHeadersContradicting } from './engine/bft'; +export { + TransactionExecutionResult, + TransactionVerifyResult, + Proof, + QueryProof, + ProveResponse, + Validator as BFTValidator, +} from './abi'; 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_module.ts b/framework/src/modules/base_module.ts index c66c25484ae..86dac154b4c 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,11 +27,7 @@ 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'; /** diff --git a/framework/src/modules/index.ts b/framework/src/modules/index.ts index 10177849001..8fc25f7824b 100644 --- a/framework/src/modules/index.ts +++ b/framework/src/modules/index.ts @@ -12,18 +12,15 @@ * 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'; @@ -33,6 +30,5 @@ export * as Reward from './reward'; export * as DynamicReward from './dynamic_reward'; export * as Random from './random'; export * as PoA from './poa'; -export * as NamedRegistry from './named_registry'; export * as Validators from './validators'; export * as Auth from './auth'; 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/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'; From 2cc3096ecc61b133bac26951c446df68f66d2d94 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 1 Dec 2023 13:58:04 +0100 Subject: [PATCH 10/53] Update imports --- .../bootstrapping/commands/base_ipc_client.ts | 4 +- .../commands/transaction/create.ts | 16 ++- .../commands/transaction/sign.ts | 10 +- commander/src/utils/genesis_creation.ts | 21 ++-- commander/src/utils/transaction.ts | 12 +- .../src/active_validators_update.ts | 28 +++-- .../src/certificate_generation.ts | 25 ++--- .../src/chain_connector_plugin.ts | 104 +++++++++--------- .../src/constants.ts | 4 +- .../src/db.ts | 10 +- .../src/endpoint.ts | 3 +- .../src/inbox_update.ts | 8 +- .../src/schemas.ts | 15 ++- .../src/types.ts | 25 ++--- .../src/utils.ts | 36 +++--- .../src/db.ts | 10 +- framework/src/index.ts | 1 + framework/src/logger/index.ts | 2 +- .../src/modules/nft/commands/transfer.ts | 11 +- framework/src/modules/nft/module.ts | 24 ++++ 20 files changed, 183 insertions(+), 186 deletions(-) diff --git a/commander/src/bootstrapping/commands/base_ipc_client.ts b/commander/src/bootstrapping/commands/base_ipc_client.ts index 9c8a7bd178b..7e3edffb6b0 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 { RegisteredSchema, Modules } from 'lisk-framework'; import { PromiseResolvedType } from '../../types'; import { isApplicationRunning } from '../../utils/application'; import { flagsWithParser } from '../../utils/flags'; @@ -35,7 +35,7 @@ export abstract class BaseIPCClientCommand extends Command { protected baseIPCClientFlags!: BaseIPCClientFlags; protected _client!: PromiseResolvedType> | undefined; protected _schema!: RegisteredSchema; - protected _metadata!: ModuleMetadataJSON[]; + protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; async finally(): Promise { diff --git a/commander/src/bootstrapping/commands/transaction/create.ts b/commander/src/bootstrapping/commands/transaction/create.ts index f867b230613..c6af3045d44 100644 --- a/commander/src/bootstrapping/commands/transaction/create.ts +++ b/commander/src/bootstrapping/commands/transaction/create.ts @@ -27,7 +27,7 @@ import { blockHeaderSchema, blockSchema, transactionSchema, - ModuleMetadataJSON, + Modules, } from 'lisk-framework'; import { PromiseResolvedType } from '../../../types'; import { deriveKeypair } from '../../../utils/commons'; @@ -74,7 +74,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); @@ -113,7 +117,7 @@ const getKeysFromFlags = async (flags: CreateFlags) => { const validateAndSignTransaction = ( transaction: Transaction, schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], chainID: string, privateKey: Buffer, noSignature: boolean, @@ -146,7 +150,7 @@ const createTransactionOffline = async ( args: Args, flags: CreateFlags, registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transaction: Transaction, ) => { const params = await getParamsObject(metadata, flags, args); @@ -170,7 +174,7 @@ const createTransactionOnline = async ( flags: CreateFlags, client: apiClient.APIClient, registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transaction: Transaction, ) => { const nodeInfo = await client.node.getNodeInfo(); @@ -276,7 +280,7 @@ export abstract class CreateCommand extends Command { protected _client!: PromiseResolvedType> | undefined; protected _schema!: RegisteredSchema; - protected _metadata!: ModuleMetadataJSON[]; + protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; async run(): Promise { diff --git a/commander/src/bootstrapping/commands/transaction/sign.ts b/commander/src/bootstrapping/commands/transaction/sign.ts index 2be81949a98..2ca98663383 100644 --- a/commander/src/bootstrapping/commands/transaction/sign.ts +++ b/commander/src/bootstrapping/commands/transaction/sign.ts @@ -18,7 +18,7 @@ import { Application, blockHeaderSchema, blockSchema, - ModuleMetadataJSON, + Modules, PartialApplicationConfig, RegisteredSchema, transactionSchema, @@ -58,7 +58,7 @@ interface SignFlags { const signTransaction = async ( flags: SignFlags, registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, chainID: string | undefined, keys: Keys, @@ -106,7 +106,7 @@ const signTransaction = async ( const signTransactionOffline = async ( flags: SignFlags, registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ): Promise> => { const mandatoryKeys = flags['mandatory-keys']; @@ -133,7 +133,7 @@ const signTransactionOnline = async ( flags: SignFlags, client: apiClient.APIClient, registeredSchema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ) => { const transactionObject = decodeTransaction(registeredSchema, metadata, transactionHexStr); @@ -191,7 +191,7 @@ export abstract class SignCommand extends Command { protected _client: PromiseResolvedType> | undefined; protected _schema!: RegisteredSchema; - protected _metadata!: ModuleMetadataJSON[]; + protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; async run(): Promise { 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..359356c2bbf 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, RegisteredSchema } 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 => { @@ -40,7 +40,7 @@ export const getParamsSchema = ( export const decodeTransaction = ( schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ) => { const transactionBytes = Buffer.from(transactionHexStr, 'hex'); @@ -60,7 +60,7 @@ export const decodeTransaction = ( export const encodeTransaction = ( schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, ): Buffer => { @@ -79,7 +79,7 @@ export const encodeTransaction = ( export const encodeTransactionJSON = ( schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, ): Buffer => { @@ -101,7 +101,7 @@ export const encodeTransactionJSON = ( export const transactionToJSON = ( schema: RegisteredSchema, - metadata: ModuleMetadataJSON[], + metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, ): Record => { 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 284eb49c3cb..11b6b861bd8 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,18 @@ */ import { + Engine, BasePlugin, PluginInitContext, apiClient, - BFTHeights, db as liskDB, codec, chain, - OutboxRootWitness, + Modules, JSONObject, Schema, Transaction, - LastCertificate, - CcmSendSuccessEventData, - CcmProcessedEventData, - CCMProcessedResult, - CrossChainUpdateTransactionParams, - certificateSchema, - ccuParamsSchema, cryptography, - ChainAccountJSON, - ActiveValidatorsUpdate, - AggregateCommit, - ChannelDataJSON, - Certificate, } from 'lisk-sdk'; import { calculateActiveValidatorsUpdate } from './active_validators_update'; import { @@ -97,7 +85,7 @@ export class ChainConnectorPlugin extends BasePlugin private _chainConnectorPluginDB!: liskDB.Database; private _chainConnectorStore!: ChainConnectorStore; - private _lastCertificate!: LastCertificate; + private _lastCertificate!: Modules.Interoperability.LastCertificate; private _ccuFrequency!: number; private _maxCCUSize!: number; private _isSaveCCU!: boolean; @@ -170,17 +158,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.'); } @@ -209,16 +199,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( @@ -267,7 +258,9 @@ export class ChainConnectorPlugin extends BasePlugin if (computedCCUParams) { try { - await this._submitCCU(codec.encode(ccuParamsSchema, computedCCUParams.ccuParams)); + await this._submitCCU( + codec.encode(Modules.Interoperability.ccuParamsSchema, computedCCUParams.ccuParams), + ); // If CCU was sent successfully then save the lastSentCCM if any // TODO: Add function to check on the receiving chain whether last sent CCM was accepted or not if (computedCCUParams.lastCCMToBeSent) { @@ -296,12 +289,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 @@ -325,7 +318,7 @@ export class ChainConnectorPlugin extends BasePlugin height: this._lastCertificate.height, }; - let activeValidatorsUpdate: ActiveValidatorsUpdate = { + let activeValidatorsUpdate: Modules.Interoperability.ActiveValidatorsUpdate = { blsKeysUpdate: [], bftWeightsUpdate: [], bftWeightsUpdateBitmap: EMPTY_BYTES, @@ -342,20 +335,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.'); @@ -430,7 +425,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 @@ -445,16 +440,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; } @@ -477,7 +472,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, @@ -551,7 +548,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'), ); @@ -569,11 +566,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); } } @@ -597,17 +594,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( 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..44a14abc8e7 100644 --- a/framework-plugins/lisk-framework-chain-connector-plugin/src/endpoint.ts +++ b/framework-plugins/lisk-framework-chain-connector-plugin/src/endpoint.ts @@ -16,7 +16,6 @@ import { BasePluginEndpoint, PluginEndpointContext, chain, - BlockHeader, BlockHeaderJSON, validator as liskValidator, } from 'lisk-sdk'; @@ -61,7 +60,7 @@ export class Endpoint extends BasePluginEndpoint { public async getBlockHeaders(_context: 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( 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 4b0aac42428..41b2ad0217c 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, @@ -128,7 +128,7 @@ export const aggregateCommitsInfoSchema = { type: 'array', fieldNumber: 1, items: { - ...aggregateCommitSchema, + ...Engine.aggregateCommitSchema, }, }, }, @@ -151,10 +151,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, + }, }, }; @@ -187,7 +190,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 b1f223b9778..4d1983794c8 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; @@ -50,7 +38,7 @@ export const getMainchainID = (chainID: Buffer): Buffer => { return Buffer.concat([networkID, Buffer.alloc(CHAIN_ID_LENGTH - 1, 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'), @@ -90,16 +78,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, @@ -114,17 +102,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, @@ -139,7 +129,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-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/src/index.ts b/framework/src/index.ts index 344529c234e..64822a4725b 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -27,6 +27,7 @@ export { export { Application } from './application'; export { systemDirs } from './system_dirs'; export * from './plugins'; +export * from './logger'; export * as Controller from './controller'; export * as testing from './testing'; export * as Modules from './modules'; diff --git a/framework/src/logger/index.ts b/framework/src/logger/index.ts index 697ec2fa359..6acf3f0acdb 100644 --- a/framework/src/logger/index.ts +++ b/framework/src/logger/index.ts @@ -12,4 +12,4 @@ * Removal or modification of this copyright notice is prohibited. */ -export { createLogger, Logger } from './logger'; +export * from './logger'; diff --git a/framework/src/modules/nft/commands/transfer.ts b/framework/src/modules/nft/commands/transfer.ts index 8fecd5f4285..7a909c58f5d 100644 --- a/framework/src/modules/nft/commands/transfer.ts +++ b/framework/src/modules/nft/commands/transfer.ts @@ -29,8 +29,17 @@ export interface TransferParams { } /** - * The Transfer command of the NFT modules transfers an NFT from one account to another. + * 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 + * ./bin/run transaction:create nft transfer 10000000 --params='{"nftID":"01000000000000010000000000000001","recipientAddress":"lskycz7hvr8yfu74bcwxy2n4mopfmjancgdvxq8xz","data":"Congratulations on completing the course!"}' + * ``` */ export class TransferCommand extends BaseCommand { public schema = transferParamsSchema; diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 3d0069704b3..14ce14d43f8 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -69,8 +69,32 @@ import { } 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 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 NFT 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 a 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, index being then 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 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 getNewAttributes} function. + * If needed, custom modules can implement a more fine-grained approach towards the attributes that are modified cross-chain. + * * @see [LIP 0052 - Introduce NFT module](https://github.com/LiskHQ/lips/blob/main/proposals/lip-0052.md) */ export class NFTModule extends BaseInteroperableModule { From 41af9dab54fd865d65ebe1584f025fd5216f0626 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 1 Dec 2023 15:05:56 +0100 Subject: [PATCH 11/53] Update example imports --- .../pos-sidechain-example-one/src/app/app.ts | 4 +- .../hello/cc_commands/react_command.ts | 8 ++-- .../src/app/modules/hello/cc_method.ts | 4 +- .../hello/commands/create_hello_command.ts | 17 +++----- .../src/app/modules/hello/endpoint.ts | 4 +- .../src/app/modules/hello/events/new_hello.ts | 4 +- .../src/app/modules/hello/method.ts | 6 +-- .../src/app/modules/hello/module.ts | 43 ++++++++----------- .../src/app/modules/hello/stores/counter.ts | 4 +- .../src/app/modules/hello/stores/message.ts | 4 +- .../src/app/modules/hello/stores/reaction.ts | 4 +- .../modules/testNft/commands/destroy_nft.ts | 10 ++--- .../app/modules/testNft/commands/mint_nft.ts | 10 ++--- .../src/app/modules/testNft/endpoint.ts | 4 +- .../src/app/modules/testNft/method.ts | 4 +- .../src/app/modules/testNft/module.ts | 12 +++--- .../src/app/modules/react/cc_method.ts | 4 +- .../modules/react/commands/react_command.ts | 19 ++++---- .../src/app/modules/react/endpoint.ts | 4 +- .../src/app/modules/react/method.ts | 4 +- .../src/app/modules/react/module.ts | 8 ++-- .../src/app/modules/react/types.ts | 21 ++++----- 22 files changed, 92 insertions(+), 110 deletions(-) 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..2df7c3453bb 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/app.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/app.ts @@ -1,4 +1,4 @@ -import { Application, PartialApplicationConfig, NFTModule } from 'lisk-sdk'; +import { Application, PartialApplicationConfig, Modules } from 'lisk-sdk'; import { TestNftModule } from './modules/testNft/module'; import { registerModules } from './modules'; import { registerPlugins } from './plugins'; @@ -7,7 +7,7 @@ import { HelloModule } from './modules/hello/module'; export const getApplication = (config: 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_command.ts b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_command.ts index 4fbdf80fd48..8787a9bcc01 100644 --- a/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_command.ts +++ b/examples/interop/pos-sidechain-example-one/src/app/modules/hello/cc_commands/react_command.ts @@ -1,12 +1,12 @@ /* 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, CCReactMessageParams } from '../schemas'; import { MAX_RESERVED_ERROR_STATUS, CROSS_CHAIN_COMMAND_NAME_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 { @@ -14,7 +14,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) { @@ -30,7 +30,7 @@ export class ReactCCCommand extends BaseCCCommand { } } - public async execute(ctx: CrossChainMessageContext): Promise { + public async execute(ctx: Modules.Interoperability.CrossChainMessageContext): Promise { const { ccm, logger } = ctx; logger.info('Executing React CCM'); // const { sendingChainID, status, receivingChainID } = 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..d242492f0ce 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,11 +1,8 @@ /* eslint-disable class-methods-use-this */ import { - BaseCommand, - CommandVerifyContext, - CommandExecuteContext, - VerificationResult, - VerifyStatus, + Modules, + StateMachine, } from 'lisk-sdk'; import { createHelloSchema } from '../schemas'; import { MessageStore } from '../stores/message'; @@ -17,7 +14,7 @@ interface Params { message: string; } -export class CreateHelloCommand extends BaseCommand { +export class CreateHelloCommand extends Modules.BaseCommand { public schema = createHelloSchema; private _blacklist!: string[]; @@ -32,8 +29,8 @@ 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 +39,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 4db39083be5..3e34303a425 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,9 +1,9 @@ -import { BaseEndpoint, ModuleEndpointContext, cryptography } from 'lisk-sdk'; +import { Modules, ModuleEndpointContext, 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 { +export class HelloEndpoint extends Modules.BaseEndpoint { public async getHelloCounter(ctx: ModuleEndpointContext): Promise { const counterSubStore = this.stores.get(CounterStore); 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 95be8d028d2..44a7d7b0292 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 @@ -2,18 +2,9 @@ import { validator, - BaseInteroperableModule, - BlockAfterExecuteContext, - BlockExecuteContext, - BlockVerifyContext, - GenesisBlockExecuteContext, - InsertAssetContext, - ModuleInitArgs, - ModuleMetadata, - TransactionExecuteContext, - TransactionVerifyContext, + StateMachine, + Modules, utils, - VerificationResult, } from 'lisk-sdk'; import { CreateHelloCommand } from './commands/create_hello_command'; import { ReactCCCommand } from './cc_commands/react_command'; @@ -29,7 +20,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 = { @@ -38,7 +29,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)]; @@ -55,7 +46,7 @@ export class HelloModule extends BaseInteroperableModule { this.events.register(NewHelloEvent, new NewHelloEvent(this.name)); } - public metadata(): ModuleMetadata { + public metadata(): Modules.ModuleMetadata { return { endpoints: [ { @@ -88,13 +79,13 @@ 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 @@ -102,17 +93,17 @@ 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: 1, @@ -121,20 +112,20 @@ export class HelloModule extends BaseInteroperableModule { } // eslint-disable-next-line @typescript-eslint/no-empty-function - public async beforeCommandExecute(_context: TransactionExecuteContext): Promise {} + public async beforeCommandExecute(_context: StateMachine.TransactionExecuteContext): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async afterCommandExecute(_context: TransactionExecuteContext): Promise {} + public async afterCommandExecute(_context: StateMachine.TransactionExecuteContext): 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): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async beforeTransactionsExecute(_context: BlockExecuteContext): Promise {} + public async beforeTransactionsExecute(_context: StateMachine.BlockExecuteContext): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async afterTransactionsExecute(_context: BlockAfterExecuteContext): Promise {} + public async afterTransactionsExecute(_context: StateMachine.BlockAfterExecuteContext): 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 867c4a97e99..6a23b96fbb5 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/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-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_command.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts index b93eca346e0..73e6c258f13 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts @@ -1,11 +1,8 @@ /* eslint-disable class-methods-use-this */ import { - BaseCommand, - CommandVerifyContext, - CommandExecuteContext, - VerificationResult, - VerifyStatus, + Modules, + StateMachine, codec, } from 'lisk-sdk'; import { CROSS_CHAIN_COMMAND_NAME_REACT } from '../constants'; @@ -17,7 +14,7 @@ import { } from '../schemas'; import { InteroperabilityMethod } from '../types'; -export class ReactCrossChainCommand extends BaseCommand { +export class ReactCrossChainCommand extends Modules.BaseCommand { private _interoperabilityMethod!: InteroperabilityMethod; public schema = CCReactCommandParamsSchema; @@ -31,8 +28,8 @@ export class ReactCrossChainCommand 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('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'); @@ -45,16 +42,16 @@ export class ReactCrossChainCommand 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 81447ef10e8..8de7eec438e 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 { ReactCrossChainCommand } from './commands/react_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 ReactCrossChainCommand(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 279823de2fe..677827fa381 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,17 +1,14 @@ import { - MethodContext, - ImmutableMethodContext, - CCMsg, - ChannelData, - OwnChainAccount, + StateMachine, + Modules, } from 'lisk-sdk'; export type TokenID = Buffer; export interface InteroperabilityMethod { - getOwnChainAccount(methodContext: ImmutableMethodContext): Promise; + getOwnChainAccount(methodContext: StateMachine.ImmutableMethodContext): Promise; send( - methodContext: MethodContext, + methodContext: StateMachine.MethodContext, feeAddress: Buffer, module: string, crossChainCommand: string, @@ -20,9 +17,9 @@ 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; } From d05ed7bbcabc75551ec7f70b2f38b13786cff9fe Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 1 Dec 2023 15:23:32 +0100 Subject: [PATCH 12/53] Update example imports --- examples/interop/pos-mainchain-fast/src/app/app.ts | 4 ++-- .../src/app/modules/testNft/commands/destroy_nft.ts | 10 +++++----- .../src/app/modules/testNft/commands/mint_nft.ts | 10 +++++----- .../src/app/modules/testNft/endpoint.ts | 4 ++-- .../src/app/modules/testNft/method.ts | 4 ++-- .../src/app/modules/testNft/module.ts | 12 ++++++------ 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/examples/interop/pos-mainchain-fast/src/app/app.ts b/examples/interop/pos-mainchain-fast/src/app/app.ts index 3250d66e460..4a1bcd7a274 100644 --- a/examples/interop/pos-mainchain-fast/src/app/app.ts +++ b/examples/interop/pos-mainchain-fast/src/app/app.ts @@ -1,4 +1,4 @@ -import { Application, PartialApplicationConfig, NFTModule } from 'lisk-sdk'; +import { Application, PartialApplicationConfig, Modules } from 'lisk-sdk'; import { TestNftModule } from './modules/testNft/module'; import { registerModules } from './modules'; import { registerPlugins } from './plugins'; @@ -6,7 +6,7 @@ import { registerPlugins } from './plugins'; export const getApplication = (config: 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, }); From 9f90fb9e146684d203b3c962fccc93234312620a Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 1 Dec 2023 15:41:02 +0100 Subject: [PATCH 13/53] Update example imports --- examples/poa-sidechain/src/app/modules.ts | 29 ++++++------------- examples/pos-mainchain/src/app/app.ts | 4 +-- .../modules/testNft/commands/destroy_nft.ts | 10 +++---- .../app/modules/testNft/commands/mint_nft.ts | 10 +++---- .../src/app/modules/testNft/endpoint.ts | 4 +-- .../src/app/modules/testNft/method.ts | 4 +-- .../src/app/modules/testNft/module.ts | 12 ++++---- 7 files changed, 31 insertions(+), 42 deletions(-) diff --git a/examples/poa-sidechain/src/app/modules.ts b/examples/poa-sidechain/src/app/modules.ts index bc8306a7c45..02e56865b1d 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, PartialApplicationConfig } from 'lisk-sdk'; export const registerModules = (config: 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/pos-mainchain/src/app/app.ts b/examples/pos-mainchain/src/app/app.ts index 6a99bf61049..d6e556bdc8d 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, PartialApplicationConfig, Modules } from 'lisk-sdk'; import { TestNftModule } from './modules/testNft/module'; export const getApplication = (config: 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, }); From 6c6e355af5a0b33884e48520d913101b23d4e94f Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 4 Dec 2023 11:54:59 +0100 Subject: [PATCH 14/53] Fix format --- .../hello/commands/create_hello_command.ts | 9 ++--- .../src/app/modules/hello/module.ts | 37 ++++++++++++------- .../modules/react/commands/react_command.ts | 10 ++--- .../src/app/modules/react/types.ts | 30 ++++++++++----- 4 files changed, 53 insertions(+), 33 deletions(-) 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 d242492f0ce..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,9 +1,6 @@ /* eslint-disable class-methods-use-this */ -import { - Modules, - StateMachine, -} 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'; @@ -29,7 +26,9 @@ export class CreateHelloCommand extends Modules.BaseCommand { } // eslint-disable-next-line @typescript-eslint/require-await - public async verify(context: StateMachine.CommandVerifyContext): Promise { + 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)); 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 44a7d7b0292..e8d2826c280 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,11 +1,6 @@ /* eslint-disable class-methods-use-this */ -import { - validator, - StateMachine, - Modules, - utils, -} from 'lisk-sdk'; +import { validator, StateMachine, Modules, utils } from 'lisk-sdk'; import { CreateHelloCommand } from './commands/create_hello_command'; import { ReactCCCommand } from './cc_commands/react_command'; import { HelloEndpoint } from './endpoint'; @@ -83,7 +78,11 @@ export class HelloModule extends Modules.Interoperability.BaseInteroperableModul // 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: ModuleConfig = utils.objects.mergeDeep({}, defaultConfig, moduleConfig) as ModuleConfig; + const config: ModuleConfig = utils.objects.mergeDeep( + {}, + defaultConfig, + moduleConfig, + ) as ModuleConfig; // Validate the provided config with the config schema validator.validator.validate(configSchema, config); // Call the command init() method with config values as parameters @@ -103,7 +102,9 @@ export class HelloModule extends Modules.Interoperability.BaseInteroperableModul // Lifecycle hooks // eslint-disable-next-line @typescript-eslint/require-await - public async verifyTransaction(_context: StateMachine.TransactionVerifyContext): Promise { + public async verifyTransaction( + _context: StateMachine.TransactionVerifyContext, + ): Promise { // verify transaction will be called multiple times in the transaction pool const result = { status: 1, @@ -112,20 +113,30 @@ export class HelloModule extends Modules.Interoperability.BaseInteroperableModul } // eslint-disable-next-line @typescript-eslint/no-empty-function - public async beforeCommandExecute(_context: StateMachine.TransactionExecuteContext): Promise {} + public async beforeCommandExecute( + _context: StateMachine.TransactionExecuteContext, + ): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async afterCommandExecute(_context: StateMachine.TransactionExecuteContext): Promise {} + public async afterCommandExecute( + _context: StateMachine.TransactionExecuteContext, + ): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function public async initGenesisState(_context: StateMachine.GenesisBlockExecuteContext): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async finalizeGenesisState(_context: StateMachine.GenesisBlockExecuteContext): Promise {} + public async finalizeGenesisState( + _context: StateMachine.GenesisBlockExecuteContext, + ): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async beforeTransactionsExecute(_context: StateMachine.BlockExecuteContext): Promise {} + public async beforeTransactionsExecute( + _context: StateMachine.BlockExecuteContext, + ): Promise {} // eslint-disable-next-line @typescript-eslint/no-empty-function - public async afterTransactionsExecute(_context: StateMachine.BlockAfterExecuteContext): Promise {} + public async afterTransactionsExecute( + _context: StateMachine.BlockAfterExecuteContext, + ): Promise {} } diff --git a/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts index 73e6c258f13..983568f96be 100644 --- a/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts +++ b/examples/interop/pos-sidechain-example-two/src/app/modules/react/commands/react_command.ts @@ -1,10 +1,6 @@ /* eslint-disable class-methods-use-this */ -import { - Modules, - StateMachine, - codec, -} from 'lisk-sdk'; +import { Modules, StateMachine, codec } from 'lisk-sdk'; import { CROSS_CHAIN_COMMAND_NAME_REACT } from '../constants'; import { CCReactCommandParamsSchema, @@ -51,7 +47,9 @@ export class ReactCrossChainCommand extends Modules.BaseCommand { }; } - public async execute(context: StateMachine.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/types.ts b/examples/interop/pos-sidechain-example-two/src/app/modules/react/types.ts index 677827fa381..5c689d0d9ac 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,12 +1,11 @@ -import { - StateMachine, - Modules, -} from 'lisk-sdk'; +import { StateMachine, Modules } from 'lisk-sdk'; export type TokenID = Buffer; export interface InteroperabilityMethod { - getOwnChainAccount(methodContext: StateMachine.ImmutableMethodContext): Promise; + getOwnChainAccount( + methodContext: StateMachine.ImmutableMethodContext, + ): Promise; send( methodContext: StateMachine.MethodContext, feeAddress: Buffer, @@ -17,9 +16,22 @@ export interface InteroperabilityMethod { parameters: Buffer, timestamp?: number, ): Promise; - error(methodContext: StateMachine.MethodContext, ccm: Modules.Interoperability.CCMsg, code: number): 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; + getChannel( + methodContext: StateMachine.MethodContext, + chainID: Buffer, + ): Promise; + getMessageFeeTokenID( + methodContext: StateMachine.ImmutableMethodContext, + chainID: Buffer, + ): Promise; + getMessageFeeTokenIDFromCCM( + methodContext: StateMachine.ImmutableMethodContext, + ccm: Modules.Interoperability.CCMsg, + ): Promise; } From a5a1832c9fc1a1586449ba84ab24e265cd0f6213 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 4 Dec 2023 12:40:49 +0100 Subject: [PATCH 15/53] Fix lint error --- .../pos-sidechain-example-one/src/app/modules/hello/module.ts | 2 +- framework/src/modules/auth/commands/register_multisignature.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 e8d2826c280..de19103bcd1 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 @@ -41,7 +41,7 @@ export class HelloModule extends Modules.Interoperability.BaseInteroperableModul this.events.register(NewHelloEvent, new NewHelloEvent(this.name)); } - public metadata(): Modules.ModuleMetadata { + public metadata() { return { endpoints: [ { 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, From 9a32aff2aee2d1c665b0943d759c379d241b4018 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 4 Dec 2023 13:23:43 +0100 Subject: [PATCH 16/53] Update test imports --- .../mainchain/endpoint.spec.ts | 25 +++++------ .../poa/commands/update_authority.spec.ts | 41 ++++++++----------- 2 files changed, 28 insertions(+), 38 deletions(-) diff --git a/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts index 949601335e3..0788b79be82 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, ModuleEndpointContext } 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,7 +150,7 @@ describe('MainchainInteroperabilityEndpoint', () => { }); describe('isChainIDAvailable', () => { - const interopMod = new MainchainInteroperabilityModule(); + const interopMod = new Modules.Interoperability.MainchainInteroperabilityModule(); const chainAccountStore = { has: jest.fn(), }; 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, From 084a2f11be54f08a339515a9abef33f51a54a2a4 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 4 Dec 2023 15:30:08 +0100 Subject: [PATCH 17/53] Fix eslint --- .../src/app/modules/hello/module.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 de19103bcd1..8802046a16d 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 @@ -112,31 +112,31 @@ export class HelloModule extends Modules.Interoperability.BaseInteroperableModul return result; } - // eslint-disable-next-line @typescript-eslint/no-empty-function 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: 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: StateMachine.GenesisBlockExecuteContext): Promise {} - // eslint-disable-next-line @typescript-eslint/no-empty-function 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: 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: StateMachine.BlockAfterExecuteContext, + // eslint-disable-next-line @typescript-eslint/no-empty-function ): Promise {} } From 226822382859b4aee0c375188bfdc13d2ffb0c56 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 5 Dec 2023 12:08:00 +0100 Subject: [PATCH 18/53] Update imports of unit tests --- .../modules/auth/stores/auth_account.spec.ts | 4 +- .../modules/dynamic_reward/module.spec.ts | 12 ++---- .../test/unit/modules/fee/cc_method.spec.ts | 4 +- .../test/unit/modules/fee/endpoint.spec.ts | 4 +- .../test/unit/modules/fee/method.spec.ts | 8 ++-- .../channel_terminated.spec.ts | 6 +-- .../base_cc_commands/registration.spec.ts | 4 +- .../base_cross_chain_update_command.spec.ts | 24 +++++------- .../base_interoperability_module.spec.ts | 35 ++++++++--------- .../base_state_recovery.spec.ts | 12 ++---- .../modules/interoperability/endpoint.spec.ts | 4 +- .../interoperability/internal_method.spec.ts | 25 +++++------- .../interoperability/interopFixtures.ts | 20 +++++----- .../initialize_message_recovery.spec.ts | 35 ++++++++--------- .../commands/recover_message.spec.ts | 12 ++---- .../commands/register_sidechain.spec.ts | 8 ++-- ...ubmit_mainchain_cross_chain_update.spec.ts | 39 +++++++------------ .../terminate_sidechain_for_liveness.spec.ts | 6 +-- .../mainchain/internal_method.spec.ts | 4 +- .../interoperability/mainchain/method.spec.ts | 11 ++---- .../interoperability/mainchain/module.spec.ts | 34 +++++++--------- .../modules/interoperability/method.spec.ts | 8 ++-- .../cc_commands/sidechain_terminated.spec.ts | 4 +- .../initialize_state_recovery.spec.ts | 6 +-- .../commands/register_mainchain.spec.ts | 4 +- ...ubmit_sidechain_cross_chain_update.spec.ts | 20 ++++------ .../sidechain/internal_method.spec.ts | 4 +- .../interoperability/sidechain/method.spec.ts | 14 +++---- .../stores/chain_account.spec.ts | 4 +- .../modules/interoperability/utils.spec.ts | 8 ++-- 30 files changed, 164 insertions(+), 219 deletions(-) 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/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 51d49194290..4b9f1360e18 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'; @@ -77,13 +71,13 @@ import { EVENT_TOPIC_TRANSACTION_EXECUTION } 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', () => { - 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); @@ -211,7 +205,7 @@ describe('BaseCrossChainUpdateCommand', () => { let internalMethod: MainchainInteroperabilityInternalMethod; beforeEach(() => { - const interopModule = new MainchainInteroperabilityModule(); + const interopModule = new Modules.Interoperability.MainchainInteroperabilityModule(); ccMethods = new Map(); ccMethods.set( 'token', @@ -269,7 +263,7 @@ describe('BaseCrossChainUpdateCommand', () => { describe('verifyCommon', () => { let stateStore: PrefixedStateReadWriter; - let verifyContext: CommandVerifyContext; + let verifyContext: StateMachine.CommandVerifyContext; const ownChainAccount: OwnChainAccount = { chainID: EMPTY_BUFFER, @@ -277,7 +271,7 @@ describe('BaseCrossChainUpdateCommand', () => { nonce: BigInt(1), }; - const chainAccount: ChainAccount = { + const chainAccount: Modules.Interoperability.ChainAccount = { status: ChainStatus.REGISTERED, name: 'chain123', lastCertificate: { @@ -530,7 +524,7 @@ describe('BaseCrossChainUpdateCommand', () => { }); describe('verifyCertificateSignatureAndPartnerChainOutboxRoot', () => { - let executeContext: CommandExecuteContext; + let executeContext: StateMachine.CommandExecuteContext; let stateStore: PrefixedStateReadWriter; beforeEach(async () => { @@ -635,7 +629,7 @@ describe('BaseCrossChainUpdateCommand', () => { // otherwise, they can fail due to some other check // also, we can simplify test cases by giving only one CCM to params.inboxUpdate.crossChainMessages array describe('beforeCrossChainMessagesExecution', () => { - let executeContext: CommandExecuteContext; + let executeContext: StateMachine.CommandExecuteContext; let stateStore: PrefixedStateReadWriter; beforeEach(async () => { @@ -1013,7 +1007,7 @@ describe('BaseCrossChainUpdateCommand', () => { }); describe('afterCrossChainMessagesExecute', () => { - let executeContext: CommandExecuteContext; + let executeContext: StateMachine.CommandExecuteContext; let chainValidatorsStore: ChainValidatorsStore; beforeEach(() => { 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..e30d4515084 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 { ModuleEndpointContext, 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(), diff --git a/framework/test/unit/modules/interoperability/internal_method.spec.ts b/framework/test/unit/modules/interoperability/internal_method.spec.ts index 739c6b3060a..78ab6e66e7e 100644 --- a/framework/test/unit/modules/interoperability/internal_method.spec.ts +++ b/framework/test/unit/modules/interoperability/internal_method.spec.ts @@ -33,14 +33,7 @@ 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, -} 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'; @@ -78,7 +71,7 @@ import { import { InvalidSMTVerificationEvent } from '../../../../src/modules/interoperability/events/invalid_smt_verification'; 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', @@ -177,7 +170,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 = { @@ -1160,7 +1153,7 @@ describe('Base interoperability internal method', () => { }); describe('verifyCertificate', () => { - const txParams: CrossChainUpdateTransactionParams = { + const txParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { certificate: Buffer.alloc(0), activeValidatorsUpdate: { blsKeysUpdate: [], @@ -1312,7 +1305,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), @@ -1377,7 +1370,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: [], @@ -1488,7 +1481,7 @@ describe('Base interoperability internal method', () => { const encodedDefaultCertificate = codec.encode(certificateSchema, { ...certificate, }); - // const txParams: CrossChainUpdateTransactionParams = { + // const txParams: Modules.Interoperability.CrossChainUpdateTransactionParams = { // certificate: encodedDefaultCertificate, // activeValidatorsUpdate: { // blsKeysUpdate: [], @@ -1518,7 +1511,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), @@ -1541,7 +1534,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 088fd60bf51..c89271b0a1c 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 } 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 { @@ -61,7 +57,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) => @@ -133,7 +129,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), @@ -475,7 +471,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 84c3aec1b5e..646888f0d49 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']).toHaveBeenCalled(); @@ -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( @@ -667,12 +658,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', @@ -689,7 +680,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/internal_method.spec.ts b/framework/test/unit/modules/interoperability/mainchain/internal_method.spec.ts index 0ac861e9749..b7d5aa95fec 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 44fecc3766c..5e9a0c3df10 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']).toHaveBeenCalled(); @@ -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/internal_method.spec.ts b/framework/test/unit/modules/interoperability/sidechain/internal_method.spec.ts index 91fc93ff2ec..b1ecc397e32 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/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); }); }); From a295ad06fb96d5d0eb1eefc9fcc000efc39dd37a Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 5 Dec 2023 13:53:33 +0100 Subject: [PATCH 19/53] Update imports of unit tests --- .../test/unit/modules/base_store.spec.ts | 4 ++-- .../nft/cc_comands/cc_transfer.spec.ts | 8 +++---- .../modules/nft/commands/transfer.spec.ts | 14 +++++------ .../nft/commands/transfer_cross_chain.spec.ts | 4 ++-- .../test/unit/modules/nft/stores/nft.spec.ts | 4 ++-- .../modules/nft/stores/supported_nfts.spec.ts | 6 ++--- .../poa/commands/register_authority.spec.ts | 16 ++++--------- .../poa/commands/update_generator_key.spec.ts | 16 ++++--------- .../test/unit/modules/poa/endpoint.spec.ts | 4 ++-- .../pos/commands/change_commission.spec.ts | 4 ++-- .../pos/commands/register_validator.spec.ts | 4 ++-- .../pos/commands/report_misbehavior.spec.ts | 23 +++++++++++++------ .../unit/modules/pos/commands/stake.spec.ts | 23 +++++++++++++------ .../unit/modules/pos/commands/unlock.spec.ts | 10 ++++---- .../test/unit/modules/pos/endpoint.spec.ts | 4 ++-- .../unit/modules/pos/internal_method.spec.ts | 22 +++++++++++++----- .../token/cc_commands/cc_transfer.spec.ts | 14 +++++++---- .../test/unit/modules/token/cc_method.spec.ts | 4 ++-- .../modules/token/commands/transfer.spec.ts | 8 +++---- .../commands/transfer_cross_chain.spec.ts | 16 ++++--------- .../test/unit/modules/token/endpoint.spec.ts | 10 +++++--- .../token/stores/supported_tokens.spec.ts | 4 ++-- .../unit/modules/token/stores/user.spec.ts | 4 ++-- .../unit/modules/token/token_module.spec.ts | 4 ++-- 24 files changed, 124 insertions(+), 106 deletions(-) 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/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/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_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/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..b25cbd662eb 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, @@ -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 { From e04639f6751839490e0b21057d4888b49dc1df49 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 5 Dec 2023 14:03:18 +0100 Subject: [PATCH 20/53] Update imports of unit tests --- framework/test/unit/application.spec.ts | 39 +++++------- .../test/unit/state_machine/custom_modules.ts | 63 ++++++++----------- framework/test/utils/mocks/transaction.ts | 4 +- 3 files changed, 44 insertions(+), 62 deletions(-) diff --git a/framework/test/unit/application.spec.ts b/framework/test/unit/application.spec.ts index 1149a1e70f8..a972ef355e6 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, BasePlugin } from '../../src'; import { Application } from '../../src/application'; import { Bus } from '../../src/controller/bus'; import { WSServer } from '../../src/controller/ws/ws_server'; @@ -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/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/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), From 7050d79df3d1b787a4980d1ca2c1d21425625482 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 5 Dec 2023 14:22:43 +0100 Subject: [PATCH 21/53] Update imports of unit tests --- framework/test/unit/abi_handler/abi_handler.spec.ts | 10 +++++----- framework/test/unit/engine/endpoint/txpool.spec.ts | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) 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/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, }); }); From 4061b9d0967b6ce89cb0439b29d440678b4913e9 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 5 Dec 2023 14:27:46 +0100 Subject: [PATCH 22/53] Update imports of unit tests --- .../interoperability/sidechain/module.spec.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) 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(', ')}.`, ); From 34041f475f5ad00ed5d87666abb609e60ecfe313 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 5 Dec 2023 14:45:23 +0100 Subject: [PATCH 23/53] Update imports of unit tests --- framework/test/unit/modules/random/endpoint.spec.ts | 4 ++-- framework/test/unit/modules/token/endpoint.spec.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/test/unit/modules/random/endpoint.spec.ts b/framework/test/unit/modules/random/endpoint.spec.ts index 5a61c63f91e..a1065abf89c 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 { ModuleEndpointContext, Modules } from '../../../../src'; import { RandomEndpoint } from '../../../../src/modules/random/endpoint'; import { HashOnionStore } from '../../../../src/modules/random/stores/hash_onion'; import { @@ -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/token/endpoint.spec.ts b/framework/test/unit/modules/token/endpoint.spec.ts index b25cbd662eb..3dc5d293574 100644 --- a/framework/test/unit/modules/token/endpoint.spec.ts +++ b/framework/test/unit/modules/token/endpoint.spec.ts @@ -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])]); From 220e1e3deb1e376ff8bb9c694835d90cc525d012 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 11:26:48 +0100 Subject: [PATCH 24/53] Fix logger export --- framework/src/logger/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/logger/index.ts b/framework/src/logger/index.ts index 6acf3f0acdb..697ec2fa359 100644 --- a/framework/src/logger/index.ts +++ b/framework/src/logger/index.ts @@ -12,4 +12,4 @@ * Removal or modification of this copyright notice is prohibited. */ -export * from './logger'; +export { createLogger, Logger } from './logger'; From fa3ff09054f91a24c0817a9ab7fd2943c251bf7d Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 11:30:53 +0100 Subject: [PATCH 25/53] Update imports in integration tests --- framework/test/integration/node/genesis_block.spec.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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, From 89d053844705863a35af8d55426ab8eb6a155712 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 12:18:10 +0100 Subject: [PATCH 26/53] Fix errors --- .../src/chain_connector_plugin.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) 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 64faf176656..6b257f9bbd0 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 @@ -177,9 +177,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; @@ -840,7 +844,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'); } @@ -866,7 +872,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: [], }; From 39d1d32303b39e6fa3f311fb017b278b755e5ee5 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 12:50:18 +0100 Subject: [PATCH 27/53] Fix error --- .../commands/submit_mainchain_cross_chain_update.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4867f1be8b0..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 @@ -498,7 +498,7 @@ describe('SubmitMainchainCrossChainUpdateCommand', () => { }, }, }), - ).resolves.toEqual({ status: VerifyStatus.OK }); + ).resolves.toEqual({ status: StateMachine.VerifyStatus.OK }); }); }); From e6eaff6a00fc7c184d24f6a268e954922fb0a0e1 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 13:57:12 +0100 Subject: [PATCH 28/53] Update links --- framework/src/modules/interoperability/index.ts | 2 +- framework/src/modules/nft/method.ts | 4 ++-- framework/src/modules/nft/module.ts | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/framework/src/modules/interoperability/index.ts b/framework/src/modules/interoperability/index.ts index 11b7012a830..a5d1275851f 100644 --- a/framework/src/modules/interoperability/index.ts +++ b/framework/src/modules/interoperability/index.ts @@ -17,7 +17,7 @@ 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'; diff --git a/framework/src/modules/nft/method.ts b/framework/src/modules/nft/method.ts index d15247e12fc..6303286958a 100644 --- a/framework/src/modules/nft/method.ts +++ b/framework/src/modules/nft/method.ts @@ -64,7 +64,7 @@ export class NFTMethod extends BaseMethod { * Adds dependencies from other module methods. * * @param internalMethod - * @param feeMethod {@link FeeMethod} + * @param feeMethod {@link Modules.Fee.FeeMethod} */ public addDependencies(internalMethod: InternalMethod, feeMethod: FeeMethod) { this._internalMethod = internalMethod; @@ -929,7 +929,7 @@ export class NFTMethod extends BaseMethod { /** * This function recovers an NFT escrowed to a terminated chain. - * It should only be called by the {@link BaseInteroperabilityModule | Interoperability module} to trigger the recovery of NFTs escrowed to terminated chains. + * 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 diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 14ce14d43f8..395679f8592 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -89,10 +89,10 @@ import { * 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 validateFormat} failure during the cross-chain NFT transfer. + * 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 getNewAttributes} function. + * 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. * * @see [LIP 0052 - Introduce NFT module](https://github.com/LiskHQ/lips/blob/main/proposals/lip-0052.md) @@ -165,8 +165,8 @@ export class NFTModule extends BaseInteroperableModule { * 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 FeeMethod} - * @param tokenMethod {@link TokenMethod} + * @param feeMethod {@link Modules.Fee.FeeMethod} + * @param tokenMethod {@link Modules.Token.TokenMethod} */ public addDependencies( interoperabilityMethod: InteroperabilityMethod, From 251c9210786e0e3b2c607efd0576d9c2fa749af3 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 14:44:55 +0100 Subject: [PATCH 29/53] Add typedocs for nft endpoints --- framework/src/modules/nft/endpoint.ts | 96 +++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/framework/src/modules/nft/endpoint.ts b/framework/src/modules/nft/endpoint.ts index 01cea421482..bacc9b98639 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-identifier| 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 '{ "id":"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 '{ "id":"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 wheter a specific NFT is supported by the network. + * + * @example + * ```sh + * lisk-core endpoint:invoke nft_isNFTSupported '{ "id":"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[] }> { From 3d08f48f54dee5ca78546fbea82e7877969e9a5e Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 14:54:45 +0100 Subject: [PATCH 30/53] Add typedocs for nft endpoints --- framework/src/modules/nft/endpoint.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/modules/nft/endpoint.ts b/framework/src/modules/nft/endpoint.ts index bacc9b98639..bd01ac0c5d5 100644 --- a/framework/src/modules/nft/endpoint.ts +++ b/framework/src/modules/nft/endpoint.ts @@ -130,7 +130,7 @@ export class NFTEndpoint extends BaseEndpoint { * * @param context * - * @returns The NFT with the specified {@link NFTModule#$nft-identifier| NFT ID}. + * @returns The NFT with the specified {@link NFTModule | NFT ID}. */ public async getNFT(context: ModuleEndpointContext): Promise> { const { params } = context; From b31234a2a2a0450134eb10c6a13553745b4a2a85 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 15:18:33 +0100 Subject: [PATCH 31/53] Add typedocs for commands --- .../modules/nft/cc_commands/cc_transfer.ts | 3 +++ .../src/modules/nft/commands/transfer.ts | 2 +- .../nft/commands/transfer_cross_chain.ts | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) 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 7a909c58f5d..dcb3ec4a1b9 100644 --- a/framework/src/modules/nft/commands/transfer.ts +++ b/framework/src/modules/nft/commands/transfer.ts @@ -38,7 +38,7 @@ export interface TransferParams { * * @example * ```sh - * ./bin/run transaction:create nft transfer 10000000 --params='{"nftID":"01000000000000010000000000000001","recipientAddress":"lskycz7hvr8yfu74bcwxy2n4mopfmjancgdvxq8xz","data":"Congratulations on completing the course!"}' + * lisk-core transaction:create nft transfer 10000000 --params='{"nftID":"01000000000000010000000000000001","recipientAddress":"lskycz7hvr8yfu74bcwxy2n4mopfmjancgdvxq8xz","data":"Congratulations on completing the course!"}' * ``` */ export class TransferCommand extends BaseCommand { 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; From 36473766e3122daa8725d19d8ee05a265cc70cdd Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 15:28:03 +0100 Subject: [PATCH 32/53] Fix snippets --- framework/src/modules/nft/endpoint.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/modules/nft/endpoint.ts b/framework/src/modules/nft/endpoint.ts index bd01ac0c5d5..9ef373e19d7 100644 --- a/framework/src/modules/nft/endpoint.ts +++ b/framework/src/modules/nft/endpoint.ts @@ -223,7 +223,7 @@ export class NFTEndpoint extends BaseEndpoint { * * @example * ```sh - * lisk-core endpoint:invoke nft_isCollectionIDSupported '{ "id":"00000001" }' --pretty + * lisk-core endpoint:invoke nft_isCollectionIDSupported '{ "chainID":"04000001","collectionID":"00000001" }' --pretty * ``` * * @param context @@ -272,7 +272,7 @@ export class NFTEndpoint extends BaseEndpoint { * * @example * ```sh - * lisk-core endpoint:invoke nft_getEscrowedNFTIDs '{ "id":"04000001" }' --pretty + * lisk-core endpoint:invoke nft_getEscrowedNFTIDs '{ "chainID":"04000001" }' --pretty * ``` * * @param context @@ -307,7 +307,7 @@ export class NFTEndpoint extends BaseEndpoint { * * @example * ```sh - * lisk-core endpoint:invoke nft_isNFTSupported '{ "id":"04000000000000010000000000000001" }' --pretty + * lisk-core endpoint:invoke nft_isNFTSupported '{ "nftID":"04000000000000010000000000000001" }' --pretty * ``` * * @param context From cdd15de35f8a9066af5f70fadea7ae99608e9456 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 7 Dec 2023 15:40:09 +0100 Subject: [PATCH 33/53] Add section about cc nft transfers --- framework/src/modules/nft/endpoint.ts | 2 +- framework/src/modules/nft/module.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/framework/src/modules/nft/endpoint.ts b/framework/src/modules/nft/endpoint.ts index 9ef373e19d7..e661fbf9fc7 100644 --- a/framework/src/modules/nft/endpoint.ts +++ b/framework/src/modules/nft/endpoint.ts @@ -130,7 +130,7 @@ export class NFTEndpoint extends BaseEndpoint { * * @param context * - * @returns The NFT with the specified {@link NFTModule | NFT ID}. + * @returns The NFT with the specified {@link NFTModule | "NFT ID"}. */ public async getNFT(context: ModuleEndpointContext): Promise> { const { params } = context; diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 395679f8592..1c23f41da6d 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -95,6 +95,12 @@ import { * 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 { From 4cad9110cf91fc013ae94513dfe73002925349b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mona=20B=C3=A4renf=C3=A4nger?= Date: Fri, 8 Dec 2023 11:14:28 +0100 Subject: [PATCH 34/53] Apply suggestions from code review Co-authored-by: Muhammad Talha <13951043+TalhaMaliktz@users.noreply.github.com> --- framework/src/modules/nft/endpoint.ts | 2 +- framework/src/modules/nft/module.ts | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/framework/src/modules/nft/endpoint.ts b/framework/src/modules/nft/endpoint.ts index e661fbf9fc7..6df2ae4b7fe 100644 --- a/framework/src/modules/nft/endpoint.ts +++ b/framework/src/modules/nft/endpoint.ts @@ -303,7 +303,7 @@ export class NFTEndpoint extends BaseEndpoint { } /** - * Checks wheter a specific NFT is supported by the network. + * Checks whether a specific NFT is supported by the network. * * @example * ```sh diff --git a/framework/src/modules/nft/module.ts b/framework/src/modules/nft/module.ts index 1c23f41da6d..4059629e16d 100644 --- a/framework/src/modules/nft/module.ts +++ b/framework/src/modules/nft/module.ts @@ -73,17 +73,17 @@ import { * 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 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 NFT are created, and who is allowed to mint them. + * 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 a 8 bytes long serialization of an index integer, automatically assigned at the NFT creation. + * 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, index being then a unique integer associated with each art piece of this artist. + * 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. @@ -91,14 +91,14 @@ import { * * 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 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. + * 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) From 48292e4f2e3231e0ca7a919dd6af45674d98ca10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mona=20B=C3=A4renf=C3=A4nger?= Date: Fri, 8 Dec 2023 11:15:07 +0100 Subject: [PATCH 35/53] Update framework/src/modules/base_module.ts Co-authored-by: Muhammad Talha <13951043+TalhaMaliktz@users.noreply.github.com> --- framework/src/modules/base_module.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/modules/base_module.ts b/framework/src/modules/base_module.ts index 86dac154b4c..26f57bdf490 100644 --- a/framework/src/modules/base_module.ts +++ b/framework/src/modules/base_module.ts @@ -47,7 +47,7 @@ export interface ModuleMetadata { name: string; // Required parameters for the endpoint. request?: Schema; - // A schema of the expected response to a request to the endpoint. + // 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. */ From 4f40de7bcff5a7a3e2ce2bbad914fddfe56d46b1 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Mon, 18 Dec 2023 11:56:39 +0100 Subject: [PATCH 36/53] Reduce exports --- framework/src/controller/index.ts | 5 ++--- framework/src/engine/bft/index.ts | 2 +- framework/src/engine/endpoint/index.ts | 19 ------------------- framework/src/engine/index.ts | 1 - 4 files changed, 3 insertions(+), 24 deletions(-) delete mode 100644 framework/src/engine/endpoint/index.ts diff --git a/framework/src/controller/index.ts b/framework/src/controller/index.ts index bc5f23b58f9..0a64a9a6e89 100644 --- a/framework/src/controller/index.ts +++ b/framework/src/controller/index.ts @@ -12,6 +12,5 @@ * Removal or modification of this copyright notice is prohibited. */ -export * from './controller'; -export * from './channels'; -export * from './event'; +export { Controller } from './controller'; +export { InMemoryChannel, IPCChannel } from './channels'; diff --git a/framework/src/engine/bft/index.ts b/framework/src/engine/bft/index.ts index 7cc0a18ca67..de7254ff9da 100644 --- a/framework/src/engine/bft/index.ts +++ b/framework/src/engine/bft/index.ts @@ -15,6 +15,6 @@ export * from './constants'; export { BFTModule } from './module'; export type { BFTMethod } from './method'; -export * from './schemas'; +export { bftParametersSchema, BFTParameters } from './schemas'; export { BFTHeights } from './types'; export { computeValidatorsHash, areDistinctHeadersContradicting } from './utils'; diff --git a/framework/src/engine/endpoint/index.ts b/framework/src/engine/endpoint/index.ts deleted file mode 100644 index 5567d35ba47..00000000000 --- a/framework/src/engine/endpoint/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright © 2021 Lisk Foundation - * - * See the LICENSE file at the top-level directory of this distribution - * for licensing information. - * - * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, - * no part of this software, including this file, may be copied, modified, - * propagated, or distributed except according to the terms contained in the - * LICENSE file. - * - * Removal or modification of this copyright notice is prohibited. - */ - -export * from './chain'; -export * from './consensus'; -export * from './state'; -export * from './system'; -export * from './txpool'; diff --git a/framework/src/engine/index.ts b/framework/src/engine/index.ts index 5ca956d4f6c..81a129809d8 100644 --- a/framework/src/engine/index.ts +++ b/framework/src/engine/index.ts @@ -15,4 +15,3 @@ export * from './engine'; export * from './bft'; export * from './consensus'; -export * from './endpoint'; From 54f8ef56f57e0681178354af0b0889619c880534 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mona=20B=C3=A4renf=C3=A4nger?= Date: Mon, 18 Dec 2023 12:03:04 +0100 Subject: [PATCH 37/53] Update framework/src/engine/consensus/index.ts Co-authored-by: !shan --- framework/src/engine/consensus/index.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/framework/src/engine/consensus/index.ts b/framework/src/engine/consensus/index.ts index fccb8d29ae1..7b9c35804dc 100644 --- a/framework/src/engine/consensus/index.ts +++ b/framework/src/engine/consensus/index.ts @@ -17,10 +17,7 @@ export * from './constants'; export { BFTHeader, ActiveValidator, - PkSigPair, AggregateCommit, - CommitPool, - ValidatorUpdate, } from './types'; export * from './schema'; export { isEmptyConsensusUpdate } from './utils'; From ae01f0eab7c53b1acef93363ed9f65032ab42a88 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 19 Dec 2023 11:30:01 +0100 Subject: [PATCH 38/53] Apply feedback --- framework/src/engine/bft/index.ts | 1 - framework/src/engine/consensus/index.ts | 2 -- framework/src/engine/index.ts | 2 +- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/framework/src/engine/bft/index.ts b/framework/src/engine/bft/index.ts index de7254ff9da..4f328824f19 100644 --- a/framework/src/engine/bft/index.ts +++ b/framework/src/engine/bft/index.ts @@ -12,7 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -export * from './constants'; export { BFTModule } from './module'; export type { BFTMethod } from './method'; export { bftParametersSchema, BFTParameters } from './schemas'; diff --git a/framework/src/engine/consensus/index.ts b/framework/src/engine/consensus/index.ts index fccb8d29ae1..994b85a69ed 100644 --- a/framework/src/engine/consensus/index.ts +++ b/framework/src/engine/consensus/index.ts @@ -13,7 +13,6 @@ */ export { Consensus } from './consensus'; -export * from './constants'; export { BFTHeader, ActiveValidator, @@ -22,7 +21,6 @@ export { CommitPool, ValidatorUpdate, } from './types'; -export * from './schema'; export { isEmptyConsensusUpdate } from './utils'; export { computeUnsignedCertificateFromBlockHeader, diff --git a/framework/src/engine/index.ts b/framework/src/engine/index.ts index 81a129809d8..fb9eb6e70d8 100644 --- a/framework/src/engine/index.ts +++ b/framework/src/engine/index.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -export * from './engine'; +export { Engine } from './engine'; export * from './bft'; export * from './consensus'; From f8329932869360833c2584eeea3b99a6cfa8a5e9 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Tue, 19 Dec 2023 14:27:54 +0100 Subject: [PATCH 39/53] Fix import error --- framework/src/engine/consensus/index.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/framework/src/engine/consensus/index.ts b/framework/src/engine/consensus/index.ts index 6f06262f23b..2c6ca5e9eba 100644 --- a/framework/src/engine/consensus/index.ts +++ b/framework/src/engine/consensus/index.ts @@ -13,11 +13,8 @@ */ export { Consensus } from './consensus'; -export { - BFTHeader, - ActiveValidator, - AggregateCommit, -} from './types'; +export { CONSENSUS_EVENT_BLOCK_DELETE, CONSENSUS_EVENT_BLOCK_NEW } from './constants'; +export { BFTHeader, ActiveValidator, AggregateCommit } from './types'; export { isEmptyConsensusUpdate } from './utils'; export { computeUnsignedCertificateFromBlockHeader, From 2205d42a453e3e25beab5f5f663df2b70e45eac5 Mon Sep 17 00:00:00 2001 From: Ishan Date: Tue, 19 Dec 2023 15:32:50 +0100 Subject: [PATCH 40/53] =?UTF-8?q?=E2=9C=85=20Fix=20unit=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/unit/controller/http/http_server.spec.ts | 6 +++++- framework/test/unit/engine/engine.spec.ts | 11 ++++------- 2 files changed, 9 insertions(+), 8 deletions(-) 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/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'; From c45cf2f0674d2c3e10ed3423345ba28079a23b69 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 16:01:24 +0100 Subject: [PATCH 41/53] Update exports --- framework/src/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/index.ts b/framework/src/index.ts index 64822a4725b..515c1adcd3f 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -26,14 +26,14 @@ export { } from '@liskhq/lisk-chain'; export { Application } from './application'; export { systemDirs } from './system_dirs'; -export * from './plugins'; -export * from './logger'; +export * as Plugins from './plugins'; +export * as Logger from './logger'; export * as Controller from './controller'; export * as testing from './testing'; export * as Modules from './modules'; export * as StateMachine from './state_machine'; export * as Engine from './engine'; -export * from './types'; +export * as Types from './types'; export { applicationConfigSchema } from './schema'; export { TransactionExecutionResult, From 55a70f40ece84b18b247a12f8bc240e67226977a Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 16:39:18 +0100 Subject: [PATCH 42/53] Update imports --- .../bootstrapping/commands/base_ipc_client.ts | 4 +-- .../src/bootstrapping/commands/config/show.ts | 8 +++--- .../commands/genesis-block/create.ts | 4 +-- commander/src/bootstrapping/commands/start.ts | 8 +++--- .../commands/transaction/create.ts | 13 +++++----- .../commands/transaction/sign.ts | 13 +++++----- .../src/chain_connector_plugin.ts | 11 ++++---- .../src/endpoint.ts | 26 ++++++++----------- .../src/plugin/dashboard_plugin.ts | 4 +-- .../src/plugin/endpoint.ts | 23 +++++++--------- .../src/plugin/faucet_plugin.ts | 6 ++--- .../src/endpoint.ts | 18 +++++-------- .../src/forger_plugin.ts | 17 +++--------- .../src/controllers/blocks.ts | 4 +-- .../src/controllers/network.ts | 6 +++-- .../src/controllers/prometheus.ts | 4 +-- .../src/controllers/transactions.ts | 4 +-- .../src/endpoint.ts | 18 +++++++------ .../src/monitor_plugin.ts | 6 ++--- .../src/endpoint.ts | 11 +++----- .../src/report_misbehavior_plugin.ts | 14 +++------- 21 files changed, 94 insertions(+), 128 deletions(-) diff --git a/commander/src/bootstrapping/commands/base_ipc_client.ts b/commander/src/bootstrapping/commands/base_ipc_client.ts index 7e3edffb6b0..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, Modules } from 'lisk-framework'; +import { Types, Modules } from 'lisk-framework'; import { PromiseResolvedType } from '../../types'; import { isApplicationRunning } from '../../utils/application'; import { flagsWithParser } from '../../utils/flags'; @@ -34,7 +34,7 @@ export abstract class BaseIPCClientCommand extends Command { protected baseIPCClientFlags!: BaseIPCClientFlags; protected _client!: PromiseResolvedType> | undefined; - protected _schema!: RegisteredSchema; + protected _schema!: Types.RegisteredSchema; protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; 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 c6af3045d44..4da3a685c65 100644 --- a/commander/src/bootstrapping/commands/transaction/create.ts +++ b/commander/src/bootstrapping/commands/transaction/create.ts @@ -22,8 +22,7 @@ import { validator } from '@liskhq/lisk-validator'; import { Command, Flags as flagParser } from '@oclif/core'; import { Application, - PartialApplicationConfig, - RegisteredSchema, + Types, blockHeaderSchema, blockSchema, transactionSchema, @@ -116,7 +115,7 @@ const getKeysFromFlags = async (flags: CreateFlags) => { const validateAndSignTransaction = ( transaction: Transaction, - schema: RegisteredSchema, + schema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], chainID: string, privateKey: Buffer, @@ -149,7 +148,7 @@ const validateAndSignTransaction = ( const createTransactionOffline = async ( args: Args, flags: CreateFlags, - registeredSchema: RegisteredSchema, + registeredSchema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transaction: Transaction, ) => { @@ -173,7 +172,7 @@ const createTransactionOnline = async ( args: Args, flags: CreateFlags, client: apiClient.APIClient, - registeredSchema: RegisteredSchema, + registeredSchema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transaction: Transaction, ) => { @@ -279,7 +278,7 @@ export abstract class CreateCommand extends Command { }; protected _client!: PromiseResolvedType> | undefined; - protected _schema!: RegisteredSchema; + protected _schema!: Types.RegisteredSchema; protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; @@ -377,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 2ca98663383..04611294d01 100644 --- a/commander/src/bootstrapping/commands/transaction/sign.ts +++ b/commander/src/bootstrapping/commands/transaction/sign.ts @@ -19,8 +19,7 @@ import { blockHeaderSchema, blockSchema, Modules, - PartialApplicationConfig, - RegisteredSchema, + Types, transactionSchema, } from 'lisk-framework'; import * as transactions from '@liskhq/lisk-transactions'; @@ -57,7 +56,7 @@ interface SignFlags { const signTransaction = async ( flags: SignFlags, - registeredSchema: RegisteredSchema, + registeredSchema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, chainID: string | undefined, @@ -105,7 +104,7 @@ const signTransaction = async ( const signTransactionOffline = async ( flags: SignFlags, - registeredSchema: RegisteredSchema, + registeredSchema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ): Promise> => { @@ -132,7 +131,7 @@ const signTransactionOffline = async ( const signTransactionOnline = async ( flags: SignFlags, client: apiClient.APIClient, - registeredSchema: RegisteredSchema, + registeredSchema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ) => { @@ -190,7 +189,7 @@ export abstract class SignCommand extends Command { ]; protected _client: PromiseResolvedType> | undefined; - protected _schema!: RegisteredSchema; + protected _schema!: Types.RegisteredSchema; protected _metadata!: Modules.ModuleMetadataJSON[]; protected _dataPath!: string; @@ -261,5 +260,5 @@ export abstract class SignCommand extends Command { } } - abstract getApplication(config: PartialApplicationConfig): Application; + abstract getApplication(config: Types.PartialApplicationConfig): Application; } 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 6b257f9bbd0..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 @@ -14,14 +14,13 @@ import { Engine, - BasePlugin, - PluginInitContext, + Plugins, apiClient, db as liskDB, codec, chain, Modules, - JSONObject, + Types, Schema, Transaction, cryptography, @@ -81,7 +80,7 @@ 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; @@ -106,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) { @@ -539,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 }, ); 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 44a14abc8e7..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,13 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - BasePluginEndpoint, - PluginEndpointContext, - chain, - BlockHeaderJSON, - validator as liskValidator, -} from 'lisk-sdk'; +import { Plugins, Types, chain, BlockHeaderJSON, validator as liskValidator } from 'lisk-sdk'; import { ChainConnectorStore } from './db'; import { AggregateCommitJSON, @@ -35,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; @@ -45,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 chain.BlockHeader(blockHeader).toJSON()); } public async getCrossChainMessages( - _context: PluginEndpointContext, + _context: Types.PluginEndpointContext, ): Promise { const ccmsAndInclusionProofs = await this._chainConnectorStore.getCrossChainMessages(); return ccmsAndInclusionProofs.map(ccmsAndInclusionProof => @@ -72,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.'); @@ -89,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-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-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-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-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); } From 85d8b8d3787a771ae714f04f695d345d743e3397 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 16:49:31 +0100 Subject: [PATCH 43/53] Update import --- commander/src/utils/transaction.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/commander/src/utils/transaction.ts b/commander/src/utils/transaction.ts index 359356c2bbf..37a0dd115dd 100644 --- a/commander/src/utils/transaction.ts +++ b/commander/src/utils/transaction.ts @@ -16,7 +16,7 @@ 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 { Modules, RegisteredSchema } from 'lisk-framework'; +import { Modules, Types } from 'lisk-framework'; import { Schema } from '../types'; import { getDefaultPath } from './path'; @@ -39,7 +39,7 @@ export const getParamsSchema = ( }; export const decodeTransaction = ( - schema: RegisteredSchema, + schema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transactionHexStr: string, ) => { @@ -59,7 +59,7 @@ export const decodeTransaction = ( }; export const encodeTransaction = ( - schema: RegisteredSchema, + schema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, @@ -78,7 +78,7 @@ export const encodeTransaction = ( }; export const encodeTransactionJSON = ( - schema: RegisteredSchema, + schema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, @@ -100,7 +100,7 @@ export const encodeTransactionJSON = ( }; export const transactionToJSON = ( - schema: RegisteredSchema, + schema: Types.RegisteredSchema, metadata: Modules.ModuleMetadataJSON[], transaction: Record, apiClient?: liskApiClient.APIClient, From d5a7a8a97f57a84e226dc0834762447e8489626d Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 17:08:47 +0100 Subject: [PATCH 44/53] Update imports --- .../src/app/modules/hello/hello_module.ts | 57 +++++++++++++++++++ .../unit/modules/hello/hello_module.spec.ts | 27 +++++++++ .../interop/pos-mainchain-fast/src/app/app.ts | 4 +- .../src/commands/genesis-block/create.ts | 4 +- .../pos-mainchain-fast/src/commands/start.ts | 8 +-- .../src/commands/transaction/create.ts | 4 +- .../src/commands/transaction/sign.ts | 4 +- .../pos-sidechain-example-one/src/app/app.ts | 4 +- .../src/commands/genesis-block/create.ts | 4 +- .../src/commands/start.ts | 8 +-- .../src/commands/transaction/create.ts | 4 +- .../src/commands/transaction/sign.ts | 4 +- .../pos-sidechain-example-two/src/app/app.ts | 4 +- .../src/commands/genesis-block/create.ts | 4 +- .../src/commands/start.ts | 8 +-- .../src/commands/transaction/create.ts | 4 +- .../src/commands/transaction/sign.ts | 4 +- examples/poa-sidechain/src/app/app.ts | 4 +- .../src/commands/genesis-block/create.ts | 4 +- examples/poa-sidechain/src/commands/start.ts | 8 +-- .../src/commands/transaction/create.ts | 4 +- .../src/commands/transaction/sign.ts | 4 +- 22 files changed, 132 insertions(+), 48 deletions(-) create mode 100644 examples/dpos-mainchain/src/app/modules/hello/hello_module.ts create mode 100644 examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts diff --git a/examples/dpos-mainchain/src/app/modules/hello/hello_module.ts b/examples/dpos-mainchain/src/app/modules/hello/hello_module.ts new file mode 100644 index 00000000000..7c70bf01fd7 --- /dev/null +++ b/examples/dpos-mainchain/src/app/modules/hello/hello_module.ts @@ -0,0 +1,57 @@ +/* eslint-disable class-methods-use-this */ + +import { + BaseModule, + ModuleInitArgs, + BlockGenerateContext, + BlockVerifyContext, + TransactionVerifyContext, + VerificationResult, + TransactionExecuteContext, + GenesisBlockExecuteContext, + BlockExecuteContext, + BlockAfterExecuteContext, +} from 'lisk-sdk'; +import { HelloModuleEndpoint } from './endpoint'; +import { HelloModuleAPI } from './api'; + +export class HelloModule extends BaseModule { + public endpoint = new HelloModuleEndpoint(); + public api = new HelloModuleAPI(); + public name = 'hello'; + public transactionAssets = []; + public events = [ + // Example below + // 'hello:newBlock', + ]; + public id = 1000; + + // Lifecycle hooks + public async init(_args: ModuleInitArgs): Promise { + // initialize this module when starting a node + } + + public async initBlock(_context: BlockGenerateContext): Promise { + // initialize block generation, add asset + } + + public async verifyAssets(_context: BlockVerifyContext): Promise { + // verify block + } + + // Lifecycle hooks + public async verifyTransaction(_context: TransactionVerifyContext): Promise { + // verify transaction will be called multiple times in the transaction pool + } + + public async beforeCommandExecute(_context: TransactionExecuteContext): Promise {} + + public async afterCommandExecute(_context: TransactionExecuteContext): Promise {} + public async initGenesisState(_context: GenesisBlockExecuteContext): Promise {} + + public async finalizeGenesisState(_context: GenesisBlockExecuteContext): Promise {} + + public async beforeTransactionsExecute(_context: BlockExecuteContext): Promise {} + + public async afterTransactionsExecute(_context: BlockAfterExecuteContext): Promise {} +} diff --git a/examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts b/examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts new file mode 100644 index 00000000000..766ef719d33 --- /dev/null +++ b/examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts @@ -0,0 +1,27 @@ +// import * as modules from '../../../src/app/modules/hello' + +describe('HelloModuleModule', () => { + describe('constructor', () => { + it.todo('should have valid id'); + it.todo('should have valid name'); + }); + + describe('beforeTransactionsExecute', () => { + it.todo('should execute before block execute'); + }); + describe('afterTransactionsExecute', () => { + it.todo('should execute after block execute'); + }); + describe('beforeCommandExecute', () => { + it.todo('should execute before transaction execute'); + }); + describe('afterCommandExecute', () => { + it.todo('should execute after transaction execute'); + }); + describe('beforeTransactionsExecute', () => { + it.todo('should execute after genesis execute'); + }); + describe('afterTransactionsExecute', () => { + it.todo('should execute after genesis execute'); + }); +}); diff --git a/examples/interop/pos-mainchain-fast/src/app/app.ts b/examples/interop/pos-mainchain-fast/src/app/app.ts index 4a1bcd7a274..24342b37d88 100644 --- a/examples/interop/pos-mainchain-fast/src/app/app.ts +++ b/examples/interop/pos-mainchain-fast/src/app/app.ts @@ -1,9 +1,9 @@ -import { Application, PartialApplicationConfig, Modules } 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 Modules.NFT.NFTModule(); 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 2df7c3453bb..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,10 +1,10 @@ -import { Application, PartialApplicationConfig, Modules } 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 Modules.NFT.NFTModule(); 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/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/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; } From 4382237bf985cac988bc24fdd924cdcc764c981a Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 17:19:42 +0100 Subject: [PATCH 45/53] Update imports --- .../src/app/modules/hello/endpoint.ts | 8 ++++---- .../src/app/modules/hello/types.ts | 4 ++-- examples/poa-sidechain/src/app/modules.ts | 4 ++-- examples/pos-mainchain/src/app/app.ts | 4 ++-- .../pos-mainchain/src/commands/genesis-block/create.ts | 4 ++-- examples/pos-mainchain/src/commands/start.ts | 8 ++++---- examples/pos-mainchain/src/commands/transaction/create.ts | 4 ++-- examples/pos-mainchain/src/commands/transaction/sign.ts | 4 ++-- 8 files changed, 20 insertions(+), 20 deletions(-) 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 d52a91c6eb5..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 { Modules, 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 Modules.BaseEndpoint { - public async getHelloCounter(ctx: ModuleEndpointContext): Promise { + 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 Modules.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 Modules.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/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/poa-sidechain/src/app/modules.ts b/examples/poa-sidechain/src/app/modules.ts index 02e56865b1d..8ea8c37d18f 100644 --- a/examples/poa-sidechain/src/app/modules.ts +++ b/examples/poa-sidechain/src/app/modules.ts @@ -1,6 +1,6 @@ -import { Application, Modules, PartialApplicationConfig } 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 Modules.Auth.AuthModule(); diff --git a/examples/pos-mainchain/src/app/app.ts b/examples/pos-mainchain/src/app/app.ts index d6e556bdc8d..dbf6225dca7 100644 --- a/examples/pos-mainchain/src/app/app.ts +++ b/examples/pos-mainchain/src/app/app.ts @@ -1,7 +1,7 @@ -import { Application, PartialApplicationConfig, Modules } 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 Modules.NFT.NFTModule(); const testNftModule = new TestNftModule(); 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; } From 235f6b7be0c392bafa9d42af72393a20e4c9e886 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 17:38:30 +0100 Subject: [PATCH 46/53] Fix unit tests --- .../test/unit/controller/controller.spec.ts | 6 +++--- .../modules/interoperability/endpoint.spec.ts | 4 ++-- .../mainchain/endpoint.spec.ts | 4 ++-- .../sidechain/endpoint.spec.ts | 4 ++-- .../test/unit/modules/nft/endpoint.spec.ts | 6 +++--- .../test/unit/modules/random/endpoint.spec.ts | 4 ++-- .../test/unit/modules/random/module.spec.ts | 20 +++++++++---------- .../unit/modules/validators/endpoint.spec.ts | 4 ++-- framework/test/utils/mocks/endpoint.ts | 4 ++-- 9 files changed, 28 insertions(+), 28 deletions(-) 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/modules/interoperability/endpoint.spec.ts b/framework/test/unit/modules/interoperability/endpoint.spec.ts index e30d4515084..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, Modules } from '../../../../src'; +import { Types, Modules } from '../../../../src'; import { BaseInteroperabilityEndpoint } from '../../../../src/modules/interoperability/base_interoperability_endpoint'; import { BLS_PUBLIC_KEY_LENGTH, @@ -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/mainchain/endpoint.spec.ts b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts index 0788b79be82..46577f7d441 100644 --- a/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { Modules, ModuleEndpointContext } from '../../../../../src'; +import { Modules, Types } from '../../../../../src'; import { CHAIN_REGISTRATION_FEE, MIN_RETURN_FEE_PER_BYTE_BEDDOWS, @@ -157,7 +157,7 @@ describe('MainchainInteroperabilityEndpoint', () => { 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/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/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/random/endpoint.spec.ts b/framework/test/unit/modules/random/endpoint.spec.ts index a1065abf89c..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, Modules } 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 = [ { 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/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/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, From d1a33a08ce7282306a7180b1ef8ee06ba07b4d92 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 17:54:28 +0100 Subject: [PATCH 47/53] Fix unit tests --- framework/test/unit/application.spec.ts | 4 ++-- framework/test/unit/controller/bus.spec.ts | 14 +++++++------- .../engine/legacy/legacy_chain_handler.spec.ts | 4 ++-- framework/test/unit/plugins/base_plugin.spec.ts | 6 +++--- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/framework/test/unit/application.spec.ts b/framework/test/unit/application.spec.ts index a972ef355e6..6ee045c731d 100644 --- a/framework/test/unit/application.spec.ts +++ b/framework/test/unit/application.spec.ts @@ -18,7 +18,7 @@ import * as childProcess from 'child_process'; import * as fs from 'fs-extra'; import * as os from 'os'; import { join } from 'path'; -import { Modules, BasePlugin } 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'; @@ -46,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; } 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/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/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: { From 480ab5cb234801df751a5f7be683b0c48dccdc02 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 18:18:53 +0100 Subject: [PATCH 48/53] Remove example --- .../src/app/modules/hello/hello_module.ts | 57 ------------------- .../unit/modules/hello/hello_module.spec.ts | 27 --------- 2 files changed, 84 deletions(-) delete mode 100644 examples/dpos-mainchain/src/app/modules/hello/hello_module.ts delete mode 100644 examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts diff --git a/examples/dpos-mainchain/src/app/modules/hello/hello_module.ts b/examples/dpos-mainchain/src/app/modules/hello/hello_module.ts deleted file mode 100644 index 7c70bf01fd7..00000000000 --- a/examples/dpos-mainchain/src/app/modules/hello/hello_module.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* eslint-disable class-methods-use-this */ - -import { - BaseModule, - ModuleInitArgs, - BlockGenerateContext, - BlockVerifyContext, - TransactionVerifyContext, - VerificationResult, - TransactionExecuteContext, - GenesisBlockExecuteContext, - BlockExecuteContext, - BlockAfterExecuteContext, -} from 'lisk-sdk'; -import { HelloModuleEndpoint } from './endpoint'; -import { HelloModuleAPI } from './api'; - -export class HelloModule extends BaseModule { - public endpoint = new HelloModuleEndpoint(); - public api = new HelloModuleAPI(); - public name = 'hello'; - public transactionAssets = []; - public events = [ - // Example below - // 'hello:newBlock', - ]; - public id = 1000; - - // Lifecycle hooks - public async init(_args: ModuleInitArgs): Promise { - // initialize this module when starting a node - } - - public async initBlock(_context: BlockGenerateContext): Promise { - // initialize block generation, add asset - } - - public async verifyAssets(_context: BlockVerifyContext): Promise { - // verify block - } - - // Lifecycle hooks - public async verifyTransaction(_context: TransactionVerifyContext): Promise { - // verify transaction will be called multiple times in the transaction pool - } - - public async beforeCommandExecute(_context: TransactionExecuteContext): Promise {} - - public async afterCommandExecute(_context: TransactionExecuteContext): Promise {} - public async initGenesisState(_context: GenesisBlockExecuteContext): Promise {} - - public async finalizeGenesisState(_context: GenesisBlockExecuteContext): Promise {} - - public async beforeTransactionsExecute(_context: BlockExecuteContext): Promise {} - - public async afterTransactionsExecute(_context: BlockAfterExecuteContext): Promise {} -} diff --git a/examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts b/examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts deleted file mode 100644 index 766ef719d33..00000000000 --- a/examples/dpos-mainchain/test/unit/modules/hello/hello_module.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -// import * as modules from '../../../src/app/modules/hello' - -describe('HelloModuleModule', () => { - describe('constructor', () => { - it.todo('should have valid id'); - it.todo('should have valid name'); - }); - - describe('beforeTransactionsExecute', () => { - it.todo('should execute before block execute'); - }); - describe('afterTransactionsExecute', () => { - it.todo('should execute after block execute'); - }); - describe('beforeCommandExecute', () => { - it.todo('should execute before transaction execute'); - }); - describe('afterCommandExecute', () => { - it.todo('should execute after transaction execute'); - }); - describe('beforeTransactionsExecute', () => { - it.todo('should execute after genesis execute'); - }); - describe('afterTransactionsExecute', () => { - it.todo('should execute after genesis execute'); - }); -}); From 7942968edcdb9f9186b54f8801cba1df8bfa3e8d Mon Sep 17 00:00:00 2001 From: Tschakki Date: Thu, 21 Dec 2023 19:01:28 +0100 Subject: [PATCH 49/53] Update plugin tests --- .../test/unit/certificate_generation.spec.ts | 14 ++--- .../test/unit/db.spec.ts | 23 +++---- .../test/unit/endpoint.spec.ts | 13 +--- .../test/unit/inbox_update.spec.ts | 4 +- .../test/unit/plugin.spec.ts | 63 +++++++++---------- .../test/unit/utils.spec.ts | 4 +- .../test/unit/auth.spec.ts | 4 +- .../test/unit/db.spec.ts | 4 +- .../test/unit/subscribe_event.spec.ts | 4 +- 9 files changed, 54 insertions(+), 79 deletions(-) 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-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..4a59dfc296c 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 @@ -14,7 +14,7 @@ import { rmSync } from 'fs-extra'; import * as sdk from 'lisk-sdk'; -import { chain, db as liskDB, blockHeaderSchema, codec, BlockHeader } from 'lisk-sdk'; +import { chain, db as liskDB, blockHeaderSchema, codec, Types } from 'lisk-sdk'; import { getContradictingBlockHeader, saveBlockHeaders } from '../../src/db'; describe('db', () => { @@ -62,7 +62,7 @@ describe('db', () => { }); describe('getContradictingBlockHeader', () => { - const headerClone = BlockHeader.fromBytes(headerBytes1); + const headerClone = Types.BlockHeader.fromBytes(headerBytes1); const header2 = new chain.BlockHeader({ id: Buffer.from('ff', 'hex'), 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, }; From f197e7fb628a6eef89b589ac59a620ae7e170a88 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 22 Dec 2023 11:18:14 +0100 Subject: [PATCH 50/53] Update plugin tests --- .../test/utils/sampleCCM.ts | 11 +++++++---- .../test/utils/sampleCCU.ts | 10 +++------- .../test/functional/faucet.spec.ts | 6 +++--- .../test/functional/fund.spec.ts | 6 +++--- .../test/unit/plugin/auth.spec.ts | 4 ++-- .../test/unit/plugin/faucet_plugin.spec.ts | 4 ++-- .../test/functional/forger_info/event_track.spec.ts | 4 ++-- .../functional/forger_info/forger_info_sync.spec.ts | 4 ++-- .../test/functional/forging_info.spec.ts | 4 ++-- .../test/functional/voters.spec.ts | 4 ++-- .../test/unit/blocks.spec.ts | 4 ++-- .../test/unit/forks.spec.ts | 4 ++-- .../test/unit/network.spec.ts | 4 ++-- .../test/unit/subscribe_event.spec.ts | 4 ++-- .../test/unit/transaction.spec.ts | 4 ++-- .../test/functional/save_new_block.spec.ts | 13 +++---------- .../test/integration/cleanup_job.spec.ts | 6 +++--- .../test/unit/send_pom_transaction.spec.ts | 4 ++-- 18 files changed, 46 insertions(+), 54 deletions(-) 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..afaf48e6864 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.Interoperability.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-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/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/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/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/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, }; From 924d5cd81f83f6cfc28f27a9ea558c4a35ce3365 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 22 Dec 2023 11:33:08 +0100 Subject: [PATCH 51/53] Fix integration test --- framework/test/integration/controller/ipc_channel.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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', () => { From 4d4c57f0ac597b7b3fb484f721ce236415047c47 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 22 Dec 2023 11:58:08 +0100 Subject: [PATCH 52/53] Fix tests --- .../test/bootstrapping/commands/transaction/sign.spec.ts | 6 +++--- .../test/utils/sampleCCM.ts | 2 +- .../test/unit/db.spec.ts | 4 ++-- framework/src/index.ts | 1 + 4 files changed, 7 insertions(+), 6 deletions(-) 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/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCM.ts b/framework-plugins/lisk-framework-chain-connector-plugin/test/utils/sampleCCM.ts index afaf48e6864..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 @@ -21,7 +21,7 @@ export const getSampleCCM = ( return { nonce: BigInt(nonce), module: Modules.Interoperability.MODULE_NAME_INTEROPERABILITY, - crossChainCommand: Modules.Interoperability.CROSS_CHAIN_COMMAND_NAME_TRANSFER, + 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-report-misbehavior-plugin/test/unit/db.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/db.spec.ts index 4a59dfc296c..a0ab3f3c307 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 @@ -14,7 +14,7 @@ import { rmSync } from 'fs-extra'; import * as sdk from 'lisk-sdk'; -import { chain, db as liskDB, blockHeaderSchema, codec, Types } from 'lisk-sdk'; +import { chain, db as liskDB, blockHeaderSchema, codec, BlockHeader } from 'lisk-sdk'; import { getContradictingBlockHeader, saveBlockHeaders } from '../../src/db'; describe('db', () => { @@ -62,7 +62,7 @@ describe('db', () => { }); describe('getContradictingBlockHeader', () => { - const headerClone = Types.BlockHeader.fromBytes(headerBytes1); + const headerClone = BlockHeader.fromBytes(headerBytes1); const header2 = new chain.BlockHeader({ id: Buffer.from('ff', 'hex'), diff --git a/framework/src/index.ts b/framework/src/index.ts index 515c1adcd3f..8ce96b4bd9b 100644 --- a/framework/src/index.ts +++ b/framework/src/index.ts @@ -20,6 +20,7 @@ export { signingBlockHeaderSchema, Block, BlockJSON, + BlockHeader, BlockHeaderJSON, BlockAssetJSON, standardEventDataSchema, From 3e7b2bb9b466e359daabcd93fb8f6aeb211e34c8 Mon Sep 17 00:00:00 2001 From: Tschakki Date: Fri, 22 Dec 2023 12:52:35 +0100 Subject: [PATCH 53/53] Fix plugin test --- .../test/unit/db.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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); });