diff --git a/examples/cactus-example-electricity-trade/BalanceManagement.ts b/examples/cactus-example-electricity-trade/BalanceManagement.ts index 2eaf10e66b..fcd4c034e7 100644 --- a/examples/cactus-example-electricity-trade/BalanceManagement.ts +++ b/examples/cactus-example-electricity-trade/BalanceManagement.ts @@ -20,8 +20,13 @@ const moduleName = "BalanceManagement"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; +export interface BalanceResponse { + status: string | number; + amount: number; +} + export class BalanceManagement { - private connectInfo: LPInfoHolder = null; // connection information + private connectInfo: LPInfoHolder | null = null; // connection information private readonly verifierFactory: VerifierFactory; constructor() { @@ -32,19 +37,12 @@ export class BalanceManagement { ); } - getBalance(account: string): Promise { + getBalance(account: string): Promise { return new Promise((resolve, reject) => { - // for LedgerOperation - // const execData = {"referedAddress": account}; - // const ledgerOperation: LedgerOperation = new LedgerOperation("getNumericBalance", "", execData); - // 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]}}; this.verifierFactory .getVerifier("84jUisrs") diff --git a/examples/cactus-example-electricity-trade/BusinessLogicElectricityTrade.ts b/examples/cactus-example-electricity-trade/BusinessLogicElectricityTrade.ts index 3e05ecee68..2f375d9c0b 100644 --- a/examples/cactus-example-electricity-trade/BusinessLogicElectricityTrade.ts +++ b/examples/cactus-example-electricity-trade/BusinessLogicElectricityTrade.ts @@ -20,10 +20,8 @@ import { } from "@hyperledger/cactus-cmd-socketio-server"; import { makeRawTransaction } from "./TransactionEthereum"; -const fs = require("fs"); -const yaml = require("js-yaml"); //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); -const config: any = ConfigUtil.getConfig(); +const config: any = ConfigUtil.getConfig() as any; import { getLogger } from "log4js"; import { VerifierFactory, @@ -39,6 +37,27 @@ const routesVerifierFactory = new VerifierFactory( config.logLevel, ); +interface SawtoothEventData { + status: number | string; + blockData: []; +} + +interface EthData { + hash: string; +} + +interface EthEvent { + blockData: { transactions: { [key: string]: EthData } }; + hash: string; + status: number; +} + +interface SawtoothBlockDataData { + header_signature: string; + hash: string; + payload_decoded: { Verb: string; Name: string; Value: string }[]; +} + export class BusinessLogicElectricityTrade extends BusinessLogicBase { businessLogicID: string; meterManagement: MeterManagement; @@ -49,7 +68,11 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { this.meterManagement = new MeterManagement(); } - startTransaction(req: Request, businessLogicID: string, tradeID: string) { + startTransaction( + req: Request, + businessLogicID: string, + tradeID: string, + ): void { logger.debug("called startTransaction()"); // set RequestInfo @@ -68,7 +91,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { this.startMonitor(tradeInfo); } - startMonitor(tradeInfo: TradeInfo) { + startMonitor(tradeInfo: TradeInfo): void { // Get Verifier Instance logger.debug( `##startMonitor(): businessLogicID: ${tradeInfo.businessLogicID}`, @@ -94,7 +117,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { logger.debug("getVerifierSawtooth"); } - remittanceTransaction(transactionSubset: object) { + remittanceTransaction(transactionSubset: Record): void { logger.debug( `called remittanceTransaction(), accountInfo = ${json2str( transactionSubset, @@ -140,17 +163,21 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { ); logger.debug("getVerifierEthereum"); + interface RawTransationResultData { + args: unknown; + } // Generate parameters for// sendRawTransaction logger.debug(`####exec makeRawTransaction!!`); makeRawTransaction(txParam) .then((result) => { logger.info("remittanceTransaction txId : " + result.txId); - // Set Parameter logger.debug("remittanceTransaction data : " + json2str(result.data)); const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "web3Eth", command: "sendRawTransaction" }; - const args = { args: [result.data["serializedTx"]] }; + const args: RawTransationResultData = { + args: [result.data["serializedTx"]], + }; // Run Verifier (Ethereum) verifierEthereum @@ -179,6 +206,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { break; case config.electricityTradeInfo.ethereum.validatorID: this.onEventEthereum(ledgerEvent.data, targetIndex); + break; default: logger.error( @@ -188,7 +216,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } } - onEventSawtooth(event: object, targetIndex: number): void { + onEventSawtooth(event: SawtoothEventData, targetIndex: number): void { logger.debug(`##in onEventSawtooth()`); const tx = this.getTransactionFromSawtoothEvent(event, targetIndex); if (tx == null) { @@ -216,15 +244,18 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } getTransactionFromSawtoothEvent( - event: object, - targetIndex: number, - ): object | null { + event: SawtoothEventData, + targetIndex: number | string, + ): SawtoothBlockDataData | undefined { try { - const retTransaction = event["blockData"][targetIndex]; - logger.debug( - `##getTransactionFromSawtoothEvent(), retTransaction: ${retTransaction}`, - ); - return retTransaction; + if (typeof targetIndex === "number") { + const retTransaction = event["blockData"][targetIndex]; + + logger.debug( + `##getTransactionFromSawtoothEvent(), retTransaction: ${retTransaction}`, + ); + return retTransaction; + } } catch (err) { logger.error( `##getTransactionFromSawtoothEvent(): invalid even, err:${err}, event:${event}`, @@ -232,7 +263,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } } - onEventEthereum(event: object, targetIndex: number): void { + onEventEthereum(event: EthEvent, targetIndex: number): void { logger.debug(`##in onEventEthereum()`); const tx = this.getTransactionFromEthereumEvent(event, targetIndex); if (tx == null) { @@ -243,6 +274,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { try { const txId = tx["hash"]; const status = event["status"]; + logger.debug(`##txId = ${txId}`); logger.debug(`##status =${status}`); @@ -260,15 +292,16 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } getTransactionFromEthereumEvent( - event: object, + event: EthEvent, targetIndex: number, - ): object | null { + ): EthData | undefined { try { const retTransaction = event["blockData"]["transactions"][targetIndex]; logger.debug( `##getTransactionFromEthereumEvent(), retTransaction: ${retTransaction}`, ); return retTransaction; + // return (retTransaction as unknown) as EthEvent; } catch (err) { logger.error( `##getTransactionFromEthereumEvent(): invalid even, err:${err}, event:${event}`, @@ -276,7 +309,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } } - getOperationStatus(tradeID: string): object { + getOperationStatus(): Record { logger.debug(`##in getOperationStatus()`); return {}; } @@ -301,7 +334,10 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { return null; } - getTxIDFromEventSawtooth(event: object, targetIndex: number): string | null { + getTxIDFromEventSawtooth( + event: SawtoothEventData, + targetIndex: number | string, + ): string | null { logger.debug(`##in getTxIDFromEventSawtooth()`); const tx = this.getTransactionFromSawtoothEvent(event, targetIndex); if (tx == null) { @@ -331,7 +367,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } } - 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) { @@ -348,10 +384,12 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { event, )}`, ); + return null; } logger.debug(`###getTxIDFromEventEtherem(): txId: ${txId}`); + return txId; } catch (err) { logger.error( @@ -369,6 +407,8 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { let retEventNum = 0; try { + logger.error(ledgerEvent.data); + switch (ledgerEvent.verifierId) { case config.electricityTradeInfo.sawtooth.validatorID: retEventNum = event["blockData"].length; @@ -394,8 +434,10 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { } } - getAccountInfo(transactionSubset: object): object { - const transactionInfo = {}; + getAccountInfo( + transactionSubset: Record, + ): Record { + const transactionInfo: Record = {}; // Get Meter Information. const meterInfo: MeterInfo | null = this.meterManagement.getMeterInfo( @@ -417,12 +459,12 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { return transactionInfo; } - setConfig(meterParams: string[]): object { + setConfig(meterParams: string[]): Record { logger.debug("called setConfig()"); // 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-electricity-trade/MeterManagement.ts b/examples/cactus-example-electricity-trade/MeterManagement.ts index fab561f02c..5d8050b5a2 100644 --- a/examples/cactus-example-electricity-trade/MeterManagement.ts +++ b/examples/cactus-example-electricity-trade/MeterManagement.ts @@ -8,7 +8,6 @@ import { MeterInfo } from "./MeterInfo"; import { ConfigUtil } from "@hyperledger/cactus-cmd-socketio-server"; const fs = require("fs"); -const yaml = require("js-yaml"); const config: any = ConfigUtil.getConfig(); import { getLogger } from "log4js"; const moduleName = "MeterManagement"; @@ -19,16 +18,18 @@ logger.level = config.logLevel; export class MeterManagement { fileName = "MeterInfo.json"; - constructor() {} + constructor() { + // do nothing. + } // For debugging - fileDump() { + fileDump(): void { const confirmData: string = fs.readFileSync(this.fileName, "utf8"); const arrayData: MeterInfo[] = JSON.parse(confirmData).table as MeterInfo[]; logger.debug(arrayData); } - addMeterInfo(addMeterInfo: MeterInfo): object { + addMeterInfo(addMeterInfo: MeterInfo): Record { // Existence check of table file try { fs.statSync(this.fileName); @@ -47,12 +48,12 @@ export class MeterManagement { .table as string[]; // Search target records / replace data - const meterInfoTableNew = { + const meterInfoTableNew: Record = { table: [], }; let existFlag = false; let action = ""; - meterInfoTable.forEach((meterInfoJSON, index) => { + meterInfoTable.forEach((meterInfoJSON) => { const meterInfo: MeterInfo = JSON.parse(meterInfoJSON) as MeterInfo; // Determine if it is a target record @@ -90,7 +91,7 @@ export class MeterManagement { return result; } - getMeterInfo(meterID: string): MeterInfo { + getMeterInfo(meterID: string): MeterInfo | null { // Existence check of table file try { fs.statSync(this.fileName); @@ -105,7 +106,7 @@ export class MeterManagement { // Search target records let retMeterInfo: MeterInfo | null = null; - meterInfoTable.forEach((meterInfoJSON, index) => { + meterInfoTable.forEach((meterInfoJSON) => { const meterInfo: MeterInfo = JSON.parse(meterInfoJSON) as MeterInfo; // Determine if it is a target record diff --git a/examples/cactus-example-electricity-trade/README.md b/examples/cactus-example-electricity-trade/README.md index 48c33ee625..504afda4db 100644 --- a/examples/cactus-example-electricity-trade/README.md +++ b/examples/cactus-example-electricity-trade/README.md @@ -8,6 +8,7 @@ In this example, we use the Sawtooth intkey transaction processor as an applicat ![electricity-trade image](./images/electricity-trade-image.png) ## Required software components + - OS: Linux (recommend: Ubuntu18.04 or CentOS7) - Docker (recommend: v17.06.2-ce or greater) - Docker-compose (recommend: v1.14.0 or greater) @@ -16,21 +17,23 @@ In this example, we use the Sawtooth intkey transaction processor as an applicat ## Prerequisites - Available ports: - - `5034`: the port of `cactus-cmd-socketio-server` - - `5050`: the port of `cactus-plugin-ledger-connector-go-ethereum-socketio` - - `5140`: the port of `cactus-plugin-ledger-connector-sawtooth-socketio` - - You can modify port exported to the host in `./docker-compose.yml` + - `5034`: the port of `cactus-cmd-socketio-server` + - `5050`: the port of `cactus-plugin-ledger-connector-go-ethereum-socketio` + - `5140`: the port of `cactus-plugin-ledger-connector-sawtooth-socketio` + - You can modify port exported to the host in `./docker-compose.yml` - Available directory (This directory must be empty): - `./etc/cactus`: the directory for storing the config files of `cactus-cmd-socketio-server`, will be mounted by the containers. ## Setup + 1. Configure Cactus: - ``` - # execute in root cactus dir - pushd ../.. - npm run configure - popd - ``` + + ``` + # execute in root cactus dir + pushd ../.. + npm run configure + popd + ``` 1. Start the ledgers: ``` @@ -43,83 +46,88 @@ In this example, we use the Sawtooth intkey transaction processor as an applicat - `geth1` 1. Launch electricity-trade and validators from local `docker-compose.yml` (use separate console for that, docker-compose will block your prompt): - ``` - docker-compose build && docker-compose up - # or - npm run start - ``` - - This will build and launch all needed containers, the final output should look like this: - ``` - cmd-socketio-base-dummy | OK - Exit - cmd-socketio-base-dummy exited with code 0 - cactus-example-electricity-trade-ethereum-validator | - cactus-example-electricity-trade-ethereum-validator | > @hyperledger/cactus-plugin-ledger-connector-go-ethereum-socketio@1.0.0-rc.3 start /root/cactus - cactus-example-electricity-trade-ethereum-validator | > cd ./dist && node common/core/bin/www.js - cactus-example-electricity-trade-ethereum-validator | - cactus-example-electricity-trade-ethereum-validator | listening on *:5050 - cactus-example-electricity-trade-sawtooth-validator | - cactus-example-electricity-trade-sawtooth-validator | > @hyperledger/cactus-plugin-ledger-connector-sawtooth-socketio@1.0.0-rc.3 start /root/cactus - cactus-example-electricity-trade-sawtooth-validator | > cd ./dist && node common/core/bin/www.js - cactus-example-electricity-trade-sawtooth-validator | - cactus-example-electricity-trade-sawtooth-validator | listening on *:5140 - cactus-example-electricity-trade-blp | [2022-02-14T15:47:47.312] [INFO] www - Using BLP with id = h40Q9eMD - cactus-example-electricity-trade-blp | start Dynamic loading. - cactus-example-electricity-trade-blp | path: /api/v1/bl/cactus-example-electricity-trade/, routerJs: /root/cactus/dist/cactus-example-electricity-trade.js - cactus-example-electricity-trade-blp | path: /api/v1/bl/balance/, routerJs: /root/cactus/dist/balance.js - cactus-example-electricity-trade-blp | [2022-02-14T15:47:47.399] [INFO] www - listening on *: 5034 - ``` + ``` + docker-compose build && docker-compose up + # or + npm run start + ``` + + This will build and launch all needed containers, the final output should look like this: + + ``` + cmd-socketio-base-dummy | OK - Exit + cmd-socketio-base-dummy exited with code 0 + cactus-example-electricity-trade-ethereum-validator | + cactus-example-electricity-trade-ethereum-validator | > @hyperledger/cactus-plugin-ledger-connector-go-ethereum-socketio@1.0.0-rc.3 start /root/cactus + cactus-example-electricity-trade-ethereum-validator | > cd ./dist && node common/core/bin/www.js + cactus-example-electricity-trade-ethereum-validator | + cactus-example-electricity-trade-ethereum-validator | listening on *:5050 + cactus-example-electricity-trade-sawtooth-validator | + cactus-example-electricity-trade-sawtooth-validator | > @hyperledger/cactus-plugin-ledger-connector-sawtooth-socketio@1.0.0-rc.3 start /root/cactus + cactus-example-electricity-trade-sawtooth-validator | > cd ./dist && node common/core/bin/www.js + cactus-example-electricity-trade-sawtooth-validator | + cactus-example-electricity-trade-sawtooth-validator | listening on *:5140 + cactus-example-electricity-trade-blp | [2022-02-14T15:47:47.312] [INFO] www - Using BLP with id = h40Q9eMD + cactus-example-electricity-trade-blp | start Dynamic loading. + cactus-example-electricity-trade-blp | path: /api/v1/bl/cactus-example-electricity-trade/, routerJs: /root/cactus/dist/cactus-example-electricity-trade.js + cactus-example-electricity-trade-blp | path: /api/v1/bl/balance/, routerJs: /root/cactus/dist/balance.js + cactus-example-electricity-trade-blp | [2022-02-14T15:47:47.399] [INFO] www - listening on *: 5034 + ``` ## How to use this application + - Source account on Ethereum: `06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97` - The privkey of source account on Ethereum: `cb5d48d371916a4ea1627189d8af4f642a5d72746a06b559780c3f5932658207` - Destination account on Ethereum: `9d624f7995e8bd70251f8265f2f9f2b49f169c55` - The key name of intkey on Sawtooth: `MI000001` 1. (Optional) Check the balance on ethereum accounts and current electricity usage - - `./script-get-app.sh` - The result looks like the following (note there's no electricity usage yet so the output is empty): + - `./script-get-app.sh` - ``` - # Source Eth balance: - {"status":200,"amount":100000} + The result looks like the following (note there's no electricity usage yet so the output is empty): - # Destination Eth balance: - {"status":200,"amount":0} + ``` + # Source Eth balance: + {"status":200,"amount":100000} - # Electricity usage - ``` + # Destination Eth balance: + {"status":200,"amount":0} + + # Electricity usage + ``` 1. Register an account information - ``` - ./script-post-setup-request.sh - ``` - ... or send request manually: + ``` + ./script-post-setup-request.sh + ``` + ... or send request manually: - ``` - curl localhost:5034/api/v1/bl/electricity-trade/meter/register/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"h40Q9eMD","meterParams":["MI000001", "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "cb5d48d371916a4ea1627189d8af4f642a5d72746a06b559780c3f5932658207", "9d624f7995e8bd70251f8265f2f9f2b49f169c55"]}' - ``` + ``` + curl localhost:5034/api/v1/bl/electricity-trade/meter/register/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"h40Q9eMD","meterParams":["MI000001", "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", "cb5d48d371916a4ea1627189d8af4f642a5d72746a06b559780c3f5932658207", "9d624f7995e8bd70251f8265f2f9f2b49f169c55"]}' + ``` 1. Start the electricity-trade application - - The example response of tradeID: `{"tradeID":"20210220075755506-001"}` - - (Then, the application starts to monitor the Sawtooth blockchain) - ``` - ./script-post-start-request.sh - ``` + - The example response of tradeID: `{"tradeID":"20210220075755506-001"}` + - (Then, the application starts to monitor the Sawtooth blockchain) - ... or send request manually: + ``` + ./script-post-start-request.sh + ``` - ``` - curl localhost:5034/api/v1/bl/electricity-trade/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"h40Q9eMD"}' - ``` + ... or send request manually: + + ``` + curl localhost:5034/api/v1/bl/electricity-trade/ -XPOST -H "Content-Type: application/json" -d '{"businessLogicID":"h40Q9eMD"}' + ``` 1. Execute the intkey transaction on Sawtooth blockchain - - `./script-gen-electricity-usage.sh` + + - `./script-gen-electricity-usage.sh` The result looks like the following: @@ -135,24 +143,26 @@ In this example, we use the Sawtooth intkey transaction processor as an applicat ``` 1. (Optional) Check the balance on Ethereum accounts using the following script - - `./script-get-app.sh` - The result looks like the following: + - `./script-get-app.sh` - ``` - # Source Eth balance: - {"status":200,"amount":99976} + The result looks like the following: - # Destination Eth balance: - {"status":200,"amount":24} + ``` + # Source Eth balance: + {"status":200,"amount":99976} - # Electricity usage - MI000001: 74 - ``` + # Destination Eth balance: + {"status":200,"amount":24} + + # Electricity usage + MI000001: 74 + ``` ## How to stop the application and cleanup Docker containers + 1. Press `Ctrl+C` in `docker-compose` console to stop the application. 1. Run cleanup script - ``` - sudo ./script-cleanup.sh - ``` + ``` + sudo ./script-cleanup.sh + ``` diff --git a/examples/cactus-example-electricity-trade/RequestInfo.ts b/examples/cactus-example-electricity-trade/RequestInfo.ts index 8753de81a9..741152fc06 100644 --- a/examples/cactus-example-electricity-trade/RequestInfo.ts +++ b/examples/cactus-example-electricity-trade/RequestInfo.ts @@ -7,19 +7,19 @@ // transaction information class TradeInfo { - ethereumAccountA: string; - ethereumAccountB: string; + ethereumAccountA!: string; + ethereumAccountB!: string; } // authorization information class AuthInfo { - company: string; + company!: string; } // request information export class RequestInfo { - businessLogicID: string; - tradeID: string; + businessLogicID!: string; + tradeID!: string; tradeInfo: TradeInfo; authInfo: AuthInfo; constructor() { @@ -27,7 +27,7 @@ export class RequestInfo { this.authInfo = new AuthInfo(); } - setTradeID(tradeID: string) { + setTradeID(tradeID: string): void { this.tradeID = tradeID; } } diff --git a/examples/cactus-example-electricity-trade/TransactionEthereum.ts b/examples/cactus-example-electricity-trade/TransactionEthereum.ts index fe609d2639..aadb6a9dfe 100644 --- a/examples/cactus-example-electricity-trade/TransactionEthereum.ts +++ b/examples/cactus-example-electricity-trade/TransactionEthereum.ts @@ -16,18 +16,21 @@ import { VerifierFactoryConfig, } from "@hyperledger/cactus-verifier-client"; -const fs = require("fs"); -const yaml = require("js-yaml"); //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); -const config: any = ConfigUtil.getConfig(); +const config: any = ConfigUtil.getConfig() as any; import { getLogger } from "log4js"; const moduleName = "TransactionEthereum"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; const mapFromAddressNonce: Map = new Map(); -let xConnectInfo: LPInfoHolder = null; // connection information -let xVerifierFactory: VerifierFactory = null; +let xConnectInfo: LPInfoHolder | null = null; // connection information +let xVerifierFactory: VerifierFactory | null = null; + +export interface EthSigner { + serializedTx: string; + txId: string; +} export function makeRawTransaction(txParam: { fromAddress: string; @@ -35,7 +38,7 @@ export function makeRawTransaction(txParam: { toAddress: string; amount: number; gas: number; -}): Promise<{ data: {}; txId: string }> { +}): Promise<{ data: Record; txId: string }> { return new Promise(async (resolve, reject) => { try { logger.debug(`makeRawTransaction: txParam: ${JSON.stringify(txParam)}`); @@ -47,13 +50,17 @@ export function makeRawTransaction(txParam: { 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: string; + to: string; + value: number; + gas: number; + } = { + nonce: txnCountHex, + to: txParam.toAddress, + value: txParam.amount, + gas: txParam.gas, + }; logger.debug( `##makeRawTransaction(B), rawTx: ${JSON.stringify(rawTx)}`, ); @@ -62,9 +69,10 @@ export function makeRawTransaction(txParam: { rawTx, txParam.fromAddressPkey, ); - const resp: { data: {}; txId: string } = { - data: { serializedTx: signedTx["serializedTx"] }, - txId: signedTx["txId"], + + const resp = { + data: { serializedTx: signedTx.serializedTx }, + txId: signedTx.txId, }; return resolve(resp); @@ -96,7 +104,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 template = "default"; const args = { args: { args: [fromAddress] } }; logger.debug(`##getNewNonce(A): call validator#getNonce()`); @@ -111,7 +119,8 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { const latestNonce = getLatestNonce(fromAddress); // logger.debug(`##getNewNonce(B): fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`); - if (txnCount <= latestNonce) { + + if (txnCount <= latestNonce && xVerifierFactory) { // nonce correction txnCount = latestNonce + 1; logger.debug( @@ -122,6 +131,7 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { const args = { args: { args: [txnCount] } }; logger.debug(`##getNewNonce(D): call validator#toHex()`); + xVerifierFactory .getVerifier("84jUisrs") .sendSyncRequest(contract, method, args) @@ -151,7 +161,7 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> { function getLatestNonce(fromAddress: string): number { if (mapFromAddressNonce.has(fromAddress)) { - return mapFromAddressNonce.get(fromAddress); + return mapFromAddressNonce.get(fromAddress) ?? -1; } //return 0; return -1; diff --git a/examples/cactus-example-electricity-trade/balance.ts b/examples/cactus-example-electricity-trade/balance.ts index 79d87dfe66..fd0aa22304 100644 --- a/examples/cactus-example-electricity-trade/balance.ts +++ b/examples/cactus-example-electricity-trade/balance.ts @@ -32,7 +32,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-electricity-trade/electricity-trade.ts b/examples/cactus-example-electricity-trade/electricity-trade.ts index a6b8184f7f..9fc260a9bf 100644 --- a/examples/cactus-example-electricity-trade/electricity-trade.ts +++ b/examples/cactus-example-electricity-trade/electricity-trade.ts @@ -48,13 +48,14 @@ router.post( "/meter/register/", (req: Request, res: Response, next: NextFunction) => { try { - const result = transactionManagement.setBusinessLogicConfig(req); + const result = transactionManagement.setBusinessLogicConfig(req) as any; if (!result) { throw new RIFError("Error when running setBusinessLogicConfig"); } let status = 200; + if (result["action"] === "add") { status = 201; } @@ -68,7 +69,7 @@ router.post( next(err); } - } + }, ); export default router; diff --git a/examples/cactus-example-electricity-trade/tsconfig.json b/examples/cactus-example-electricity-trade/tsconfig.json index bc78419774..e8ecedf943 100644 --- a/examples/cactus-example-electricity-trade/tsconfig.json +++ b/examples/cactus-example-electricity-trade/tsconfig.json @@ -3,12 +3,9 @@ "compilerOptions": { "composite": true, "outDir": "./dist/", - "tsBuildInfoFile": "../../.build-cache/cactus-example-electricity-trade.tsbuildinfo", - "strict": false // TODO - true, fix warnings + "tsBuildInfoFile": "../../.build-cache/cactus-example-electricity-trade.tsbuildinfo" }, - "include": [ - "./*.ts", - ], + "include": ["./*.ts"], "references": [ { "path": "../../packages/cactus-cmd-socketio-server/tsconfig.json" @@ -17,4 +14,4 @@ "path": "../../packages/cactus-verifier-client/tsconfig.json" } ] -} \ No newline at end of file +} 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 268b82f3f0..af2b3fa7fd 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 @@ -38,13 +38,7 @@ const EC = elliptic.ec; let fabricChannel: any = undefined; export class TransactionSigner { - static signTxEthereum( - rawTx: object, - signPkey: string, - ): { - serializedTx: string; - txId: string; - } { + static signTxEthereum(rawTx: object, signPkey: string) { logger.debug(`####in signTxEthereum()`); // ethereumjs-tx2.1.2_support const customCommon = ethJsCommon.forCustomChain(