From 15b81060fa3c20703ff728f8d0d028686400cf7d Mon Sep 17 00:00:00 2001 From: Peter Somogyvari Date: Wed, 27 Sep 2023 18:19:47 -0700 Subject: [PATCH] refactor(core-api,verifier-client): use unknown instead of any type 1. Changes the ISocketApiClient and the Verifier type definitions so that instead of `any` they are heavily relying on `unknown` which helps spotting bugs in the code where type checks should be done at runtime but currently aren't. 2. It also helps with spotting breaking changes in the future because if the test cases stop compiling it means you've done a breaking API change, but they'll always compile if the parameters and the return values are using `any` for their own types. 3. I've updated a big chunk of the test cases to have explicit type casts onto the shapes that are needed for them to compile (without changing any of the runtime behavior). 4. Also made it so that the json2str function of the DriverCommon code file now accepts unknown instead of object type which makes one of the linter warnings go away as well. Signed-off-by: Peter Somogyvari --- .../balance-management.ts | 12 ++-- .../template-trade-management.ts | 2 +- .../transaction-ethereum.ts | 17 ++++-- .../transaction-fabric.ts | 37 ++++++++---- .../transaction-indy.ts | 3 +- .../BalanceManagement.ts | 11 ++-- .../BusinessLogicTcsElectricityTrade.ts | 34 +++++------ .../TransactionEthereum.ts | 23 +++++--- .../cactus-example-tcs-huawei/package.json | 1 + .../main/typescript/verifier/DriverCommon.ts | 2 +- .../ledger-connector/i-socket-api-client.ts | 14 ++--- ...ntegration-with-ethereum-connector.test.ts | 17 +++--- ...-integration-with-quorum-connector.test.ts | 56 ++++++++++--------- .../src/main/typescript/verifier.ts | 9 +-- yarn.lock | 1 + 15 files changed, 143 insertions(+), 96 deletions(-) diff --git a/examples/cactus-example-discounted-asset-trade/balance-management.ts b/examples/cactus-example-discounted-asset-trade/balance-management.ts index ac973c4ae2..9f58d471f4 100644 --- a/examples/cactus-example-discounted-asset-trade/balance-management.ts +++ b/examples/cactus-example-discounted-asset-trade/balance-management.ts @@ -7,12 +7,13 @@ import { LPInfoHolder } from "@hyperledger/cactus-cmd-socketio-server"; import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; +import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api"; import { VerifierFactory, VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const config: any = ConfigUtil.getConfig() as any; +const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; const moduleName = "BalanceManagement"; const logger = getLogger(`${moduleName}`); @@ -30,9 +31,7 @@ export class BalanceManagement { ); } - getBalance( - account: string, - ): Promise<{ + getBalance(account: string): Promise<{ status: number; amount: number; }> { @@ -47,9 +46,10 @@ export class BalanceManagement { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { + const res1 = result as ISendRequestResultV1; const response = { - status: result.status, - amount: parseFloat(result.data), + status: res1.status, + amount: parseFloat(res1.data), }; resolve(response); }) diff --git a/examples/cactus-example-discounted-asset-trade/template-trade-management.ts b/examples/cactus-example-discounted-asset-trade/template-trade-management.ts index d09a809652..87e7a1f8ea 100644 --- a/examples/cactus-example-discounted-asset-trade/template-trade-management.ts +++ b/examples/cactus-example-discounted-asset-trade/template-trade-management.ts @@ -50,7 +50,7 @@ export class TemplateTradeManagement { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { - resolve(result); + resolve(result as VerifierFactory); }) .catch((err) => { logger.error(err); diff --git a/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts b/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts index 060d593855..793b46ff48 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts @@ -10,6 +10,7 @@ import { LPInfoHolder, TransactionSigner, } from "@hyperledger/cactus-cmd-socketio-server"; +import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api"; import { VerifierFactory, @@ -95,8 +96,13 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { - let txnCount: number = result.data.nonce; - let txnCountHex: string = result.data.nonceHex; + const res1 = result as ISendRequestResultV1<{ + readonly nonce: number; + readonly nonceHex: string; + }>; + + let txnCount = res1.data.nonce; + let txnCountHex: string = res1.data.nonceHex; const latestNonce = getLatestNonce(fromAddress); if (latestNonce) { @@ -115,11 +121,14 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { - txnCountHex = result.data.hexStr; + const res2 = result as ISendRequestResultV1<{ + readonly hexStr: string; + }>; + txnCountHex = res2.data.hexStr; logger.debug(`##getNewNonce(E): txnCountHex: ${txnCountHex}`); setLatestNonce(fromAddress, txnCount); - return resolve({ txnCountHex: txnCountHex }); + return resolve({ txnCountHex }); }); } else { setLatestNonce(fromAddress, txnCount); diff --git a/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts b/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts index 662b43b719..2ff96d0699 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts @@ -16,7 +16,10 @@ */ import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; -import { ISocketApiClient } from "@hyperledger/cactus-core-api"; +import { + ISendRequestResultV1, + ISocketApiClient, +} from "@hyperledger/cactus-core-api"; import { Verifier } from "@hyperledger/cactus-verifier-client"; import { signProposal } from "./sign-utils"; @@ -57,9 +60,14 @@ export function makeSignedProposal>( const submitterExists = await wallet.exists(submitter); if (submitterExists) { - const submitterIdentity = await wallet.export(submitter); - certPem = (submitterIdentity as any).certificate; - privateKeyPem = (submitterIdentity as any).privateKey; + const submitterIdentity = (await wallet.export( + submitter, + )) as unknown as { + readonly certificate: string; + readonly privateKey: string; + }; + certPem = submitterIdentity.certificate; + privateKeyPem = submitterIdentity.privateKey; } if (!certPem || !privateKeyPem) { @@ -84,11 +92,15 @@ export function makeSignedProposal>( }; logger.debug("Sending fabric.generateUnsignedProposal"); - const responseUnsignedProp = await verifierFabric.sendSyncRequest( + const responseUnsignedProp = (await verifierFabric.sendSyncRequest( contractUnsignedProp, methodUnsignedProp, argsUnsignedProp, - ); + )) as ISendRequestResultV1<{ + readonly proposalBuffer: Buffer; + readonly proposal: unknown; + readonly txId: string; + }>; const proposalBuffer = Buffer.from( responseUnsignedProp.data.proposalBuffer, ); @@ -113,11 +125,14 @@ export function makeSignedProposal>( }; logger.debug("Sending fabric.sendSignedProposalV2"); - const responseSignedEndorse = await verifierFabric.sendSyncRequest( + const responseSignedEndorse = (await verifierFabric.sendSyncRequest( contractSignedProposal, methodSignedProposal, argsSignedProposal, - ); + )) as ISendRequestResultV1<{ + readonly endorsmentStatus: string; + readonly proposalResponses: unknown; + }>; if (!responseSignedEndorse.data.endorsmentStatus) { throw new Error("Fabric TX endorsment was not OK."); @@ -140,11 +155,13 @@ export function makeSignedProposal>( }; logger.debug("Sending fabric.generateUnsignedTransaction"); - const responseUnsignedTx = await verifierFabric.sendSyncRequest( + const responseUnsignedTx = (await verifierFabric.sendSyncRequest( contractUnsignedTx, methodUnsignedTx, argsUnsignedTx, - ); + )) as ISendRequestResultV1<{ + readonly txProposalBuffer: Buffer; + }>; const commitProposalBuffer = Buffer.from( responseUnsignedTx.data.txProposalBuffer, diff --git a/examples/cactus-example-discounted-asset-trade/transaction-indy.ts b/examples/cactus-example-discounted-asset-trade/transaction-indy.ts index ae82d22178..28d93c9689 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-indy.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-indy.ts @@ -9,6 +9,7 @@ import { LPInfoHolder, ConfigUtil, } from "@hyperledger/cactus-cmd-socketio-server"; +import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api"; import { VerifierFactory, @@ -77,7 +78,7 @@ function sendRequest( .getVerifier("3PfTJw8g") .sendSyncRequest(contract, method, args) .then((result) => { - return resolve(result); + return resolve(result as ISendRequestResultV1>); }); } catch (err) { logger.error(err); diff --git a/examples/cactus-example-tcs-huawei/BalanceManagement.ts b/examples/cactus-example-tcs-huawei/BalanceManagement.ts index 2eaf10e66b..4fc12061ed 100644 --- a/examples/cactus-example-tcs-huawei/BalanceManagement.ts +++ b/examples/cactus-example-tcs-huawei/BalanceManagement.ts @@ -9,6 +9,9 @@ import { LPInfoHolder, ConfigUtil, } from "@hyperledger/cactus-cmd-socketio-server"; + +import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api"; + import { VerifierFactory, VerifierFactoryConfig, @@ -32,7 +35,7 @@ export class BalanceManagement { ); } - getBalance(account: string): Promise { + getBalance(account: string): Promise { return new Promise((resolve, reject) => { // for LedgerOperation // const execData = {"referedAddress": account}; @@ -41,7 +44,6 @@ export class BalanceManagement { // for Neo const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "web3Eth", command: "getBalance" }; - const template = "default"; const args = { args: [account] }; // const method = "default"; // const args = {"method": {type: "web3Eth", command: "getBalance"}, "args": {"args": [account]}}; @@ -50,9 +52,10 @@ export class BalanceManagement { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { + const res1 = result as ISendRequestResultV1; const response = { - status: result.status, - amount: parseFloat(result.data), + status: res1.status, + amount: parseFloat(res1.data), }; resolve(response); }) diff --git a/examples/cactus-example-tcs-huawei/BusinessLogicTcsElectricityTrade.ts b/examples/cactus-example-tcs-huawei/BusinessLogicTcsElectricityTrade.ts index c9cb6ee16d..5de75beda0 100644 --- a/examples/cactus-example-tcs-huawei/BusinessLogicTcsElectricityTrade.ts +++ b/examples/cactus-example-tcs-huawei/BusinessLogicTcsElectricityTrade.ts @@ -20,8 +20,6 @@ import { } from "@hyperledger/cactus-cmd-socketio-server"; import { makeRawTransaction } from "./TransactionEthereum"; -import fs from "fs"; -import yaml from "js-yaml"; //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; @@ -71,7 +69,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { startMonitor(tradeInfo: TradeInfo) { // Get Verifier Instance - logger.debug( + logger.debug( `##startMonitor(): businessLogicID: ${tradeInfo.businessLogicID}`, ); const useValidator = JSON.parse( @@ -172,7 +170,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { logger.debug( `##onEvent(): ${json2str(ledgerEvent["data"]["blockData"][targetIndex])}`, ); - switch (ledgerEvent.verifierId) { + switch (ledgerEvent.verifierId) { case config.electricityTradeInfo.tcsHuawei.validatorID: this.onEventTCS(ledgerEvent.data, targetIndex); break; @@ -189,15 +187,21 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { onEventTCS(event: any, targetIndex: number): void { logger.debug(`##in onEventTCS()`); - logger.debug("event.blockData", event["blockData"]) - logger.debug("event.blockData[0]", event["blockData"][targetIndex]) - logger.debug("event.blockData[0].Payload", event["blockData"][targetIndex]["Payload"]) - logger.debug("event.blockData.Payload.Name", event["blockData"][targetIndex]["Payload"]["Name"]) + logger.debug("event.blockData", event["blockData"]); + logger.debug("event.blockData[0]", event["blockData"][targetIndex]); + logger.debug( + "event.blockData[0].Payload", + event["blockData"][targetIndex]["Payload"], + ); + logger.debug( + "event.blockData.Payload.Name", + event["blockData"][targetIndex]["Payload"]["Name"], + ); - var trxPayload = event["blockData"][targetIndex]["Payload"] + const trxPayload = event["blockData"][targetIndex]["Payload"]; if (trxPayload == undefined || trxPayload == NIL) { - logger.error("transaction payload is empty") - return + logger.error("transaction payload is empty"); + return; } try { if (trxPayload["Verb"].Verb !== "set") { @@ -209,9 +213,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { this.remittanceTransaction(transactionSubset); } } catch (err) { - logger.error( - `##onEventTCS(): err: ${err}, event: ${json2str(event)}`, - ); + logger.error(`##onEventTCS(): err: ${err}, event: ${json2str(event)}`); } } @@ -310,7 +312,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } try { - return "txId-test-1" + return "txId-test-1"; const txId = tx["header_signature"]; if (typeof txId !== "string") { @@ -423,7 +425,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { // add MeterInfo const meterInfo = new MeterInfo(meterParams); - const result: {} = this.meterManagement.addMeterInfo(meterInfo); + const result = this.meterManagement.addMeterInfo(meterInfo); return result; } } diff --git a/examples/cactus-example-tcs-huawei/TransactionEthereum.ts b/examples/cactus-example-tcs-huawei/TransactionEthereum.ts index 8e63a04c5c..bc8d44f8bb 100644 --- a/examples/cactus-example-tcs-huawei/TransactionEthereum.ts +++ b/examples/cactus-example-tcs-huawei/TransactionEthereum.ts @@ -10,15 +10,13 @@ import { TransactionSigner, ConfigUtil, } from "@hyperledger/cactus-cmd-socketio-server"; +import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api"; import { VerifierFactory, VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; - -import fs from "fs"; -import yaml from "js-yaml"; //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; @@ -36,7 +34,7 @@ export function makeRawTransaction(txParam: { toAddress: string; amount: number; gas: number; -}): Promise<{ data: {}; txId: string }> { +}): Promise<{ data: unknown; txId: string }> { return new Promise(async (resolve, reject) => { try { logger.debug(`makeRawTransaction: txParam: ${JSON.stringify(txParam)}`); @@ -63,7 +61,7 @@ export function makeRawTransaction(txParam: { rawTx, txParam.fromAddressPkey, ); - const resp: { data: {}; txId: string } = { + const resp: { data: unknown; txId: string } = { data: { serializedTx: signedTx["serializedTx"] }, txId: signedTx["txId"], }; @@ -97,7 +95,6 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { // Get the number of transactions in account const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "function", command: "getNonce" }; - const template = "default"; const args = { args: { args: [fromAddress] } }; logger.debug(`##getNewNonce(A): call validator#getNonce()`); @@ -107,8 +104,13 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { .then((result) => { // logger.debug(`##getNewNonce(A): result: ${JSON.stringify(result)}`); - let txnCount: number = result.data.nonce; - let txnCountHex: string = result.data.nonceHex; + const res1 = result as ISendRequestResultV1<{ + readonly nonce: number; + readonly nonceHex: string; + }>; + + let txnCount: number = res1.data.nonce; + let txnCountHex: string = res1.data.nonceHex; const latestNonce = getLatestNonce(fromAddress); // logger.debug(`##getNewNonce(B): fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`); @@ -127,7 +129,10 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { - txnCountHex = result.data.hexStr; + const res2 = result as ISendRequestResultV1<{ + readonly hexStr: string; + }>; + txnCountHex = res2.data.hexStr; logger.debug(`##getNewNonce(E): txnCountHex: ${txnCountHex}`); // logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`); diff --git a/examples/cactus-example-tcs-huawei/package.json b/examples/cactus-example-tcs-huawei/package.json index c29f8bbcf0..719ed3cce1 100644 --- a/examples/cactus-example-tcs-huawei/package.json +++ b/examples/cactus-example-tcs-huawei/package.json @@ -13,6 +13,7 @@ }, "dependencies": { "@hyperledger/cactus-cmd-socketio-server": "2.0.0-alpha.2", + "@hyperledger/cactus-core-api": "2.0.0-alpha.2", "@hyperledger/cactus-verifier-client": "2.0.0-alpha.2", "@types/node": "14.18.54", "body-parser": "1.19.2", diff --git a/packages/cactus-cmd-socketio-server/src/main/typescript/verifier/DriverCommon.ts b/packages/cactus-cmd-socketio-server/src/main/typescript/verifier/DriverCommon.ts index 7a1e4344fb..093b0e6bc4 100644 --- a/packages/cactus-cmd-socketio-server/src/main/typescript/verifier/DriverCommon.ts +++ b/packages/cactus-cmd-socketio-server/src/main/typescript/verifier/DriverCommon.ts @@ -17,7 +17,7 @@ const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; // for debug -export function json2str(jsonObj: object) { +export function json2str(jsonObj: unknown) { try { return JSON.stringify(jsonObj); } catch (error) { diff --git a/packages/cactus-core-api/src/main/typescript/plugin/ledger-connector/i-socket-api-client.ts b/packages/cactus-core-api/src/main/typescript/plugin/ledger-connector/i-socket-api-client.ts index 494f212259..8e5731f596 100644 --- a/packages/cactus-core-api/src/main/typescript/plugin/ledger-connector/i-socket-api-client.ts +++ b/packages/cactus-core-api/src/main/typescript/plugin/ledger-connector/i-socket-api-client.ts @@ -10,18 +10,18 @@ export interface ISocketApiClient { sendAsyncRequest?( contract?: Record, method?: Record, - args?: any, - baseConfig?: any, + args?: unknown, + baseConfig?: unknown, ): void; sendSyncRequest?( contract?: Record, method?: Record, - args?: any, - baseConfig?: any, - ): Promise; + args?: unknown, + baseConfig?: unknown, + ): Promise; - watchBlocksV1?(monitorOptions?: any): Observable; + watchBlocksV1?(monitorOptions?: unknown): Observable; - watchBlocksAsyncV1?(monitorOptions?: any): Promise>; + watchBlocksAsyncV1?(monitorOptions?: unknown): Promise>; } diff --git a/packages/cactus-test-plugin-ledger-connector-ethereum/src/test/typescript/integration/api-client/verifier-integration-with-ethereum-connector.test.ts b/packages/cactus-test-plugin-ledger-connector-ethereum/src/test/typescript/integration/api-client/verifier-integration-with-ethereum-connector.test.ts index 1c032dc080..3ae0613198 100644 --- a/packages/cactus-test-plugin-ledger-connector-ethereum/src/test/typescript/integration/api-client/verifier-integration-with-ethereum-connector.test.ts +++ b/packages/cactus-test-plugin-ledger-connector-ethereum/src/test/typescript/integration/api-client/verifier-integration-with-ethereum-connector.test.ts @@ -29,6 +29,7 @@ import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; import { ICactusPlugin, + ISendRequestResultV1, IVerifierEventListener, LedgerEvent, } from "@hyperledger/cactus-core-api"; @@ -280,7 +281,7 @@ describe("Verifier integration with ethereum connector tests", () => { correctContract, correctMethod, correctArgs, - ); + ) as ISendRequestResultV1; expect(resultCorrect.status).toEqual(200); // Failing: Missing contract ABI @@ -367,7 +368,7 @@ describe("Verifier integration with ethereum connector tests", () => { contractCommon, methodSend, argsSend, - ); + ) as ISendRequestResultV1<{ readonly status: string }>; expect(resultsSend.status).toEqual(200); expect(resultsSend.data.status).toEqual("1"); @@ -384,7 +385,7 @@ describe("Verifier integration with ethereum connector tests", () => { contractCommon, methodCall, argsCall, - ); + ) as ISendRequestResultV1; expect(resultCall.status).toEqual(200); expect(resultCall.data).toEqual(newName); }); @@ -407,7 +408,7 @@ describe("Verifier integration with ethereum connector tests", () => { contractCommon, methodEncode, argsEncode, - ); + ) as ISendRequestResultV1; expect(resultsEncode.status).toEqual(200); expect(resultsEncode.data.length).toBeGreaterThan(5); @@ -437,7 +438,7 @@ describe("Verifier integration with ethereum connector tests", () => { contractCommon, methodEstimateGas, argsEstimateGas, - ); + ) as ISendRequestResultV1; expect(resultsEstimateGas.status).toEqual(200); expect(Number(resultsEstimateGas.data)).toBeGreaterThan(0); @@ -495,7 +496,7 @@ describe("Verifier integration with ethereum connector tests", () => { contractCommon, methodCall, argsCall, - ); + ) as ISendRequestResultV1; expect(resultsCall.status).toEqual(200); expect(resultsCall.data).toEqual(newName); }); @@ -509,7 +510,7 @@ describe("Verifier integration with ethereum connector tests", () => { const results = await globalVerifierFactory .getVerifier(ethereumValidatorId) - .sendSyncRequest(contract, method, args); + .sendSyncRequest(contract, method, args) as ISendRequestResultV1; expect(results.status).toEqual(200); expect(results.data.length).toBeGreaterThan(0); }); @@ -531,7 +532,7 @@ describe("Verifier integration with ethereum connector tests", () => { correctContract, correctMethod, correctArgs, - ); + ) as ISendRequestResultV1<{}>; expect(resultCorrect.status).toEqual(200); // Failing: Empty web3.eth method diff --git a/packages/cactus-test-plugin-ledger-connector-quorum/src/test/typescript/integration/api-client/verifier-integration-with-quorum-connector.test.ts b/packages/cactus-test-plugin-ledger-connector-quorum/src/test/typescript/integration/api-client/verifier-integration-with-quorum-connector.test.ts index 1e86af0deb..bf8a063c84 100644 --- a/packages/cactus-test-plugin-ledger-connector-quorum/src/test/typescript/integration/api-client/verifier-integration-with-quorum-connector.test.ts +++ b/packages/cactus-test-plugin-ledger-connector-quorum/src/test/typescript/integration/api-client/verifier-integration-with-quorum-connector.test.ts @@ -32,6 +32,7 @@ import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; import { ICactusPlugin, + ISendRequestResultV1, IVerifierEventListener, LedgerEvent, } from "@hyperledger/cactus-core-api"; @@ -225,7 +226,7 @@ describe("Verifier integration with quorum connector tests", () => { reject(err); } }, - onError(err: any): void { + onError(err: unknown): void { log.error("Ledger monitoring error:", err); reject(err); }, @@ -288,7 +289,7 @@ describe("Verifier integration with quorum connector tests", () => { command: "getBlock", }; - const correctArgs: any = { args: ["latest"] }; + const correctArgs: Record = { args: ["latest"] }; const resultCorrect = await verifier.sendSyncRequest( correctContract, @@ -303,23 +304,22 @@ describe("Verifier integration with quorum connector tests", () => { test("Invalid web3EthContract calls are rejected by QuorumApiClient", async () => { // Define correct input parameters - const correctContract: Record = lodash.clone( - contractCommon, - ); + const correctContract: Record = + lodash.clone(contractCommon); const correctMethod: Record = { type: "web3EthContract", command: "call", function: "getName", params: [], }; - const correctArgs: any = {}; + const correctArgs: Record = {}; // Sanity check if correct parameters work - const resultCorrect = await verifier.sendSyncRequest( + const resultCorrect = (await verifier.sendSyncRequest( correctContract, correctMethod, correctArgs, - ); + )) as ISendRequestResultV1; expect(resultCorrect.status).toEqual(200); // Failing: Missing contract ABI @@ -402,11 +402,11 @@ describe("Verifier integration with quorum connector tests", () => { }, }; - const resultsSend = await verifier.sendSyncRequest( + const resultsSend = (await verifier.sendSyncRequest( contractCommon, methodSend, argsSend, - ); + )) as ISendRequestResultV1<{ readonly status: boolean }>; expect(resultsSend.status).toEqual(200); expect(resultsSend.data.status).toBeTrue(); @@ -419,11 +419,11 @@ describe("Verifier integration with quorum connector tests", () => { }; const argsCall = {}; - const resultCall = await verifier.sendSyncRequest( + const resultCall = (await verifier.sendSyncRequest( contractCommon, methodCall, argsCall, - ); + )) as ISendRequestResultV1; expect(resultCall.status).toEqual(200); expect(resultCall.data).toEqual(newName); }); @@ -442,11 +442,11 @@ describe("Verifier integration with quorum connector tests", () => { }, }; - const resultsEncode = await verifier.sendSyncRequest( + const resultsEncode = (await verifier.sendSyncRequest( contractCommon, methodEncode, argsEncode, - ); + )) as ISendRequestResultV1>; expect(resultsEncode.status).toEqual(200); expect(resultsEncode.data.length).toBeGreaterThan(5); @@ -471,11 +471,11 @@ describe("Verifier integration with quorum connector tests", () => { }; const argsEstimateGas = {}; - const resultsEstimateGas = await verifier.sendSyncRequest( + const resultsEstimateGas = (await verifier.sendSyncRequest( contractCommon, methodEstimateGas, argsEstimateGas, - ); + )) as ISendRequestResultV1; expect(resultsEstimateGas.status).toEqual(200); expect(resultsEstimateGas.data).toBeGreaterThan(0); @@ -526,11 +526,11 @@ describe("Verifier integration with quorum connector tests", () => { }; const argsCall = {}; - const resultsCall = await verifier.sendSyncRequest( + const resultsCall = (await verifier.sendSyncRequest( contractCommon, methodCall, argsCall, - ); + )) as ISendRequestResultV1; log.error(resultsCall); expect(resultsCall.status).toEqual(200); expect(resultsCall.data).toEqual(newName); @@ -543,9 +543,11 @@ describe("Verifier integration with quorum connector tests", () => { const method = { type: "web3Eth", command: "getBalance" }; const args = { args: [connectionProfile.quorum.member2.accountAddress] }; - const results = await globalVerifierFactory + const results = (await globalVerifierFactory .getVerifier(quorumValidatorId) - .sendSyncRequest(contract, method, args); + .sendSyncRequest(contract, method, args)) as ISendRequestResultV1< + Array + >; expect(results.status).toEqual(200); expect(results.data.length).toBeGreaterThan(0); }); @@ -557,17 +559,17 @@ describe("Verifier integration with quorum connector tests", () => { type: "web3Eth", command: "getBalance", }; - const correctArgs: any = { + const correctArgs: Record = { args: [connectionProfile.quorum.member2.accountAddress], }; const verifier = globalVerifierFactory.getVerifier(quorumValidatorId); // Sanity check if correct parameters work - const resultCorrect = await verifier.sendSyncRequest( + const resultCorrect = (await verifier.sendSyncRequest( correctContract, correctMethod, correctArgs, - ); + )) as ISendRequestResultV1; expect(resultCorrect.status).toEqual(200); // Failing: Empty web3.eth method @@ -599,9 +601,13 @@ describe("Verifier integration with quorum connector tests", () => { const method = { type: "web3Eth", command: "foo" }; const args = {}; - const results = await globalVerifierFactory + const results = (await globalVerifierFactory .getVerifier(quorumValidatorId) - .sendSyncRequest(contract, method, args); + .sendSyncRequest( + contract, + method, + args, + )) as ISendRequestResultV1; expect(results).toBeTruthy(); expect(results.status).toEqual(504); diff --git a/packages/cactus-verifier-client/src/main/typescript/verifier.ts b/packages/cactus-verifier-client/src/main/typescript/verifier.ts index 2cbf18304c..3b1aefa5a6 100644 --- a/packages/cactus-verifier-client/src/main/typescript/verifier.ts +++ b/packages/cactus-verifier-client/src/main/typescript/verifier.ts @@ -40,7 +40,8 @@ type BlockTypeFromSocketApi = T extends ISocketApiClient * @todo Don't throw exception for not supported operations, don't include these methods at all (if possible) */ export class Verifier> - implements IVerifier { + implements IVerifier +{ private readonly log: Logger; readonly className: string; readonly runningMonitors = new Map(); @@ -165,7 +166,7 @@ export class Verifier> async sendAsyncRequest( contract: Record, method: Record, - args: any, + args: unknown, ): Promise { if (!this.ledgerApi.sendAsyncRequest) { throw new Error("sendAsyncRequest not supported on this ledger"); @@ -184,8 +185,8 @@ export class Verifier> async sendSyncRequest( contract: Record, method: Record, - args: any, - ): Promise { + args: unknown, + ): Promise { if (!this.ledgerApi.sendSyncRequest) { throw new Error("sendSyncRequest not supported on this ledger"); } diff --git a/yarn.lock b/yarn.lock index 06439845ca..6c06558ad7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6129,6 +6129,7 @@ __metadata: resolution: "@hyperledger/cactus-example-tcs-huawei@workspace:examples/cactus-example-tcs-huawei" dependencies: "@hyperledger/cactus-cmd-socketio-server": 2.0.0-alpha.2 + "@hyperledger/cactus-core-api": 2.0.0-alpha.2 "@hyperledger/cactus-verifier-client": 2.0.0-alpha.2 "@types/body-parser": 1.19.2 "@types/cookie-parser": 1.4.2