From 9bc856e1d2693106c68a4ae1bd7eee45b210f693 Mon Sep 17 00:00:00 2001 From: tomasz awramski Date: Wed, 31 Aug 2022 17:35:49 +0200 Subject: [PATCH] fix(cactus-example-discounted-asset-trade): enable ...tsconfig strict flag and fix all the warnings - Fixed all warnings when strict flag is enabled Closes: #2145 Signed-off-by: Tomasz Awramski --- .../balance-management.ts | 15 +- .../balance.ts | 7 +- .../business-logic-asset-trade.ts | 351 +++++++++++------- ...siness-logic-inquire-asset-trade-status.ts | 24 +- .../fabric-asset-management.ts | 6 +- .../fabric-asset.ts | 8 +- .../package.json | 8 +- .../result-transactions-status-data.ts | 5 +- .../template-trade-management.ts | 27 +- .../template-trade.ts | 19 +- .../trades.ts | 6 +- .../transaction-ethereum.ts | 104 +++--- .../transaction-fabric.ts | 41 +- .../transaction-indy.ts | 46 +-- .../transaction-info-management.ts | 71 ++-- .../transaction-info.ts | 70 ++-- .../transaction-status.ts | 8 +- .../tsconfig.json | 1 - .../routing-interface/RequestInfo.ts | 10 +- .../main/typescript/util/TransactionSigner.ts | 22 +- 20 files changed, 483 insertions(+), 366 deletions(-) diff --git a/examples/cactus-example-discounted-asset-trade/balance-management.ts b/examples/cactus-example-discounted-asset-trade/balance-management.ts index fb6c55c275..8a352dedd9 100644 --- a/examples/cactus-example-discounted-asset-trade/balance-management.ts +++ b/examples/cactus-example-discounted-asset-trade/balance-management.ts @@ -12,16 +12,14 @@ import { VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const fs = require("fs"); -const path = require("path"); -const config: any = ConfigUtil.getConfig(); +const config: any = ConfigUtil.getConfig() as any; import { getLogger } from "log4js"; const moduleName = "BalanceManagement"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; export class BalanceManagement { - private connectInfo: LPInfoHolder = null; // connection information + private connectInfo: LPInfoHolder | null = null; // connection information private readonly verifierFactory: VerifierFactory; constructor() { @@ -32,7 +30,12 @@ export class BalanceManagement { ); } - getBalance(account: string): Promise { + getBalance( + account: string, + ): Promise<{ + status: number; + amount: number; + }> { return new Promise((resolve, reject) => { // for LedgerOperation // const execData = {"referedAddress": account}; @@ -41,7 +44,7 @@ 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 template = "default"; const args = { args: [account] }; // const method = "default"; // const args = {"method": {type: "web3Eth", command: "getBalance"},"args": {"args": [account]}}; diff --git a/examples/cactus-example-discounted-asset-trade/balance.ts b/examples/cactus-example-discounted-asset-trade/balance.ts index 7049582d81..a954858fbb 100644 --- a/examples/cactus-example-discounted-asset-trade/balance.ts +++ b/examples/cactus-example-discounted-asset-trade/balance.ts @@ -10,8 +10,7 @@ import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; import { RIFError } from "@hyperledger/cactus-cmd-socketio-server"; import { BalanceManagement } from "./balance-management"; -const fs = require("fs"); -const path = require("path"); + const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; const moduleName = "balance"; @@ -35,7 +34,9 @@ router.get("/:account", (req: Request, res: Response, next: NextFunction) => { logger.error(err); }); } catch (err) { - logger.error(`##err name: ${err.constructor.name}`); + if (err instanceof Error) { + logger.error(`##err name: ${err.constructor.name}`); + } if (err instanceof RIFError) { logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); diff --git a/examples/cactus-example-discounted-asset-trade/business-logic-asset-trade.ts b/examples/cactus-example-discounted-asset-trade/business-logic-asset-trade.ts index edf550e7f7..b4740b69ef 100644 --- a/examples/cactus-example-discounted-asset-trade/business-logic-asset-trade.ts +++ b/examples/cactus-example-discounted-asset-trade/business-logic-asset-trade.ts @@ -14,13 +14,16 @@ import { TransactionData } from "./transaction-data"; import { BusinessLogicInquireAssetTradeStatus } from "./business-logic-inquire-asset-trade-status"; import { TxInfoData } from "./tx-info-data"; import { routesTransactionManagement } from "@hyperledger/cactus-cmd-socketio-server"; -import { LedgerOperation } from "@hyperledger/cactus-cmd-socketio-server"; +// import { LedgerOperation } from "@hyperledger/cactus-cmd-socket-server"; import { BusinessLogicBase } from "@hyperledger/cactus-cmd-socketio-server"; import { LPInfoHolder } from "@hyperledger/cactus-cmd-socketio-server"; import { makeRawTransaction } from "./transaction-ethereum"; import { makeSignedProposal } from "./transaction-fabric"; import { getDataFromIndy } from "./transaction-indy"; -import { LedgerEvent, ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; +import { + LedgerEvent, + ConfigUtil, +} from "@hyperledger/cactus-cmd-socketio-server"; import { json2str } from "@hyperledger/cactus-cmd-socketio-server"; import { AssetTradeStatus } from "./define"; import { @@ -28,10 +31,7 @@ import { VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const fs = require("fs"); -const path = require("path"); -const yaml = require("js-yaml"); -//const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); + const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; @@ -50,6 +50,32 @@ const assert = require("assert"); const identifierSchema = "schema"; const identifierCredDef = "credDef"; +interface EthEvent { + blockData: { transactions: { [key: string]: EthData } }; + hash: string; + status: number; +} +interface EthData { + hash: string; +} + +interface FabricEvent { + txId: string; + blockData: []; + hash: string; + status: number; +} + +interface TransactionStatusData { + stateInfo: number | undefined; + transactionStatus: { + state: string; + ledger: string; + txID: string; + txInfo: string; // JSON string + }[]; +} + export class BusinessLogicAssetTrade extends BusinessLogicBase { transactionInfoManagement: TransactionInfoManagement; // useValidator: {}; @@ -59,7 +85,11 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { this.transactionInfoManagement = new TransactionInfoManagement(); } - startTransaction(req: Request, businessLogicID: string, tradeID: string) { + startTransaction( + req: Request, + businessLogicID: string, + tradeID: string, + ): void { logger.debug("called startTransaction"); // set RequestInfo @@ -93,13 +123,13 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { // Create trade information const tradeInfo: TradeInfo = new TradeInfo( requestInfo.businessLogicID, - requestInfo.tradeID + requestInfo.tradeID, ); // trade status update this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.UnderEscrow + AssetTradeStatus.UnderEscrow, ); // Get varidator information @@ -113,48 +143,48 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { }); } - dummyTransaction(requestInfo: RequestInfo, tradeInfo: TradeInfo) { + dummyTransaction(requestInfo: RequestInfo, tradeInfo: TradeInfo): void { logger.debug("called dummyTransaction"); let transactionData: TransactionData = new TransactionData( "escrow", "ledger001", - "tid001" + "tid001", ); this.transactionInfoManagement.setTransactionData( tradeInfo, - transactionData + transactionData, ); this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.UnderTransfer + AssetTradeStatus.UnderTransfer, ); transactionData = new TransactionData("transfer", "ledger002", "tid002"); this.transactionInfoManagement.setTransactionData( tradeInfo, - transactionData + transactionData, ); this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.UnderSettlement + AssetTradeStatus.UnderSettlement, ); transactionData = new TransactionData("settlement", "ledger003", "tid003"); this.transactionInfoManagement.setTransactionData( tradeInfo, - transactionData + transactionData, ); this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.Completed + AssetTradeStatus.Completed, ); } - async Pricing(requestInfo: RequestInfo) { + async Pricing(requestInfo: RequestInfo): Promise { logger.debug("called Pricing"); // price list @@ -162,7 +192,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { logger.debug(JSON.stringify(requestInfo.tradeInfo.proofJson)); const isPreferredCustomer = await this.isPreferredCustomer( - requestInfo.tradeInfo.proofJson + requestInfo.tradeInfo.proofJson, ); // decide the price from result of isPreferredCustomer @@ -178,7 +208,11 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { return requestInfo; } - async isPreferredCustomer(input_obj) { + async isPreferredCustomer(input_obj: { + tradeInfo: string; + proof_request: string; + proof: string; + }): Promise { let proofRequestJson; let proofJson; try { @@ -186,7 +220,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { proofJson = JSON.parse(input_obj["proof"]); } catch (err) { logger.error( - "Error while reading proof and proof request. returning false." + "Error while reading proof and proof request. returning false.", ); return false; } @@ -194,33 +228,40 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { // get schema & credential definition from indy // now verifierGetEntitiesFromLedger don't get revRegDefs & revRegs // did is null. If it is null, indy.buidlGetSchemaRequest API get data by default param. - const [schemasJson, credDefsJson, revRegDefsJson, revRegsJson] = - await this.verifierGetEntitiesFromLedger(null, proofJson["identifiers"]); + const [ + schemasJson, + credDefsJson, + revRegDefsJson, + revRegsJson, + ] = await this.verifierGetEntitiesFromLedger( + null, + proofJson["identifiers"], + ); assert( "Permanent" === - proofJson["requested_proof"]["revealed_attrs"]["attr1_referent"]["raw"] + proofJson["requested_proof"]["revealed_attrs"]["attr1_referent"]["raw"], ); logger.debug( `##isPreferredCustomer verifierGetEntitiesFromLedger schemasJson : ${JSON.stringify( - schemasJson - )}` + schemasJson, + )}`, ); logger.debug( `##isPreferredCustomer verifierGetEntitiesFromLedger credDefsJson : ${JSON.stringify( - credDefsJson - )}` + credDefsJson, + )}`, ); logger.debug( `##isPreferredCustomer verifierGetEntitiesFromLedger revRegDefsJson : ${JSON.stringify( - revRegDefsJson - )}` + revRegDefsJson, + )}`, ); logger.debug( `##isPreferredCustomer verifierGetEntitiesFromLedger revRegsJson : ${JSON.stringify( - revRegsJson - )}` + revRegsJson, + )}`, ); try { @@ -230,32 +271,43 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { schemasJson, credDefsJson, revRegDefsJson, - revRegsJson + revRegsJson, ); logger.debug("verify proof: " + (verif_result ? "ok" : "not ok")); return verif_result; } catch (err) { logger.error( - "error raised during indy.verifierVerifyProof() invocation. defaulting to false (= NO DISCOUNT)" + "error raised during indy.verifierVerifyProof() invocation. defaulting to false (= NO DISCOUNT)", ); logger.error(err); return false; } } - async verifierGetEntitiesFromLedger(did, identifiers) { - const schemas = {}; - const credDefs = {}; + async verifierGetEntitiesFromLedger( + did: string | null, + identifiers: { + [keyof: string]: { schema_id: string; cred_def_id: string }; + }, + ): Promise< + [ + Record, + Record, + Record, + Record, + ] + > { + const schemas: { [keyof: string]: string } = {}; + const credDefs: { [keyof: string]: string } = {}; const revRegDefs = {}; const revRegs = {}; for (const referent of Object.keys(identifiers)) { const item = identifiers[referent]; const args_request_getSchema = { did: did, schemaId: item["schema_id"] }; - const responseSchema = await getDataFromIndy( - args_request_getSchema, - identifierSchema - ); + const responseSchema: { + data: string[]; + } = await getDataFromIndy(args_request_getSchema, identifierSchema); const [receivedSchemaId, receivedSchema] = responseSchema["data"]; schemas[receivedSchemaId] = JSON.parse(receivedSchema); @@ -263,16 +315,16 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { did: did, schemaId: item["cred_def_id"], }; - const responseCredDef = await getDataFromIndy( - args_request_getCredDef, - identifierCredDef - ); + const responseCredDef: { + data: string[]; + } = await getDataFromIndy(args_request_getCredDef, identifierCredDef); + const [receivedCredDefId, receivedCredDef] = responseCredDef["data"]; credDefs[receivedCredDefId] = JSON.parse(receivedCredDef); - if (item.rev_reg_seq_no) { - // TODO Get Revocation Definitions and Revocation Registries - } + // if (item.rev_reg_seq_no) { + // // TODO Get Revocation Definitions and Revocation Registries + // } } logger.debug("finish get Data from indy"); @@ -280,17 +332,17 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { return [schemas, credDefs, revRegDefs, revRegs]; } - firstTransaction(requestInfo: RequestInfo, tradeInfo: TradeInfo) { + firstTransaction(requestInfo: RequestInfo, tradeInfo: TradeInfo): void { logger.debug("called firstTransaction"); ///// Eth Escrow // Get Verifier Instance logger.debug( - `##firstTransaction(): businessLogicID: ${tradeInfo.businessLogicID}` + `##firstTransaction(): businessLogicID: ${tradeInfo.businessLogicID}`, ); const useValidator = JSON.parse( - routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID) + routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID), ); // const verifierEthereum = routesTransactionManagement.getVerifier(useValidator['validatorID'][0]); const verifierEthereum = routesVerifierFactory.getVerifier( @@ -305,7 +357,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { // TODO: get private key from logger.debug( - `####fromAddress: ${requestInfo.tradeInfo.ethereumAccountFrom}` + `####fromAddress: ${requestInfo.tradeInfo.ethereumAccountFrom}`, ); const fromAddressPkey = config.assetTradeInfo.ethereum[ @@ -338,18 +390,18 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { const transactionData: TransactionData = new TransactionData( "escrow", "ledger001", - result.txId + result.txId, ); this.transactionInfoManagement.setTransactionData( tradeInfo, - transactionData + transactionData, ); // Set Parameter logger.debug("firstTransaction data : " + JSON.stringify(result.data)); const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "web3Eth", command: "sendRawTransaction" }; - const template = "default"; + // const template = "default"; const args = { args: [result.data["serializedTx"]] }; // const method = "default"; // const args = {"method": {type: "web3Eth", command: "sendRawTransaction"},"args": {"args": [result.data["serializedTx"]]}}; @@ -372,18 +424,18 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { secondTransaction( assetID: string, fabricAccountTo: string, - tradeInfo: TradeInfo - ) { + tradeInfo: TradeInfo, + ): void { logger.debug("called secondTransaction"); ///// Fab Transfer // Get Verifier Instance logger.debug( - `##secondTransaction(): businessLogicID: ${tradeInfo.businessLogicID}` + `##secondTransaction(): businessLogicID: ${tradeInfo.businessLogicID}`, ); const useValidator = JSON.parse( - routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID) + routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID), ); // const verifierFabric = routesTransactionManagement.getVerifier(useValidator['validatorID'][1]); const verifierFabric = routesVerifierFactory.getVerifier( @@ -412,27 +464,27 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { const transactionData: TransactionData = new TransactionData( "transfer", "ledger002", - result.txId + result.txId, ); this.transactionInfoManagement.setTransactionData( tradeInfo, - transactionData + transactionData, ); // NOTE: Convert properties to binary. // If you do not convert the following, you will get an error. result.data["signedCommitProposal"].signature = Buffer.from( - result.data["signedCommitProposal"].signature + result.data["signedCommitProposal"].signature, ); result.data["signedCommitProposal"].proposal_bytes = Buffer.from( - result.data["signedCommitProposal"].proposal_bytes + result.data["signedCommitProposal"].proposal_bytes, ); // Set Parameter //logger.debug('secondTransaction data : ' + JSON.stringify(result.data)); const contract = { channelName: "mychannel" }; const method = { type: "sendSignedTransaction" }; - const template = "default"; + // const template = "default"; const args = { args: [result.data] }; // Run Verifier (Fabric) @@ -453,16 +505,16 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { thirdTransaction( ethereumAccountTo: string, tradingValue: string, - tradeInfo: TradeInfo - ) { + tradeInfo: TradeInfo, + ): void { logger.debug("called thirdTransaction"); // Get Verifier Instance logger.debug( - `##thirdTransaction(): businessLogicID: ${tradeInfo.businessLogicID}` + `##thirdTransaction(): businessLogicID: ${tradeInfo.businessLogicID}`, ); const useValidator = JSON.parse( - routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID) + routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID), ); // const verifierEthereum = routesTransactionManagement.getVerifier(useValidator['validatorID'][0]); const verifierEthereum = routesVerifierFactory.getVerifier( @@ -497,20 +549,20 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { const transactionData: TransactionData = new TransactionData( "settlement", "ledger003", - result.txId + result.txId, ); this.transactionInfoManagement.setTransactionData( tradeInfo, - transactionData + transactionData, ); // Set LedgerOperation logger.debug("thirdTransaction data : " + JSON.stringify(result.data)); - const ledgerOperation: LedgerOperation = new LedgerOperation( - "sendRawTransaction", - "", - result.data - ); + // const ledgerOperation: LedgerOperation = new LedgerOperation( + // "sendRawTransaction", + // "", + // result.data, + // ); // Run Verifier (Ethereum) // verifierEthereum.requestLedgerOperation(ledgerOperation); @@ -519,7 +571,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { // Set Parameter const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "web3Eth", command: "sendRawTransaction" }; - const template = "default"; + // const template = "default"; const args = { args: [result.data["serializedTx"]] }; // const method = "default"; // const args = {"method": {type: "web3Eth", command: "sendRawTransaction"}, "args": {"args": [result.data["serializedTx"]]}}; @@ -539,19 +591,19 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { }); } - completedTransaction(tradeInfo: TradeInfo) { + completedTransaction(tradeInfo: TradeInfo): void { logger.debug("called completedTransaction"); logger.debug( - `##completedTransaction(): businessLogicID: ${tradeInfo.businessLogicID}` + `##completedTransaction(): businessLogicID: ${tradeInfo.businessLogicID}`, ); - const useValidator = JSON.parse( - routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID) - ); - const validatorId = useValidator["validatorID"][0]; + // const useValidator = JSON.parse( + // routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID), + // ); + // const validatorId = useValidator["validatorID"][0]; } - finish() { + finish(): void { logger.debug("called finish"); } @@ -568,13 +620,13 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { break; default: logger.error( - `##onEvent(), invalid verifierId: ${ledgerEvent.verifierId}` + `##onEvent(), invalid verifierId: ${ledgerEvent.verifierId}`, ); return; } } - onEvenEtherem(event: object, targetIndex: number): void { + onEvenEtherem(event: EthEvent, targetIndex: number): void { logger.debug(`##in onEvenEtherem()`); const tx = this.getTransactionFromEthereumEvent(event, targetIndex); if (tx == null) { @@ -590,7 +642,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { if (status !== 200) { logger.error( - `##onEvenEtherem(): error event, status: ${status}, txId: ${txId}` + `##onEvenEtherem(): error event, status: ${status}, txId: ${txId}`, ); return; } @@ -603,25 +655,29 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { } getTransactionFromEthereumEvent( - event: object, - targetIndex: number - ): object | null { + event: EthEvent, + targetIndex: number, + ): EthData | undefined { try { const retTransaction = event["blockData"]["transactions"][targetIndex]; logger.debug( - `##getTransactionFromEthereumEvent(), retTransaction: ${retTransaction}` + `##getTransactionFromEthereumEvent(), retTransaction: ${retTransaction}`, ); return retTransaction; } catch (err) { logger.error( - `##getTransactionFromEthereumEvent(): invalid even, err:${err}, event:${event}` + `##getTransactionFromEthereumEvent(): invalid even, err:${err}, event:${event}`, ); } } - onEvenFabric(event: object, targetIndex: number): void { + onEvenFabric(event: FabricEvent, targetIndex: number): void { logger.debug(`##in onEvenFabric()`); - const tx = this.getTransactionFromFabricEvent(event, targetIndex); + const tx: + | { + txId: string; + } + | undefined = this.getTransactionFromFabricEvent(event, targetIndex); if (tx == null) { logger.warn(`##onEvenFabric(): invalid event: ${json2str(event)}`); return; @@ -635,7 +691,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { if (status !== 200) { logger.error( - `##onEvenFabric(): error event, status: ${status}, txId: ${txId}` + `##onEvenFabric(): error event, status: ${status}, txId: ${txId}`, ); return; } @@ -644,103 +700,112 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { this.executeNextTransaction(tx, txId); } catch (err) { logger.error( - `##onEvenFabric(): onEvent, err: ${err}, event: ${json2str(event)}` + `##onEvenFabric(): onEvent, err: ${err}, event: ${json2str(event)}`, ); } } - getTransactionFromFabricEvent(event: object, targetIndex): object | null { + getTransactionFromFabricEvent( + event: FabricEvent, + targetIndex: number, + ): FabricEvent | undefined { try { const retTransaction = event["blockData"][targetIndex]; logger.debug( - `##getTransactionFromFabricEvent(): retTransaction: ${retTransaction}` + `##getTransactionFromFabricEvent(): retTransaction: ${retTransaction}`, ); return retTransaction; } catch (err) { logger.error( - `##getTransactionFromFabricEvent(): invalid even, err:${err}, event:${event}` + `##getTransactionFromFabricEvent(): invalid even, err:${err}, event:${event}`, ); } } - executeNextTransaction(txInfo: object, txId: string): void { - let transactionInfo: TransactionInfo = null; + executeNextTransaction( + txInfo: Record | EthData, + txId: string, + ): void { + let transactionInfo: TransactionInfo | null = null; try { // Retrieve DB transaction information - transactionInfo = - this.transactionInfoManagement.getTransactionInfoByTxId(txId); + transactionInfo = this.transactionInfoManagement.getTransactionInfoByTxId( + txId, + ); if (transactionInfo != null) { logger.debug( - `##onEvent(A), transactionInfo: ${json2str(transactionInfo)}` + `##onEvent(A), transactionInfo: ${json2str(transactionInfo)}`, ); } else { logger.warn(`##onEvent(B), not found transactionInfo, txId: ${txId}`); return; } const txStatus = transactionInfo.status; - const tradeInfo = - this.createTradeInfoFromTransactionInfo(transactionInfo); + const tradeInfo = this.createTradeInfoFromTransactionInfo( + transactionInfo, + ); let txInfoData: TxInfoData; + switch (txStatus) { case AssetTradeStatus.UnderEscrow: // store transaction information in DB - txInfoData = new TxInfoData("escrow", json2str(txInfo)); + txInfoData = new TxInfoData("escrow", JSON.stringify(txInfo)); this.transactionInfoManagement.setTxInfo(tradeInfo, txInfoData); // underEscrow -> underTransfer logger.info( - `##INFO: underEscrow -> underTransfer, businessLogicID: ${transactionInfo.businessLogicID}, tradeID: ${transactionInfo.tradeID}` + `##INFO: underEscrow -> underTransfer, businessLogicID: ${transactionInfo.businessLogicID}, tradeID: ${transactionInfo.tradeID}`, ); // const tradeInfo = this.createTradeInfoFromTransactionInfo(transactionInfo); this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.UnderTransfer + AssetTradeStatus.UnderTransfer, ); this.secondTransaction( transactionInfo.assetID, transactionInfo.fabricAccountTo, - tradeInfo + tradeInfo, ); break; case AssetTradeStatus.UnderTransfer: // store transaction information in DB - txInfoData = new TxInfoData("transfer", json2str(txInfo)); + txInfoData = new TxInfoData("transfer", JSON.stringify(txInfo)); this.transactionInfoManagement.setTxInfo(tradeInfo, txInfoData); // underTransfer -> underSettlement logger.info( - `##INFO: underTransfer -> underSettlement, businessLogicID: ${transactionInfo.businessLogicID}, tradeID: ${transactionInfo.tradeID}` + `##INFO: underTransfer -> underSettlement, businessLogicID: ${transactionInfo.businessLogicID}, tradeID: ${transactionInfo.tradeID}`, ); // const tradeInfo = this.createTradeInfoFromTransactionInfo(transactionInfo); this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.UnderSettlement + AssetTradeStatus.UnderSettlement, ); this.thirdTransaction( transactionInfo.ethereumAccountTo, transactionInfo.tradingValue, - tradeInfo + tradeInfo, ); break; case AssetTradeStatus.UnderSettlement: // store transaction information in DB - txInfoData = new TxInfoData("settlement", json2str(txInfo)); + txInfoData = new TxInfoData("settlement", JSON.stringify(txInfo)); this.transactionInfoManagement.setTxInfo(tradeInfo, txInfoData); // underSettlement -> completed // const tradeInfo = this.createTradeInfoFromTransactionInfo(transactionInfo); this.transactionInfoManagement.setStatus( tradeInfo, - AssetTradeStatus.Completed + AssetTradeStatus.Completed, ); logger.info( - `##INFO: completed asset-trade, businessLogicID: ${transactionInfo.businessLogicID}, tradeID: ${transactionInfo.tradeID}` + `##INFO: completed asset-trade, businessLogicID: ${transactionInfo.businessLogicID}, tradeID: ${transactionInfo.tradeID}`, ); this.completedTransaction(tradeInfo); break; case AssetTradeStatus.Completed: logger.warn( - `##WARN: already completed, txinfo: ${json2str(transactionInfo)}` + `##WARN: already completed, txinfo: ${json2str(transactionInfo)}`, ); return; default: @@ -749,9 +814,9 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { } } catch (err) { logger.error( - `##ERR: executeNextTransaction(), err: ${err}, tx: ${json2str( - transactionInfo - )}` + `##ERR: executeNextTransaction(), err: ${err}, tx: ${JSON.stringify( + transactionInfo, + )}`, ); } } @@ -765,19 +830,19 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { } } - getOperationStatus(tradeID: string): object { + getOperationStatus(tradeID: string): TransactionStatusData { logger.debug(`##in getOperationStatus()`); - const businessLogicInquireAssetTradeStatus: BusinessLogicInquireAssetTradeStatus = - new BusinessLogicInquireAssetTradeStatus(); - const transactionStatusData = - businessLogicInquireAssetTradeStatus.getAssetTradeOperationStatus(tradeID); + const businessLogicInquireAssetTradeStatus: BusinessLogicInquireAssetTradeStatus = new BusinessLogicInquireAssetTradeStatus(); + const transactionStatusData = businessLogicInquireAssetTradeStatus.getAssetTradeOperationStatus( + tradeID, + ); return transactionStatusData; } getTxIDFromEvent( ledgerEvent: LedgerEvent, - targetIndex: number + targetIndex: number, ): string | null { logger.debug(`##in getTxIDFromEvent`); logger.debug(`##event: ${json2str(ledgerEvent)}`); @@ -789,13 +854,13 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { return this.getTxIDFromEventFabric(ledgerEvent.data, targetIndex); default: logger.error( - `##getTxIDFromEvent(): invalid verifierId: ${ledgerEvent.verifierId}` + `##getTxIDFromEvent(): invalid verifierId: ${ledgerEvent.verifierId}`, ); } return null; } - getTxIDFromEventEtherem(event: object, targetIndex: number): string | null { + getTxIDFromEventEtherem(event: EthEvent, targetIndex: number): string | null { logger.debug(`##in getTxIDFromEventEtherem()`); const tx = this.getTransactionFromEthereumEvent(event, targetIndex); if (tx == null) { @@ -809,8 +874,8 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { if (typeof txId !== "string") { logger.warn( `#getTxIDFromEventEtherem(): skip(invalid block, not found txId.), event: ${json2str( - event - )}` + event, + )}`, ); return null; } @@ -819,13 +884,16 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { return txId; } catch (err) { logger.error( - `##getTxIDFromEventEtherem(): err: ${err}, event: ${json2str(event)}` + `##getTxIDFromEventEtherem(): err: ${err}, event: ${json2str(event)}`, ); return null; } } - getTxIDFromEventFabric(event: object, targetIndex: number): string | null { + getTxIDFromEventFabric( + event: FabricEvent, + targetIndex: number, + ): string | null { logger.debug(`##in getTxIDFromEventFabric()`); const tx = this.getTransactionFromFabricEvent(event, targetIndex); if (tx == null) { @@ -839,8 +907,8 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { if (typeof txId !== "string") { logger.warn( `#getTxIDFromEventFabric(): skip(invalid block, not found txId.), event: ${json2str( - event - )}` + event, + )}`, ); return null; } @@ -849,7 +917,7 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { return txId; } catch (err) { logger.error( - `##getTxIDFromEventFabric(): err: ${err}, event: ${json2str(event)}` + `##getTxIDFromEventFabric(): err: ${err}, event: ${json2str(event)}`, ); return null; } @@ -857,15 +925,16 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { hasTxIDInTransactions(txID: string): boolean { logger.debug(`##in hasTxIDInTransactions(), txID: ${txID}`); - const transactionInfo = - this.transactionInfoManagement.getTransactionInfoByTxId(txID); + const transactionInfo = this.transactionInfoManagement.getTransactionInfoByTxId( + txID, + ); logger.debug(`##hasTxIDInTransactions(), ret: ${transactionInfo !== null}`); return transactionInfo !== null; } getEventDataNum(ledgerEvent: LedgerEvent): number { logger.debug( - `##in BLP:getEventDataNum(), ledgerEvent.verifierId: ${ledgerEvent.verifierId}` + `##in BLP:getEventDataNum(), ledgerEvent.verifierId: ${ledgerEvent.verifierId}`, ); const event = ledgerEvent.data; let retEventNum = 0; @@ -880,17 +949,17 @@ export class BusinessLogicAssetTrade extends BusinessLogicBase { break; default: logger.error( - `##getEventDataNum(): invalid verifierId: ${ledgerEvent.verifierId}` + `##getEventDataNum(): invalid verifierId: ${ledgerEvent.verifierId}`, ); break; } logger.debug( - `##getEventDataNum(): retEventNum: ${retEventNum}, verifierId: ${ledgerEvent.verifierId}` + `##getEventDataNum(): retEventNum: ${retEventNum}, verifierId: ${ledgerEvent.verifierId}`, ); return retEventNum; } catch (err) { logger.error( - `##getEventDataNum(): invalid even, err: ${err}, event: ${event}` + `##getEventDataNum(): invalid even, err: ${err}, event: ${event}`, ); return 0; } diff --git a/examples/cactus-example-discounted-asset-trade/business-logic-inquire-asset-trade-status.ts b/examples/cactus-example-discounted-asset-trade/business-logic-inquire-asset-trade-status.ts index 4755c4677e..bac25435da 100644 --- a/examples/cactus-example-discounted-asset-trade/business-logic-inquire-asset-trade-status.ts +++ b/examples/cactus-example-discounted-asset-trade/business-logic-inquire-asset-trade-status.ts @@ -18,7 +18,9 @@ export class BusinessLogicInquireAssetTradeStatus extends BusinessLogicBase { super(); } - getAssetTradeOperationStatus(tradeID: string): object { + getAssetTradeOperationStatus( + tradeID: string, + ): { stateInfo: number | undefined; transactionStatus: TransactionStatus[] } { // Existence check of table file try { fs.statSync(this.fileName); @@ -32,11 +34,10 @@ export class BusinessLogicInquireAssetTradeStatus extends BusinessLogicBase { .table as string[]; // Create Response Information - const resultTransactionStatusData: ResultTransactionStatusData = - new ResultTransactionStatusData(); + const resultTransactionStatusData: ResultTransactionStatusData = new ResultTransactionStatusData(); for (const transactionInfoJson of transactionInfoTable) { const transactionInfo: TransactionInfo = JSON.parse( - transactionInfoJson + transactionInfoJson, ) as TransactionInfo; // Determine if target record @@ -44,16 +45,15 @@ export class BusinessLogicInquireAssetTradeStatus extends BusinessLogicBase { // Set information resultTransactionStatusData.stateInfo = transactionInfo.status; - const escrowTransactionStatus: TransactionStatus = - new TransactionStatus(); + const escrowTransactionStatus: TransactionStatus = new TransactionStatus(); escrowTransactionStatus.state = "escrow"; escrowTransactionStatus.ledger = transactionInfo.escrowLedger; escrowTransactionStatus.txID = transactionInfo.escrowTxID; escrowTransactionStatus.txInfo = JSON.parse( - transactionInfo.escrowTxInfo + transactionInfo.escrowTxInfo, ); resultTransactionStatusData.transactionStatus.push( - escrowTransactionStatus + escrowTransactionStatus, ); const transferTransactionStatus = new TransactionStatus(); @@ -61,10 +61,10 @@ export class BusinessLogicInquireAssetTradeStatus extends BusinessLogicBase { transferTransactionStatus.ledger = transactionInfo.transferLedger; transferTransactionStatus.txID = transactionInfo.transferTxID; transferTransactionStatus.txInfo = JSON.parse( - transactionInfo.transferTxInfo + transactionInfo.transferTxInfo, ); resultTransactionStatusData.transactionStatus.push( - transferTransactionStatus + transferTransactionStatus, ); const settlementTransactionStatus = new TransactionStatus(); @@ -72,10 +72,10 @@ export class BusinessLogicInquireAssetTradeStatus extends BusinessLogicBase { settlementTransactionStatus.ledger = transactionInfo.settlementLedger; settlementTransactionStatus.txID = transactionInfo.settlementTxID; settlementTransactionStatus.txInfo = JSON.parse( - transactionInfo.settlementTxInfo + transactionInfo.settlementTxInfo, ); resultTransactionStatusData.transactionStatus.push( - settlementTransactionStatus + settlementTransactionStatus, ); break; diff --git a/examples/cactus-example-discounted-asset-trade/fabric-asset-management.ts b/examples/cactus-example-discounted-asset-trade/fabric-asset-management.ts index 077c096cd2..151c201e30 100644 --- a/examples/cactus-example-discounted-asset-trade/fabric-asset-management.ts +++ b/examples/cactus-example-discounted-asset-trade/fabric-asset-management.ts @@ -19,7 +19,7 @@ const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; export class FabricAssetManagement { - private connectInfo: LPInfoHolder = null; // connection information + private connectInfo: LPInfoHolder | null = null; // connection information private readonly verifierFactory: VerifierFactory; constructor() { @@ -30,7 +30,7 @@ export class FabricAssetManagement { ); } - queryAsset(assetID: string): Promise { + queryAsset(assetID: string): Promise { return new Promise((resolve, reject) => { const contract = { channelName: "mychannel", contractName: "basic" }; const method = { type: "evaluateTransaction", command: "ReadAsset" }; @@ -51,7 +51,7 @@ export class FabricAssetManagement { }); } - queryAllAssets(): Promise { + queryAllAssets(): Promise { return new Promise((resolve, reject) => { const contract = { channelName: "mychannel", contractName: "basic" }; const method = { type: "evaluateTransaction", command: "GetAllAssets" }; diff --git a/examples/cactus-example-discounted-asset-trade/fabric-asset.ts b/examples/cactus-example-discounted-asset-trade/fabric-asset.ts index 02838a1fd6..b5bf81001a 100644 --- a/examples/cactus-example-discounted-asset-trade/fabric-asset.ts +++ b/examples/cactus-example-discounted-asset-trade/fabric-asset.ts @@ -34,7 +34,9 @@ router.get("/:assetID", (req: Request, res: Response, next: NextFunction) => { logger.error(err); }); } catch (err) { - logger.error(`##(queryAsset)err name: ${err.constructor.name}`); + if (err instanceof Error) { + logger.error(`##(queryAsset)err name: ${err.constructor.name}`); + } if (err instanceof RIFError) { logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); @@ -63,7 +65,9 @@ router.get("/", (req: Request, res: Response, next: NextFunction) => { logger.error(err); }); } catch (err) { - logger.error(`##(queryAllAssets)err name: ${err.constructor.name}`); + if (err instanceof Error) { + logger.error(`##(queryAllAssets)err name: ${err.constructor.name}`); + } if (err instanceof RIFError) { logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); diff --git a/examples/cactus-example-discounted-asset-trade/package.json b/examples/cactus-example-discounted-asset-trade/package.json index 41f53f22ab..cac26bacb2 100644 --- a/examples/cactus-example-discounted-asset-trade/package.json +++ b/examples/cactus-example-discounted-asset-trade/package.json @@ -38,12 +38,6 @@ "xmlhttprequest": "1.8.0" }, "devDependencies": { - "@typescript-eslint/eslint-plugin": "4.33.0", - "@typescript-eslint/parser": "4.33.0", - "@types/escape-html": "1.0.1", - "eslint": "7.32.0", - "eslint-config-prettier": "8.4.0", - "eslint-plugin-prettier": "4.0.0", - "prettier": "2.5.1" + "@types/escape-html": "1.0.1" } } \ No newline at end of file diff --git a/examples/cactus-example-discounted-asset-trade/result-transactions-status-data.ts b/examples/cactus-example-discounted-asset-trade/result-transactions-status-data.ts index 78f64d3c2c..428f359e65 100644 --- a/examples/cactus-example-discounted-asset-trade/result-transactions-status-data.ts +++ b/examples/cactus-example-discounted-asset-trade/result-transactions-status-data.ts @@ -8,10 +8,9 @@ import { TransactionStatus } from "./transaction-status"; export class ResultTransactionStatusData { + stateInfo: number | undefined; + transactionStatus: TransactionStatus[]; constructor() { this.transactionStatus = []; } - - stateInfo: number; - transactionStatus: TransactionStatus[]; } 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 6c3b0c612b..8f9a58cc82 100644 --- a/examples/cactus-example-discounted-asset-trade/template-trade-management.ts +++ b/examples/cactus-example-discounted-asset-trade/template-trade-management.ts @@ -13,8 +13,6 @@ import { VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const fs = require("fs"); -const path = require("path"); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; const moduleName = "TemplateTradeManagement"; @@ -22,7 +20,7 @@ const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; export class TemplateTradeManagement { - private connectInfo: LPInfoHolder = null; // connection information + private connectInfo: LPInfoHolder | null = null; // connection information private readonly verifierFactory: VerifierFactory; constructor() { @@ -33,7 +31,10 @@ export class TemplateTradeManagement { ); } - execTemplateTrade(functionName: string, req: Request): Promise { + execTemplateTrade( + functionName: string, + req: Request, + ): Promise { return new Promise((resolve, reject) => { const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = {}; @@ -41,8 +42,8 @@ export class TemplateTradeManagement { const args = req.body.args; logger.debug( `##contract: ${contract}, method: ${JSON.stringify( - method - )}, template: ${template}, args: ${JSON.stringify(args)}` + method, + )}, template: ${template}, args: ${JSON.stringify(args)}`, ); // ex. @@ -54,10 +55,10 @@ export class TemplateTradeManagement { .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) .then((result) => { - const response = { - status: result.status, - result: JSON.stringify(result.data), - }; + // const response = { + // status: result.status, + // result: JSON.stringify(result.data), + // }; // resolve(response); resolve(result); }) @@ -74,12 +75,12 @@ export class TemplateTradeManagement { const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = {}; - const template = req.body.template; + // const template = req.body.template; const args = req.body.args; logger.debug( `##contract: ${contract}, method: ${method}, args: ${JSON.stringify( - args - )}` + args, + )}`, ); // ex. diff --git a/examples/cactus-example-discounted-asset-trade/template-trade.ts b/examples/cactus-example-discounted-asset-trade/template-trade.ts index 6083ab2c2b..cff352eb92 100644 --- a/examples/cactus-example-discounted-asset-trade/template-trade.ts +++ b/examples/cactus-example-discounted-asset-trade/template-trade.ts @@ -10,8 +10,6 @@ import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; import { RIFError } from "@hyperledger/cactus-cmd-socketio-server"; import { TemplateTradeManagement } from "./template-trade-management"; -const fs = require("fs"); -const path = require("path"); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; const moduleName = "template-trade"; @@ -19,8 +17,7 @@ const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; const router: Router = Router(); -const templateTradeManagement: TemplateTradeManagement = - new TemplateTradeManagement(); +const templateTradeManagement: TemplateTradeManagement = new TemplateTradeManagement(); /* POST template-trade. */ // router.post('/:functionName', (req: Request, res: Response, next: NextFunction) => { @@ -69,7 +66,9 @@ router.post( logger.error(err); }); } catch (err) { - logger.error(`##err name: ${err.constructor.name}`); + if (err instanceof Error) { + logger.error(`##err name: ${err.constructor.name}`); + } if (err instanceof RIFError) { logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); @@ -81,7 +80,7 @@ router.post( logger.error(`##err in balance: ${err}`); next(err); } - } + }, ); router.post( @@ -93,13 +92,15 @@ router.post( const tradeID: string = templateTradeManagement.execTemplateTradeAsync( functionName, - req + req, ); const result = { tradeID: tradeID }; //res.status(201).location(config.applicationHostInfo.hostName + "/api/v1/trades/" + tradeID).json(result); res.status(201).json(result); } catch (err) { - logger.error(`##err name: ${err.constructor.name}`); + if (err instanceof Error) { + logger.error(`##err name: ${err.constructor.name}`); + } if (err instanceof RIFError) { logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); @@ -111,7 +112,7 @@ router.post( logger.error(`##err in balance: ${err}`); next(err); } - } + }, ); export default router; diff --git a/examples/cactus-example-discounted-asset-trade/trades.ts b/examples/cactus-example-discounted-asset-trade/trades.ts index 7a5f968c2c..ac32b5159e 100644 --- a/examples/cactus-example-discounted-asset-trade/trades.ts +++ b/examples/cactus-example-discounted-asset-trade/trades.ts @@ -10,8 +10,7 @@ import { TransactionManagement } from "@hyperledger/cactus-cmd-socketio-server"; import { RIFError } from "@hyperledger/cactus-cmd-socketio-server"; import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; -const fs = require("fs"); -const path = require("path"); + import escapeHtml from "escape-html"; const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; @@ -20,8 +19,7 @@ const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; const router: Router = Router(); -export const transactionManagement: TransactionManagement = - new TransactionManagement(); +export const transactionManagement: TransactionManagement = new TransactionManagement(); // Request Execution of Trade router.post("/", (req: Request, res: Response, next: NextFunction) => { diff --git a/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts b/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts index ef83a38229..f88d211998 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-ethereum.ts @@ -16,14 +16,10 @@ import { VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const ethJsCommon = require("ethereumjs-common").default; -const ethJsTx = require("ethereumjs-tx").Transaction; -const libWeb3 = require("web3"); - -const fs = require("fs"); -const path = require("path"); -const yaml = require("js-yaml"); -//const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); +// const ethJsCommon = require("ethereumjs-common").default; +// const ethJsTx = require("ethereumjs-tx").Transaction; +// const libWeb3 = require("web3"); + const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; const moduleName = "TransactionEthereum"; @@ -43,34 +39,36 @@ export function makeRawTransaction(txParam: { toAddress: string; amount: number; gas: number; -}): Promise<{ data: {}; txId: string }> { +}): Promise<{ + data: { serializedTx: string }; + txId: string; +}> { return new Promise(async (resolve, reject) => { try { logger.debug(`makeRawTransaction: txParam: ${JSON.stringify(txParam)}`); getNewNonce(txParam.fromAddress).then((result) => { logger.debug( - `##makeRawTransaction(A): result: ${JSON.stringify(result)}` + `##makeRawTransaction(A): result: ${JSON.stringify(result)}`, ); const txnCountHex: string = result.txnCountHex; - const rawTx: { nonce: string; to: string; value: number; gas: number } = - { - nonce: txnCountHex, - to: txParam.toAddress, - value: txParam.amount, - gas: txParam.gas, - }; + const rawTx = { + nonce: txnCountHex, + to: txParam.toAddress, + value: txParam.amount, + gas: txParam.gas, + }; logger.debug( - `##makeRawTransaction(B), rawTx: ${JSON.stringify(rawTx)}` + `##makeRawTransaction(B), rawTx: ${JSON.stringify(rawTx)}`, ); const signedTx = TransactionSigner.signTxEthereum( rawTx, - txParam.fromAddressPkey + txParam.fromAddressPkey, ); - const resp: { data: {}; txId: string } = { + const resp = { data: { serializedTx: signedTx["serializedTx"] }, txId: signedTx["txId"], }; @@ -92,7 +90,7 @@ 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,37 +105,39 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { let txnCountHex: string = result.data.nonceHex; const latestNonce = getLatestNonce(fromAddress); - // logger.debug(`##getNewNonce(B): fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`); - if (txnCount <= latestNonce) { - // nonce correction - txnCount = latestNonce + 1; - logger.debug( - `##getNewNonce(C): Adjust txnCount, fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}` - ); - - const method = { type: "function", command: "toHex" }; - const args = { args: { args: [txnCount] } }; - - logger.debug(`##getNewNonce(D): call validator#toHex()`); - verifierFactory - .getVerifier("84jUisrs") - .sendSyncRequest(contract, method, args) - .then((result) => { - txnCountHex = result.data.hexStr; - logger.debug(`##getNewNonce(E): txnCountHex: ${txnCountHex}`); - - // logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`); - setLatestNonce(fromAddress, txnCount); - - return resolve({ txnCountHex: txnCountHex }); - }); - } else { - // logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`); - setLatestNonce(fromAddress, txnCount); - - logger.debug(`##getNewNonce(G): txnCountHex: ${txnCountHex}`); - return resolve({ txnCountHex: txnCountHex }); + if (latestNonce) { + if (txnCount <= latestNonce && latestNonce) { + // nonce correction + txnCount = latestNonce + 1; + logger.debug( + `##getNewNonce(C): Adjust txnCount, fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`, + ); + + const method = { type: "function", command: "toHex" }; + const args = { args: { args: [txnCount] } }; + + logger.debug(`##getNewNonce(D): call validator#toHex()`); + verifierFactory + .getVerifier("84jUisrs") + .sendSyncRequest(contract, method, args) + .then((result) => { + txnCountHex = result.data.hexStr; + logger.debug(`##getNewNonce(E): txnCountHex: ${txnCountHex}`); + + // logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`); + setLatestNonce(fromAddress, txnCount); + + return resolve({ txnCountHex: txnCountHex }); + }); + } else { + // logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`); + setLatestNonce(fromAddress, txnCount); + + logger.debug(`##getNewNonce(G): txnCountHex: ${txnCountHex}`); + return resolve({ txnCountHex: txnCountHex }); + } } + // logger.debug(`##getNewNonce(B): fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`); }); } catch (err) { logger.error(err); @@ -146,7 +146,7 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { }); } -function getLatestNonce(fromAddress: string): number { +function getLatestNonce(fromAddress: string): number | undefined { if (mapFromAddressNonce.has(fromAddress)) { return mapFromAddressNonce.get(fromAddress); } diff --git a/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts b/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts index d5d431ea99..8ce9f90eb8 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-fabric.ts @@ -18,9 +18,6 @@ import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; import { Verifier } from "@hyperledger/cactus-verifier-client"; -const fs = require("fs"); -const path = require("path"); -const yaml = require("js-yaml"); import { FileSystemWallet } from "fabric-network"; //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); @@ -30,15 +27,25 @@ const moduleName = "TransactionFabric"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; +interface SendSyncRequestResult { + data: { + signedCommitProposal: { + signature: string | Buffer; + proposal_bytes: string | Buffer; + }; + }; + txId: string; +} + export function makeSignedProposal( ccFncName: string, ccArgs: string[], verifierFabric: Verifier, -): Promise<{ data: {}; txId: string }> { +): Promise { // exports.Invoke = async function(reqBody, isWait){ // let eventhubs = []; // For the time being, give up the eventhub connection of multiple peers. - let invokeResponse; // Return value from chain code - let channel; + // let invokeResponse; // Return value from chain code + // let channel; return new Promise(async (resolve, reject) => { try { @@ -57,7 +64,9 @@ export function makeSignedProposal( let certPem = undefined; let privateKeyPem = undefined; const submitter = config.assetTradeInfo.fabric.submitter.name; - const wallet = new FileSystemWallet(config.assetTradeInfo.fabric.keystore); + const wallet = new FileSystemWallet( + config.assetTradeInfo.fabric.keystore, + ); logger.debug(`Wallet path: ${config.assetTradeInfo.fabric.keystore}`); const submitterExists = await wallet.exists(submitter); @@ -68,10 +77,18 @@ export function makeSignedProposal( } // const signedTx = await TransactionSigner.signTxFabric(transactionProposalReq, certPem, privateKeyPem); - const contract = { channelName: config.assetTradeInfo.fabric.channelName }; + const contract = { + channelName: config.assetTradeInfo.fabric.channelName, + }; const method = { type: "function", command: "sendSignedProposal" }; - const template = "default"; - const argsParam: {} = { + // const template = "default"; + const argsParam: { + args: { + transactionProposalReq: Record; + certPem: undefined; + privateKeyPem: undefined; + }; + } = { args: { transactionProposalReq: transactionProposalReq, certPem: certPem, @@ -85,13 +102,13 @@ export function makeSignedProposal( // logger.debug(`##makeSignedProposal: resp.data: ${JSON.stringify(resp.data)}`); logger.debug(`Successfully build endorse and commit`); - const args: {} = { + const args = { // signedCommitProposal: resp["signedCommitProposal"], signedCommitProposal: resp.data["signedCommitProposal"], // commitReq: resp["commitReq"] commitReq: resp.data["commitReq"], }; - const result: { data: {}; txId: string } = { + const result: SendSyncRequestResult = { data: args, // txId: resp["txId"] txId: resp.data["txId"], diff --git a/examples/cactus-example-discounted-asset-trade/transaction-indy.ts b/examples/cactus-example-discounted-asset-trade/transaction-indy.ts index ea767a620f..e45a4f9ce0 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-indy.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-indy.ts @@ -15,15 +15,12 @@ import { VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const libWeb3 = require("web3"); +// const libWeb3 = require("web3"); -const fs = require("fs"); -const path = require("path"); -const yaml = require("js-yaml"); //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; -import { stringify } from "querystring"; +// import { stringify } from "querystring"; const moduleName = "TransactionIndy"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; @@ -34,11 +31,13 @@ const verifierFactory = new VerifierFactory( config.logLevel, ); - export function getDataFromIndy( - arg_request: {}, - identifier: string -): Promise<{}> { + arg_request: { + did: string | null; + schemaId: string; + }, + identifier: string, +): Promise<{ data: string[] }> { return new Promise(async (resolve, reject) => { try { logger.debug(`getDataFromIndy: arg_request: ${arg_request}`); @@ -55,23 +54,26 @@ export function getDataFromIndy( } // convert response to list value -function convertResponse(response) { - logger.debug("called convertResponse"); +// function convertResponse(response) { +// logger.debug("called convertResponse"); - logger.debug(`##convertResponse response: ${JSON.stringify(response)}`); - const responseObj = response["data"]; +// logger.debug(`##convertResponse response: ${JSON.stringify(response)}`); +// const responseObj = response["data"]; - logger.debug(`##responseObj : ${responseObj}`); +// logger.debug(`##responseObj : ${responseObj}`); - const receivedId = responseObj[0]; - const receivedData = responseObj[1]; - const result = { receivedId: receivedId, receivedData: receivedData }; +// const receivedId = responseObj[0]; +// const receivedData = responseObj[1]; +// const result = { receivedId: receivedId, receivedData: receivedData }; - logger.debug(`##convertResponse response: ${JSON.stringify(result)}`); - return result; -} +// logger.debug(`##convertResponse response: ${JSON.stringify(result)}`); +// return result; +// } -function sendRequest(arg_request: {}, identifier: string): Promise<{}> { +function sendRequest( + arg_request: Record, + identifier: string, +): Promise<{ data: string[] }> { return new Promise(async (resolve, reject) => { try { logger.debug(`##sendRequest: arg_request: ${arg_request}`); @@ -89,7 +91,7 @@ function sendRequest(arg_request: {}, identifier: string): Promise<{}> { contractName: "indysomething", }; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "evaluateTransaction", command: commandName }; - const template = "default"; + // const template = "default"; const args = { args: arg_request }; diff --git a/examples/cactus-example-discounted-asset-trade/transaction-info-management.ts b/examples/cactus-example-discounted-asset-trade/transaction-info-management.ts index 1c2251ec62..b56e4487b4 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-info-management.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-info-management.ts @@ -12,8 +12,6 @@ import { TradeInfo, ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; import { AssetTradeStatus } from "./define"; const fs = require("fs"); -const path = require("path"); -const yaml = require("js-yaml"); //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; @@ -21,21 +19,27 @@ const moduleName = "TransactionInfoManagement"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; +interface TransactionInfoTable { + table: string[]; +} + // Transaction Information Management Class export class TransactionInfoManagement { fileName = "transaction-Info.json"; - constructor() {} + constructor() { + // Do nothing + } // For debugging - fileDump() { + fileDump(): void { const confirmData: string = fs.readFileSync(this.fileName, "utf8"); const arrayData: TransactionInfo[] = JSON.parse(confirmData) .table as TransactionInfo[]; - // logger.debug(arrayData); + logger.debug(arrayData); } - addTransactionInfo(transactionInfo: TransactionInfo) { + addTransactionInfo(transactionInfo: TransactionInfo): void { // Existence check of table file try { fs.statSync(this.fileName); @@ -50,23 +54,24 @@ export class TransactionInfoManagement { const transactionInfoJson: string = JSON.stringify(transactionInfo); - let transactionInfoTable = { + let transactionInfoTable: TransactionInfoTable = { table: [], }; const transactionInfoFileData: string = fs.readFileSync( this.fileName, - "utf8" + "utf8", ); transactionInfoTable = JSON.parse(transactionInfoFileData); transactionInfoTable.table.push(transactionInfoJson); - const transactionInfoTableJson: string = - JSON.stringify(transactionInfoTable); + const transactionInfoTableJson: string = JSON.stringify( + transactionInfoTable, + ); fs.writeFileSync(this.fileName, transactionInfoTableJson, "utf8"); this.fileDump(); } - setStatus(tradeInfo: TradeInfo, status: AssetTradeStatus) { + setStatus(tradeInfo: TradeInfo, status: AssetTradeStatus): void { // Existence check of table file try { fs.statSync(this.fileName); @@ -80,12 +85,12 @@ export class TransactionInfoManagement { .table as string[]; // Search target records / replace data - const transactionInfoTableNew = { + const transactionInfoTableNew: TransactionInfoTable = { table: [], }; - transactionInfoTable.forEach((transactionInfoJSON, index) => { + transactionInfoTable.forEach((transactionInfoJSON) => { const transactionInfo: TransactionInfo = JSON.parse( - transactionInfoJSON + transactionInfoJSON, ) as TransactionInfo; // Determine if it is a target record @@ -104,14 +109,17 @@ export class TransactionInfoManagement { // Table File Write const transactionInfoTableNewJson: string = JSON.stringify( - transactionInfoTableNew + transactionInfoTableNew, ); fs.writeFileSync(this.fileName, transactionInfoTableNewJson, "utf8"); this.fileDump(); } - setTransactionData(tradeInfo: TradeInfo, transactionData: TransactionData) { + setTransactionData( + tradeInfo: TradeInfo, + transactionData: TransactionData, + ): void { // Existence check of table file try { fs.statSync(this.fileName); @@ -125,12 +133,12 @@ export class TransactionInfoManagement { .table as string[]; // Search target records / replace data - const transactionInfoTableNew = { + const transactionInfoTableNew: TransactionInfoTable = { table: [], }; - transactionInfoTable.forEach((transactionInfoJSON, index) => { + transactionInfoTable.forEach((transactionInfoJSON) => { const transactionInfo: TransactionInfo = JSON.parse( - transactionInfoJSON + transactionInfoJSON, ) as TransactionInfo; // Determine if it is a target record @@ -161,14 +169,14 @@ export class TransactionInfoManagement { // Table File Write const transactionInfoTableNewJson: string = JSON.stringify( - transactionInfoTableNew + transactionInfoTableNew, ); fs.writeFileSync(this.fileName, transactionInfoTableNewJson, "utf8"); this.fileDump(); } - setTxInfo(tradeInfo: TradeInfo, txInfoData: TxInfoData) { + setTxInfo(tradeInfo: TradeInfo, txInfoData: TxInfoData): void { // Existence check of table file try { fs.statSync(this.fileName); @@ -182,12 +190,12 @@ export class TransactionInfoManagement { .table as string[]; // Search target records / replace data - const transactionInfoTableNew = { + const transactionInfoTableNew: TransactionInfoTable = { table: [], }; - transactionInfoTable.forEach((transactionInfoJSON, index) => { + transactionInfoTable.forEach((transactionInfoJSON) => { const transactionInfo: TransactionInfo = JSON.parse( - transactionInfoJSON + transactionInfoJSON, ) as TransactionInfo; // Determine if it is a target record @@ -215,7 +223,7 @@ export class TransactionInfoManagement { // Table File Write const transactionInfoTableNewJson: string = JSON.stringify( - transactionInfoTableNew + transactionInfoTableNew, ); fs.writeFileSync(this.fileName, transactionInfoTableNewJson, "utf8"); @@ -229,7 +237,7 @@ export class TransactionInfoManagement { * @return Transaction data corresponding to txId. Returns null if it does not exist. * */ - getTransactionInfoByTxId(txId: string): TransactionInfo { + getTransactionInfoByTxId(txId: string): TransactionInfo | null { // Existence check of table file try { fs.statSync(this.fileName); @@ -243,13 +251,14 @@ export class TransactionInfoManagement { .table as string[]; // Search target records - const transactionInfoTableNew = { - table: [], - }; + // const transactionInfoTableNew: TransactionInfoTable = { + // table: [], + // }; + let retTransactionInfo: TransactionInfo | null = null; - transactionInfoTable.forEach((transactionInfoJSON, index) => { + transactionInfoTable.forEach((transactionInfoJSON) => { const transactionInfo: TransactionInfo = JSON.parse( - transactionInfoJSON + transactionInfoJSON, ) as TransactionInfo; // Determine if it is a target record diff --git a/examples/cactus-example-discounted-asset-trade/transaction-info.ts b/examples/cactus-example-discounted-asset-trade/transaction-info.ts index dcc1dfa9a6..c7d73324d5 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-info.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-info.ts @@ -8,32 +8,34 @@ import { RequestInfo } from "@hyperledger/cactus-cmd-socketio-server"; export class TransactionInfo { - businessLogicID: string; - tradeID: string; - ethereumAccountFrom: string; - ethereumAccountTo: string; - ethereumAccountFromKey: string; - ethereumAccountToKey: string; - fabricAccountFrom: string; - fabricAccountTo: string; - fabricAccountFromKey: string; - fabricAccountToKey: string; - tradingValue: string; - assetID: string; - status: number; - escrowLedger: string; - escrowTxID: string; - escrowTxInfo: string; - transferLedger: string; - transferTxID: string; - transferTxInfo: string; - settlementLedger: string; - settlementTxID: string; - settlementTxInfo: string; + businessLogicID = ""; + tradeID = ""; + ethereumAccountFrom = ""; + ethereumAccountTo = ""; + ethereumAccountFromKey = ""; + ethereumAccountToKey = ""; + fabricAccountFrom = ""; + fabricAccountTo = ""; + fabricAccountFromKey = ""; + fabricAccountToKey = ""; + tradingValue = ""; + assetID = ""; + status = 0; + escrowLedger = ""; + escrowTxID = ""; + escrowTxInfo = ""; + transferLedger = ""; + transferTxID = ""; + transferTxInfo = ""; + settlementLedger = ""; + settlementTxID = ""; + settlementTxInfo = ""; - constructor() {} + constructor() { + // Do nothing + } - setRequestInfo(mode: number, requestInfo: RequestInfo) { + setRequestInfo(mode: number, requestInfo: RequestInfo): void { // Set request information this.businessLogicID = requestInfo.businessLogicID; this.tradeID = requestInfo.tradeID; @@ -48,16 +50,16 @@ export class TransactionInfo { if (mode === 0) { // init mode // Initialize anything other than request information - this.status = null; - this.escrowLedger = null; - this.escrowTxID = null; - this.escrowTxInfo = null; - this.transferLedger = null; - this.transferTxID = null; - this.transferTxInfo = null; - this.settlementLedger = null; - this.settlementTxID = null; - this.settlementTxInfo = null; + this.status = 0; + this.escrowLedger = ""; + this.escrowTxID = ""; + this.escrowTxInfo = ""; + this.transferLedger = ""; + this.transferTxID = ""; + this.transferTxInfo = ""; + this.settlementLedger = ""; + this.settlementTxID = ""; + this.settlementTxInfo = ""; } } } diff --git a/examples/cactus-example-discounted-asset-trade/transaction-status.ts b/examples/cactus-example-discounted-asset-trade/transaction-status.ts index f9118efa05..cd50f2f587 100644 --- a/examples/cactus-example-discounted-asset-trade/transaction-status.ts +++ b/examples/cactus-example-discounted-asset-trade/transaction-status.ts @@ -6,8 +6,8 @@ */ export class TransactionStatus { - state: string; - ledger: string; - txID: string; - txInfo: string; // JSON string + state = ""; + ledger = ""; + txID = ""; + txInfo = ""; // JSON string } diff --git a/examples/cactus-example-discounted-asset-trade/tsconfig.json b/examples/cactus-example-discounted-asset-trade/tsconfig.json index 42f82ee7c4..dd6ddc0203 100644 --- a/examples/cactus-example-discounted-asset-trade/tsconfig.json +++ b/examples/cactus-example-discounted-asset-trade/tsconfig.json @@ -4,7 +4,6 @@ "composite": true, "outDir": "./dist/", "tsBuildInfoFile": "../../.build-cache/cactus-example-discounted-asset-trade.tsbuildinfo", - "strict": false // TODO - true, fix warnings }, "include": [ "./*.ts", diff --git a/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/RequestInfo.ts b/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/RequestInfo.ts index 2c2fa75027..6d2878be47 100644 --- a/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/RequestInfo.ts +++ b/packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/RequestInfo.ts @@ -6,14 +6,20 @@ */ // transaction information -class TradeInfo { + +export class ProofJsonObj { + tradeInfo = ""; + proof_request = ""; + proof = ""; +} +export class TradeInfo { ethereumAccountFrom: string = ""; ethereumAccountTo: string = ""; fabricAccountFrom: string = ""; fabricAccountTo: string = ""; tradingValue: string = ""; assetID: string = ""; - proofJson: object = {}; + proofJson: ProofJsonObj = new ProofJsonObj(); } // authorization information diff --git a/packages/cactus-cmd-socketio-server/src/main/typescript/util/TransactionSigner.ts b/packages/cactus-cmd-socketio-server/src/main/typescript/util/TransactionSigner.ts index 6580d4e62e..268b82f3f0 100644 --- a/packages/cactus-cmd-socketio-server/src/main/typescript/util/TransactionSigner.ts +++ b/packages/cactus-cmd-socketio-server/src/main/typescript/util/TransactionSigner.ts @@ -17,7 +17,7 @@ const yaml = require("js-yaml"); const config: any = ConfigUtil.getConfig(); // const configVerifier: any = yaml.safeLoad(fs.readFileSync("", 'utf8')); const configVerifier: ValidatorRegistry = new ValidatorRegistry( - path.resolve(__dirname, "/etc/cactus/validator-registry-config.yaml") + path.resolve(__dirname, "/etc/cactus/validator-registry-config.yaml"), ); import { getLogger } from "log4js"; const moduleName = "TransactionEthereum"; @@ -38,7 +38,13 @@ const EC = elliptic.ec; let fabricChannel: any = undefined; export class TransactionSigner { - static signTxEthereum(rawTx: object, signPkey: string): object { + static signTxEthereum( + rawTx: object, + signPkey: string, + ): { + serializedTx: string; + txId: string; + } { logger.debug(`####in signTxEthereum()`); // ethereumjs-tx2.1.2_support const customCommon = ethJsCommon.forCustomChain( @@ -185,9 +191,10 @@ export class TransactionSigner { // stand alone fabric-sig package in future. static _preventMalleability( sig: any, - curveParams: {name: keyof (typeof TransactionSigner.ordersForCurve)}, + curveParams: { name: keyof typeof TransactionSigner.ordersForCurve }, ) { - const halfOrder: any = TransactionSigner.ordersForCurve[curveParams.name].halfOrder; + const halfOrder: any = + TransactionSigner.ordersForCurve[curveParams.name].halfOrder; if (!halfOrder) { throw new Error( 'Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + @@ -214,7 +221,12 @@ export class TransactionSigner { * @param {string} privateKey PEM encoded private key * @param {Buffer} proposalBytes proposal bytes */ - static sign(privateKey: any, proposalBytes: any, algorithm: any, keySize: any) { + static sign( + privateKey: any, + proposalBytes: any, + algorithm: any, + keySize: any, + ) { const hashAlgorithm = algorithm.toUpperCase(); const hashFunction = hash[`${hashAlgorithm}_${keySize}`]; const ecdsaCurve = elliptic.curves[`p${keySize}`];