Skip to content

Commit

Permalink
refactor(core-api,verifier-client): use unknown instead of any type
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
petermetz committed Oct 12, 2023
1 parent 483de38 commit 15b8106
Show file tree
Hide file tree
Showing 15 changed files with 143 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand All @@ -30,9 +31,7 @@ export class BalanceManagement {
);
}

getBalance(
account: string,
): Promise<{
getBalance(account: string): Promise<{
status: number;
amount: number;
}> {
Expand All @@ -47,9 +46,10 @@ export class BalanceManagement {
.getVerifier("84jUisrs")
.sendSyncRequest(contract, method, args)
.then((result) => {
const res1 = result as ISendRequestResultV1<string>;
const response = {
status: result.status,
amount: parseFloat(result.data),
status: res1.status,
amount: parseFloat(res1.data),
};
resolve(response);
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
LPInfoHolder,
TransactionSigner,
} from "@hyperledger/cactus-cmd-socketio-server";
import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api";

import {
VerifierFactory,
Expand Down Expand Up @@ -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) {
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -57,9 +60,14 @@ export function makeSignedProposal<T extends ISocketApiClient<unknown>>(

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) {
Expand All @@ -84,11 +92,15 @@ export function makeSignedProposal<T extends ISocketApiClient<unknown>>(
};

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,
);
Expand All @@ -113,11 +125,14 @@ export function makeSignedProposal<T extends ISocketApiClient<unknown>>(
};

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.");
Expand All @@ -140,11 +155,13 @@ export function makeSignedProposal<T extends ISocketApiClient<unknown>>(
};

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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
LPInfoHolder,
ConfigUtil,
} from "@hyperledger/cactus-cmd-socketio-server";
import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api";

import {
VerifierFactory,
Expand Down Expand Up @@ -77,7 +78,7 @@ function sendRequest(
.getVerifier("3PfTJw8g")
.sendSyncRequest(contract, method, args)
.then((result) => {
return resolve(result);
return resolve(result as ISendRequestResultV1<Array<string>>);
});
} catch (err) {
logger.error(err);
Expand Down
11 changes: 7 additions & 4 deletions examples/cactus-example-tcs-huawei/BalanceManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import {
LPInfoHolder,
ConfigUtil,
} from "@hyperledger/cactus-cmd-socketio-server";

import { ISendRequestResultV1 } from "@hyperledger/cactus-core-api";

import {
VerifierFactory,
VerifierFactoryConfig,
Expand All @@ -32,7 +35,7 @@ export class BalanceManagement {
);
}

getBalance(account: string): Promise<any> {
getBalance(account: string): Promise<unknown> {
return new Promise((resolve, reject) => {
// for LedgerOperation
// const execData = {"referedAddress": account};
Expand All @@ -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]}};
Expand All @@ -50,9 +52,10 @@ export class BalanceManagement {
.getVerifier("84jUisrs")
.sendSyncRequest(contract, method, args)
.then((result) => {
const res1 = result as ISendRequestResultV1<string>;
const response = {
status: result.status,
amount: parseFloat(result.data),
status: res1.status,
amount: parseFloat(res1.data),
};
resolve(response);
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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;
Expand All @@ -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") {
Expand All @@ -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)}`);
}
}

Expand Down Expand Up @@ -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") {
Expand Down Expand Up @@ -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;
}
}
23 changes: 14 additions & 9 deletions examples/cactus-example-tcs-huawei/TransactionEthereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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)}`);
Expand All @@ -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"],
};
Expand Down Expand Up @@ -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()`);
Expand All @@ -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}`);
Expand All @@ -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}`);
Expand Down
1 change: 1 addition & 0 deletions examples/cactus-example-tcs-huawei/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit 15b8106

Please sign in to comment.