From 57212a60dd3bba72ad07396519d2317114155010 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 8 Dec 2023 14:58:58 +0000 Subject: [PATCH 01/53] code porting to TypeScript --- src/{bls.mjs => bls.ts} | 25 +- src/{cc.mjs => cc.ts} | 283 +++++---- src/{cli.mjs => cli.ts} | 36 +- src/{clpTools.mjs => clpTools.ts} | 34 +- src/{discoveryTools.mjs => discoveryTools.ts} | 10 +- ...eventDispatcher.mjs => eventDispatcher.ts} | 0 src/{imaCore.mjs => imaCore.ts} | 24 +- ...aEthOperations.mjs => imaEthOperations.ts} | 14 +- ...imaEventLogScan.mjs => imaEventLogScan.ts} | 10 +- ...perations.mjs => imaGasUsageOperations.ts} | 4 +- src/{imaHelperAPIs.mjs => imaHelperAPIs.ts} | 12 +- ...eOperations.mjs => imaOracleOperations.ts} | 12 +- ...tions.mjs => imaRegistrationOperations.ts} | 8 +- ...ions.mjs => imaReimbursementOperations.ts} | 8 +- ...rnalSigner.mjs => imaSgxExternalSigner.ts} | 6 +- ...enOperations.mjs => imaTokenOperations.ts} | 14 +- ...ndling.mjs => imaTransferErrorHandling.ts} | 2 +- src/{imaTx.mjs => imaTx.ts} | 12 +- src/{log.mjs => log.ts} | 539 +++++++++--------- src/{loop.mjs => loop.ts} | 24 +- src/{loopWorker.mjs => loopWorker.ts} | 35 +- src/{main.mjs => main.ts} | 24 +- src/{observer.mjs => observer.ts} | 8 +- src/{oracle.mjs => oracle.ts} | 6 +- src/{owaspUtils.mjs => owaspUtils.ts} | 129 ++--- src/{pwa.mjs => pwa.ts} | 8 +- src/{rpcCall.mjs => rpcCall.ts} | 4 +- src/{socket.mjs => socket.ts} | 42 +- src/{socketServer.mjs => socketServer.ts} | 29 +- src/{socketSettings.mjs => socketSettings.ts} | 2 +- src/{socketUtils.mjs => socketUtils.ts} | 63 +- src/{state.mjs => state.ts} | 6 +- src/{threadInfo.mjs => threadInfo.ts} | 2 +- src/{utils.mjs => utils.ts} | 100 ++-- 34 files changed, 782 insertions(+), 753 deletions(-) rename src/{bls.mjs => bls.ts} (99%) rename src/{cc.mjs => cc.ts} (77%) rename src/{cli.mjs => cli.ts} (99%) rename src/{clpTools.mjs => clpTools.ts} (98%) rename src/{discoveryTools.mjs => discoveryTools.ts} (99%) rename src/{eventDispatcher.mjs => eventDispatcher.ts} (100%) rename src/{imaCore.mjs => imaCore.ts} (99%) rename src/{imaEthOperations.mjs => imaEthOperations.ts} (97%) rename src/{imaEventLogScan.mjs => imaEventLogScan.ts} (99%) rename src/{imaGasUsageOperations.mjs => imaGasUsageOperations.ts} (96%) rename src/{imaHelperAPIs.mjs => imaHelperAPIs.ts} (96%) rename src/{imaOracleOperations.mjs => imaOracleOperations.ts} (98%) rename src/{imaRegistrationOperations.mjs => imaRegistrationOperations.ts} (97%) rename src/{imaReimbursementOperations.mjs => imaReimbursementOperations.ts} (98%) rename src/{imaSgxExternalSigner.mjs => imaSgxExternalSigner.ts} (97%) rename src/{imaTokenOperations.mjs => imaTokenOperations.ts} (99%) rename src/{imaTransferErrorHandling.mjs => imaTransferErrorHandling.ts} (98%) rename src/{imaTx.mjs => imaTx.ts} (99%) rename src/{log.mjs => log.ts} (64%) rename src/{loop.mjs => loop.ts} (98%) rename src/{loopWorker.mjs => loopWorker.ts} (95%) rename src/{main.mjs => main.ts} (97%) rename src/{observer.mjs => observer.ts} (94%) rename src/{oracle.mjs => oracle.ts} (98%) rename src/{owaspUtils.mjs => owaspUtils.ts} (84%) rename src/{pwa.mjs => pwa.ts} (98%) rename src/{rpcCall.mjs => rpcCall.ts} (99%) rename src/{socket.mjs => socket.ts} (99%) rename src/{socketServer.mjs => socketServer.ts} (91%) rename src/{socketSettings.mjs => socketSettings.ts} (99%) rename src/{socketUtils.mjs => socketUtils.ts} (81%) rename src/{state.mjs => state.ts} (99%) rename src/{threadInfo.mjs => threadInfo.ts} (97%) rename src/{utils.mjs => utils.ts} (82%) diff --git a/src/bls.mjs b/src/bls.ts similarity index 99% rename from src/bls.mjs rename to src/bls.ts index 041a1150..c73490d2 100644 --- a/src/bls.mjs +++ b/src/bls.ts @@ -25,19 +25,18 @@ import * as fs from "fs"; import * as path from "path"; -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; import * as childProcessModule from "child_process"; -import * as rpcCall from "./rpcCall.mjs"; +import * as rpcCall from "./rpcCall"; import * as shellModule from "shelljs"; -import * as imaUtils from "./utils.mjs"; +import * as imaUtils from "./utils"; import * as sha3Module from "sha3"; -import * as skaleObserver from "./observer.mjs"; -import * as discoveryTools from "./discoveryTools.mjs"; -import * as threadInfo from "./threadInfo.mjs"; - -import * as state from "./state.mjs"; -import { randomCallID } from "./socketUtils.mjs"; +import * as skaleObserver from "./observer"; +import * as discoveryTools from "./discoveryTools"; +import * as threadInfo from "./threadInfo"; +import * as utils from "./socketUtils"; +import * as state from "./state"; const shell = shellModule.default; @@ -1856,7 +1855,7 @@ export async function doSignReadyHash( strMessageHash, isExposeOutput ) { throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); const joIn = { "jsonrpc": "2.0", - "id": randomCallID(), + "id": utils.randomCallID(), "method": "blsSignMessageHash", "params": { "keyShareName": joAccount.strBlsKeyName, @@ -2088,7 +2087,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData ) { throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); const joIn = { "jsonrpc": "2.0", - "id": randomCallID(), + "id": utils.randomCallID(), "method": "blsSignMessageHash", "params": { "keyShareName": joAccount.strBlsKeyName, @@ -2230,7 +2229,7 @@ export async function handleSkaleImaBSU256( joCallData ) { } const joIn = { "jsonrpc": "2.0", - "id": randomCallID(), + "id": utils.randomCallID(), "method": "blsSignMessageHash", "params": { "keyShareName": optsBSU256.joAccount.strBlsKeyName, diff --git a/src/cc.mjs b/src/cc.ts similarity index 77% rename from src/cc.mjs rename to src/cc.ts index 68444599..8883d53d 100644 --- a/src/cc.mjs +++ b/src/cc.ts @@ -23,34 +23,34 @@ * @copyright SKALE Labs 2019-Present */ -let gFlagIsEnabled = false; +let gFlagIsEnabled: boolean = false; -export function autoEnableFromCommandLineArgs() { - const b = +export function autoEnableFromCommandLineArgs() : void { + const b: boolean = ( process.argv.indexOf( "--colors" ) >= 0 || process.argv.indexOf( "-colors" ) >= 0 ) ? true : false; enable( b ); } -export function enable( b ) { +export function enable( b?: boolean ) : void { gFlagIsEnabled = !!b; } -export function isStringAlreadyColorized( s ) { +export function isStringAlreadyColorized( s?: any ) : boolean { if( s && typeof s == "string" && s.length > 0 && s[0] == "\x1b" ) return true; return false; } -export function isEnabled() { +export function isEnabled() : boolean { return !!gFlagIsEnabled; } -export function replaceAll( str, find, replace ) { +export function replaceAll( str: string, find: string, replace: string ) : string { return str.replace( new RegExp( find, "g" ), replace ); } -export function validateRadix( value, radix ) { +export function validateRadix( value?: any, radix?: any ) { value = "" + ( value ? value.toString() : "10" ); value = value.trim(); radix = ( radix == null || radix == undefined ) @@ -60,7 +60,7 @@ export function validateRadix( value, radix ) { return radix; } -export function validateInteger( value, radix ) { +export function validateInteger( value?: any, radix?: any ) : boolean { try { value = "" + value; value = value.trim(); @@ -68,7 +68,7 @@ export function validateInteger( value, radix ) { return false; radix = validateRadix( value, radix ); if( ( !isNaN( value ) ) && - ( parseInt( Number( value ), radix ) == value || radix !== 10 ) && + ( parseInt( value, radix ) == value || radix !== 10 ) && ( !isNaN( parseInt( value, radix ) ) ) ) return true; @@ -77,7 +77,7 @@ export function validateInteger( value, radix ) { return false; } -export function toInteger( value, radix ) { +export function toInteger( value?: any, radix?: any ) : number { try { radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) @@ -85,10 +85,10 @@ export function toInteger( value, radix ) { return parseInt( value, radix ); } catch ( err ) { } - return false; + return 0; } -export function validateFloat( value ) { +export function validateFloat( value?: any ) : boolean { try { const f = parseFloat( value ); if( isNaN( f ) ) @@ -99,16 +99,16 @@ export function validateFloat( value ) { return false; } -function toFloat( value ) { +function toFloat( value?: any ) : number { try { const f = parseFloat( value ); return f; } catch ( err ) { } - return false; + return 0.0; } -export function toBoolean( value ) { +export function toBoolean( value?: any ) : boolean { let b = false; try { if( typeof value === "boolean" ) @@ -131,24 +131,24 @@ export function toBoolean( value ) { return b; } -export function yn( flag ) { +export function yn( flag?: any ) : string { if( !gFlagIsEnabled ) - return flag; + return flag ? "true" : "false"; return toBoolean( flag ) ? yes( "yes" ) : no( "no" ); } -export function tf( flag ) { +export function tf( flag?: any ) : string { if( !gFlagIsEnabled ) - return flag; + return flag ? "true" : "false"; return toBoolean( flag ) ? yes( "true" ) : no( "false" ); } -export function onOff( flag ) { +export function onOff( flag?: any ) : string { if( !gFlagIsEnabled ) - return flag; + return flag ? "true" : "false"; return toBoolean( flag ) ? yes( "on" ) : no( "off" ); } -const gMapColorDefinitions = { +const gMapColorDefinitions: any = { reset: "\x1b[0m", enlight: "\x1b[1m", dim: "\x1b[2m", @@ -174,7 +174,7 @@ const gMapColorDefinitions = { bBgWhite: "\x1b[47m" }; -const gArrRainbowParts = [ +const gArrRainbowParts: any[] = [ gMapColorDefinitions.enlight + gMapColorDefinitions.fgRed, gMapColorDefinitions.fgRed, gMapColorDefinitions.enlight + gMapColorDefinitions.fgYellow, @@ -189,16 +189,16 @@ const gArrRainbowParts = [ gMapColorDefinitions.fgMagenta ]; -export function rainbowPart( s, i ) { +export function rainbowPart( s: string, i: number ) { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); const j = i % gArrRainbowParts.length; return gArrRainbowParts[j] + s + gMapColorDefinitions.reset; } -export function rainbow( s ) { +export function rainbow( s?: any ) : string { if( ( !gFlagIsEnabled ) || ( !s ) || ( typeof s != "string" ) || s.length == 0 ) - return s; + return s ? s.toString() : JSON.stringify( s ); let res = ""; const cnt = s.length; for( let i = 0; i < cnt; ++ i ) @@ -206,7 +206,7 @@ export function rainbow( s ) { return res; } -export function isInt2( n ) { +export function isInt2( n?: any ) : boolean { const intRegex = /^-?\d+$/; if( !intRegex.test( n ) ) return false; @@ -215,12 +215,12 @@ export function isInt2( n ) { return parseFloat( n ) == intVal && !isNaN( intVal ); } -export function isFloat2( n ) { +export function isFloat2( n?: any ) : boolean { const val = parseFloat( n ); return !isNaN( val ); } -function urlObjColorized( objURL ) { +function urlObjColorized( objURL?: any ) : string { let strURL = ""; if( !objURL ) return strURL; @@ -244,24 +244,24 @@ function urlObjColorized( objURL ) { return strURL; } -export function urlStrColorized( s ) { +export function urlStrColorized( s?: any ) : string { const objURL = safeURL( s ); if( !objURL ) return ""; return urlObjColorized( objURL ); } -export function urlColorized( x ) { +export function urlColorized( x?: any ) : string { if( typeof x === "string" || x instanceof String ) return urlStrColorized( x ); return urlObjColorized( x ); } -export function u( x ) { +export function u( x?: any ) : string { return urlColorized( x ); } -export function safeURL( arg ) { +export function safeURL( arg?: any ) : URL|null { try { const sc = arg[0]; if( sc == "\"" || sc == "'" ) { @@ -270,7 +270,7 @@ export function safeURL( arg ) { const ss = arg.substring( 1, cnt - 1 ); const objURL = safeURL( ss ); if( objURL != null && objURL != undefined ) - objURL.strStrippedStringComma = sc; + objURL["strStrippedStringComma"] = sc; return objURL; } @@ -283,14 +283,14 @@ export function safeURL( arg ) { if( objURL.hostname.length === 0 ) return null; - objURL.strStrippedStringComma = null; + objURL["strStrippedStringComma"] = null; return objURL; } catch ( err ) { return null; } } -export function toIpv4Arr( s ) { +export function toIpv4Arr( s: string ) : any[]|null { // eslint-disable-next-line max-len if( /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test( s ) ) { const arr = s.split( "." ); @@ -302,11 +302,10 @@ export function toIpv4Arr( s ) { return null; } -export function logArgToStringAsIpv4( arg ) { +export function logArgToStringAsIpv4( arg?: any ) : string { const arr = toIpv4Arr( arg ); if( !arr ) - return arg; - + return arg.toString(); let s = ""; for( let i = 0; i < 4; ++i ) { if( i > 0 ) @@ -317,7 +316,7 @@ export function logArgToStringAsIpv4( arg ) { return s; } -export function logArgToString() { +export function logArgToString( ...args: any[] ) : string { let i; const cnt = arguments.length; let s = ""; @@ -355,8 +354,8 @@ export function logArgToString() { const objURL = safeURL( arg ); if( objURL != null && objURL != undefined ) { let strURL = ""; - if( objURL.strStrippedStringComma ) - strURL += normal( objURL.strStrippedStringComma ); + if( objURL["strStrippedStringComma"] ) + strURL += normal( objURL["strStrippedStringComma"] ); if( objURL.protocol ) strURL += "" + yellow( objURL.protocol ) + normal( "//" ); @@ -380,8 +379,8 @@ export function logArgToString() { if( objURL.search ) strURL += "" + magenta( objURL.search ); - if( objURL.strStrippedStringComma ) - strURL += normal( objURL.strStrippedStringComma ); + if( objURL["strStrippedStringComma"] ) + strURL += normal( objURL["strStrippedStringComma"] ); s += strURL; continue; @@ -414,9 +413,9 @@ export function logArgToString() { return s; } -export const getCircularReplacerForJsonStringify = () => { +export const getCircularReplacerForJsonStringify = () : any => { const seen = new WeakSet(); - return ( key, value ) => { + return ( key: any, value: any ) : any => { if( typeof value === "object" && value !== null ) { if( seen.has( value ) ) return; @@ -428,7 +427,7 @@ export const getCircularReplacerForJsonStringify = () => { export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ cntCensoredMax: 30000, // zero to disable censoring - censor: ( censor ) => { + censor: ( censor: any ) : any => { let i = 0; return ( key, value ) => { if( i !== 0 && typeof ( censor ) === "object" && @@ -443,7 +442,7 @@ export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ return value; }; }, - replacerHTML: ( match, pIndent, pKey, pVal, pEnd ) => { + replacerHTML: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ) : any => { const key = ""; const val = ""; const str = ""; @@ -456,7 +455,7 @@ export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ return r + ( pEnd || "" ); }, - prettyPrintHTML: ( obj ) => { + prettyPrintHTML: ( obj?: any ) => { const jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg; const s = JSON.stringify( @@ -468,7 +467,7 @@ export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ .replace( jsonLine, jsonColorizer.replacerHTML ); return s; }, - replacerConsole: ( match, pIndent, pKey, pVal, pEnd ) => { + replacerConsole: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ) : any => { let r = pIndent || ""; if( pKey ) r = r + logArgToString( pKey.replace( /[": ]/g, "" ) ) + ": "; @@ -478,7 +477,7 @@ export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ return r + ( pEnd || "" ); }, - prettyPrintConsole: ( obj ) => { + prettyPrintConsole: ( obj?: any ) : any => { if( !gFlagIsEnabled ) { if( obj === null ) return "null"; @@ -498,10 +497,10 @@ export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ } catch ( err ) { } return obj; } - const cntSpaces = 4; + const cntSpaces: number = 4; const jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg; try { - const tmp = JSON.stringify( + const tmp: string = JSON.stringify( obj, ( jsonColorizer.cntCensoredMax > 0 ) ? jsonColorizer.censor( obj ) : null, cntSpaces @@ -523,7 +522,7 @@ export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ // see: // http://jsfiddle.net/KJQ9K/554 // https://qastack.ru/programming/4810841/pretty-print-json-using-javascript -export function syntaxHighlightJSON( jo, strKeyNamePrefix ) { +export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ) : string { strKeyNamePrefix = strKeyNamePrefix || ""; jo = jo.replace( /&/g, "&" ).replace( //g, ">" ); return jo.replace( @@ -573,7 +572,7 @@ export function syntaxHighlightJSON( jo, strKeyNamePrefix ) { } ); } -export function safeStringifyJSON( jo, n ) { +export function safeStringifyJSON( jo?: any, n?: number ) : string|undefined { try { const s = "" + JSON.stringify( jo, getCircularReplacerForJsonStringify(), n ); return s; @@ -582,11 +581,11 @@ export function safeStringifyJSON( jo, n ) { return undefined; } -export function jn( x ) { +export function jn( x?: any ) : string { return "" + jsonColorizer.prettyPrintConsole( x ); } -export function j1( x, n, strKeyNamePrefix ) { +export function j1( x?: any, n?: number, strKeyNamePrefix?: string ) : string { let isDefaultKeyNamePrefix = false; if( typeof strKeyNamePrefix !== "string" ) { strKeyNamePrefix = " "; @@ -594,14 +593,14 @@ export function j1( x, n, strKeyNamePrefix ) { } let s = safeStringifyJSON( x, n ); if( ! gFlagIsEnabled ) - return s; + return s || ""; s = "" + syntaxHighlightJSON( s, strKeyNamePrefix ); if( isDefaultKeyNamePrefix && s.length > 9 && s[0] == " " ) s = s.substring( 1, s.length ); return s; } -export function j( x ) { +export function j( x?: any ) : string { return j1( x ); // jn } @@ -654,229 +653,229 @@ export { bBgWhite }; -export function normal( s ) { +export function normal( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + s + reset; } -export function trace( s ) { +export function trace( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + s + reset; } -export function debug( s ) { +export function debug( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + s + reset; } -export function debugDark( s ) { +export function debugDark( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgBlack + enlight + s + reset; } -export function note( s ) { +export function note( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + s + reset; } -export function notice( s ) { +export function notice( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function info( s ) { +export function info( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + enlight + s + reset; } -export function warning( s ) { +export function warning( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function warn( s ) { +export function warn( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function error( s ) { +export function error( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgRed + s + reset; } -export function fatal( s ) { +export function fatal( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + bgRed + fgYellow + enlight + s + reset; } -export function success( s ) { +export function success( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function attention( s ) { +export function attention( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgCyan + s + reset; } -export function bright( s ) { +export function bright( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + enlight + s + reset; } -export function sunny( s ) { +export function sunny( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + enlight + s + reset; } -export function rx( s ) { +export function rx( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function rxa( s ) { +export function rxa( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + enlight + s + reset; } -export function tx( s ) { +export function tx( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + s + reset; } -export function txa( s ) { +export function txa( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function date( s ) { +export function date( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function time( s ) { +export function time( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + enlight + s + reset; } -export function frac_time( s ) { +export function frac_time( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function yes( s ) { +export function yes( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function no( s ) { +export function no( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgRed + s + reset; } -export function number( s ) { +export function number( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + enlight + s + reset; } -export function real( s ) { +export function real( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function undefval( s ) { +export function undefval( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function nullval( s ) { +export function nullval( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function nanval( s ) { +export function nanval( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function yellow( s ) { +export function yellow( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function magenta( s ) { +export function magenta( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function cla( s ) { +export function cla( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + dim + s + reset; } -export function kk( s ) { +export function kk( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + enlight + s + reset; } -export function strval( s ) { +export function strval( s?: any ) : string { if( !gFlagIsEnabled ) - return s; + return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function n2s( n, sz ) { +export function n2s( n: any, sz: number ) { let s = "" + n; while( s.length < sz ) s = "0" + s; return s; } -export function timestampHR() { +export function timestampHR() : number { const d = new Date(); const ts = Math.floor( ( d ).getTime() ); return ts; } -export function timestampUnix() { +export function timestampUnix() : number { const d = new Date(); const ts = Math.floor( ( d ).getTime() / 1000 ); return ts; } -function trimLeftUnneededTimestampZeros( s ) { +function trimLeftUnneededTimestampZeros( s?: any ) : string { while( s.length >= 2 ) { if( s[0] == "0" && s[1] >= "0" && s[1] <= "9" ) s = s.substring( 1 ); @@ -886,7 +885,7 @@ function trimLeftUnneededTimestampZeros( s ) { return s; } -export function getDurationString( tsFrom, tsTo ) { +export function getDurationString( tsFrom : number, tsTo : number ) : string { let s = ""; let n = tsTo - tsFrom; @@ -919,17 +918,17 @@ export function getDurationString( tsFrom, tsTo ) { return "" + n + " " + ( ( n > 1 ) ? "days" : "day" ) + "," + s; } -export function capitalizeFirstLetter( s ) { +export function capitalizeFirstLetter( s?: any ) : string { if( ! s ) - return s; + return JSON.stringify( s ); let s2 = s.toString(); if( ! s2 ) - return s; + return s.toString(); s2 = s2.charAt( 0 ).toUpperCase() + s2.slice( 1 ); return s2; } -function errFnDottedName( s ) { +function errFnDottedName( s?: any ) : string { const arr = s.split( "." ); const cnt = arr.length; let i, s2 = ""; @@ -941,13 +940,13 @@ function errFnDottedName( s ) { return s2; } -function errFnName( s ) { +function errFnName( s?: any ) : string { if( s.indexOf( "async " ) == 0 ) return bright( "async" ) + " " + errFnDottedName( s.substring( 6 ) ); return errFnDottedName( s ); } -function errLocLn( s, isWithBraces ) { +function errLocLn( s: string, isWithBraces?: boolean ) : string { let s2 = ""; s = s.replace( "file://", "" ); s = s.replace( "node:", "" ); @@ -970,9 +969,9 @@ function errLocLn( s, isWithBraces ) { return s2; } -export function stack( strIn ) { +export function stack( strIn?: string ) : string { if( ! strIn ) - return strIn; + return strIn || ""; try { const arr = ( typeof strIn == "string" ) ? strIn.split( "\n" ) : strIn; const cnt = arr.length; diff --git a/src/cli.mjs b/src/cli.ts similarity index 99% rename from src/cli.mjs rename to src/cli.ts index 0587b252..2d204425 100644 --- a/src/cli.mjs +++ b/src/cli.ts @@ -26,15 +26,15 @@ import * as path from "path"; import * as url from "url"; import * as os from "os"; -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaUtils from "./utils.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; -import * as imaOracleOperations from "./imaOracleOperations.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as state from "./state.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as imaUtils from "./utils"; +import * as rpcCall from "./rpcCall"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as imaOracleOperations from "./imaOracleOperations"; +import * as imaTx from "./imaTx"; +import * as state from "./state"; const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); @@ -42,9 +42,9 @@ const gStrAppName = "IMA AGENT"; const gStrVersion = imaUtils.fileLoad( path.join( __dirname, "../VERSION" ), "N/A" ).toString().trim(); -function att() { return log.fmtAttention( ...arguments ); }; +function att( ...args: any[] ) : string { return log.fmtAttention( ...arguments ); }; -export function printAbout( isLog ) { +export function printAbout( isLog?: boolean ) { isLog = isLog || false; const strMsg = log.fmtTrace( att( gStrAppName ), " version ", log.fmtNotice( gStrVersion ) ); if( isLog ) @@ -78,8 +78,8 @@ export function parseCommandLineArgument( s ) { // check correctness of command line arguments export function ensureHaveValue( - name, value, isExitIfEmpty, - isPrintValue, fnNameColorizer, fnValueColorizer + name: string, value: any, isExitIfEmpty: boolean, + isPrintValue: boolean, fnNameColorizer?: any, fnValueColorizer?: any ) { isExitIfEmpty = isExitIfEmpty || false; isPrintValue = isPrintValue || false; @@ -631,7 +631,7 @@ function parseTransactionArgs( imaState, joArg ) { return true; } if( joArg.name == "gas-price-multiplier-mn" ) { - let gasPriceMultiplier = owaspUtils.toFloat( joArg.value ); + let gasPriceMultiplier : number = owaspUtils.toFloat( joArg.value ); if( gasPriceMultiplier < 0.0 ) gasPriceMultiplier = 0.0; imaState.chainProperties.mn.transactionCustomizer.gasPriceMultiplier = @@ -1070,12 +1070,12 @@ function parseBlsArgs( imaState, joArg ) { function parseMonitoringArgs( imaState, joArg ) { if( joArg.name == "monitoring-port" ) { - owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg, true ); + owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nMonitoringPort = owaspUtils.toInteger( joArg.value ); return true; } if( joArg.name == "monitoring-log" ) { - owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg, true ); + owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.bLogMonitoringServer = true; return true; } @@ -1162,7 +1162,7 @@ function parseBlockScannerArgs( imaState, joArg ) { function parseJsonRpcServerArgs( imaState, joArg ) { if( joArg.name == "json-rpc-port" ) { - owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg, true ); + owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nJsonRpcPort = owaspUtils.toInteger( joArg.value ); return true; } @@ -1269,7 +1269,7 @@ export function parse( joExternalHandlers, argv ) { joArg.name == "s2m-payment" || joArg.name == "s2m-receive" || joArg.name == "s2m-view" || - joArg.name == "s2s-payment" | + joArg.name == "s2s-payment" || joArg.name == "m2s-transfer" || joArg.name == "s2m-transfer" || joArg.name == "s2s-transfer" || diff --git a/src/clpTools.mjs b/src/clpTools.ts similarity index 98% rename from src/clpTools.mjs rename to src/clpTools.ts index ca11c751..e4ec11dd 100644 --- a/src/clpTools.mjs +++ b/src/clpTools.ts @@ -23,23 +23,23 @@ * @copyright SKALE Labs 2019-Present */ -import * as owaspUtils from "./owaspUtils.mjs"; -import * as log from "./log.mjs"; -import * as imaCLI from "./cli.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as state from "./state.mjs"; -import * as IMA from "./imaCore.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaGasUsage from "./imaGasUsageOperations.mjs"; -import * as imaReimbursement from "./imaReimbursementOperations.mjs"; -import * as imaReg from "./imaRegistrationOperations.mjs"; -import * as imaEth from "./imaEthOperations.mjs"; -import * as imaToken from "./imaTokenOperations.mjs"; -import * as skaleObserver from "./observer.mjs"; -import * as discoveryTools from "./discoveryTools.mjs"; -import * as loop from "./loop.mjs"; -import * as imaUtils from "./utils.mjs"; -import * as imaBLS from "./bls.mjs"; +import * as owaspUtils from "./owaspUtils"; +import * as log from "./log"; +import * as imaCLI from "./cli"; +import * as rpcCall from "./rpcCall"; +import * as state from "./state"; +import * as IMA from "./imaCore"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaGasUsage from "./imaGasUsageOperations"; +import * as imaReimbursement from "./imaReimbursementOperations"; +import * as imaReg from "./imaRegistrationOperations"; +import * as imaEth from "./imaEthOperations"; +import * as imaToken from "./imaTokenOperations"; +import * as skaleObserver from "./observer"; +import * as discoveryTools from "./discoveryTools"; +import * as loop from "./loop"; +import * as imaUtils from "./utils"; +import * as imaBLS from "./bls"; export async function registerAll( isPrintSummaryRegistrationCosts ) { if( !await registerStep1( false ) ) diff --git a/src/discoveryTools.mjs b/src/discoveryTools.ts similarity index 99% rename from src/discoveryTools.mjs rename to src/discoveryTools.ts index fb63b4ce..ad1ee23d 100644 --- a/src/discoveryTools.mjs +++ b/src/discoveryTools.ts @@ -23,11 +23,11 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as state from "./state.mjs"; -import * as imaUtils from "./utils.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as rpcCall from "./rpcCall"; +import * as state from "./state"; +import * as imaUtils from "./utils"; +import * as threadInfo from "./threadInfo"; export function formatBalanceInfo( bi, strAddress ) { let s = ""; diff --git a/src/eventDispatcher.mjs b/src/eventDispatcher.ts similarity index 100% rename from src/eventDispatcher.mjs rename to src/eventDispatcher.ts diff --git a/src/imaCore.mjs b/src/imaCore.ts similarity index 99% rename from src/imaCore.mjs rename to src/imaCore.ts index afa49263..8639ab25 100644 --- a/src/imaCore.mjs +++ b/src/imaCore.ts @@ -23,18 +23,18 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as loop from "./loop.mjs"; -import * as pwa from "./pwa.mjs"; -import * as state from "./state.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as imaGasUsage from "./imaGasUsageOperations.mjs"; -import * as imaEventLogScan from "./imaEventLogScan.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; -import * as skaleObserver from "./observer.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as loop from "./loop"; +import * as pwa from "./pwa"; +import * as state from "./state"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTx from "./imaTx"; +import * as imaGasUsage from "./imaGasUsageOperations"; +import * as imaEventLogScan from "./imaEventLogScan"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as skaleObserver from "./observer"; +import * as threadInfo from "./threadInfo"; log.enableColorization( false ); log.addStdout(); diff --git a/src/imaEthOperations.mjs b/src/imaEthOperations.ts similarity index 97% rename from src/imaEthOperations.mjs rename to src/imaEthOperations.ts index b8c2320b..767a251a 100644 --- a/src/imaEthOperations.mjs +++ b/src/imaEthOperations.ts @@ -23,13 +23,13 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as imaGasUsage from "./imaGasUsageOperations.mjs"; -import * as imaEventLogScan from "./imaEventLogScan.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTx from "./imaTx"; +import * as imaGasUsage from "./imaGasUsageOperations"; +import * as imaEventLogScan from "./imaEventLogScan"; +import * as threadInfo from "./threadInfo"; export async function getBalanceEth( isMainNet, diff --git a/src/imaEventLogScan.mjs b/src/imaEventLogScan.ts similarity index 99% rename from src/imaEventLogScan.mjs rename to src/imaEventLogScan.ts index 99f7889d..f3852418 100644 --- a/src/imaEventLogScan.mjs +++ b/src/imaEventLogScan.ts @@ -23,11 +23,11 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as rpcCall from "./rpcCall"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; export function createProgressiveEventsScanPlan( details, nLatestBlockNumber ) { // assume Main Net mines 6 blocks per minute diff --git a/src/imaGasUsageOperations.mjs b/src/imaGasUsageOperations.ts similarity index 96% rename from src/imaGasUsageOperations.mjs rename to src/imaGasUsageOperations.ts index 33cdde22..5b652edc 100644 --- a/src/imaGasUsageOperations.mjs +++ b/src/imaGasUsageOperations.ts @@ -23,8 +23,8 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; export function composeGasUsageReportFromArray( strName, jarrReceipts ) { if( ! ( strName && typeof strName == "string" && jarrReceipts ) ) diff --git a/src/imaHelperAPIs.mjs b/src/imaHelperAPIs.ts similarity index 96% rename from src/imaHelperAPIs.mjs rename to src/imaHelperAPIs.ts index cefa6f81..1b760194 100644 --- a/src/imaHelperAPIs.mjs +++ b/src/imaHelperAPIs.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as rpcCall from "./rpcCall"; +import * as threadInfo from "./threadInfo"; export const longSeparator = "============================================================" + @@ -178,13 +178,13 @@ export function isReverseS2S() { return ( !!gFlagIsForwardS2S ); } -export function setForwardS2S( b ) { +export function setForwardS2S( b?: boolean ) { if( b == null || b == undefined ) b = true; gFlagIsForwardS2S = ( !!b ); } -export function setReverseS2S( b ) { +export function setReverseS2S( b?: boolean ) { if( b == null || b == undefined ) b = true; gFlagIsForwardS2S = b ? false : true; diff --git a/src/imaOracleOperations.mjs b/src/imaOracleOperations.ts similarity index 98% rename from src/imaOracleOperations.mjs rename to src/imaOracleOperations.ts index ef6e0bfa..4214ab28 100644 --- a/src/imaOracleOperations.mjs +++ b/src/imaOracleOperations.ts @@ -23,12 +23,12 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaOracle from "./oracle.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as imaGasUsage from "./imaGasUsageOperations.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as imaOracle from "./oracle"; +import * as imaTx from "./imaTx"; +import * as imaGasUsage from "./imaGasUsageOperations"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; let gFlagIsEnabledOracle = false; diff --git a/src/imaRegistrationOperations.mjs b/src/imaRegistrationOperations.ts similarity index 97% rename from src/imaRegistrationOperations.mjs rename to src/imaRegistrationOperations.ts index d7bdc477..65152754 100644 --- a/src/imaRegistrationOperations.mjs +++ b/src/imaRegistrationOperations.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTx from "./imaTx"; +import * as threadInfo from "./threadInfo"; export async function invokeHasChain( details, diff --git a/src/imaReimbursementOperations.mjs b/src/imaReimbursementOperations.ts similarity index 98% rename from src/imaReimbursementOperations.mjs rename to src/imaReimbursementOperations.ts index 3ca1848f..71fce684 100644 --- a/src/imaReimbursementOperations.mjs +++ b/src/imaReimbursementOperations.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as imaGasUsage from "./imaGasUsageOperations.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as imaTx from "./imaTx"; +import * as imaGasUsage from "./imaGasUsageOperations"; export async function reimbursementShowBalance( ethersProviderMainNet, diff --git a/src/imaSgxExternalSigner.mjs b/src/imaSgxExternalSigner.ts similarity index 97% rename from src/imaSgxExternalSigner.mjs rename to src/imaSgxExternalSigner.ts index dce548de..4f7d0a8d 100644 --- a/src/imaSgxExternalSigner.mjs +++ b/src/imaSgxExternalSigner.ts @@ -1,7 +1,7 @@ import * as fs from "fs"; -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as rpcCall from "./rpcCall.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as rpcCall from "./rpcCall"; const gIsDebugLogging = false; // development option only, must be always false log.addStdout(); diff --git a/src/imaTokenOperations.mjs b/src/imaTokenOperations.ts similarity index 99% rename from src/imaTokenOperations.mjs rename to src/imaTokenOperations.ts index da4e1a64..8382ab50 100644 --- a/src/imaTokenOperations.mjs +++ b/src/imaTokenOperations.ts @@ -23,13 +23,13 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as imaGasUsage from "./imaGasUsageOperations.mjs"; -import * as imaEventLogScan from "./imaEventLogScan.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTx from "./imaTx"; +import * as imaGasUsage from "./imaGasUsageOperations"; +import * as imaEventLogScan from "./imaEventLogScan"; +import * as threadInfo from "./threadInfo"; export async function getBalanceErc20( isMainNet, diff --git a/src/imaTransferErrorHandling.mjs b/src/imaTransferErrorHandling.ts similarity index 98% rename from src/imaTransferErrorHandling.mjs rename to src/imaTransferErrorHandling.ts index 7324e10b..12fad59e 100644 --- a/src/imaTransferErrorHandling.mjs +++ b/src/imaTransferErrorHandling.ts @@ -24,7 +24,7 @@ */ import { UniversalDispatcherEvent, EventDispatcher } - from "./eventDispatcher.mjs"; + from "./eventDispatcher"; export function verifyTransferErrorCategoryName( strCategory ) { return "" + ( strCategory ? strCategory : "default" ); diff --git a/src/imaTx.mjs b/src/imaTx.ts similarity index 99% rename from src/imaTx.mjs rename to src/imaTx.ts index d7460956..15c8ab5d 100644 --- a/src/imaTx.mjs +++ b/src/imaTx.ts @@ -30,14 +30,14 @@ import * as childProcessModule from "child_process"; import Redis from "ioredis"; import * as ethereumJsUtilModule from "ethereumjs-util"; -import * as log from "./log.mjs"; +import * as log from "./log"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaUtils from "./utils.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaEventLogScan from "./imaEventLogScan.mjs"; +import * as owaspUtils from "./owaspUtils"; +import * as imaUtils from "./utils"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaEventLogScan from "./imaEventLogScan"; -import * as threadInfo from "./threadInfo.mjs"; +import * as threadInfo from "./threadInfo"; const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); diff --git a/src/log.mjs b/src/log.ts similarity index 64% rename from src/log.mjs rename to src/log.ts index aced35d8..c952270e 100644 --- a/src/log.mjs +++ b/src/log.ts @@ -23,12 +23,12 @@ * @copyright SKALE Labs 2019-Present */ -import * as cc from "./cc.mjs"; +import * as cc from "./cc"; import * as fs from "fs"; -let gArrStreams = []; +let gArrStreams: any[] = []; -let gFlagLogWithTimeStamps = true; +let gFlagLogWithTimeStamps: boolean = true; let gIdentifierAllocatorCounter = 0; @@ -40,40 +40,40 @@ const getDurationString = cc.getDurationString; export { safeURL, replaceAll, timestampHR, capitalizeFirstLetter, getDurationString }; -export function autoEnableColorizationFromCommandLineArgs() { +export function autoEnableColorizationFromCommandLineArgs() : void { return cc.autoEnableFromCommandLineArgs(); } -export function enableColorization( bIsEnable ) { +export function enableColorization( bIsEnable?: boolean ) : void { cc.enable( !!bIsEnable ); } -export function isEnabledColorization() { +export function isEnabledColorization() : boolean { return ( !! ( cc.isEnabled() ) ); } -export function getPrintTimestamps() { +export function getPrintTimestamps() : boolean { return gFlagLogWithTimeStamps; } -export function setPrintTimestamps( b ) { +export function setPrintTimestamps( b?: boolean ) : void { gFlagLogWithTimeStamps = ( !!b ); } -export function n2s( n, sz ) { - let s = "" + n; +export function n2s( n: any, sz: number ) : string { + let s:string = "" + n; while( s.length < sz ) s = "0" + s; return s; } -export function generateTimestampString( ts, isColorized ) { +export function generateTimestampString( ts?: any, isColorized?: boolean ) : string { isColorized = ( typeof isColorized == "undefined" ) ? true : ( !!isColorized ); ts = ( ts instanceof Date ) ? ts : new Date(); - const ccDate = function( x ) { return isColorized ? cc.date( x ) : x; }; - const ccTime = function( x ) { return isColorized ? cc.time( x ) : x; }; - const ccFractionPartOfTime = function( x ) { return isColorized ? cc.frac_time( x ) : x; }; - const ccBright = function( x ) { return isColorized ? cc.bright( x ) : x; }; + const ccDate = function( x?: any ) : string { return isColorized ? cc.date( x ) : x; }; + const ccTime = function( x?: any ) : string { return isColorized ? cc.time( x ) : x; }; + const ccFractionPartOfTime = function( x?: any ) : string { return isColorized ? cc.frac_time( x ) : x; }; + const ccBright = function( x?: any ) : string { return isColorized ? cc.bright( x ) : x; }; const s = "" + ccDate( n2s( ts.getUTCFullYear(), 4 ) ) + ccBright( "-" ) + ccDate( n2s( ts.getUTCMonth() + 1, 2 ) ) + @@ -86,11 +86,11 @@ export function generateTimestampString( ts, isColorized ) { return s; } -export function generateTimestampPrefix( ts, isColorized ) { +export function generateTimestampPrefix( ts?: any, isColorized?: boolean ) : string { return generateTimestampString( ts, isColorized ) + cc.bright( ":" ) + " "; } -export function removeAllStreams() { +export function removeAllStreams() : void { let i = 0; let cnt = 0; try { cnt = gArrStreams.length; @@ -106,7 +106,7 @@ export function removeAllStreams() { gArrStreams = []; } -export function getStreamWithFilePath( strFilePath ) { +export function getStreamWithFilePath( strFilePath: string ) : any { try { let i = 0; const cnt = gArrStreams.length; for( i = 0; i < cnt; ++i ) { @@ -122,7 +122,7 @@ export function getStreamWithFilePath( strFilePath ) { return null; } -export function createStandardOutputStream() { +export function createStandardOutputStream() : any { try { const objEntry = { "id": gIdentifierAllocatorCounter ++, @@ -133,18 +133,18 @@ export function createStandardOutputStream() { "haveOwnTimestamps": false, "isPausedTimeStamps": false, "strOwnIndent": "", - "write": function() { + "write": function( ...args: any[] ) : void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) ? generateTimestampPrefix( null, true ) : "" ); - s += fmtArgumentsArray( arguments ); + s += fmtArgumentsArray( args ); try { if( this.objStream && s.length > 0 ) this.objStream.write( s ); } catch ( err ) { } }, - "writeRaw": function() { - const s = fmtArgumentsArray( arguments ); + "writeRaw": function( ...args: any[] ) : void { + const s = fmtArgumentsArray( args ); try { if( this.objStream && s.length > 0 ) this.objStream.write( s ); @@ -154,64 +154,65 @@ export function createStandardOutputStream() { "open": function() { try { this.objStream = process.stdout; } catch ( err ) { } }, "size": function() { return 0; }, "rotate": function( nBytesToWrite ) { }, - "toString": function() { return "" + strFilePath; }, - "exposeDetailsTo": function( otherStream, strTitle, isSuccess ) { }, + "toString": function() : string { return "" + this.strFilePath; }, + "exposeDetailsTo": + function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { }, // high-level formatters - "fatal": function() { - if( verboseGet() >= verboseReversed().fatal ) - this.write( getLogLinePrefixFatal() + fmtFatal( ...arguments ) ); + "fatal": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["fatal"] ) + this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function() { - if( verboseGet() >= verboseReversed().critical ) { + "critical": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["critical"] ) { this.write( - getLogLinePrefixCritical() + fmtCritical( ...arguments ) ); + getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, - "error": function() { - if( verboseGet() >= verboseReversed().error ) - this.write( getLogLinePrefixError() + fmtError( ...arguments ) ); + "error": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["error"] ) + this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function() { - if( verboseGet() >= verboseReversed().warning ) - this.write( getLogLinePrefixWarning() + fmtWarning( ...arguments ) ); + "warning": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["warning"] ) + this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function() { - if( verboseGet() >= verboseReversed().attention ) { + "attention": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["attention"] ) { this.write( - getLogLinePrefixAttention() + fmtAttention( ...arguments ) ); + getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function() { - if( verboseGet() >= verboseReversed().information ) { + "information": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) { this.write( - getLogLinePrefixInformation() + fmtInformation( ...arguments ) ); + getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function() { - if( verboseGet() >= verboseReversed().information ) { + "info": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) { this.write( - getLogLinePrefixInformation() + fmtInformation( ...arguments ) ); + getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function() { - if( verboseGet() >= verboseReversed().notice ) - this.write( getLogLinePrefixNotice() + fmtNotice( ...arguments ) ); + "notice": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function() { - if( verboseGet() >= verboseReversed().notice ) - this.write( getLogLinePrefixNote() + fmtNote( ...arguments ) ); + "note": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function() { - if( verboseGet() >= verboseReversed().debug ) - this.write( getLogLinePrefixDebug() + fmtDebug( ...arguments ) ); + "debug": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["debug"] ) + this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function() { - if( verboseGet() >= verboseReversed().trace ) - this.write( getLogLinePrefixTrace() + fmtTrace( ...arguments ) ); + "trace": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["trace"] ) + this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function() { - if( verboseGet() >= verboseReversed().information ) - this.write( getLogLinePrefixSuccess() + fmtSuccess( ...arguments ) ); + "success": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) + this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } }; objEntry.open(); @@ -221,7 +222,7 @@ export function createStandardOutputStream() { return null; } -export function insertStandardOutputStream() { +export function insertStandardOutputStream() : boolean { let objEntry = getStreamWithFilePath( "stdout" ); if( objEntry !== null ) return true; @@ -232,7 +233,7 @@ export function insertStandardOutputStream() { return true; } -export function createMemoryOutputStream() { +export function createMemoryOutputStream() : any { try { const objEntry = { "id": gIdentifierAllocatorCounter ++, @@ -259,8 +260,8 @@ export function createMemoryOutputStream() { return true; return false; }, - "write": function() { - const s = fmtArgumentsArray( arguments ); + "write": function( ...args: any[] ) : void { + const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); for( let i = 0; i < arr.length; ++ i ) { const strLine = arr[i]; @@ -274,8 +275,8 @@ export function createMemoryOutputStream() { this.arrAccumulatedLogTextLines.push( strHeader + strLine + "\n" ); } }, - "writeRaw": function() { - const s = fmtArgumentsArray( arguments ); + "writeRaw": function( ...args: any[] ) : void { + const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); for( let i = 0; i < arr.length; ++ i ) { const strLine = arr[i]; @@ -287,13 +288,13 @@ export function createMemoryOutputStream() { "open": function() { this.clear(); }, "size": function() { return 0; }, "rotate": function( nBytesToWrite ) { this.this.arrAccumulatedLogTextLines = []; }, - "toString": function() { + "toString": function() : string { let s = ""; for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) s += this.arrAccumulatedLogTextLines[i]; return s; }, - "exposeDetailsTo": function( otherStream, strTitle, isSuccess ) { + "exposeDetailsTo": function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { if( ! ( this.arrAccumulatedLogTextLines && this.arrAccumulatedLogTextLines.length > 0 ) ) return; @@ -333,59 +334,59 @@ export function createMemoryOutputStream() { } }, // high-level formatters - "fatal": function() { - if( verboseGet() >= verboseReversed().fatal ) - this.write( getLogLinePrefixFatal() + fmtFatal( ...arguments ) ); + "fatal": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["fatal"] ) + this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function() { - if( verboseGet() >= verboseReversed().critical ) - this.write( getLogLinePrefixCritical() + fmtCritical( ...arguments ) ); + "critical": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["critical"] ) + this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); }, - "error": function() { - if( verboseGet() >= verboseReversed().error ) - this.write( getLogLinePrefixError() + fmtError( ...arguments ) ); + "error": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["error"] ) + this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function() { - if( verboseGet() >= verboseReversed().warning ) - this.write( getLogLinePrefixWarning() + fmtWarning( ...arguments ) ); + "warning": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["warning"] ) + this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function() { - if( verboseGet() >= verboseReversed().attention ) { + "attention": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["attention"] ) { this.write( - getLogLinePrefixAttention() + fmtAttention( ...arguments ) ); + getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function() { - if( verboseGet() >= verboseReversed().information ) { + "information": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) { this.write( - getLogLinePrefixInformation() + fmtInformation( ...arguments ) ); + getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function() { - if( verboseGet() >= verboseReversed().information ) { + "info": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) { this.write( - getLogLinePrefixInformation() + fmtInformation( ...arguments ) ); + getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function() { - if( verboseGet() >= verboseReversed().notice ) - this.write( getLogLinePrefixNotice() + fmtNotice( ...arguments ) ); + "notice": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function() { - if( verboseGet() >= verboseReversed().notice ) - this.write( getLogLinePrefixNote() + fmtNote( ...arguments ) ); + "note": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function() { - if( verboseGet() >= verboseReversed().debug ) - this.write( getLogLinePrefixDebug() + fmtDebug( ...arguments ) ); + "debug": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["debug"] ) + this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function() { - if( verboseGet() >= verboseReversed().trace ) - this.write( getLogLinePrefixTrace() + fmtTrace( ...arguments ) ); + "trace": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["trace"] ) + this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function() { - if( verboseGet() >= verboseReversed().information ) - this.write( getLogLinePrefixSuccess() + fmtSuccess( ...arguments ) ); + "success": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) + this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } }; objEntry.open(); @@ -395,7 +396,7 @@ export function createMemoryOutputStream() { return null; } -export function insertMemoryOutputStream() { +export function insertMemoryOutputStream() : boolean { let objEntry = getStreamWithFilePath( "memory" ); if( objEntry !== null ) return true; @@ -406,22 +407,23 @@ export function insertMemoryOutputStream() { return true; } -export function createFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFilesCount ) { +export function createFileOutput( + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : any { try { const objEntry = { "id": gIdentifierAllocatorCounter ++, "strPath": "" + strFilePath, - "nMaxSizeBeforeRotation": 0 + nMaxSizeBeforeRotation, - "nMaxFilesCount": 0 + nMaxFilesCount, + "nMaxSizeBeforeRotation": 0 + ( nMaxSizeBeforeRotation || 0 ), + "nMaxFilesCount": 0 + ( nMaxFilesCount || 0 ), "objStream": null, "haveOwnTimestamps": false, "isPausedTimeStamps": false, "strOwnIndent": "", - "write": function() { + "write": function( ...args: any[] ) : void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) ? generateTimestampPrefix( null, true ) : "" ); - s += fmtArgumentsArray( arguments ); + s += fmtArgumentsArray( args ); try { if( s.length > 0 ) { this.rotate( s.length ); @@ -429,8 +431,8 @@ export function createFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFiles } } catch ( err ) { } }, - "writeRaw": function() { - const s = fmtArgumentsArray( arguments ); + "writeRaw": function( ...args: any[] ) : void { + const s = fmtArgumentsArray( args ); try { if( s.length > 0 ) { this.rotate( s.length ); @@ -446,7 +448,7 @@ export function createFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFiles }, "open": function() { this.objStream = - fs.openSync( this.strPath, "a", fs.constants.O_NONBLOCK | fs.constants.O_WR ); + fs.openSync( this.strPath, "a", fs.constants.O_NONBLOCK | fs.constants.O_RDWR ); }, "size": function() { try { return fs.lstatSync( this.strPath ).size; } catch ( err ) { return 0; } @@ -481,64 +483,65 @@ export function createFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFiles } catch ( err ) { } }, - "toString": function() { return "" + strFilePath; }, - "exposeDetailsTo": function( otherStream, strTitle, isSuccess ) { }, + "toString": function() : string { return "" + strFilePath; }, + "exposeDetailsTo": + function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { }, // high-level formatters - "fatal": function() { - if( verboseGet() >= verboseReversed().fatal ) - this.write( getLogLinePrefixFatal() + fmtFatal( ...arguments ) ); + "fatal": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["fatal"] ) + this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function() { - if( verboseGet() >= verboseReversed().critical ) { + "critical": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["critical"] ) { this.write( - getLogLinePrefixCritical() + fmtCritical( ...arguments ) ); + getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, - "error": function() { - if( verboseGet() >= verboseReversed().error ) - this.write( getLogLinePrefixError() + fmtError( ...arguments ) ); + "error": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["error"] ) + this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function() { - if( verboseGet() >= verboseReversed().warning ) - this.write( getLogLinePrefixWarning() + fmtWarning( ...arguments ) ); + "warning": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["warning"] ) + this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function() { - if( verboseGet() >= verboseReversed().attention ) { + "attention": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["attention"] ) { this.write( - getLogLinePrefixAttention() + fmtAttention( ...arguments ) ); + getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function() { - if( verboseGet() >= verboseReversed().information ) { + "information": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) { this.write( - getLogLinePrefixInformation() + fmtInformation( ...arguments ) ); + getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function() { - if( verboseGet() >= verboseReversed().information ) { + "info": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) { this.write( - getLogLinePrefixInformation() + fmtInformation( ...arguments ) ); + getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function() { - if( verboseGet() >= verboseReversed().notice ) - this.write( getLogLinePrefixNotice() + fmtNotice( ...arguments ) ); + "notice": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function() { - if( verboseGet() >= verboseReversed().notice ) - this.write( getLogLinePrefixNote() + fmtNote( ...arguments ) ); + "note": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function() { - if( verboseGet() >= verboseReversed().debug ) - this.write( getLogLinePrefixDebug() + fmtDebug( ...arguments ) ); + "debug": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["debug"] ) + this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function() { - if( verboseGet() >= verboseReversed().trace ) - this.write( getLogLinePrefixTrace() + fmtTrace( ...arguments ) ); + "trace": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["trace"] ) + this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function() { - if( verboseGet() >= verboseReversed().information ) - this.write( getLogLinePrefixSuccess() + fmtSuccess( ...arguments ) ); + "success": function( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) + this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } }; objEntry.open(); @@ -551,7 +554,8 @@ export function createFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFiles } return null; } -export function insertFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFilesCount ) { +export function insertFileOutput( + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : any { let objEntry = getStreamWithFilePath( "" + strFilePath ); if( objEntry !== null ) return true; @@ -562,7 +566,7 @@ export function insertFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFiles return true; } -export function extractErrorMessage( jo, strDefaultErrorText ) { +export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ) : string { strDefaultErrorText = strDefaultErrorText || "unknown error or error without a description"; if( ! jo ) return strDefaultErrorText; @@ -590,10 +594,12 @@ export function extractErrorMessage( jo, strDefaultErrorText ) { return strDefaultErrorText; } -function tryToSplitFormatString( strFormat, cntArgsMax ) { +function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ) : any[]|null { if( !( strFormat && typeof strFormat == "string" ) ) return null; - const arrParts = []; + if( ! cntArgsMax ) + cntArgsMax = 0; + const arrParts: any[] = []; let s = strFormat, cntFoundArgs = 0; for( ; true; ) { if( cntFoundArgs >= cntArgsMax ) @@ -621,12 +627,12 @@ function tryToSplitFormatString( strFormat, cntArgsMax ) { return arrParts; } -export function fmtArgumentsArray( arrArgs, fnFormatter ) { +export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string { fnFormatter = fnFormatter || function( arg ) { return arg; }; const arrParts = ( arrArgs && arrArgs.length > 0 ) ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; let s = "", isValueMode = false; - const fnDefaultOneArgumentFormatter = function( arg, fnCustomFormatter ) { + const fnDefaultOneArgumentFormatter = function( arg?: any, fnCustomFormatter?: any ) : string { if( ! fnCustomFormatter ) fnCustomFormatter = fnFormatter; const t = typeof arg; @@ -641,7 +647,7 @@ export function fmtArgumentsArray( arrArgs, fnFormatter ) { return cc.logArgToString( arg ); return arg; }; - const fnFormatOneArgument = function( arg, fmt ) { + const fnFormatOneArgument = function( arg: any, fmt?: any ) : string { if( ! arg ) return arg; if( arg == " " || arg == "\n" ) @@ -705,7 +711,7 @@ export function fmtArgumentsArray( arrArgs, fnFormatter ) { return s; } -export function outputStringToAllStreams( s ) { +export function outputStringToAllStreams( s: string ) : void { try { if( s.length <= 0 ) return; @@ -721,155 +727,160 @@ export function outputStringToAllStreams( s ) { } } -export function write() { - let s = getPrintTimestamps() ? generateTimestampPrefix( null, true ) : ""; - s += fmtArgumentsArray( arguments ); +export function write( ...args: any[] ) : void { + let s: string = getPrintTimestamps() ? generateTimestampPrefix( null, true ) : ""; + s += fmtArgumentsArray( args ); outputStringToAllStreams( s ); } -export function writeRaw() { - const s = fmtArgumentsArray( arguments ); +export function writeRaw( ...args: any[] ) : void { + const s: string = fmtArgumentsArray( args ); outputStringToAllStreams( s ); } -export function getLogLinePrefixFatal() { +export function getLogLinePrefixFatal() : string { return cc.fatal( "FATAL ERROR:" ) + " "; } -export function getLogLinePrefixCritical() { +export function getLogLinePrefixCritical() : string { return cc.fatal( "CRITICAL ERROR:" ) + " "; } -export function getLogLinePrefixError() { +export function getLogLinePrefixError() : string { return cc.fatal( "ERROR:" ) + " "; } -export function getLogLinePrefixWarning() { +export function getLogLinePrefixWarning() : string { return cc.error( "WARNING:" ) + " "; } -export function getLogLinePrefixAttention() { +export function getLogLinePrefixAttention() : string { return ""; } -export function getLogLinePrefixInformation() { +export function getLogLinePrefixInformation() : string { return ""; } -export function getLogLinePrefixNotice() { +export function getLogLinePrefixNotice() : string { return ""; } -export function getLogLinePrefixNote() { +export function getLogLinePrefixNote() : string { return ""; } -export function getLogLinePrefixDebug() { +export function getLogLinePrefixDebug() : string { return ""; } -export function getLogLinePrefixTrace() { +export function getLogLinePrefixTrace() : string { return ""; } -export function getLogLinePrefixSuccess() { +export function getLogLinePrefixSuccess() : string { return ""; } // high-level format to returned string -export function fmtFatal() { - return fmtArgumentsArray( arguments, cc.error ); +export function fmtFatal( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.error ); } -export function fmtCritical() { - return fmtArgumentsArray( arguments, cc.error ); +export function fmtCritical( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.error ); } -export function fmtError() { - return fmtArgumentsArray( arguments, cc.error ); +export function fmtError( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.error ); } -export function fmtWarning() { - return fmtArgumentsArray( arguments, cc.warning ); +export function fmtWarning( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.warning ); } -export function fmtAttention() { - return fmtArgumentsArray( arguments, cc.attention ); +export function fmtAttention( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.attention ); } -export function fmtInformation() { - return fmtArgumentsArray( arguments, cc.info ); +export function fmtInformation( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.info ); } -export function fmtInfo() { - return fmtArgumentsArray( arguments, cc.info ); +export function fmtInfo( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.info ); } -export function fmtNotice() { - return fmtArgumentsArray( arguments, cc.notice ); +export function fmtNotice( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.notice ); } -export function fmtNote() { - return fmtArgumentsArray( arguments, cc.note ); +export function fmtNote( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.note ); } -export function fmtDebug() { - return fmtArgumentsArray( arguments, cc.debug ); +export function fmtDebug( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.debug ); } -export function fmtTrace() { - return fmtArgumentsArray( arguments, cc.trace ); +export function fmtTrace( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.trace ); } -export function fmtSuccess() { - return fmtArgumentsArray( arguments, cc.success ); +export function fmtSuccess( ...args: any[] ) : string { + return fmtArgumentsArray( args, cc.success ); } // high-level formatted output -export function fatal() { - if( verboseGet() >= verboseReversed().fatal ) - write( getLogLinePrefixFatal() + fmtFatal( ...arguments ) + "\n" ); +export function fatal( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["fatal"] ) + write( getLogLinePrefixFatal() + fmtFatal( ...args ) + "\n" ); } -export function critical() { - if( verboseGet() >= verboseReversed().critical ) - write( getLogLinePrefixCritical() + fmtCritical( ...arguments ) + "\n" ); +export function critical( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["critical"] ) + write( getLogLinePrefixCritical() + fmtCritical( ...args ) + "\n" ); } -export function error() { - if( verboseGet() >= verboseReversed().error ) - write( getLogLinePrefixError() + fmtError( ...arguments ) + "\n" ); +export function error( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["error"] ) + write( getLogLinePrefixError() + fmtError( ...args ) + "\n" ); } -export function warning() { - if( verboseGet() >= verboseReversed().warning ) - write( getLogLinePrefixWarning() + fmtWarning( ...arguments ) + "\n" ); +export function warning( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["warning"] ) + write( getLogLinePrefixWarning() + fmtWarning( ...args ) + "\n" ); } -export function attention() { - if( verboseGet() >= verboseReversed().attention ) - write( getLogLinePrefixAttention() + fmtAttention( ...arguments ) + "\n" ); +export function attention( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["attention"] ) + write( getLogLinePrefixAttention() + fmtAttention( ...args ) + "\n" ); } -export function information() { - if( verboseGet() >= verboseReversed().information ) - write( getLogLinePrefixInformation() + fmtInformation( ...arguments ) + "\n" ); +export function information( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) + write( getLogLinePrefixInformation() + fmtInformation( ...args ) + "\n" ); } -export function info() { - if( verboseGet() >= verboseReversed().information ) - write( getLogLinePrefixInformation() + fmtInformation( ...arguments ) + "\n" ); +export function info( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) + write( getLogLinePrefixInformation() + fmtInformation( ...args ) + "\n" ); } -export function notice() { - if( verboseGet() >= verboseReversed().notice ) - write( getLogLinePrefixNotice() + fmtNotice( ...arguments ) + "\n" ); +export function notice( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + write( getLogLinePrefixNotice() + fmtNotice( ...args ) + "\n" ); } -export function note() { - if( verboseGet() >= verboseReversed().notice ) - write( getLogLinePrefixNote() + fmtNote( ...arguments ) + "\n" ); +export function note( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["notice"] ) + write( getLogLinePrefixNote() + fmtNote( ...args ) + "\n" ); } -export function debug() { - if( verboseGet() >= verboseReversed().debug ) - write( getLogLinePrefixDebug() + fmtDebug( ...arguments ) + "\n" ); +export function debug( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["debug"] ) + write( getLogLinePrefixDebug() + fmtDebug( ...args ) + "\n" ); } -export function trace() { - if( verboseGet() >= verboseReversed().trace ) - write( getLogLinePrefixTrace() + fmtTrace( ...arguments ) + "\n" ); +export function trace( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["trace"] ) + write( getLogLinePrefixTrace() + fmtTrace( ...args ) + "\n" ); } -export function success() { - if( verboseGet() >= verboseReversed().information ) - write( getLogLinePrefixSuccess() + fmtSuccess( ...arguments ) + "\n" ); +export function success( ...args: any[] ) : void { + if( verboseGet() >= verboseReversed()["information"] ) + write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) + "\n" ); } -export function removeAll() { +export function removeAll() : void { removeAllStreams(); } -export function addStdout() { +export function addStdout() : boolean { return insertStandardOutputStream(); } -export function addMemory() { +export function addMemory() : boolean { return insertMemoryOutputStream(); } -export function createMemoryStream() { +export function createMemoryStream() : any { return createMemoryOutputStream(); } -export function add( strFilePath, nMaxSizeBeforeRotation, nMaxFilesCount ) { +export function add( + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : boolean { + if( ! nMaxSizeBeforeRotation ) + nMaxSizeBeforeRotation = 0; + if( ! nMaxFilesCount ) + nMaxFilesCount = 0; return insertFileOutput( strFilePath, ( nMaxSizeBeforeRotation <= 0 ) ? -1 : nMaxSizeBeforeRotation, @@ -877,20 +888,20 @@ export function add( strFilePath, nMaxSizeBeforeRotation, nMaxFilesCount ) { ); } -export function close() { +export function close() : void { // for compatibility with created streams } -export function exposeDetailsTo() { +export function exposeDetailsTo( otherStream: any, strTitle: string, isSuccess: boolean ) : void { // for compatibility with created streams } -export function toString() { +export function toString() : string { // for compatibility with created streams return ""; } -const gMapVerbose = { +const gMapVerbose : any = { 0: "silent", 1: "fatal", 2: "critical", @@ -903,7 +914,7 @@ const gMapVerbose = { 9: "trace" }; function computeVerboseAlias() { - const m = {}; + const m: any = {}; for( const key in gMapVerbose ) { if( !gMapVerbose.hasOwnProperty( key ) ) continue; // skip loop if the property is from prototype @@ -924,10 +935,10 @@ function computeVerboseAlias() { m.detailed = 0 + parseInt( m.trace ); // alias return m; } -let gMapReversedVerbose = null; +let gMapReversedVerbose: any = null; -export function verbose() { return gMapVerbose; } -export function verboseReversed() { +export function verbose() : any { return gMapVerbose; } +export function verboseReversed() : Map < string, number > { if( ! gMapReversedVerbose ) gMapReversedVerbose = computeVerboseAlias(); return gMapReversedVerbose; @@ -939,11 +950,11 @@ export function verboseLevelAsTextForLog( vl ) { const tl = gMapVerbose[vl]; return tl; } - return "unknown(" + JSON.stringify( y ) + ")"; + return "unknown(" + JSON.stringify( vl ) + ")"; } let gFlagIsExposeDetails = false; -let gVerboseLevel = 0 + verboseReversed().information; +let gVerboseLevel = 0 + verboseReversed()["information"]; export function exposeDetailsGet() { return ( !!gFlagIsExposeDetails ); @@ -952,15 +963,15 @@ export function exposeDetailsSet( isExpose ) { gFlagIsExposeDetails = ( !!isExpose ); } -export function verboseGet() { +export function verboseGet() : number { return 0 + gVerboseLevel; } -export function verboseSet( vl ) { +export function verboseSet( vl?: any ) : void { gVerboseLevel = parseInt( vl ); } -export function verboseParse( s ) { - let n = 5; +export function verboseParse( s: string ) : number { + let n: number = 5; try { const isNumbersOnly = /^\d+$/.test( s ); if( isNumbersOnly ) @@ -973,7 +984,7 @@ export function verboseParse( s ) { const name = gMapVerbose[key]; const ch1 = name[0].toLowerCase(); if( ch0 == ch1 ) { - n = key; + n = parseInt( key ); return n; } } @@ -982,7 +993,7 @@ export function verboseParse( s ) { return n; } -export function verboseList() { +export function verboseList() : void { for( const key in gMapVerbose ) { if( !gMapVerbose.hasOwnProperty( key ) ) continue; // skip loop if the property is from prototype @@ -991,31 +1002,31 @@ export function verboseList() { } } -export function u( x ) { +export function u( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.u( x ); } -export function v( x ) { +export function v( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.j( x ); } -export function em( x ) { +export function em( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.warning( x ); } -export function stack( x ) { +export function stack( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.stack( x ); } -export function onOff( x ) { +export function onOff( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.onOff( x ); } -export function yn( x ) { +export function yn( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.yn( x ); } -export function posNeg( condition, strPositive, strNegative ) { +export function posNeg( condition: any, strPositive: string, strNegative: string ) : string { return condition ? ( cc.isStringAlreadyColorized( strPositive ) ? strPositive : cc.success( strPositive ) ) : ( cc.isStringAlreadyColorized( strNegative ) ? strNegative : cc.error( strNegative ) ); diff --git a/src/loop.mjs b/src/loop.ts similarity index 98% rename from src/loop.mjs rename to src/loop.ts index 5b1d5e7e..62a3a8ee 100644 --- a/src/loop.mjs +++ b/src/loop.ts @@ -23,20 +23,20 @@ * @copyright SKALE Labs 2019-Present */ -import * as networkLayer from "./socket.mjs"; +import * as networkLayer from "./socket"; import * as url from "url"; -import * as threadInfo from "./threadInfo.mjs"; +import * as threadInfo from "./threadInfo"; import * as path from "path"; -import * as log from "./log.mjs"; -import * as IMA from "./imaCore.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; -import * as imaOracleOperations from "./imaOracleOperations.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaBLS from "./bls.mjs"; -import * as skaleObserver from "./observer.mjs"; -import * as pwa from "./pwa.mjs"; -import * as state from "./state.mjs"; +import * as log from "./log"; +import * as IMA from "./imaCore"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as imaOracleOperations from "./imaOracleOperations"; +import * as owaspUtils from "./owaspUtils"; +import * as imaBLS from "./bls"; +import * as skaleObserver from "./observer"; +import * as pwa from "./pwa"; +import * as state from "./state"; const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); diff --git a/src/loopWorker.mjs b/src/loopWorker.ts similarity index 95% rename from src/loopWorker.mjs rename to src/loopWorker.ts index 648cbb65..df44a72e 100644 --- a/src/loopWorker.mjs +++ b/src/loopWorker.ts @@ -24,24 +24,26 @@ */ import { parentPort, workerData } from "worker_threads"; -import * as networkLayer from "./socket.mjs"; -import { SocketServer } from "./socketServer.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as loop from "./loop.mjs"; -import * as imaTx from "./imaTx.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; -import * as imaCLI from "./cli.mjs"; -import * as state from "./state.mjs"; -import * as pwa from "./pwa.mjs"; -import * as log from "./log.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as networkLayer from "./socket"; +import { SocketServer } from "./socketServer"; +import * as owaspUtils from "./owaspUtils"; +import * as loop from "./loop"; +import * as imaTx from "./imaTx"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as imaCLI from "./cli"; +import * as state from "./state"; +import * as pwa from "./pwa"; +import * as log from "./log"; +import * as threadInfo from "./threadInfo"; let imaState = state.get(); -parentPort.on( "message", jo => { - if( networkLayer.inWorkerAPIs.onMessage( jo ) ) - return; -} ); +if( parentPort ) { + parentPort.on( "message", jo => { + if( networkLayer.inWorkerAPIs.onMessage( jo ) ) + return; + } ); +} function doSendMessage( type, endpoint, workerUUID, data ) { const jo = networkLayer.socketReceivedDataReverseMarshall( data ); @@ -54,7 +56,8 @@ function doSendMessage( type, endpoint, workerUUID, data ) { "workerUUID": workerUUID, "data": jo }; - parentPort.postMessage( networkLayer.socketSentDataMarshall( joSend ) ); + if( parentPort ) + parentPort.postMessage( networkLayer.socketSentDataMarshall( joSend ) ); } class ObserverServer extends SocketServer { diff --git a/src/main.mjs b/src/main.ts similarity index 97% rename from src/main.mjs rename to src/main.ts index 8bac2e66..73ed46d0 100644 --- a/src/main.mjs +++ b/src/main.ts @@ -26,19 +26,19 @@ import express from "express"; import bodyParser from "body-parser"; import * as ws from "ws"; -import * as owaspUtils from "./owaspUtils.mjs"; -import * as log from "./log.mjs"; -import * as imaCLI from "./cli.mjs"; -import * as loop from "./loop.mjs"; -import * as imaHelperAPIs from "./imaHelperAPIs.mjs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling.mjs"; -import * as imaBLS from "./bls.mjs"; -import * as pwa from "./pwa.mjs"; -import * as clpTools from "./clpTools.mjs"; -import * as discoveryTools from "./discoveryTools.mjs"; -import * as skaleObserver from "./observer.mjs"; +import * as owaspUtils from "./owaspUtils"; +import * as log from "./log"; +import * as imaCLI from "./cli"; +import * as loop from "./loop"; +import * as imaHelperAPIs from "./imaHelperAPIs"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as imaBLS from "./bls"; +import * as pwa from "./pwa"; +import * as clpTools from "./clpTools"; +import * as discoveryTools from "./discoveryTools"; +import * as skaleObserver from "./observer"; -import * as state from "./state.mjs"; +import * as state from "./state"; // allow self-signed wss and https process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; diff --git a/src/observer.mjs b/src/observer.ts similarity index 94% rename from src/observer.mjs rename to src/observer.ts index ec84efc6..8eb3fc4c 100644 --- a/src/observer.mjs +++ b/src/observer.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as state from "./state.mjs"; -import * as imaUtils from "./utils.mjs"; -import * as log from "./log.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as state from "./state"; +import * as imaUtils from "./utils"; +import * as log from "./log"; +import * as threadInfo from "./threadInfo"; export function findSChainIndexInArrayByName( arrSChains, strSChainName ) { for( let idxSChain = 0; idxSChain < arrSChains.length; ++ idxSChain ) { diff --git a/src/oracle.mjs b/src/oracle.ts similarity index 98% rename from src/oracle.mjs rename to src/oracle.ts index 99be174d..db603973 100644 --- a/src/oracle.mjs +++ b/src/oracle.ts @@ -23,9 +23,9 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as threadInfo from "./threadInfo.mjs"; +import * as log from "./log"; +import * as rpcCall from "./rpcCall"; +import * as threadInfo from "./threadInfo"; import numberToBN from "number-to-bn"; import * as sha3Module from "sha3"; const Keccak = sha3Module.Keccak; diff --git a/src/owaspUtils.mjs b/src/owaspUtils.ts similarity index 84% rename from src/owaspUtils.mjs rename to src/owaspUtils.ts index 27ee5c0b..db87b61a 100644 --- a/src/owaspUtils.mjs +++ b/src/owaspUtils.ts @@ -28,12 +28,12 @@ // https://www.gitbook.com/download/pdf/book/checkmarx/JS-SCP // top 10 hit parade: https://owasp.org/www-project-top-ten/ -import * as log from "./log.mjs"; +import * as log from "./log"; import * as ethersMod from "ethers"; import * as fs from "fs"; import * as ethereumJsUtilModule from "ethereumjs-util"; import * as ethereumJsWalletModule from "ethereumjs-wallet"; -const Wallet = ethereumJsWalletModule.default.default; +const Wallet = ethereumJsWalletModule.default; const safeURL = log.safeURL; const replaceAll = log.replaceAll; @@ -41,7 +41,7 @@ const extractErrorMessage = log.extractErrorMessage; export { ethersMod, safeURL, replaceAll, extractErrorMessage }; -export function rxIsInt( val ) { +export function rxIsInt( val: any ) : boolean { try { const intRegex = /^-?\d+$/; if( !intRegex.test( val ) ) @@ -54,7 +54,7 @@ export function rxIsInt( val ) { return false; } -export function rxIsFloat( val ) { +export function rxIsFloat( val: any ) : boolean { try { const floatRegex = /^-?\d+(?:[.,]\d*?)?$/; if( !floatRegex.test( val ) ) @@ -68,7 +68,7 @@ export function rxIsFloat( val ) { return false; } -export function parseIntOrHex( s ) { +export function parseIntOrHex( s: any ) : number { if( typeof s != "string" ) return parseInt( s ); s = s.trim(); @@ -77,7 +77,7 @@ export function parseIntOrHex( s ) { return parseInt( s, 10 ); } -export function validateRadix( value, radix ) { +export function validateRadix( value: any, radix?: any ) : boolean { value = "" + ( value ? value.toString() : "10" ); value = value.trim(); radix = ( radix == null || radix == undefined ) @@ -87,7 +87,7 @@ export function validateRadix( value, radix ) { return radix; } -export function validateInteger( value, radix ) { +export function validateInteger( value: any, radix?: any ) : boolean { try { value = "" + value; value = value.trim(); @@ -95,7 +95,7 @@ export function validateInteger( value, radix ) { return false; radix = validateRadix( value, radix ); if( ( !isNaN( value ) ) && - ( parseInt( Number( value ), radix ) == value || radix !== 10 ) && + ( parseInt( value, radix ) == value || radix !== 10 ) && ( !isNaN( parseInt( value, radix ) ) ) ) return true; @@ -104,7 +104,7 @@ export function validateInteger( value, radix ) { return false; } -export function toInteger( value, radix ) { +export function toInteger( value: any, radix?: any ) : number { try { radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) @@ -112,10 +112,10 @@ export function toInteger( value, radix ) { return parseInt( value, radix ); } catch ( err ) { } - return false; + return 0; } -export function validateFloat( value ) { +export function validateFloat( value: any ) : boolean { try { const f = parseFloat( value ); if( isNaN( f ) ) @@ -126,23 +126,23 @@ export function validateFloat( value ) { return false; } -export function toFloat( value ) { +export function toFloat( value: any ) : number { try { const f = parseFloat( value ); return f; } catch ( err ) { } - return false; + return 0.0; } -export function validateURL( s ) { +export function validateURL( s: any ) : boolean { const url = toURL( s ); if( url == null ) return false; return true; } -export function toURL( s ) { +export function toURL( s: any ) : URL | null { try { if( s == null || s == undefined ) return null; @@ -158,7 +158,7 @@ export function toURL( s ) { const ss = s.substring( 1, cnt - 1 ); const url = toURL( ss ); if( url != null && url != undefined ) - url.strStrippedStringComma = sc; + url["strStrippedStringComma"] = sc; return url; } return null; @@ -168,14 +168,14 @@ export function toURL( s ) { return null; if( url.hostname.length === 0 ) return null; - url.strStrippedStringComma = null; + url["strStrippedStringComma"] = null; return url; } catch ( err ) { return null; } } -export function toStringURL( s, defValue ) { +export function toStringURL( s?: any, defValue?: string ) : string { defValue = defValue || ""; try { const url = toURL( s ); @@ -187,7 +187,7 @@ export function toStringURL( s, defValue ) { } } -export function isUrlHTTP( strURL ) { +export function isUrlHTTP( strURL?: any ) : boolean { try { if( !validateURL( strURL ) ) return false; @@ -199,7 +199,7 @@ export function isUrlHTTP( strURL ) { return false; } -export function isUrlWS( strURL ) { +export function isUrlWS( strURL?: any ) : boolean { try { if( !validateURL( strURL ) ) return false; @@ -211,7 +211,7 @@ export function isUrlWS( strURL ) { return false; } -export function toBoolean( value ) { +export function toBoolean( value?: any ) : boolean { let b = false; try { if( typeof value === "boolean" ) @@ -232,11 +232,11 @@ export function toBoolean( value ) { return b; } -export function validateInputAddresses( address ) { +export function validateInputAddresses( address?: any ) : boolean { return ( /^(0x){1}[0-9a-fA-F]{40}$/i.test( address ) ); } -export function validateEthAddress( value ) { +export function validateEthAddress( value?: any ) : boolean { try { if( validateInputAddresses( ensureStartsWith0x( value ) ) ) return true; @@ -245,7 +245,7 @@ export function validateEthAddress( value ) { return false; } -export function validateEthPrivateKey( value ) { +export function validateEthPrivateKey( value?: any ) : boolean { try { const ethersWallet = new ethersMod.ethers.Wallet( ensureStartsWith0x( value ) ); if( ethersWallet.address ) @@ -255,7 +255,7 @@ export function validateEthPrivateKey( value ) { return false; } -export function toEthAddress( value, defValue ) { +export function toEthAddress( value?: any, defValue?: string ) : string { try { value = "" + ( value ? ensureStartsWith0x( value.toString() ) : "" ); defValue = defValue || ""; @@ -266,7 +266,7 @@ export function toEthAddress( value, defValue ) { return value; } -export function toEthPrivateKey( value, defValue ) { +export function toEthPrivateKey( value?: any, defValue?: string ) : string { try { value = "" + ( value ? value.toString() : "" ); defValue = defValue || ""; @@ -277,7 +277,7 @@ export function toEthPrivateKey( value, defValue ) { return value; } -export function verifyArgumentWithNonEmptyValue( joArg ) { +export function verifyArgumentWithNonEmptyValue( joArg?: any ) : any { if( ( !joArg.value ) || ( typeof joArg.value === "string" && joArg.value.length === 0 ) ) { console.log( log.fmtFatal( "(OWASP) Value {} of argument {} must not be empty", joArg.value, joArg.name ) ); @@ -286,7 +286,7 @@ export function verifyArgumentWithNonEmptyValue( joArg ) { return joArg; } -export function verifyArgumentIsURL( joArg ) { +export function verifyArgumentIsURL( joArg?: any ) : any { try { verifyArgumentWithNonEmptyValue( joArg ); const url = toURL( joArg.value ); @@ -308,7 +308,7 @@ export function verifyArgumentIsURL( joArg ) { } } -export function verifyArgumentIsInteger( joArg ) { +export function verifyArgumentIsInteger( joArg?: any ) : any { try { verifyArgumentWithNonEmptyValue( joArg ); if( !validateInteger( joArg.value ) ) { @@ -325,7 +325,7 @@ export function verifyArgumentIsInteger( joArg ) { } } -export function verifyArgumentIsIntegerIpPortNumber( joArg ) { +export function verifyArgumentIsIntegerIpPortNumber( joArg: any ) : any { try { verifyArgumentIsInteger( joArg ); if( joArg.value < 0 ) @@ -342,7 +342,7 @@ export function verifyArgumentIsIntegerIpPortNumber( joArg ) { } } -export function verifyArgumentIsPathToExistingFile( joArg ) { +export function verifyArgumentIsPathToExistingFile( joArg?: any ) : any { try { verifyArgumentWithNonEmptyValue( joArg ); const stats = fs.lstatSync( joArg.value ); @@ -364,7 +364,7 @@ export function verifyArgumentIsPathToExistingFile( joArg ) { } } -export function verifyArgumentIsPathToExistingFolder( joArg ) { +export function verifyArgumentIsPathToExistingFolder( joArg?: any ) : any { try { verifyArgumentWithNonEmptyValue( joArg ); const stats = fs.lstatSync( joArg.value ); @@ -386,7 +386,7 @@ export function verifyArgumentIsPathToExistingFolder( joArg ) { } } -export function verifyArgumentIsArrayOfIntegers( joArg ) { +export function verifyArgumentIsArrayOfIntegers( joArg?: any ) : any { try { verifyArgumentWithNonEmptyValue( joArg ); if( joArg.value.length < 3 ) { @@ -423,7 +423,7 @@ export function verifyArgumentIsArrayOfIntegers( joArg ) { } } -export function ensureStartsWith0x( s ) { +export function ensureStartsWith0x( s?: any ) : string { if( s == null || s == undefined || typeof s !== "string" ) return s; if( s.length < 2 ) @@ -433,7 +433,7 @@ export function ensureStartsWith0x( s ) { return "0x" + s; } -export function removeStarting0x( s ) { +export function removeStarting0x( s?: any ) : string { if( s == null || s == undefined || typeof s !== "string" ) return s; if( s.length < 2 ) @@ -443,7 +443,7 @@ export function removeStarting0x( s ) { return s; } -export function inetNtoA( n ) { +export function inetNtoA( n: number ) : string { const a = ( ( n >> 24 ) & 0xFF ) >>> 0; const b = ( ( n >> 16 ) & 0xFF ) >>> 0; const c = ( ( n >> 8 ) & 0xFF ) >>> 0; @@ -451,11 +451,11 @@ export function inetNtoA( n ) { return ( a + "." + b + "." + c + "." + d ); } -export function ipFromHex( hex ) { +export function ipFromHex( hex?: any ) : string { return inetNtoA( parseInt( removeStarting0x( hex ), 16 ) ); } -export function cloneObjectByRootKeys( joIn ) { +export function cloneObjectByRootKeys( joIn?: any ) : any { const joOut = { }, arrKeys = Object.keys( joIn ); for( let i = 0; i < arrKeys.length; ++ i ) { const key = arrKeys[i]; @@ -467,7 +467,7 @@ export function cloneObjectByRootKeys( joIn ) { // example: "1ether" -> "1000000000000000000" // supported suffix aliases, lowercase -const gMapMoneyNameSuffixAliases = { +const gMapMoneyNameSuffixAliases : any = { "ethe": "ether", "ethr": "ether", "eth": "ether", @@ -541,7 +541,7 @@ const gMapMoneyNameSuffixAliases = { "tether": "tether" }; -export function parseMoneyUnitName( s ) { +export function parseMoneyUnitName( s: string ) : string { s = s.trim().toLowerCase(); if( s == "" ) return "wei"; @@ -552,7 +552,7 @@ export function parseMoneyUnitName( s ) { return s; } -function moneyUnitNameToEthersParseSpec( s ) { +function moneyUnitNameToEthersParseSpec( s: string ) : string|number { switch ( s.toString().trim().toLowerCase() ) { case "shannon": return 9; case "lovelace": return 6; @@ -570,7 +570,7 @@ function moneyUnitNameToEthersParseSpec( s ) { return s; } -function moneyUnitNameToPostDivider( s ) { +function moneyUnitNameToPostDivider( s: string ) : string|null { switch ( s.toString().trim().toLowerCase() ) { case "femtoether": return "1000000000000000"; case "picoether": return "1000000000000"; @@ -580,7 +580,7 @@ function moneyUnitNameToPostDivider( s ) { } return null; } -function moneyUnitNameToPostMultiplier( s ) { +function moneyUnitNameToPostMultiplier( s: string ) : string|null { switch ( s.toString().trim().toLowerCase() ) { case "kether": return "1000"; case "mether": return "1000000"; @@ -590,7 +590,7 @@ function moneyUnitNameToPostMultiplier( s ) { return null; } -export function parseMoneySpecToWei( s, isThrowException ) { +export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ) : string { try { isThrowException = ( !!isThrowException ); if( s == null || s == undefined ) { @@ -637,7 +637,7 @@ export function parseMoneySpecToWei( s, isThrowException ) { return "0"; } -export function computeChainIdFromSChainName( strName ) { +export function computeChainIdFromSChainName( strName: string ) : string { let h = ethersMod.ethers.utils.id( strName ); h = removeStarting0x( h ).toLowerCase(); while( h.length < 64 ) @@ -646,12 +646,12 @@ export function computeChainIdFromSChainName( strName ) { return ensureStartsWith0x( h ); } -export function privateKeyToAccountAddress( keyPrivate ) { +export function privateKeyToAccountAddress( keyPrivate: string ) : string { return ethersMod.ethers.utils.computeAddress( ensureStartsWith0x( keyPrivate ) ); } -export function privateKeyToPublicKey( keyPrivate ) { +export function privateKeyToPublicKey( keyPrivate: string ) : string { const privateKeyBuffer = ethereumJsUtilModule.toBuffer( ensureStartsWith0x( keyPrivate ) ); const wallet = Wallet.fromPrivateKey( privateKeyBuffer ); @@ -659,13 +659,13 @@ export function privateKeyToPublicKey( keyPrivate ) { return removeStarting0x( publicKey ); } -export function publicKeyToAccountAddress( keyPublic ) { +export function publicKeyToAccountAddress( keyPublic : string ) : string { const hash = ethersMod.ethers.utils.keccak256( ensureStartsWith0x( keyPublic ) ); const strAddress = ensureStartsWith0x( hash.substr( hash.length - 40 ) ); return strAddress; } -export function fnAddressImpl_() { +export function fnAddressImpl_() : string { if( this.address_ == undefined || this.address_ == null || this.address_ == "" ) { if( this.privateKey ) this.address_ = "" + privateKeyToAccountAddress( this.privateKey ); @@ -673,9 +673,9 @@ export function fnAddressImpl_() { return this.address_; } -export function getEthersProviderFromURL( strURL ) { +export function getEthersProviderFromURL( strURL: string ) : any { const url = new URL( strURL ); - let userName = null, userPwd = null; + let userName:string|null = null, userPwd:string|null = null; if( url.username ) { userName = url.username; userPwd = url.password; @@ -683,7 +683,7 @@ export function getEthersProviderFromURL( strURL ) { url.password = ""; strURL = url.href; // remove credentials } - const joConnectionInfo = { // see https://docs.ethers.io/v5/api/utils/web/#ConnectionInfo + const joConnectionInfo: any = { // see https://docs.ethers.io/v5/api/utils/web/#ConnectionInfo url: strURL, allowInsecureAuthentication: true }; @@ -696,26 +696,26 @@ export function getEthersProviderFromURL( strURL ) { return ethersProvider; } -export function ethersProviderToUrl( ethersProvider ) { - let strURL = null; +export function ethersProviderToUrl( ethersProvider: any ) : string { + let strURL: string|null = null; if( ethersProvider && "connection" in ethersProvider && typeof ethersProvider.connection == "object" && "url" in ethersProvider.connection && typeof ethersProvider.connection.url == "string" ) strURL = "" + ethersProvider.connection.url; - return strURL; + return strURL || "N/A-URL"; } -export function toBN( x ) { +export function toBN( x?: any ) : any { const bn = ethersMod.ethers.BigNumber.from( x ); return bn; } -export function isNumeric( s ) { +export function isNumeric( s?: any ) : boolean { return /^\d+$/.test( s ); } -export function toHexStringSafe( val ) { +export function toHexStringSafe( val?: any ) : string { if( ! val ) return "0x0"; if( "toHexString" in val && typeof val.toHexString == "function" ) @@ -727,11 +727,11 @@ export function toHexStringSafe( val ) { return "" + val; } -export function setInterval2( fn, t, stepMilliSeconds ) { - const iv = { +export function setInterval2( fn: any, t: number, stepMilliSeconds?: number ) : any { + const iv: any = { real_iv: null, - stepMilliSeconds: stepMilliSeconds ? parseInt( stepMilliSeconds ) : 1000, - maxMilliSeconds: parseInt( t ), + stepMilliSeconds: stepMilliSeconds || 1000, + maxMilliSeconds: t, accumulatedMilliSeconds: 0 }; iv.real_iv = setInterval( () => { @@ -744,7 +744,7 @@ export function setInterval2( fn, t, stepMilliSeconds ) { return iv; } -export function clearInterval2( iv ) { +export function clearInterval2( iv: any ) : void { if( ! iv ) return; if( ! ( "real_iv" in iv ) ) @@ -755,6 +755,7 @@ export function clearInterval2( iv ) { iv.real_iv = null; } -export function escapeShell( cmd ) { +export function escapeShell( cmd: string ) : string { return "\"" + cmd.replace( /(["'$`\\])/g,"\\$1" ) + "\""; } + diff --git a/src/pwa.mjs b/src/pwa.ts similarity index 98% rename from src/pwa.mjs rename to src/pwa.ts index 2a290589..858f168c 100644 --- a/src/pwa.mjs +++ b/src/pwa.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as rpcCall from "./rpcCall.mjs"; -import * as imaBLS from "./bls.mjs"; -import * as imaUtils from "./utils.mjs"; +import * as log from "./log"; +import * as rpcCall from "./rpcCall"; +import * as imaBLS from "./bls"; +import * as imaUtils from "./utils"; function computeWalkNodeIndices( nNodeNumber, nNodesCount ) { if( nNodesCount <= 1 ) diff --git a/src/rpcCall.mjs b/src/rpcCall.ts similarity index 99% rename from src/rpcCall.mjs rename to src/rpcCall.ts index 34b68d3c..ed07ff35 100644 --- a/src/rpcCall.mjs +++ b/src/rpcCall.ts @@ -27,8 +27,8 @@ import * as ws from "ws"; import * as urllib from "urllib"; import * as https from "https"; import * as net from "net"; -import { validateURL, isUrlWS } from "./owaspUtils.mjs"; -import * as log from "./log.mjs"; +import { validateURL, isUrlWS } from "./owaspUtils"; +import * as log from "./log"; const gSecondsConnectionTimeout = 60; diff --git a/src/socket.mjs b/src/socket.ts similarity index 99% rename from src/socket.mjs rename to src/socket.ts index 0f81d90e..9810f740 100644 --- a/src/socket.mjs +++ b/src/socket.ts @@ -23,9 +23,9 @@ * @copyright SKALE Labs 2019-Present */ -import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher.mjs"; -import { settings } from "./socketSettings.mjs"; -import * as utils from "./socketUtils.mjs"; +import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher"; +import { settings } from "./socketSettings"; +import * as utils from "./socketUtils"; export let httpsModule = null; // server side only export let wsModule = null; // server side only @@ -97,6 +97,14 @@ export const generateSocketDataStatsJSON = function( jo ) { }; export class BasicServerAcceptor extends EventDispatcher { + socketType: string; + socketSubtype: string; + isListening: boolean; + strEndPoint: string|null; + nextClientNumber: number; + mapClients: any; + isDisposing: boolean; + isDisposed: boolean; constructor() { super(); this.socketType = "BasicAcceptor"; @@ -106,7 +114,7 @@ export class BasicServerAcceptor extends EventDispatcher { this.nextClientNumber = 1; this.mapClients = { }; } - dispose() { + dispose() : void { if( this.isDisposed ) return; this.isDisposing = true; @@ -700,7 +708,7 @@ export class OutOfWorkerRelay extends EventDispatcher { } ) ); // 1) configure incoming pipe let _offAllPipeEventListeners = null; - let _onExternalPipeClose = function() { + let _onExternalPipeClose: any = function() { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" external-client socket closed \"" + @@ -718,7 +726,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onRelayPipeClose = function() { + let _onRelayPipeClose: any = function() { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" relay-client socket closed \"" + @@ -736,7 +744,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onExternalPipeError = function( eventData ) { + let _onExternalPipeError: any = function( eventData ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + "\" external-client socket error \"" + @@ -754,7 +762,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onRelayPipeError = function( eventData ) { + let _onRelayPipeError: any = function( eventData ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + "\" relay-client socket error \"" + @@ -772,7 +780,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onExternalPipeMessage = function( eventData ) { + let _onExternalPipeMessage: any = function( eventData ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" external-client socket \"" + eventData.strSavedRemoteAddress + "\" raw message", eventData ); @@ -798,7 +806,7 @@ export class OutOfWorkerRelay extends EventDispatcher { if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); }; - let _onRelayPipeMessage = function( eventData ) { + let _onRelayPipeMessage: any = function( eventData ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" relay-client socket \"" + eventData.strSavedRemoteAddress + "\" raw message", eventData ); @@ -914,8 +922,8 @@ export class OneToOneRelay extends EventDispatcher { pipeOutgoing.strSavedRemoteAddress = "" + pipeOutgoing.constructor.name; // 1) configure incoming pipe - let _offAllPipeEventListeners = null; - let _onIncomingPipeClose = function() { + let _offAllPipeEventListeners: any = null; + let _onIncomingPipeClose: any = function() { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" incoming-client socket closed \"" + @@ -936,7 +944,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onOutgoingPipeClose = function() { + let _onOutgoingPipeClose: any = function() { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" outgoing-client socket closed \"" + @@ -957,7 +965,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onIncomingPipeError = function( eventData ) { + let _onIncomingPipeError: any = function( eventData ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + @@ -980,7 +988,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onOutgoingPipeError = function( eventData ) { + let _onOutgoingPipeError: any = function( eventData ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + @@ -1003,7 +1011,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onIncomingPipeMessage = function( eventData ) { + let _onIncomingPipeMessage: any = function( eventData ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" incoming-client socket \"" + @@ -1036,7 +1044,7 @@ export class OneToOneRelay extends EventDispatcher { if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); }; - let _onOutgoingPipeMessage = function( eventData ) { + let _onOutgoingPipeMessage: any = function( eventData ) { if( settings.logging.net.relay.rawMessage ) { console.log( `Relay ${self.strRelayName}` + "\" outgoing-client socket \"" + diff --git a/src/socketServer.mjs b/src/socketServer.ts similarity index 91% rename from src/socketServer.mjs rename to src/socketServer.ts index 5b58a5e8..b282e004 100644 --- a/src/socketServer.mjs +++ b/src/socketServer.ts @@ -23,12 +23,21 @@ * @copyright SKALE Labs 2019-Present */ -import { EventDispatcher, UniversalDispatcherEvent } from "./eventDispatcher.mjs"; -import * as utils from "./socketUtils.mjs"; -import * as log from "./log.mjs"; +import { EventDispatcher, UniversalDispatcherEvent } from "./eventDispatcher"; +import * as utils from "./socketUtils"; +import * as log from "./log"; export class SocketServer extends EventDispatcher { - constructor( acceptor ) { + log: any; + acceptor: any; + mapApiHandlers: any; + mapAcceptedPipes: any; + isLogAcceptedSocket: boolean; + isLogSocketErrors: boolean; + isLogSocketTraffic: boolean; + isLogSocketTrafficRaw: boolean; + isDisposing: boolean; + constructor( acceptor: any ) { super(); if( acceptor == null || acceptor == undefined || typeof acceptor != "object" ) throw new Error( "Cannot create server on bad acceptor" ); @@ -54,8 +63,8 @@ export class SocketServer extends EventDispatcher { socket.strSavedRemoteAddress, "accepted" ) ); } self.mapAcceptedPipes[socket] = { }; - let _offAllPipeEventListeners = null; - let _onPipeClose = function() { + let _offAllPipeEventListeners: any = null; + let _onPipeClose: any = function() { if( self.isLogAcceptedSocket ) { self.log( log.fmtInformation( "Socket {url} was {bright}", socket.strSavedRemoteAddress, "closed" ) ); @@ -66,7 +75,7 @@ export class SocketServer extends EventDispatcher { } delete self.mapAcceptedPipes[socket]; }; - let _onPipeError = function( eventData ) { + let _onPipeError: any = function( eventData ) { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Socket {url} error {err}", socket.strSavedRemoteAddress, eventData ) ); @@ -77,7 +86,7 @@ export class SocketServer extends EventDispatcher { } delete self.mapAcceptedPipes[socket]; }; - let _onPipeMessage = function( eventData ) { + let _onPipeMessage: any = function( eventData ) { if( self.isLogSocketTrafficRaw ) { self.log( log.fmtInformation( "Socket {url} did received {sunny} {}", socket.strSavedRemoteAddress, "raw-message", eventData ) ); @@ -87,7 +96,7 @@ export class SocketServer extends EventDispatcher { self.log( log.fmtInformation( "Socket {url} did received {sunny} {}", socket.strSavedRemoteAddress, "JSON-message", joMessage ) ); } - let joAnswer = null; + let joAnswer: any = null; let isFlush = false; try { if( joMessage.method in self.mapApiHandlers ) { @@ -153,7 +162,7 @@ export class SocketServer extends EventDispatcher { this.dispatchEvent( new UniversalDispatcherEvent( "initialized", { "detail": { "ref": this } } ) ); } - dispose() { + dispose() : void { this.isDisposing = true; super.dispose(); } diff --git a/src/socketSettings.mjs b/src/socketSettings.ts similarity index 99% rename from src/socketSettings.mjs rename to src/socketSettings.ts index fc366ae9..7826d084 100644 --- a/src/socketSettings.mjs +++ b/src/socketSettings.ts @@ -23,7 +23,7 @@ * @copyright SKALE Labs 2019-Present */ -const settings = { +const settings: any = { rtcSpace: { defaultSpaceName: "default space", defaultSpaceCategory: "default category" diff --git a/src/socketUtils.mjs b/src/socketUtils.ts similarity index 81% rename from src/socketUtils.mjs rename to src/socketUtils.ts index b9a19d63..20721997 100644 --- a/src/socketUtils.mjs +++ b/src/socketUtils.ts @@ -23,27 +23,26 @@ * @copyright SKALE Labs 2019-Present */ -import { settings } from "./socketSettings.mjs"; +import { settings } from "./socketSettings"; -export const UUIDv4 = function() { +export const UUIDv4 = function() : string { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( /[xy]/g, function( c ) { const r = Math.random() * 16 | 0, v = c == "x" ? r : ( r & 0x3 | 0x8 ); return v.toString( 16 ); } ); }; -export const getRandomInt = function( nMax ) { - return parseInt( Math.floor( Math.random() * Math.floor( nMax ) ), 10 ); +export const getRandomInt = function( nMax: number ): number { + return Math.floor( Math.random() * Math.floor( nMax ) ); }; -export const randomFixedInteger = function( length ) { +export const randomFixedInteger = function( length: number ): number { return Math.floor( Math.pow( 10, length - 1 ) + Math.random() * ( Math.pow( 10, length ) - Math.pow( 10, length - 1 ) - 1 ) ); }; -export const randomStringABC = function( length, arrCharacters ) { - length = parseInt( length, 10 ); +export const randomStringABC = function( length: number, arrCharacters: string ) : string { if( length <= 0 || arrCharacters.length == 0 ) return ""; let s = ""; @@ -53,9 +52,9 @@ export const randomStringABC = function( length, arrCharacters ) { }; export const randomString = function( - length, isABC, isDigits, isSpecChr, isPunctuation -) { // by default only isABC=true - length = parseInt( length, 10 ); + length: number, + isABC?: boolean, isDigits?: boolean, isSpecChr?: boolean, isPunctuation?: boolean +): string { // by default only isABC=true if( length <= 0 ) return ""; isABC = ( isABC == null || isABC == undefined ) @@ -80,17 +79,17 @@ export const randomString = function( return randomStringABC( length, arrCharacters ); }; -export const randomHexString = function( length ) { +export const randomHexString = function( length: number ) : string { // length in characters, not bytes, each byte is 2 characters const arrCharacters = "0123456789abcdef"; return randomStringABC( length, arrCharacters ); }; -export const replaceAll = function( str, find, replace ) { +export const replaceAll = function( str: string, find: string, replace: string ) : string { return str.replace( new RegExp( find, "g" ), replace ); }; -export const simpleEscapeString = function( s ) { +export const simpleEscapeString = function( s?: any ) : string { if( s == null || s == undefined || typeof s != "string" ) return s; s = replaceAll( s, "&", "&" ); @@ -100,37 +99,31 @@ export const simpleEscapeString = function( s ) { return s; }; -export const abstractUniqueID = function() { +export const abstractUniqueID = function() : string { const id = replaceAll( UUIDv4(), "-", "" ).toLowerCase(); return id; }; -export const isEven = function( n ) { +export const isEven = function( n: number ) : boolean { return n % 2 == 0; }; -export const isOdd = function( n ) { +export const isOdd = function( n: number ) : boolean { return Math.abs( n % 2 ) == 1; }; -const gCountOfCallIdDigits = 10; -export const randomCallID = function() { +const gCountOfCallIdDigits: number = 10; +export const randomCallID = function() : string { const id = randomHexString( gCountOfCallIdDigits ); return id; }; -const gCountOfDirectPipeIdDigits = 10; -export const randomDirectPipeID = function() { +const gCountOfDirectPipeIdDigits : number = 10; +export const randomDirectPipeID = function() : string { const id = randomHexString( gCountOfDirectPipeIdDigits ); return id; }; -export const bindScopeToFunction = function( scope, fn ) { - return function() { - fn.apply( scope, arguments ); - }; -}; - -export const prepareAnswerJSON = function( joMessage ) { +export const prepareAnswerJSON = function( joMessage: any ) : any { const joAnswer = { "id": "" + ( ( joMessage != null && @@ -147,7 +140,7 @@ export const prepareAnswerJSON = function( joMessage ) { return joAnswer; }; -export const makeValidSignalingServerURL = function( strSignalingServerURL ) { +export const makeValidSignalingServerURL = function( strSignalingServerURL: string ) : string { const proto = settings.net.secure ? "wss" : "ws"; return "" + ( ( strSignalingServerURL != null && @@ -159,7 +152,7 @@ export const makeValidSignalingServerURL = function( strSignalingServerURL ) { ); }; -export const zeroPaddingLeft = function( val, cntCharsNeeded ) { +export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ) : string { if( val == null || val == undefined ) return val; let s = "" + val; @@ -167,7 +160,7 @@ export const zeroPaddingLeft = function( val, cntCharsNeeded ) { s = "0" + s; return s; }; -export const zeroPaddingRight = function( val, cntCharsNeeded ) { +export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ) : string { if( val == null || val == undefined ) return val; let s = "" + val; @@ -176,7 +169,7 @@ export const zeroPaddingRight = function( val, cntCharsNeeded ) { return s; }; -export const parseDateTime = function( ts ) { +export const parseDateTime = function( ts?: any ) : Date|null { if( ts === null || ts === undefined ) return ts; if( typeof ts != "string" ) @@ -191,7 +184,7 @@ export const parseDateTime = function( ts ) { const hour = parseInt( ts.substring( 11, 13 ), 10 ); const minute = parseInt( ts.substring( 14, 16 ), 10 ); const second = parseInt( ts.substring( 17, 19 ), 10 ); - let millisecond = ts.substring( 20 ); + let millisecond: any = ts.substring( 20 ); if( millisecond.length > 3 ) millisecond = millisecond.substring( 0, 3 ); else { @@ -205,8 +198,10 @@ export const parseDateTime = function( ts ) { return d; }; export const formatDateTime = function( - dt, isDate, isTime, isMilliseconds, sepDate, sepTime, sepBetween, sepMilliseconds -) { + dt: any, + isDate?: boolean, isTime?: boolean, isMilliseconds?: boolean, + sepDate?: string, sepTime?: string, sepBetween?: string, sepMilliseconds?: string +) : string { if( dt === null ) return "null-date-time"; if( dt === undefined ) diff --git a/src/state.mjs b/src/state.ts similarity index 99% rename from src/state.mjs rename to src/state.ts index c7289d9d..95f0e451 100644 --- a/src/state.mjs +++ b/src/state.ts @@ -1,5 +1,5 @@ -import * as owaspUtils from "./owaspUtils.mjs"; -import * as imaTx from "./imaTx.mjs"; +import * as owaspUtils from "./owaspUtils"; +import * as imaTx from "./imaTx"; export const gDefaultValueForLoopState = { "oracle": { @@ -138,7 +138,7 @@ function constructChainProperties() { }; } -let imaState = null; +let imaState: any = null; export function get() { if( imaState ) diff --git a/src/threadInfo.mjs b/src/threadInfo.ts similarity index 97% rename from src/threadInfo.mjs rename to src/threadInfo.ts index 5fb82b85..fc89622d 100644 --- a/src/threadInfo.mjs +++ b/src/threadInfo.ts @@ -24,7 +24,7 @@ */ import * as worker_threads from "worker_threads"; -import * as log from "./log.mjs"; +import * as log from "./log"; const Worker = worker_threads.Worker; export { Worker }; diff --git a/src/utils.mjs b/src/utils.ts similarity index 82% rename from src/utils.mjs rename to src/utils.ts index e0c60174..4ca602e9 100644 --- a/src/utils.mjs +++ b/src/utils.ts @@ -23,12 +23,12 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log.mjs"; -import * as owaspUtils from "./owaspUtils.mjs"; +import * as log from "./log"; +import * as owaspUtils from "./owaspUtils"; import * as fs from "fs"; import * as path from "path"; import * as os from "os"; -import * as threadInfo from "./threadInfo.mjs"; +import * as threadInfo from "./threadInfo"; import { v4 as uuid } from "uuid"; export { uuid }; @@ -36,25 +36,25 @@ export { uuid }; const ethersMod = owaspUtils.ethersMod; export { ethersMod }; -export function replaceAll( str, find, replace ) { +export function replaceAll( str: string, find: string, replace: string ) : string { return str.replace( new RegExp( find, "g" ), replace ); } -export function normalizePath( strPath ) { +export function normalizePath( strPath: string ) : string { strPath = strPath.replace( /^~/, os.homedir() ); strPath = path.normalize( strPath ); strPath = path.resolve( strPath ); return strPath; } -export function getRandomFileName() { +export function getRandomFileName() : string { const timestamp = new Date().toISOString().replace( /[-:.]/g,"" ); const random = ( "" + Math.random() ).substring( 2, 8 ); const randomNumber = timestamp + random; return randomNumber; } -export function fileExists( strPath ) { +export function fileExists( strPath: string ) : boolean { try { if( fs.existsSync( strPath ) ) { const stats = fs.statSync( strPath ); @@ -65,18 +65,18 @@ export function fileExists( strPath ) { return false; } -export function fileLoad( strPath, strDefault ) { +export function fileLoad( strPath: string, strDefault?: string ) : string { strDefault = strDefault || ""; if( !fileExists( strPath ) ) return strDefault; try { - const s = fs.readFileSync( strPath ); + const s = fs.readFileSync( strPath ).toString(); return s; } catch ( err ) {} return strDefault; } -export function fileSave( strPath, s ) { +export function fileSave( strPath: string, s: string ) : boolean { try { fs.writeFileSync( strPath, s ); return true; @@ -84,7 +84,7 @@ export function fileSave( strPath, s ) { return false; } -export function jsonFileLoad( strPath, joDefault, bLogOutput ) { +export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boolean ) : boolean { if( bLogOutput == undefined || bLogOutput == null ) bLogOutput = false; joDefault = joDefault || {}; @@ -97,7 +97,7 @@ export function jsonFileLoad( strPath, joDefault, bLogOutput ) { return joDefault; } try { - const s = fs.readFileSync( strPath ); + const s = fs.readFileSync( strPath ).toString(); if( bLogOutput ) log.debug( "Did loaded content of JSON file {}, will parse it...", strPath ); @@ -112,7 +112,7 @@ export function jsonFileLoad( strPath, joDefault, bLogOutput ) { return joDefault; } -export function jsonFileSave( strPath, jo, bLogOutput ) { +export function jsonFileSave( strPath: string, jo?: any, bLogOutput?: boolean ) : boolean { if( bLogOutput == undefined || bLogOutput == null ) bLogOutput = false; if( bLogOutput ) @@ -130,15 +130,15 @@ export function jsonFileSave( strPath, jo, bLogOutput ) { return false; } -const gMillisecondsToSleepStepWaitForClonedTokenToAppear = 1000; +const gMillisecondsToSleepStepWaitForClonedTokenToAppear: number = 1000; export async function waitForClonedTokenToAppear( - sc, - strTokenSuffix, // example "erc20" - addressCallFrom, - cntAttempts, - tokensMN, - strMainnetName + sc: any, + strTokenSuffix: string, // example "erc20" + addressCallFrom: string, + cntAttempts: number, + tokensMN: any, + strMainnetName: string ) { const strTokenSuffixLC = strTokenSuffix.toLowerCase(); const strTokenSuffixUC = @@ -181,7 +181,7 @@ export async function waitForClonedTokenToAppear( } export async function waitForClonedTokenAppearErc20( - sc, tokenERC20SC, joAccountSC, tokensMN, strMainnetName + sc: any, tokenERC20SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC20SC && typeof tokenERC20SC.abi == "object" && "address" in tokenERC20SC && typeof tokenERC20SC.address == "string" @@ -197,7 +197,7 @@ export async function waitForClonedTokenAppearErc20( } export async function waitForClonedTokenAppearErc721( - sc, tokenERC721SC, joAccountSC, tokensMN, strMainnetName + sc: any, tokenERC721SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" @@ -214,7 +214,7 @@ export async function waitForClonedTokenAppearErc721( } export async function waitForClonedTokenAppearErc721WithMetadata( - sc, tokenERC721SC, joAccountSC, tokensMN, strMainnetName + sc: any, tokenERC721SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" @@ -231,7 +231,7 @@ export async function waitForClonedTokenAppearErc721WithMetadata( } export async function waitForClonedTokenAppearErc1155( - sc, tokenERC1155SC, joAccountSC, tokensMN, strMainnetName + sc: any, tokenERC1155SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC1155SC && typeof tokenERC1155SC.abi == "object" && "address" in tokenERC1155SC && typeof tokenERC1155SC.address == "string" @@ -246,7 +246,7 @@ export async function waitForClonedTokenAppearErc1155( tokenERC1155SC.address = "" + addressOnSChain; } -export function hexToBytes( strHex, isInversiveOrder ) { // convert a hex string to a byte array +export function hexToBytes( strHex?: any, isInversiveOrder?: boolean ) : Uint8Array { // convert a hex string to a byte array isInversiveOrder = !!( ( isInversiveOrder != null && isInversiveOrder != undefined && isInversiveOrder ) ); @@ -258,7 +258,7 @@ export function hexToBytes( strHex, isInversiveOrder ) { // convert a hex string if( ( strHex.length & 1 ) !== 0 ) strHex = "0" + strHex; const cnt = strHex.length; - let i, j; + let i: number, j: number; const arrBytes = new Uint8Array( cnt / 2 ); for( i = 0, j = 0; i < cnt; ++j, i += 2 ) arrBytes[j] = parseInt( strHex.substr( i, 2 ), 16 ); @@ -267,11 +267,11 @@ export function hexToBytes( strHex, isInversiveOrder ) { // convert a hex string return arrBytes; } -export function bytesToHex( arrBytes, isInversiveOrder ) { // convert a byte array to a hex string +export function bytesToHex( arrBytes: Uint8Array, isInversiveOrder?: boolean ) : string { // convert a byte array to a hex string isInversiveOrder = !!( ( isInversiveOrder != null && isInversiveOrder != undefined && isInversiveOrder ) ); - const hex = []; + const hex: any[] = []; for( let i = 0; i < arrBytes.length; i++ ) { const current = arrBytes[i] < 0 ? arrBytes[i] + 256 : arrBytes[i]; const c0 = ( current >>> 4 ).toString( 16 ); @@ -287,7 +287,7 @@ export function bytesToHex( arrBytes, isInversiveOrder ) { // convert a byte arr return hex.join( "" ); } -export function bytesAlignLeftWithZeroes( arrBytes, cntMin ) { +export function bytesAlignLeftWithZeroes( arrBytes: Uint8Array, cntMin: number ) : Uint8Array { if( arrBytes.length >= cntMin ) return arrBytes; const cntNewZeros = cntMin - arrBytes.length; @@ -297,7 +297,7 @@ export function bytesAlignLeftWithZeroes( arrBytes, cntMin ) { return arrBytes; } -export function bytesAlignRightWithZeroes( arrBytes, cntMin ) { +export function bytesAlignRightWithZeroes( arrBytes: Uint8Array, cntMin: number ) : Uint8Array { if( arrBytes.length >= cntMin ) return arrBytes; const cntNewZeros = cntMin - arrBytes.length; @@ -307,34 +307,34 @@ export function bytesAlignRightWithZeroes( arrBytes, cntMin ) { return arrBytes; } -export function concatTypedArrays( a, b ) { // a, b TypedArray of same type +export function concatUint8Arrays( a: Uint8Array, b: Uint8Array ) : Uint8Array { // a, b TypedArray of same type if( typeof a == "string" ) a = hexToBytes( a ); if( typeof b == "string" ) b = hexToBytes( b ); - const c = new ( a.constructor )( a.length + b.length ); + const c = new Uint8Array( a["length"] + b["length"] ); c.set( a, 0 ); - c.set( b, a.length ); + c.set( b, a["length"] ); return c; } -export function concatByte( ui8a, byte ) { +export function concatByte( ui8a: Uint8Array, byte: number ) : Uint8Array { const b = new Uint8Array( 1 ); b[0] = byte; - return concatTypedArrays( ui8a, b ); + return concatUint8Arrays( ui8a, b ); } -export function bytesConcat( a1, a2 ) { +export function bytesConcat( a1: Uint8Array, a2: Uint8Array ) : Uint8Array { a1 = a1 || new Uint8Array(); a2 = a2 || new Uint8Array(); - return concatTypedArrays( a1, a2 ); + return concatUint8Arrays( a1, a2 ); } -export function toBuffer( ab ) { +export function toBuffer( ab?: any ) { return Buffer.from( new Uint8Array( ab ) ); } -export function discoverCoinNameInJSON( jo ) { +export function discoverCoinNameInJSON( jo?: any ) : string { if( typeof jo !== "object" ) return ""; const arrKeys = Object.keys( jo ); @@ -364,23 +364,27 @@ export function discoverCoinNameInJSON( jo ) { return s1; } -export function checkKeyExistInABI( strName, strFile, joABI, strKey, isExitOnError ) { +export function checkKeyExistInABI( + strName: string, strFile: string, joABI: any, strKey: string, isExitOnError?: boolean + ) : boolean { if( isExitOnError == null || isExitOnError == undefined ) isExitOnError = true; try { if( strKey in joABI ) return true; } catch ( err ) { - } - if( isExitOnError ) { - log.fatal( "Loaded {} ABI JSON file {} does not contain needed key {}, stack is:\n{stack}", - strName, strFile, strKey, err.stack ); - process.exit( 126 ); + if( isExitOnError ) { + log.fatal( "Loaded {} ABI JSON file {} does not contain needed key {}, stack is:\n{stack}", + strName, strFile, strKey, err.stack ); + process.exit( 126 ); + } } return false; } -export function checkKeysExistInABI( strName, strFile, joABI, arrKeys, isExitOnError ) { +export function checkKeysExistInABI( + strName: string, strFile: string, joABI: any, arrKeys: any[], isExitOnError?: boolean + ): boolean { const cnt = arrKeys.length; for( let i = 0; i < cnt; ++i ) { const strKey = arrKeys[i]; @@ -390,7 +394,7 @@ export function checkKeysExistInABI( strName, strFile, joABI, arrKeys, isExitOnE return true; } -export function composeSChainNodeUrl( joNode ) { +export function composeSChainNodeUrl( joNode: any ) : string { if( "ip" in joNode && typeof joNode.ip === "string" && joNode.ip.length > 0 ) { if( "httpRpcPort" in joNode && typeof joNode.httpRpcPort === "number" && @@ -431,7 +435,7 @@ export function composeSChainNodeUrl( joNode ) { return ""; } -export function composeImaAgentNodeUrl( joNode, isThisNode ) { +export function composeImaAgentNodeUrl( joNode: any, isThisNode: boolean ): string { let nPort = -1; if( "imaAgentRpcPort" in joNode && typeof joNode.imaAgentRpcPort === "number" && From 7d59ed93ebee912c1c1eefed9252517bc4d14454 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 8 Dec 2023 18:35:48 +0000 Subject: [PATCH 02/53] code porting to TypeScript --- src/bls.ts | 4 +- src/imaGasUsageOperations.ts | 2 +- src/imaTransferErrorHandling.ts | 2 +- src/loop.ts | 2 +- src/loopWorker.ts | 8 +- src/main.ts | 2 +- src/observer.ts | 2 +- src/rpcCall.ts | 4 +- src/socket.ts | 567 ++++++++++++++++++++------------ src/socketUtils.ts | 2 +- src/threadInfo.ts | 14 +- src/utils.ts | 2 +- 12 files changed, 372 insertions(+), 239 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index c73490d2..d8fc16d4 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -291,7 +291,7 @@ function performBlsGlue( let strInput = ""; const cnt = arrSignResults.length; for( let i = 0; i < cnt; ++i ) { - const jo = arrSignResults[i]; + const jo: any = arrSignResults[i]; if( ( !jo ) || typeof jo != "object" ) throw new Error( `Failed to save BLS part ${i} because it's not JSON object` ); const strPath = strActionDir + "/sign-result" + jo.index + ".json"; @@ -379,7 +379,7 @@ function performBlsGlueU256( details, u256, arrSignResults ) { let strInput = ""; const cnt = arrSignResults.length; for( let i = 0; i < cnt; ++i ) { - const jo = arrSignResults[i]; + const jo: any = arrSignResults[i]; if( ( !jo ) || typeof jo != "object" ) throw new Error( `Failed to save BLS part ${i} because it's not JSON object` ); const strPath = strActionDir + "/sign-result" + jo.index + ".json"; diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 5b652edc..6783134f 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -47,7 +47,7 @@ export function composeGasUsageReportFromArray( strName, jarrReceipts ) { export function printGasUsageReportFromArray( strName, jarrReceipts, details ) { details = details || log; - const jo = composeGasUsageReportFromArray( strName, jarrReceipts ); + const jo: any = composeGasUsageReportFromArray( strName, jarrReceipts ); if( jo.strReport && typeof jo.strReport == "string" && jo.strReport.length > 0 && jo.sumGasUsed && jo.sumGasUsed.gt( owaspUtils.toBN( "0" ) ) ) log.information( jo.strReport ); diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 12fad59e..df4e3d1d 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -74,7 +74,7 @@ export function getLastTransferErrors( isIncludeTextLog ) { const jarr = JSON.parse( JSON.stringify( gArrLastTransferErrors ) ); if( ! isIncludeTextLog ) { for( let i = 0; i < jarr.length; ++ i ) { - const jo = jarr[i]; + const jo: any = jarr[i]; if( "textLog" in jo ) delete jo.textLog; } diff --git a/src/loop.ts b/src/loop.ts index 62a3a8ee..4b29b687 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -550,7 +550,7 @@ export async function ensureHaveWorkers( opts ) { break; } // switch ( joMessage.method ) } ); - const jo = { + const jo: any = { "method": "init", "message": { "opts": { diff --git a/src/loopWorker.ts b/src/loopWorker.ts index df44a72e..5df4d0f3 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -46,7 +46,7 @@ if( parentPort ) { } function doSendMessage( type, endpoint, workerUUID, data ) { - const jo = networkLayer.socketReceivedDataReverseMarshall( data ); + const jo: any = networkLayer.socketReceivedDataReverseMarshall( data ); const joSend = { "workerMessageType": ( type && typeof type == "string" && type.length > 0 ) @@ -78,7 +78,7 @@ class ObserverServer extends SocketServer { return joAnswer; self.log = function() { const args = Array.prototype.slice.call( arguments ); - const jo = { + const jo: any = { "method": "log", "error": null, "message": args.join( " " ) @@ -107,7 +107,7 @@ class ObserverServer extends SocketServer { log.verboseSet( self.opts.imaState.verbose_ ); log.exposeDetailsSet( self.opts.imaState.expose_details_ ); imaTransferErrorHandling.saveTransferEvents.on( "error", function( eventData ) { - const jo = { + const jo: any = { "method": "saveTransferError", "message": eventData.detail }; @@ -115,7 +115,7 @@ class ObserverServer extends SocketServer { socket.send( jo, isFlush ); } ); imaTransferErrorHandling.saveTransferEvents.on( "success", function( eventData ) { - const jo = { + const jo: any = { "method": "saveTransferSuccess", "message": eventData.detail }; diff --git a/src/main.ts b/src/main.ts index 73ed46d0..03f9bb2c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -265,7 +265,7 @@ function initJsonRpcServer() { const isSkipMode = false; const message = JSON.stringify( req.body ); const ip = req.connection.remoteAddress.split( ":" ).pop(); - const fnSendAnswer = function( joAnswer ) { + const fnSendAnswer: any = function( joAnswer ) { try { res.header( "Content-Type", "application/json" ); res.status( 200 ).send( JSON.stringify( joAnswer ) ); diff --git a/src/observer.ts b/src/observer.ts index 8eb3fc4c..cede7401 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -43,7 +43,7 @@ export function autoUpdateLastCachedSChains() { const imaState = state.get(); if( ! imaState.optsS2S.strNetworkBrowserPath ) return false; - const jo = imaUtils.jsonFileLoad( imaState.optsS2S.strNetworkBrowserPath, null ); + const jo: any = imaUtils.jsonFileLoad( imaState.optsS2S.strNetworkBrowserPath, null ); if( ! ( jo && "schains" in jo && "updatedAt" in jo ) ) { log.error( "Connected S-chains cache in thread {} was not updated from file {}, bad data format", diff --git a/src/rpcCall.ts b/src/rpcCall.ts index ed07ff35..bec5a656 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -461,7 +461,7 @@ export function getValidHostAndPort( s ) { const u = getValidUrl( s ); if( ! u ) return null; - const jo = { + const jo: any = { strHost: u.hostname, nPort: u.port ? parseInt( u.port, 10 ) : getDefaultPort( u.protocol ) }; @@ -564,7 +564,7 @@ export async function checkTcp( strHost, nPort, nTimeoutMilliseconds, isLog ) { export async function checkUrl( u, nTimeoutMilliseconds, isLog ) { if( ! u ) return false; - const jo = getValidHostAndPort( u ); + const jo: any = getValidHostAndPort( u ); if( isLog ) { console.log( `${gStrTcpConnectionHeader}Extracted from URL ${u.toString()} data ` + `fields are: ${JSON.stringify( jo )}` ); diff --git a/src/socket.ts b/src/socket.ts index 9810f740..b25461a1 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -27,23 +27,23 @@ import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher"; import { settings } from "./socketSettings"; import * as utils from "./socketUtils"; -export let httpsModule = null; // server side only -export let wsModule = null; // server side only -export let webRtcModule = null; // server side only +export let httpsModule: any = null; // server side only +export let wsModule: any = null; // server side only +export let webRtcModule: any = null; // server side only -export function setHttpsModule( mod ) { +export function setHttpsModule( mod: any ) : void { httpsModule = mod ? mod : null; } -export function setWsModule( mod ) { +export function setWsModule( mod: any ) : void { wsModule = mod ? mod : null; } -export function setWebRtcModule( mod ) { +export function setWebRtcModule( mod: any ) : void { webRtcModule = mod ? mod : null; } export const gMapLocalServers = { }; // used both for local and in-worker servers -export const socketSentDataMarshall = function( data ) { +export const socketSentDataMarshall = function( data?: any ) : void { const s = data ? ( ( typeof data == "string" ) ? data @@ -52,9 +52,9 @@ export const socketSentDataMarshall = function( data ) { : ""; return s; }; -export const socketReceivedDataReverseMarshall = function( data ) { +export const socketReceivedDataReverseMarshall = function( data?: any ) : object { try { - const jo = data + const jo: any = data ? ( ( typeof data == "object" ) ? data : ( ( typeof data == "string" ) ? JSON.parse( data ) : data ) @@ -70,7 +70,7 @@ export const socketReceivedDataReverseMarshall = function( data ) { } }; -export const updateSocketDataStatsForMessage = function( joMessage, joStats ) { +export const updateSocketDataStatsForMessage = function( joMessage: any, joStats: any ) { let strMethod = "_N/A_"; if( "method" in joMessage && joMessage.method && @@ -82,7 +82,7 @@ export const updateSocketDataStatsForMessage = function( joMessage, joStats ) { else joStats[strMethod] = 1; }; -export const generateSocketDataStatsJSON = function( jo ) { +export const generateSocketDataStatsJSON = function( jo: any ) { const joStats = {}; if( "arrPackedMessages" in jo && jo.arrPackedMessages && @@ -105,6 +105,7 @@ export class BasicServerAcceptor extends EventDispatcher { mapClients: any; isDisposing: boolean; isDisposed: boolean; + url: string; constructor() { super(); this.socketType = "BasicAcceptor"; @@ -124,9 +125,10 @@ export class BasicServerAcceptor extends EventDispatcher { super.dispose(); } disposeNotifyClients() { - for( const [ /*key*/, entry ] of Object.entries( this.mapClients ) ) { + for( const [ keyWalk, entryWalk ] of Object.entries( this.mapClients ) ) { + const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { - const pair = entry; + const pair: any = entry; pair.serverPipe.handleServerDisposed(); pair.clientPipe.handleServerDisposed(); pair.serverPipe = null; @@ -138,7 +140,7 @@ export class BasicServerAcceptor extends EventDispatcher { } this.mapClients = { }; } - unregisterClientByKey( key ) { + unregisterClientByKey( key: any ) { if( key in this.mapClients ) { const entry = this.mapClients[key]; if( entry ) { @@ -154,9 +156,10 @@ export class BasicServerAcceptor extends EventDispatcher { flush() { if( this.isDisposing || this.isDisposed ) return; - for( const [ /*key*/, entry ] of Object.entries( this.mapClients ) ) { + for( const [ keyWalk, entryWalk ] of Object.entries( this.mapClients ) ) { + const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { - const pair = entry; + const pair: any = entry; pair.serverPipe.flush(); } else { const pipe = entry; @@ -169,8 +172,8 @@ export class BasicServerAcceptor extends EventDispatcher { return null; if( !this.isListening ) return null; - const clientPipe = new DirectPipe( null, false ); - const serverPipe = new DirectPipe( clientPipe, false ); + const clientPipe: DirectPipe = new DirectPipe( null, false ); + const serverPipe: DirectPipe = new DirectPipe( clientPipe, false ); serverPipe.acceptor = this; this.mapClients["" + serverPipe.clientPort] = serverPipe; const self = this; @@ -190,6 +193,18 @@ export class BasicServerAcceptor extends EventDispatcher { }; export class BasicSocketPipe extends EventDispatcher { + socketType: string; + socketSubtype: string; + url: string; + isConnected: boolean; + arrAccumulatedMessages: any[]; + maxAccumulatedMessagesCount: number; + relayClientSocket: any; + mapImpersonatedEntries: any; // for external in-app usage only + isDisposing: boolean; + isDisposed: boolean; + acceptor: any; + clientPort: any; constructor() { super(); this.socketType = "N/A"; @@ -212,7 +227,8 @@ export class BasicSocketPipe extends EventDispatcher { super.dispose(); } disposeImpersonatedEntries() { // for external in-app usage only - for( const [ /*key*/, entry ] of Object.entries( this.mapImpersonatedEntries ) ) { + for( const [ keyWalk, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { + const entry: any = entryWalk; try { if( entry && "dispose" in entry && typeof entry.dispose == "function" ) entry.dispose(); @@ -221,7 +237,7 @@ export class BasicSocketPipe extends EventDispatcher { } this.mapImpersonatedEntries = { }; // for app usage } - implSend( data ) { + implSend( data: any ) { throw new Error( "BasicSocketPipe.implSend() must be overridden but calling it was attempted" ); } @@ -241,10 +257,10 @@ export class BasicSocketPipe extends EventDispatcher { // + " " this.url; } - socketLoggingTextPrefix( strLogEventName ) { + socketLoggingTextPrefix( strLogEventName: string ) { return "" + strLogEventName + " " + this.socketDescription() + " -"; } - send( data, isFlush ) { + send( data: any, isFlush: boolean ) { if( this.isDisposed || ( !this.isConnected ) ) return; if( this.isAutoFlush() ) { @@ -254,7 +270,7 @@ export class BasicSocketPipe extends EventDispatcher { return; } isFlush = ( isFlush == undefined || isFlush == null ) ? true : ( !!( isFlush ) ); - const jo = socketReceivedDataReverseMarshall( data ); + const jo: any = socketReceivedDataReverseMarshall( data ); if( settings.logging.net.socket.accumulate ) console.log( this.socketLoggingTextPrefix( "accumulate" ), data ); this.arrAccumulatedMessages.push( jo ); @@ -269,7 +285,7 @@ export class BasicSocketPipe extends EventDispatcher { return; if( settings.logging.net.socket.flushCount ) console.log( this.socketLoggingTextPrefix( "flush-count(" + cnt + ")" ) ); - let joSend = null; + let joSend: any = null; if( cnt == 1 ) { joSend = this.arrAccumulatedMessages[0]; if( settings.logging.net.socket.flushOne || settings.logging.net.socket.flush ) @@ -290,15 +306,15 @@ export class BasicSocketPipe extends EventDispatcher { if( this.relayClientSocket ) this.relayClientSocket.flush(); } - implReceive( data ) { - const jo = socketReceivedDataReverseMarshall( data ); + implReceive( data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); } - receive( data ) { + receive( data: any ) { if( settings.logging.net.socket.receiveBlock ) console.log( this.socketLoggingTextPrefix( "receive-block" ), data ); - const jo = socketReceivedDataReverseMarshall( data ); + const jo: any = socketReceivedDataReverseMarshall( data ); if( "arrPackedMessages" in jo && jo.arrPackedMessages && typeof jo.arrPackedMessages == "object" @@ -350,13 +366,13 @@ export class NullSocketPipe extends BasicSocketPipe { this.isConnected = false; super.dispose(); } - implSend( data ) { + implSend( data: any ) { } - implReceive( data ) { + implReceive( data: any ) { } - send( data ) { + send( data: any ) { } - receive( data ) { + receive( data: any ) { } flush() { } @@ -374,8 +390,8 @@ export const gMapAwaitingInWorkerClients = { }; export const gMapConnectedInWorkerClients = { }; export const outOfWorkerAPIs = { - "onMessage": function( worker, data ) { - const jo = socketReceivedDataReverseMarshall( data ); + "onMessage": function( worker: any, data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); if( ! ( "workerMessageType" in jo ) || typeof jo.workerMessageType != "string" || jo.workerMessageType.length == 0 ) @@ -384,9 +400,8 @@ export const outOfWorkerAPIs = { typeof jo.workerEndPoint != "string" || jo.workerEndPoint.length == 0 ) return false; // TO-DO: send error answer and return true - if( ! ( "workerUUID" in jo ) || - typeof jo.workerUUID != "string" || - jo.workerUUID.length == 0 ) + if( ! ( "workerUUID" in jo ) || typeof jo.workerUUID != "string" || + jo.workerUUID.length == 0 ) return false; // TO-DO: send error answer and return true switch ( jo.workerMessageType ) { case "inWorkerConnect": { @@ -411,8 +426,8 @@ export const outOfWorkerAPIs = { return false; // TO-DO: send error answer and return true } // switch( jo.workerMessageType ) }, - "onSendMessage": function( worker, type, endpoint, workerUUID, data ) { - const jo = socketReceivedDataReverseMarshall( data ); + "onSendMessage": function( worker: any, type: any, endpoint: any, workerUUID: any, data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); const joSend = { "workerMessageType": ( type && typeof type == "string" && type.length > 0 ) @@ -426,8 +441,8 @@ export const outOfWorkerAPIs = { } }; export const inWorkerAPIs = { - "onMessage": function( data ) { - const jo = socketReceivedDataReverseMarshall( data ); + "onMessage": function( data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); if( ! ( "workerMessageType" in jo ) || typeof jo.workerMessageType != "string" || jo.workerMessageType.length == 0 ) @@ -454,8 +469,8 @@ export const inWorkerAPIs = { return false; // TO-DO: send error answer and return true } // switch( jo.workerMessageType ) }, - "onSendMessage": function( type, endpoint, workerUUID, data ) { - const jo = socketReceivedDataReverseMarshall( data ); + "onSendMessage": function( type: any, endpoint: any, workerUUID: any, data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); const joSend = { "workerMessageType": ( type && typeof type == "string" && type.length > 0 ) @@ -470,7 +485,8 @@ export const inWorkerAPIs = { }; export class InWorkerServerPipe extends BasicSocketPipe { - constructor( acceptor, clientPort, fnSend ) { + fnSend: any; + constructor( acceptor: any, clientPort: string, fnSend: any ) { super(); this.socketType = "InWorker"; this.socketSubtype = "server"; @@ -515,14 +531,14 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.fnSend = null; this.url = ""; } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend != "function" ) { const s = "Cannot send messages to disconnected in-worker server pipe"; this.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); throw new Error( s ); } - const jo = socketReceivedDataReverseMarshall( data ); + const jo: any = socketReceivedDataReverseMarshall( data ); this.fnSend( "inWorkerMessage", this.acceptor.strEndPoint, this.clientPort, jo ); } disconnect() { @@ -532,7 +548,8 @@ export class InWorkerServerPipe extends BasicSocketPipe { }; export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { - constructor( strEndPoint, fnSend ) { + fnSend: any; + constructor( strEndPoint: string, fnSend: any ) { super(); this.socketType = "InWorker"; this.strEndPoint = @@ -569,20 +586,20 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { } super.dispose(); } - performAccept( jo ) { + performAccept( jo: any ) { if( jo.workerUUID in this.mapClients ) return false; // TO-DO: send error answer and return true new InWorkerServerPipe( this, "" + jo.workerUUID, this.fnSend ); return true; } - performDisconnect( jo ) { + performDisconnect( jo: any ) { if( ! ( jo.workerUUID in this.mapClients ) ) return false; // TO-DO: send error answer and return true const pipe = this.mapClients[jo.workerUUID]; pipe.performDisconnect(); return true; } - receiveForClientPort( clientPort, jo ) { + receiveForClientPort( clientPort: any, jo: any ) { if( ! ( clientPort in this.mapClients ) ) return false; // TO-DO: send error answer and return true const pipe = this.mapClients[clientPort]; @@ -592,7 +609,10 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { }; export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { - constructor( strEndPoint, worker, fnSend ) { + worker: any; + fnSend: any; + strEndPoint: string; + constructor( strEndPoint: string, worker: any, fnSend: any ) { super(); this.socketType = "InWorker"; this.socketSubtype = "client"; @@ -638,7 +658,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.isConnected = true; this.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": this } ) ); } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.worker ) || ( !this.fnSend ) || @@ -652,7 +672,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { ); throw new Error( s ); } - const jo = socketReceivedDataReverseMarshall( data ); + const jo: any = socketReceivedDataReverseMarshall( data ); this.fnSend( this.worker, "inWorkerMessage", this.strEndPoint, this.clientPort, jo ); } disconnect() { @@ -662,9 +682,18 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { }; export class OutOfWorkerRelay extends EventDispatcher { + strRelayName: string; + isAutoFlushIncoming: boolean; + isAutoFlushOutgoing: boolean; + acceptor: any; + fnCreateClient: any; + onConnection_: any; + isDisposing: any; + isDisposed: any; // eslint-disable-next-line max-lines-per-function constructor( - strRelayName, acceptor, fnCreateClient, isAutoFlushIncoming, isAutoFlushOutgoing ) { + strRelayName: string, acceptor: any, fnCreateClient: any, + isAutoFlushIncoming: boolean, isAutoFlushOutgoing: boolean ) { super(); const self = this; self.strRelayName = ( strRelayName != null && strRelayName != undefined && @@ -687,9 +716,9 @@ export class OutOfWorkerRelay extends EventDispatcher { self.acceptor = acceptor; self.fnCreateClient = fnCreateClient; // eslint-disable-next-line max-lines-per-function - self.onConnection_ = function( eventData ) { - const pipeIncoming = eventData.socket; - let pipeOutgoing = null; + self.onConnection_ = function( eventData: any ) { + const pipeIncoming: any = eventData.socket; + let pipeOutgoing: any = null; if( ( ! ( "remoteAddress" in eventData ) ) || eventData.remoteAddress == null || eventData.remoteAddress == undefined ) pipeIncoming.strSavedRemoteAddress = pipeIncoming.constructor.name; @@ -707,7 +736,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress } ) ); // 1) configure incoming pipe - let _offAllPipeEventListeners = null; + let _offAllPipeEventListeners: any = null; let _onExternalPipeClose: any = function() { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + @@ -744,7 +773,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onExternalPipeError: any = function( eventData ) { + let _onExternalPipeError: any = function( eventData: any ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + "\" external-client socket error \"" + @@ -762,7 +791,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onRelayPipeError: any = function( eventData ) { + let _onRelayPipeError: any = function( eventData: any ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + "\" relay-client socket error \"" + @@ -780,7 +809,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onExternalPipeMessage: any = function( eventData ) { + let _onExternalPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" external-client socket \"" + eventData.strSavedRemoteAddress + "\" raw message", eventData ); @@ -806,7 +835,7 @@ export class OutOfWorkerRelay extends EventDispatcher { if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); }; - let _onRelayPipeMessage: any = function( eventData ) { + let _onRelayPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" relay-client socket \"" + eventData.strSavedRemoteAddress + "\" raw message", eventData ); @@ -894,9 +923,17 @@ export class OutOfWorkerRelay extends EventDispatcher { }; export class OneToOneRelay extends EventDispatcher { + strRelayName: string; + isAutoFlushIncoming: boolean; + isAutoFlushOutgoing: boolean; + pipeIncoming: any; + pipeOutgoing: any; + isDisposing: boolean; + isDisposed: boolean; // eslint-disable-next-line max-lines-per-function constructor( - strRelayName, pipeIncoming, pipeOutgoing, isAutoFlushIncoming, isAutoFlushOutgoing + strRelayName: string, pipeIncoming: any, pipeOutgoing: any, + isAutoFlushIncoming: boolean, isAutoFlushOutgoing: boolean ) { super(); const self = this; @@ -965,7 +1002,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onIncomingPipeError: any = function( eventData ) { + let _onIncomingPipeError: any = function( eventData: any ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + @@ -988,7 +1025,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onOutgoingPipeError: any = function( eventData ) { + let _onOutgoingPipeError: any = function( eventData: any ) { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + @@ -1011,7 +1048,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onIncomingPipeMessage: any = function( eventData ) { + let _onIncomingPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" incoming-client socket \"" + @@ -1044,7 +1081,7 @@ export class OneToOneRelay extends EventDispatcher { if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); }; - let _onOutgoingPipeMessage: any = function( eventData ) { + let _onOutgoingPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( `Relay ${self.strRelayName}` + "\" outgoing-client socket \"" + @@ -1131,7 +1168,15 @@ export class OneToOneRelay extends EventDispatcher { }; export class DirectPipe extends BasicSocketPipe { - constructor( counterPipe, isBroadcastOpenEvents ) { + socketType: string; + socketSubtype: string; + isConnected: boolean; + acceptor: any; + counterPipe: any; + strEndPoint: string; + clientPort: number; + url: string; + constructor( counterPipe: any, isBroadcastOpenEvents: boolean ) { super(); isBroadcastOpenEvents = ( !!isBroadcastOpenEvents ); this.socketType = "Direct"; @@ -1189,7 +1234,7 @@ export class DirectPipe extends BasicSocketPipe { this.clientPort = 0; this.url = ""; } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.counterPipe ) || ( !this.counterPipe.isConnected ) ) { const s = "Cannot send messages to disconnected local server pipe"; this.dispatchEvent( @@ -1197,7 +1242,7 @@ export class DirectPipe extends BasicSocketPipe { throw new Error( s ); } const s = socketSentDataMarshall( data ); - const jo = socketReceivedDataReverseMarshall( s ); + const jo: any = socketReceivedDataReverseMarshall( s ); this.counterPipe.receive( jo ); } disconnect() { @@ -1207,13 +1252,13 @@ export class DirectPipe extends BasicSocketPipe { }; export class LocalSocketServerPipe extends DirectPipe { - constructor( counterPipe, acceptor, clientPort ) { + constructor( counterPipe: any, acceptor: any, clientPort: number ) { super( counterPipe, false ); this.socketType = "Local"; this.socketSubtype = "server"; this.isConnected = true; this.acceptor = acceptor; - this.clientPort = 0 + parseInt( clientPort, 10 ); + this.clientPort = 0 + clientPort; this.url = "local_server_pipe://" + acceptor.strEndPoint + ":" + clientPort; this.acceptor.mapClients["" + clientPort] = this; const self = this; @@ -1228,7 +1273,8 @@ export class LocalSocketServerPipe extends DirectPipe { }; export class LocalSocketServerAcceptor extends BasicServerAcceptor { - constructor( strEndPoint ) { + nextClientPort: number; + constructor( strEndPoint: string ) { super(); this.socketType = "Local"; this.nextClientPort = 1; @@ -1269,7 +1315,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { }; export class LocalSocketClientPipe extends DirectPipe { - constructor( strEndPoint ) { + constructor( strEndPoint: string ) { super( null, false ); this.socketType = "Local"; this.socketSubtype = "client"; @@ -1319,7 +1365,14 @@ export class LocalSocketClientPipe extends DirectPipe { }; export class WebSocketServerPipe extends BasicSocketPipe { - constructor( acceptor, wsConnection, remoteAddress ) { + clientNumber: number; + wsConnection: any; + remoteAddress: string; + _onWsClose: any; + _onWsError: any; + _onWsMessage: any; + _removeWsEventListeners: any; + constructor( acceptor: any, wsConnection: any, remoteAddress: string ) { super(); this.socketType = "WS"; this.socketSubtype = "server"; @@ -1336,11 +1389,11 @@ export class WebSocketServerPipe extends BasicSocketPipe { self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self } ) ); }; - this._onWsError = function( event ) { + this._onWsError = function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": self, "message": event } ) ); }; - this._onWsMessage = function( event ) { + this._onWsMessage = function( event: any ) { self.receive( event.data ); }; this._removeWsEventListeners = function() { @@ -1407,7 +1460,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.url = ""; this.remoteAddress = ""; } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket server pipe"; this.dispatchEvent( @@ -1421,14 +1474,16 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.performDisconnect(); super.disconnect(); } - implReceive( data ) { - const jo = socketReceivedDataReverseMarshall( data ); + implReceive( data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); } }; export class WebSocketServerAcceptor extends BasicServerAcceptor { + wsServer: any; + httpsModule: any; constructor( nTcpPort, key, cert ) { super(); this.socketType = "WS"; @@ -1468,7 +1523,14 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { }; export class WebSocketClientPipe extends BasicSocketPipe { - constructor( url ) { + wsConnection: any; + _onWsOpen: any; + _onWsClose: any; + _onWsError: any; + _onWsMessage: any; + urlWS: string|null; + _removeWsEventListeners: any; + constructor( url: string|URL|null ) { super(); this.socketType = "WS"; this.socketSubtype = "client"; @@ -1491,7 +1553,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.urlWS = null; super.dispose(); } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket client pipe"; this.dispatchEvent( @@ -1514,7 +1576,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { return; this.wsDisconnect(); } - wsConnectAttempt( url, reconnectAfterMilliseconds, iv ) { + wsConnectAttempt( url: string, reconnectAfterMilliseconds?: number, iv?: any ) { const self = this; try { if( this.isConnected || this.wsConnection ) @@ -1532,21 +1594,21 @@ export class WebSocketClientPipe extends BasicSocketPipe { new UniversalDispatcherEvent( "open", { "socket": self } ) ); }; - this._onWsClose = function( event ) { + this._onWsClose = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self, "message": event } ) ); }; - this._onWsError = function( event ) { + this._onWsError = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": self, "message": event } ) ); }; - this._onWsMessage = function( event ) { + this._onWsMessage = function( event: any ) { self.receive( event.data ); }; this._removeWsEventListeners = function() { @@ -1578,7 +1640,6 @@ export class WebSocketClientPipe extends BasicSocketPipe { console.warn( "WS client connect error:", err ); } if( reconnectAfterMilliseconds != null && reconnectAfterMilliseconds != undefined ) { - reconnectAfterMilliseconds = parseInt( reconnectAfterMilliseconds, 10 ); if( reconnectAfterMilliseconds > 0 && ( !iv ) ) { const iv = setTimeout( function() { try { @@ -1591,7 +1652,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } return false; } - wsConnect( url ) { + wsConnect( url: string ) { if( url.length == 0 ) { const s = "Cannot connect web socket server \"" + url + "\", bad url"; this.dispatchEvent( @@ -1628,15 +1689,23 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.isConnected = false; this.url = ""; } - implReceive( data ) { - const jo = socketReceivedDataReverseMarshall( data ); + implReceive( data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); } }; export class RTCConnection extends EventDispatcher { - constructor( strSignalingServerURL, idRtcParticipant ) { + strSignalingServerURL: string|null; + idRtcParticipant: string|null; + wasIdentified: boolean; + iceComplete: any; + pc: any; + dc: any; + isDisposing: boolean; + isDisposed: boolean; + constructor( strSignalingServerURL?: string, idRtcParticipant?: string ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); this.idRtcParticipant = "" + @@ -1660,7 +1729,7 @@ export class RTCConnection extends EventDispatcher { this.idRtcParticipant = null; super.dispose(); } - describe( strInstanceType, arrAdditionalProps ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { let strInstanceDescription = ( strInstanceType == null || strInstanceType == undefined || ( typeof strInstanceType != "string" ) || strInstanceType.length == 0 ) @@ -1668,7 +1737,7 @@ export class RTCConnection extends EventDispatcher { : ( "" + strInstanceType ); if( typeof this.idRtcParticipant == "string" && this.idRtcParticipant.length > 0 ) strInstanceDescription += " " + this.idRtcParticipant; - const arrProps = []; + const arrProps: any[] = []; if( this.isDisposed ) arrProps.push( "disposed" ); if( this.wasIdentified ) @@ -1732,7 +1801,7 @@ export class RTCConnection extends EventDispatcher { this.closeDataChannel(); this.closePeer(); } - send( data ) { + send( data: any ) { const s = socketSentDataMarshall( data ); if( ! this.dc ) { this.onError( "Attempt to send message to uninitialized RTC data channel: " + s ); @@ -1744,23 +1813,23 @@ export class RTCConnection extends EventDispatcher { this.onError( "Failed to send message to RTC data channel: " + err.toString() ); } } - onDataChannelOpen( event ) { + onDataChannelOpen( event: any ) { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelOpen", { "detail": { "actor": this } } ) ); } - onDataChannelClose( event ) { + onDataChannelClose( even: any ) { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelClose", { "detail": { "actor": this } } ) ); } - onDataChannelError( event ) { + onDataChannelError( event: any ) { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelError", { "detail": { "actor": this } } ) ); this.onError( "Data channel error " + event.toString() ); } - onDataChannelMessage( event ) { + onDataChannelMessage( event: any ) { if( event.data.size ) { if( settings.logging.net.rtc.error ) { console.warn( @@ -1781,9 +1850,9 @@ export class RTCConnection extends EventDispatcher { } } } - onIceComplete( event ) { + onIceComplete( event: any ) { } - onIceConnectionStateChange( event ) { + onIceConnectionStateChange( event: any ) { // handler for self.pc.oniceconnectionstatechange, // see https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/oniceconnectionstatechange @@ -1810,7 +1879,7 @@ export class RTCConnection extends EventDispatcher { ); } } - onIceGatheringStateChange( event ) { + onIceGatheringStateChange( event: any ) { // handler for self.pc.onicegatheringstatechange - this is recommended to handle // in a same way as oniceconnectionstatechange, // see https://developer.mozilla.org/en-US/docs/ @@ -1846,7 +1915,7 @@ export class RTCConnection extends EventDispatcher { ); } } - onIceIdentifyResult( event ) { + onIceIdentifyResult( event: any ) { // handler for self.pc.onidentityresult, // see https://developer.mozilla.org/en-US/docs/Web/API/RTCIdentityEvent if( settings.logging.net.rtc.iceIceIdentifyResult ) { @@ -1864,7 +1933,7 @@ export class RTCConnection extends EventDispatcher { } } } - onIceSignalingStateChange( event ) { + onIceSignalingStateChange( event: any ) { // handler for self.pc.onsignalingstatechange, see // https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/onsignalingstatechange @@ -1876,7 +1945,7 @@ export class RTCConnection extends EventDispatcher { "\", event is:", event ); } } - onIceNegotiationNeeded( event ) { + onIceNegotiationNeeded( event: any ) { // handler for self.pc.onnegotiationneeded, // see https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/onnegotiationneeded @@ -1891,14 +1960,23 @@ export class RTCConnection extends EventDispatcher { }; export class RTCActor extends RTCConnection { - constructor( strSignalingServerURL, idRtcParticipant, offerOptions, signalingOptions ) { + idSomebodyCreator: string|null; + bWasImpersonated: boolean; + isCreator: boolean; + isJoiner: boolean; + offerOptions: any; + signalingOptions: any; + signalingPipe: any; + constructor( + strSignalingServerURL: string, idRtcParticipant: string, + offerOptions: any, signalingOptions: any + ) { super( strSignalingServerURL, idRtcParticipant ); this.isDisposed = false; this.idSomebodyCreator = null; this.bWasImpersonated = false; this.isCreator = false; this.isJoiner = false; - this.offerOptions = { optional: [], // offer to the remote peer the opportunity to try to send audio @@ -1950,7 +2028,7 @@ export class RTCActor extends RTCConnection { this.bWasImpersonated = false; super.dispose(); } - describe( strInstanceType, arrAdditionalProps ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || @@ -1960,7 +2038,7 @@ export class RTCActor extends RTCConnection { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } - onError( err ) { + onError( err: any ) { super.onError( err ); } signalingPipeOpen() { @@ -1972,13 +2050,13 @@ export class RTCActor extends RTCConnection { "signalingWillStart", { "detail": { "actor": this } } ) ); self.signalingPipe = new WebSocketClientPipe( self.strSignalingServerURL ); self.signalingPipe.on( - "open", function( eventData ) { self.signalingPipeOnOpen( eventData ); } ); + "open", function( eventData: any ) { self.signalingPipeOnOpen( eventData ); } ); self.signalingPipe.on( - "close", function( eventData ) { self.signalingPipeOnClose( eventData ); } ); + "close", function( eventData: any ) { self.signalingPipeOnClose( eventData ); } ); self.signalingPipe.on( - "error", function( eventData ) { self.signalingPipeOnError( eventData ); } ); + "error", function( eventData: any ) { self.signalingPipeOnError( eventData ); } ); self.signalingPipe.on( - "message", function( eventData ) { self.signalingPipeOnRawMessage( eventData ); } ); + "message", function( eventData: any ) { self.signalingPipeOnRawMessage( eventData ); } ); self.dispatchEvent( new UniversalDispatcherEvent( "signalingDidStarted", { "detail": { "actor": this } } ) ); @@ -2007,7 +2085,7 @@ export class RTCActor extends RTCConnection { "signalingClosed", { "detail": { "actor": this } } ) ); } } - signalingPipeOnOpen( eventData ) { + signalingPipeOnOpen( eventData: any ) { try { this.dispatchEvent( new UniversalDispatcherEvent( @@ -2037,7 +2115,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } - signalingPipeOnClose( eventData ) { + signalingPipeOnClose( eventData: any ) { this.dispatchEvent( new UniversalDispatcherEvent( "signalingPipeClose", { "detail": { "actor": this } } ) ); @@ -2049,7 +2127,7 @@ export class RTCActor extends RTCConnection { } this.signalingPipeClose(); } - signalingPipeOnError( eventData ) { + signalingPipeOnError( eventData: any ) { // alert( JSON.stringify( eventData ) ); this.dispatchEvent( new UniversalDispatcherEvent( @@ -2063,7 +2141,7 @@ export class RTCActor extends RTCConnection { this.onError( eventData ); this.signalingPipeClose(); } - signalingPipeOnRawMessage( eventData ) { + signalingPipeOnRawMessage( eventData: any ) { try { if( settings.logging.net.signaling.rawMessage ) { console.log( @@ -2081,7 +2159,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } - signalingPipeOnMessage( joMessage ) { + signalingPipeOnMessage( joMessage: any ) { switch ( joMessage.method ) { case "signalingImpersonate": { if( joMessage.error == null ) { @@ -2127,9 +2205,28 @@ export class RTCActor extends RTCConnection { }; export class RTCServerPeer extends RTCConnection { + rtcCreator: any; + idSomebodyOtherSide: string|null; + idOffer: number; + tsOfferCreated: any; + isPublishing: boolean; + isSignalingNegotiation: boolean; + isPublishTimeout: boolean; + isSignalingNegotiationTimeout: boolean; + timerPublishing: any; + timerSignalingNegotiation: any; + timeToPublishMilliseconds: any; + timeToSignalingNegotiationMilliseconds: number; + peerConfiguration: any; + peerAdditionalOptions: any; + localMediaStream: any; + isOfferPublishedOnSignalingServer: boolean; + offerOptions: any; + serverPipe: any; constructor( - rtcCreator, timeToPublishMilliseconds, timeToSignalingNegotiationMilliseconds, - peerConfiguration, peerAdditionalOptions, localMediaStream + rtcCreator: any, + timeToPublishMilliseconds: number, timeToSignalingNegotiationMilliseconds: number, + peerConfiguration: any, peerAdditionalOptions: any, localMediaStream?: any ) { super(); this.rtcCreator = rtcCreator; @@ -2146,10 +2243,10 @@ export class RTCServerPeer extends RTCConnection { this.timerPublishing = null; this.timerSignalingNegotiation = null; this.timeToPublishMilliseconds = timeToPublishMilliseconds - ? parseInt( timeToPublishMilliseconds, 10 ) + ? timeToPublishMilliseconds : settings.net.rtc.timeToPublishMilliseconds; this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds - ? parseInt( timeToSignalingNegotiationMilliseconds, 10 ) + ? timeToSignalingNegotiationMilliseconds : settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration == "object" ) @@ -2172,7 +2269,7 @@ export class RTCServerPeer extends RTCConnection { this.publishCancel(); this.signalingNegotiationCancel(); if( this.rtcCreator ) { - if( this.idOffer in this.rtcCreator.mapServerOffers ) { + if( this.idOffer && this.idOffer in this.rtcCreator.mapServerOffers ) { if( settings.logging.net.signaling.offerUnregister ) console.log( "Unregister offer", this.idOffer, "(RTCServerPeer dispose)" ); delete this.rtcCreator.mapServerOffers[this.idOffer]; @@ -2190,7 +2287,7 @@ export class RTCServerPeer extends RTCConnection { this.tsOfferCreated = null; super.dispose(); } - describe( strInstanceType, arrAdditionalProps ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || ( typeof strInstanceType != "string" ) || strInstanceType.length == 0 ) @@ -2215,13 +2312,13 @@ export class RTCServerPeer extends RTCConnection { self.pc.createDataChannel( settings.net.rtc.dataChannel.label, settings.net.rtc.dataChannel.opts ); self.dc.addEventListener( - "open", function( event ) { self.onDataChannelOpen( event ); } ); + "open", function( event: any ) { self.onDataChannelOpen( event ); } ); self.dc.addEventListener( - "close", function( event ) { self.onDataChannelClose( event ); } ); + "close", function( event: any ) { self.onDataChannelClose( event ); } ); self.dc.addEventListener( - "error", function( event ) { self.onDataChannelError( event ); } ); + "error", function( event: any ) { self.onDataChannelError( event ); } ); self.dc.addEventListener( - "message", function( event ) { self.onDataChannelMessage( event ); } ); + "message", function( event: any ) { self.onDataChannelMessage( event ); } ); } } publishCancel() { @@ -2280,15 +2377,15 @@ export class RTCServerPeer extends RTCConnection { new UniversalDispatcherEvent( "publishStart", { "detail": { "participant": self } } ) ); self.pc.oniceconnectionstatechange = - function( event ) { self.onIceConnectionStateChange( event ); }; + function( event: any ) { self.onIceConnectionStateChange( event ); }; self.pc.onicegatheringstatechange = - function( event ) { self.onIceGatheringStateChange( event ); }; + function( event: any ) { self.onIceGatheringStateChange( event ); }; self.pc.onidentityresult = - function( event ) { self.onIceIdentifyResult( event ); }; + function( event: any ) { self.onIceIdentifyResult( event ); }; self.pc.onsignalingstatechange = - function( event ) { self.onIceSignalingStateChange( event ); }; + function( event: any ) { self.onIceSignalingStateChange( event ); }; self.pc.onnegotiationneeded = - function( event ) { self.onIceNegotiationNeeded( event ); }; + function( event: any ) { self.onIceNegotiationNeeded( event ); }; self.pc.createOffer( self.offerOptions ).then( function( offerDescription ) { // success @@ -2317,7 +2414,7 @@ export class RTCServerPeer extends RTCConnection { "localDescriptionSet", { "detail": { "participant": self } } ) ); - self.pc.onicecandidate = function( event ) { + self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; self.onIceComplete( event ); }; // onicecandidate @@ -2327,14 +2424,14 @@ export class RTCServerPeer extends RTCConnection { self.signalingNegotiationCancel(); self.onError( "Failed to set local description: " + err.toString() ); } ); - }, function() { + }, function( err ) { self.publishCancel(); self.signalingNegotiationCancel(); // error of createOffer self.onError( "Failed to create offer:" + err.toString() ); } ); } - onOtherSideIdentified( idSomebodyOtherSide ) { + onOtherSideIdentified( idSomebodyOtherSide: any ) { this.publishCancel(); this.signalingNegotiationCancel(); this.idSomebodyOtherSide = "" + idSomebodyOtherSide; @@ -2353,12 +2450,10 @@ export class RTCServerPeer extends RTCConnection { onError( err ) { if( this.rtcCreator ) { this.rtcCreator.onRtcPeerError( this, err ); - if( this.idOffer in this.rtcCreator.mapServerOffers ) { + if( this.idOffer && this.idOffer in this.rtcCreator.mapServerOffers ) { if( settings.logging.net.signaling.offerUnregister ) { console.log( - "Unregister offer", this.idOffer, - "due to RTCServerPeer error:".err - ); + "Unregister offer", this.idOffer, "due to RTCServerPeer error:", err ); } delete this.rtcCreator.mapServerOffers[this.idOffer]; } @@ -2389,7 +2484,7 @@ export class RTCServerPeer extends RTCConnection { "method": "signalingPublishOffer", "offer": self.pc.localDescription, "idSomebodyCreator": "" + self.rtcCreator.idRtcParticipant, - "idOffer": 0 + self.idOffer + "idOffer": 0 + ( self.idOffer || 0 ) }; if( settings.logging.net.signaling.message ) { console.log( @@ -2432,7 +2527,7 @@ export class RTCServerPeer extends RTCConnection { throw err; } } - onIceComplete( event ) { + onIceComplete( event: any ) { super.onIceComplete( event ); const self = this; try { @@ -2460,11 +2555,12 @@ export class RTCServerPeer extends RTCConnection { }; export class RTCCreator extends RTCActor { + idOfferNext: number; + mapServerOffers: any; + mapServerPeers: any; constructor( - strSignalingServerURL, - idRtcParticipant, - offerOptions, - signalingOptions + strSignalingServerURL: string, idRtcParticipant: string, + offerOptions: any, signalingOptions: any ) { super( strSignalingServerURL, idRtcParticipant, offerOptions, signalingOptions ); const self = this; @@ -2478,18 +2574,21 @@ export class RTCCreator extends RTCActor { if( this.isDisposed ) return; this.isDisposing = true; - for( const [ idOffer, rtcPeer ] of Object.entries( this.mapServerOffers ) ) { + for( const [ idOfferWalk, rtcPeerWalk ] of Object.entries( this.mapServerOffers ) ) { + const rtcPeer: any = rtcPeerWalk; if( settings.logging.net.signaling.offerUnregister ) - console.log( "Unregister offer", idOffer, "(one of all, RTCCreator dispose)" ); + console.log( "Unregister offer", idOfferWalk, "(one of all, RTCCreator dispose)" ); rtcPeer.dispose(); } - for( const [ /*idSomebodyOtherSide*/, rtcPeer ] of - Object.entries( this.mapServerPeers ) ) + for( const [ idSomebodyOtherSideWalk, rtcPeerWalk ] of + Object.entries( this.mapServerPeers ) ) { + const rtcPeer: any = rtcPeerWalk; rtcPeer.dispose(); + } this.mapServerOffers = { }; super.dispose(); } - describe( strInstanceType, arrAdditionalProps ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || ( typeof strInstanceType != "string" ) || strInstanceType.length == 0 ) @@ -2497,7 +2596,7 @@ export class RTCCreator extends RTCActor { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } - onOtherSideIdentified( idSomebodyOtherSide, idOffer ) { // server peer got result + onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ) { // server peer got result if( settings.logging.net.signaling.impersonate ) { console.log( this.describe() + " did identified other side RTC joiner \"" + @@ -2510,8 +2609,7 @@ export class RTCCreator extends RTCActor { console.warn( " >>> " + this.describe() + " came across with incorrect other side identification for *somebody*", - idSomebodyOtherSide, "and offer ID", idOffer, ":".strError - ); + idSomebodyOtherSide, "and offer ID", idOffer, ":", strError ); } this.onError( strError ); return; @@ -2526,7 +2624,7 @@ export class RTCCreator extends RTCActor { this.mapServerPeers["" + idSomebodyOtherSide] = rtcPeer; rtcPeer.onOtherSideIdentified( "" + idSomebodyOtherSide ); } - onRtcPeerError( rtcPeer, err ) { + onRtcPeerError( rtcPeer: any, err: any ) { if( settings.logging.net.rtc.error ) console.warn( " !!! " + this.describe() + " rtc peer error", err ); this.dispatchEvent( @@ -2535,7 +2633,7 @@ export class RTCCreator extends RTCActor { { "detail": { "actor": this, "peer": rtcPeer, "error": err } } ) ); } - signalingPipeOnMessage( joMessage ) { + signalingPipeOnMessage( joMessage: any ) { const self = this; switch ( joMessage.method ) { case "signalingPublishOffer": { @@ -2655,11 +2753,12 @@ export class RTCCreator extends RTCActor { break; } // switch( joMessage.method ) } - send( data ) { // implementation in RTCCreator does send to all + send( data: any ) { // implementation in RTCCreator does send to all try { const s = socketSentDataMarshall( data ); - for( const [ /*idSomebodyOtherSide*/, rtcPeer ] + for( const [ idSomebodyOtherSideWalk, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { + const rtcPeer: any = rtcPeerWalk; try { rtcPeer.send( s ); } catch ( err ) { @@ -2672,23 +2771,29 @@ export class RTCCreator extends RTCActor { } onImpersonationComplete() { super.onImpersonationComplete(); - for( const [ /*idOffer*/, rtcPeer ] - of Object.entries( this.mapServerOffers ) ) + for( const [ idOfferWalk, rtcPeerWalk ] + of Object.entries( this.mapServerOffers ) ) { + const rtcPeer: any = rtcPeerWalk; rtcPeer.onImpersonationCompleteForCreator(); - for( const [ /*idSomebodyOtherSide*/, rtcPeer ] - of Object.entries( this.mapServerPeers ) ) + } + for( const [ idSomebodyOtherSideWalk, rtcPeerWalk ] + of Object.entries( this.mapServerPeers ) ) { + const rtcPeer: any = rtcPeerWalk; rtcPeer.onImpersonationCompleteForCreator(); + } } }; export class RTCJoiner extends RTCActor { + idSomebodyOtherSide: any; + idOffer: number; + tsAnswerCreated: any; + isAnswerPublishedOnSignalingServer: boolean; + peerConfiguration: any; + peerAdditionalOptions: any; constructor( - strSignalingServerURL, - idRtcParticipant, - offerOptions, - signalingOptions, - peerConfiguration, - peerAdditionalOptions + strSignalingServerURL: string, idRtcParticipant: string, offerOptions: any, + signalingOptions: any, peerConfiguration: any, peerAdditionalOptions: any ) { super( strSignalingServerURL, idRtcParticipant, offerOptions, signalingOptions ); this.idSomebodyOtherSide = null; @@ -2714,7 +2819,7 @@ export class RTCJoiner extends RTCActor { this.isAnswerPublishedOnSignalingServer = false; super.dispose(); } - describe( strInstanceType, arrAdditionalProps ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || @@ -2733,23 +2838,23 @@ export class RTCJoiner extends RTCActor { self.pc = new webRtcModule.RTCPeerConnection( self.peerConfiguration, self.peerAdditionalOptions ); - self.pc.addEventListener( "track", function( event ) { + self.pc.addEventListener( "track", function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "trackAvailable", { "detail": { "participant": self, "event": event } } ) ); } ); self.pc.oniceconnectionstatechange = - function( event ) { self.onIceConnectionStateChange( event ); }; + function( event: any ) { self.onIceConnectionStateChange( event ); }; self.pc.onicegatheringstatechange = - function( event ) { self.onIceGatheringStateChange( event ); }; + function( event: any ) { self.onIceGatheringStateChange( event ); }; self.pc.onidentityresult = - function( event ) { self.onIceIdentifyResult( event ); }; + function( event: any ) { self.onIceIdentifyResult( event ); }; self.pc.onsignalingstatechange = - function( event ) { self.onIceSignalingStateChange( event ); }; + function( event: any ) { self.onIceSignalingStateChange( event ); }; self.pc.onnegotiationneeded = - function( event ) { self.onIceNegotiationNeeded( event ); }; - self.pc.ondatachannel = function( event ) { + function( event: any ) { self.onIceNegotiationNeeded( event ); }; + self.pc.ondatachannel = function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "dataChannelAvailable", @@ -2759,18 +2864,18 @@ export class RTCJoiner extends RTCActor { self.dc = dataChannel; self.dc.addEventListener( "open", - function( event ) { self.onDataChannelOpen( event ); } ); + function( event: any ) { self.onDataChannelOpen( event ); } ); self.dc.addEventListener( "close", - function( event ) { self.onDataChannelClose( event ); } ); + function( event: any ) { self.onDataChannelClose( event ); } ); self.dc.addEventListener( "error", - function( event ) { self.onDataChannelError( event ); } ); + function( event: any ) { self.onDataChannelError( event ); } ); self.dc.addEventListener( "message", - function( event ) { self.onDataChannelMessage( event ); } ); + function( event: any ) { self.onDataChannelMessage( event ); } ); }; - self.pc.onicecandidate = function( event ) { + self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; self.onIceComplete( event ); try { @@ -2781,7 +2886,7 @@ export class RTCJoiner extends RTCActor { } if( ! self.isAnswerPublishedOnSignalingServer ) { self.publishSignalingAnswer( event ); - self.iAnswerPublishedOnSignalingServer = true; + self.isAnswerPublishedOnSignalingServer = true; } if( event.candidate != null ) { if( settings.logging.net.signaling.candidateWalk ) { @@ -2798,7 +2903,7 @@ export class RTCJoiner extends RTCActor { } }; // onicecandidate } - publishSignalingAnswer( event ) { + publishSignalingAnswer( event: any ) { const self = this; try { if( event.candidate == null || @@ -2851,7 +2956,7 @@ export class RTCJoiner extends RTCActor { } this.signalingPipe.send( joFetchOfferMessage ); } - onIceComplete( event ) { + onIceComplete( event: any ) { super.onIceComplete( event ); } onOtherSideIdentified( idSomebodyOtherSide, idOffer ) { // client peer got result @@ -2874,7 +2979,7 @@ export class RTCJoiner extends RTCActor { } } ) ); } - signalingPipeOnMessage( joMessage ) { + signalingPipeOnMessage( joMessage: any ) { const self = this; switch ( joMessage.method ) { case "signalingFetchOffer": { @@ -2990,7 +3095,10 @@ export class RTCJoiner extends RTCActor { }; export class WebRTCServerPipe extends BasicSocketPipe { - constructor( acceptor, rtcPeer, strSignalingServerURL ) { + clientNumber: number; + rtcPeer: any; + strSignalingServerURL: string; + constructor( acceptor: any, rtcPeer: any, strSignalingServerURL: string ) { super(); const self = this; self.socketType = "WebRTC"; @@ -3002,7 +3110,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { ++ acceptor.nextClientNumber; self.rtcPeer = rtcPeer; self.strSignalingServerURL = - utils.makeValidSignalingServerURL( strSignalingServerURL ); + utils.makeValidSignalingServerURL( strSignalingServerURL ); self.url = "rtc_server_pipe(" + self.clientNumber + ")://" + strSignalingServerURL; self.rtcPeer.on( "dataChannelOpen", function( jo ) { self.isConnected = true; @@ -3049,7 +3157,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { this.rtcPeer = null; this.url = ""; this.strSignalingServerURL = ""; - super.handleServerDisposed(); + //super.handleServerDisposed(); this.dispose(); } performDisconnect() { @@ -3067,7 +3175,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { this.url = ""; this.strSignalingServerURL = ""; } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const err = "Cannot send messages to disconnected WebRTC socket server pipe"; this.onError( err ); @@ -3076,22 +3184,37 @@ export class WebRTCServerPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); } + onError( err ) { + } disconnect() { this.performDisconnect(); super.disconnect(); } - implReceive( data ) { - const jo = socketReceivedDataReverseMarshall( data ); + implReceive( data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); } }; export class WebRTCServerAcceptor extends BasicServerAcceptor { + strSignalingServerURL: string; + idRtcParticipant: string; + offerOptions: any; + signalingOptions: any; + peerConfiguration: any; + peerAdditionalOptions: any; + maxActiveOfferCount: number; + mapPendingOffers: any; + timeToPublishMilliseconds: number; + timeToSignalingNegotiationMilliseconds: number; + rtcCreator: any; + isConnected: false; constructor( - strSignalingServerURL, idRtcParticipant, offerOptions, - signalingOptions, maxActiveOfferCount, timeToPublishMilliseconds, - timeToSignalingNegotiationMilliseconds, peerConfiguration, peerAdditionalOptions + strSignalingServerURL: string, idRtcParticipant: any, offerOptions: any, + signalingOptions: any, maxActiveOfferCount?: number, timeToPublishMilliseconds?: number, + timeToSignalingNegotiationMilliseconds?: number, + peerConfiguration?: any, peerAdditionalOptions?: any ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); @@ -3110,15 +3233,15 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.socketType = "WebRTC"; this.maxActiveOfferCount = ( maxActiveOfferCount != null && maxActiveOfferCount != undefined ) - ? parseInt( maxActiveOfferCount, 10 ) : settings.net.rtc.maxActiveOfferCount; + ? maxActiveOfferCount : settings.net.rtc.maxActiveOfferCount; if( this.maxActiveOfferCount < 1 ) this.maxActiveOfferCount = 1; this.mapPendingOffers = { }; // idOffer -> RTCServerPeer this.timeToPublishMilliseconds = timeToPublishMilliseconds - ? parseInt( timeToPublishMilliseconds, 10 ) + ? timeToPublishMilliseconds : settings.net.rtc.timeToPublishMilliseconds; this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds - ? parseInt( timeToSignalingNegotiationMilliseconds, 10 ) + ? timeToSignalingNegotiationMilliseconds : settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.rtcCreator = new RTCCreator( @@ -3128,20 +3251,20 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.signalingOptions ); this.isListening = true; const self = this; - this.rtcCreator.on( "signalingPassedImpersonation", function( eventData ) { + this.rtcCreator.on( "signalingPassedImpersonation", function( eventData: any ) { self.updateAllPendingOffers(); self.dispatchEvent( new UniversalDispatcherEvent( "signalingPassedImpersonation", { "detail": { "acceptor": self } } ) ); } ); - this.rtcCreator.on( "signalingFailedImpersonation", function( eventData ) { + this.rtcCreator.on( "signalingFailedImpersonation", function( eventData: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedImpersonation", { "detail": { "acceptor": self } } ) ); } ); - this.rtcCreator.on( "error", function( eventData ) { + this.rtcCreator.on( "error", function( eventData: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3153,7 +3276,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } } ) ); } ); - this.rtcCreator.on( "close", function( eventData ) { + this.rtcCreator.on( "close", function( eventData: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "close", @@ -3188,7 +3311,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.timeToSignalingNegotiationMilliseconds, this.peerConfiguration, this.peerAdditionalOptions ); const self = this; - rtcPeer.on( "identified", function( event ) { + rtcPeer.on( "identified", function( event: any ) { if( rtcPeer.isDisposing || rtcPeer.isDisposed ) return; if( settings.logging.net.signaling.generic ) { @@ -3203,7 +3326,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { new UniversalDispatcherEvent( "identified", { "detail": { "peer": rtcPeer } } ) ); self.updateAllPendingOffers(); } ); - rtcPeer.on( "localDescriptionSet", function( event ) { + rtcPeer.on( "localDescriptionSet", function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "peerLocalDescriptionSet", @@ -3219,7 +3342,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { self.updateAllPendingOffers(); } ); - const retranslateError = function( eventData ) { + const retranslateError = function( eventData: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3237,11 +3360,11 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.mapPendingOffers[rtcPeer.idOffer] = rtcPeer; } - detachPendingOffer( idOffer ) { + detachPendingOffer( idOffer: any ) { if( idOffer in this.mapPendingOffers ) delete this.mapPendingOffers[idOffer]; } - disposePendingOffer( idOffer ) { + disposePendingOffer( idOffer: any ) { if( idOffer in this.mapPendingOffers ) { const rtcPeer = this.mapPendingOffers[idOffer]; rtcPeer.dispose(); @@ -3249,30 +3372,40 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } } removeAllPendingOffers() { - for( const [ /*idOffer*/, rtcPeer ] + for( const [ idOfferWalk, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapServerPeers ) ) { + const rtcPeer: any = rtcPeerWalk; const serverPipe = rtcPeer.serverPipe; serverPipe.dispose(); } this.rtcCreator.mapServerPeers = { }; - for( const [ /*idOffer*/, rtcPeer ] - of Object.entries( this.rtcCreator.mapPendingOffers ) ) + for( const [ idOfferWalk, rtcPeerWalk ] + of Object.entries( this.rtcCreator.mapPendingOffers ) ) { + const rtcPeer: any = rtcPeerWalk; rtcPeer.dispose(); - + } this.mapPendingOffers = { }; } updateAllPendingOffers() { if( this.isDisposed ) return; - for( let n = Object.keys( this.mapPendingOffers ); n < this.maxActiveOfferCount; ++ n ) + for( let n = Object.keys( this.mapPendingOffers ).length; n < this.maxActiveOfferCount; ++ n ) this.addPendingOffer(); } }; export class WebRTCClientPipe extends BasicSocketPipe { + strSignalingServerURL: string|null; + idRtcParticipant: string; + offerOptions: any; + signalingOptions: any; + peerConfiguration: any; + peerAdditionalOptions: any; + rtcPeer: any; + isAutoCloseSignalingPipeOnDataChannelOpen: boolean; constructor( - strSignalingServerURL, idRtcParticipant, offerOptions, - signalingOptions, peerConfiguration, peerAdditionalOptions + strSignalingServerURL: string, idRtcParticipant: string, offerOptions: any, + signalingOptions: any, peerConfiguration: any, peerAdditionalOptions: any ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); @@ -3305,7 +3438,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.strSignalingServerURL = null; super.dispose(); } - implSend( data ) { + implSend( data: any ) { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const s = "Cannot send messages to disconnected WebRTC socket client pipe"; this.dispatchEvent( @@ -3330,7 +3463,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { return; this.rtcDisconnect(); } - rtcConnect( strSignalingServerURL ) { + rtcConnect( strSignalingServerURL: string ) { if( strSignalingServerURL.length == 0 ) { const s = "Cannot connect signaling server \"" + strSignalingServerURL + "\", bad url"; this.dispatchEvent( @@ -3352,7 +3485,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { ); // client side self.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); - self.rtcPeer.on( "identified", function( event ) { + self.rtcPeer.on( "identified", function( event: any ) { if( settings.logging.net.signaling.generic ) { console.log( self.rtcPeer.describe() + " is now identified peer", @@ -3434,8 +3567,8 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.isConnected = false; this.url = ""; } - implReceive( data ) { - const jo = socketReceivedDataReverseMarshall( data ); + implReceive( data: any ) { + const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 20721997..57878beb 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -140,7 +140,7 @@ export const prepareAnswerJSON = function( joMessage: any ) : any { return joAnswer; }; -export const makeValidSignalingServerURL = function( strSignalingServerURL: string ) : string { +export const makeValidSignalingServerURL = function( strSignalingServerURL?: string ) : string { const proto = settings.net.secure ? "wss" : "ws"; return "" + ( ( strSignalingServerURL != null && diff --git a/src/threadInfo.ts b/src/threadInfo.ts index fc89622d..38527dcf 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -29,26 +29,26 @@ import * as log from "./log"; const Worker = worker_threads.Worker; export { Worker }; -const joCustomThreadProperties = { }; +const joCustomThreadProperties: any = { }; export { joCustomThreadProperties }; -export const sleep = ( milliseconds ) => { +export const sleep = ( milliseconds: number ) : Promise => { return new Promise( resolve => setTimeout( resolve, milliseconds ) ); }; -export function getCurrentThreadID() { +export function getCurrentThreadID() : number { return worker_threads.threadId; } -export function isMainThread() { +export function isMainThread() : boolean { return ( !!( worker_threads.isMainThread ) ); } -export function threadDescription( isColorized ) { +export function threadDescription( isColorized?: boolean ) : string { if( typeof isColorized == "undefined" ) isColorized = true; - const tid = getCurrentThreadID(); - const st = isMainThread() ? "main" : "worker"; + const tid: number = getCurrentThreadID(); + const st: string = isMainThread() ? "main" : "worker"; return isColorized ? ( log.fmtAttention( st ) + log.fmtDebug( " thread " ) + log.fmtInformation( tid ) ) diff --git a/src/utils.ts b/src/utils.ts index 4ca602e9..0d98733a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -101,7 +101,7 @@ export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boo if( bLogOutput ) log.debug( "Did loaded content of JSON file {}, will parse it...", strPath ); - const jo = JSON.parse( s ); + const jo: any = JSON.parse( s ); if( bLogOutput ) log.success( "Done, loaded content of JSON file {}.", strPath ); return jo; From 29ab85b683c22c3d0f86f49bc655c4ddf8871a81 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 8 Dec 2023 22:39:04 +0000 Subject: [PATCH 03/53] code porting to TypeScript --- src/cli.ts | 10 ++--- src/imaHelperAPIs.ts | 59 ++++++++++++------------- src/imaOracleOperations.ts | 2 +- src/imaSgxExternalSigner.ts | 2 +- src/loopWorker.ts | 86 +++++++++++++++++++------------------ src/main.ts | 27 ++++++------ src/observer.ts | 15 +++---- src/oracle.ts | 49 +++++++++++---------- src/pwa.ts | 37 ++++++++-------- src/rpcCall.ts | 48 +++++++++++---------- 10 files changed, 174 insertions(+), 161 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 2d204425..62eb90fc 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -42,7 +42,7 @@ const gStrAppName = "IMA AGENT"; const gStrVersion = imaUtils.fileLoad( path.join( __dirname, "../VERSION" ), "N/A" ).toString().trim(); -function att( ...args: any[] ) : string { return log.fmtAttention( ...arguments ); }; +function att( ...args: any[] ) : string { return log.fmtAttention( ...args ); }; export function printAbout( isLog?: boolean ) { isLog = isLog || false; @@ -1198,9 +1198,9 @@ function parseOtherArgs( imaState, joArg ) { return false; } -export function parse( joExternalHandlers, argv ) { +export function parse( joExternalHandlers: any ) { const imaState = state.get(); - const cntArgs = argv || process.argv.length; + const cntArgs = process.argv.length; for( let idxArg = 2; idxArg < cntArgs; ++idxArg ) { const joArg = parseCommandLineArgument( process.argv[idxArg] ); parseHelp( imaState, joArg ); // exits process on "--help" @@ -1342,7 +1342,7 @@ function commonInitPrintSysInfo() { log.debug( "OS {sunny} is {}", "tmp dir", os.tmpdir() ); log.debug( "OS {sunny} is {}", "uptime", os.uptime() ); log.debug( "OS {sunny} is {}", "user", os.userInfo() ); - const joMemory = { total: os.totalmem(), free: os.freemem() }; + const joMemory: any = { total: os.totalmem(), free: os.freemem() }; joMemory.freePercent = ( joMemory.free / joMemory.total ) * 100.0; log.debug( "OS {sunny} is {}", "memory", joMemory ); const joLA = os.loadavg(); @@ -2627,7 +2627,7 @@ export function commonInit() { commonInitCheckErc20(); commonInitCheckErc721(); commonInitCheckErc1155(); - if( log.verboseGet() > log.verboseReversed().debug || imaState.bShowConfigMode ) { + if( log.verboseGet() > log.verboseReversed()["debug"] || imaState.bShowConfigMode ) { commonInitCheckGeneralArgs(); commonInitCheckCredentialsArgs(); commonInitCheckTransferAmountArgs(); diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 1b760194..7ff36837 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -28,41 +28,41 @@ import * as owaspUtils from "./owaspUtils"; import * as rpcCall from "./rpcCall"; import * as threadInfo from "./threadInfo"; -export const longSeparator = +export const longSeparator: string = "============================================================" + "==========================================================="; -let gMillisecondsSleepBeforeFetchOutgoingMessageEvent = 5000; -let gMillisecondsSleepBetweenTransactionsOnSChain = 0; // example - 5000 -let gFlagWaitForNextBlockOnSChain = false; +let gMillisecondsSleepBeforeFetchOutgoingMessageEvent: number = 5000; +let gMillisecondsSleepBetweenTransactionsOnSChain: number = 0; // example - 5000 +let gFlagWaitForNextBlockOnSChain: boolean = false; -export function getMillisecondsSleepBeforeFetchOutgoingMessageEvent() { +export function getMillisecondsSleepBeforeFetchOutgoingMessageEvent() : number { return gMillisecondsSleepBeforeFetchOutgoingMessageEvent; } -export function setMillisecondsSleepBeforeFetchOutgoingMessageEvent( val ) { +export function setMillisecondsSleepBeforeFetchOutgoingMessageEvent( val?: number ) : void { gMillisecondsSleepBeforeFetchOutgoingMessageEvent = val ? val : 0; } -export function getSleepBetweenTransactionsOnSChainMilliseconds() { +export function getSleepBetweenTransactionsOnSChainMilliseconds() : number { return gMillisecondsSleepBetweenTransactionsOnSChain; } -export function setSleepBetweenTransactionsOnSChainMilliseconds( val ) { +export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ) : void { gMillisecondsSleepBetweenTransactionsOnSChain = val ? val : 0; } -export function getWaitForNextBlockOnSChain() { +export function getWaitForNextBlockOnSChain() : boolean { return ( !!gFlagWaitForNextBlockOnSChain ); } export function setWaitForNextBlockOnSChain( val ) { gFlagWaitForNextBlockOnSChain = ( !!val ); } -export const currentTimestamp = () => { - return parseInt( parseInt( Date.now().valueOf() ) / 1000 ); +export const currentTimestamp = () : number => { + return Date.now().valueOf() / 1000; }; -export async function safeWaitForNextBlockToAppear( details, ethersProvider ) { - const nBlockNumber = +export async function safeWaitForNextBlockToAppear( details: any, ethersProvider: any ) { + const nBlockNumber: any = owaspUtils.toBN( await safeGetBlockNumber( details, 10, ethersProvider ) ); details.trace( "Waiting for next block to appear..." ); details.trace( " ...have block {}", nBlockNumber.toHexString() ); @@ -77,10 +77,11 @@ export async function safeWaitForNextBlockToAppear( details, ethersProvider ) { } export async function safeGetBlockNumber( - details, cntAttempts, ethersProvider, retValOnFail, throwIfServerOffline + details: any, cntAttempts: number, ethersProvider: any, + retValOnFail?: any, throwIfServerOffline?: boolean ) { - const strFnName = "getBlockNumber"; - const u = owaspUtils.ethersProviderToUrl( ethersProvider ); + const strFnName: string = "getBlockNumber"; + const u: string = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; @@ -130,13 +131,13 @@ export async function safeGetBlockNumber( return ret; } -let gCountOfBlocksInIterativeStep = 1000; -let gMaxBlockScanIterationsInAllRange = 5000; +let gCountOfBlocksInIterativeStep: number = 1000; +let gMaxBlockScanIterationsInAllRange: number = 5000; -export function getBlocksCountInInIterativeStepOfEventsScan() { +export function getBlocksCountInInIterativeStepOfEventsScan(): number { return gCountOfBlocksInIterativeStep; } -export function setBlocksCountInInIterativeStepOfEventsScan( n ) { +export function setBlocksCountInInIterativeStepOfEventsScan( n?: number ) : void { if( ! n ) gCountOfBlocksInIterativeStep = 0; else { @@ -146,10 +147,10 @@ export function setBlocksCountInInIterativeStepOfEventsScan( n ) { } } -export function getMaxIterationsInAllRangeEventsScan() { +export function getMaxIterationsInAllRangeEventsScan() : number { return gCountOfBlocksInIterativeStep; } -export function setMaxIterationsInAllRangeEventsScan( n ) { +export function setMaxIterationsInAllRangeEventsScan( n?: number ) : void { if( ! n ) gMaxBlockScanIterationsInAllRange = 0; else { @@ -160,31 +161,31 @@ export function setMaxIterationsInAllRangeEventsScan( n ) { } // default S<->S transfer mode for "--s2s-transfer" is "forward" -let gFlagIsForwardS2S = true; +let gFlagIsForwardS2S: boolean = true; -export function getS2STransferModeDescription() { +export function getS2STransferModeDescription() : string { return gFlagIsForwardS2S ? "forward" : "reverse"; } -export function getS2STransferModeDescriptionColorized() { +export function getS2STransferModeDescriptionColorized() : string { return log.posNeg( gFlagIsForwardS2S, "forward", "reverse" ); } -export function isForwardS2S() { +export function isForwardS2S() : boolean { return ( !!gFlagIsForwardS2S ); } -export function isReverseS2S() { +export function isReverseS2S() : boolean { return ( !!gFlagIsForwardS2S ); } -export function setForwardS2S( b?: boolean ) { +export function setForwardS2S( b?: boolean ) : void { if( b == null || b == undefined ) b = true; gFlagIsForwardS2S = ( !!b ); } -export function setReverseS2S( b?: boolean ) { +export function setReverseS2S( b?: boolean ) : void { if( b == null || b == undefined ) b = true; gFlagIsForwardS2S = b ? false : true; diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 4214ab28..b0bcc700 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -32,7 +32,7 @@ import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; let gFlagIsEnabledOracle = false; -export function getEnabledOracle( isEnabled ) { +export function getEnabledOracle() : boolean { return ( !!gFlagIsEnabledOracle ); } export function setEnabledOracle( isEnabled ) { diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 4f7d0a8d..070ad4f5 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -7,7 +7,7 @@ const gIsDebugLogging = false; // development option only, must be always false log.addStdout(); // allow self-signed wss and https -process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; +process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; function finalizeOutput( jo ) { if( ! jo ) diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 5df4d0f3..49c424a8 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -36,7 +36,7 @@ import * as pwa from "./pwa"; import * as log from "./log"; import * as threadInfo from "./threadInfo"; -let imaState = state.get(); +let imaState: any = state.get(); if( parentPort ) { parentPort.on( "message", jo => { @@ -61,9 +61,13 @@ function doSendMessage( type, endpoint, workerUUID, data ) { } class ObserverServer extends SocketServer { + initComplete: boolean; + opts: any; + intervalPeriodicSchainsCaching: number|null; + bIsPeriodicCachingStepInProgress: boolean; constructor( acceptor ) { super( acceptor ); - const self = this; + const self: any = this; self.initComplete = false; log.enableColorization( workerData.colorization.isEnabled ); self.opts = null; @@ -207,7 +211,7 @@ class ObserverServer extends SocketServer { workerData.url, threadInfo.threadDescription() ); } dispose() { - const self = this; + const self:any = this; self.isDisposing = true; if( self.intervalPeriodicSchainsCaching ) { clearInterval( self.intervalPeriodicSchainsCaching ); @@ -216,79 +220,79 @@ class ObserverServer extends SocketServer { super.dispose(); } initLogMethods() { - const self = this; + const self:any = this; if( "fatal" in self && self.fatal && typeof self.fatal == "function" ) return; - self.fatal = function() { - if( log.verboseGet() >= log.verboseReversed().fatal ) { + self.fatal = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["fatal"] ) { self.log( log.getLogLinePrefixFatal() + - log.fmtFatal( ...arguments ) ); + log.fmtFatal( ...args ) ); } }; - self.critical = function() { - if( log.verboseGet() >= log.verboseReversed().critical ) { + self.critical = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["critical"] ) { self.log( log.getLogLinePrefixCritical() + - log.fmtCritical( ...arguments ) ); + log.fmtCritical( ...args ) ); } }; - self.error = function() { - if( log.verboseGet() >= log.verboseReversed().error ) { + self.error = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["error"] ) { self.log( log.getLogLinePrefixError() + - log.fmtError( ...arguments ) ); + log.fmtError( ...args ) ); } }; - self.warning = function() { - if( log.verboseGet() >= log.verboseReversed().warning ) { + self.warning = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["warning"] ) { self.log( log.getLogLinePrefixWarning() + - log.fmtWarning( ...arguments ) ); + log.fmtWarning( ...args ) ); } }; - self.attention = function() { - if( log.verboseGet() >= log.verboseReversed().attention ) { + self.attention = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["attention"] ) { self.log( log.getLogLinePrefixAttention() + - log.fmtAttention( ...arguments ) ); + log.fmtAttention( ...args ) ); } }; - self.information = function() { - if( log.verboseGet() >= log.verboseReversed().information ) { + self.information = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["information"] ) { self.log( log.getLogLinePrefixInformation() + - log.fmtInformation( ...arguments ) ); + log.fmtInformation( ...args ) ); } }; - self.info = function() { - if( log.verboseGet() >= log.verboseReversed().information ) { + self.info = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["information"] ) { self.log( log.getLogLinePrefixInformation() + - log.fmtInformation( ...arguments ) ); + log.fmtInformation( ...args ) ); } }; - self.notice = function() { - if( log.verboseGet() >= log.verboseReversed().notice ) { + self.notice = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["notice"] ) { self.log( log.getLogLinePrefixNotice() + - log.fmtNotice( ...arguments ) ); + log.fmtNotice( ...args ) ); } }; - self.note = function() { - if( log.verboseGet() >= log.verboseReversed().notice ) { + self.note = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["notice"] ) { self.log( log.getLogLinePrefixNote() + - log.fmtNote( ...arguments ) ); + log.fmtNote( ...args ) ); } }; - self.debug = function() { - if( log.verboseGet() >= log.verboseReversed().debug ) { + self.debug = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["debug"] ) { self.log( log.getLogLinePrefixDebug() + - log.fmtDebug( ...arguments ) ); + log.fmtDebug( ...args ) ); } }; - self.trace = function() { - if( log.verboseGet() >= log.verboseReversed().trace ) { + self.trace = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["trace"] ) { self.log( log.getLogLinePrefixTrace() + - log.fmtTrace( ...arguments ) ); + log.fmtTrace( ...args ) ); } }; - self.success = function() { - if( log.verboseGet() >= log.verboseReversed().information ) { + self.success = function( ...args: any[] ) { + if( log.verboseGet() >= log.verboseReversed()["information"] ) { self.log( log.getLogLinePrefixSuccess() + - log.fmtSuccess( ...arguments ) ); + log.fmtSuccess( ...args ) ); } }; } @@ -297,7 +301,7 @@ class ObserverServer extends SocketServer { const acceptor = new networkLayer.InWorkerSocketServerAcceptor( workerData.url, doSendMessage ); const server = new ObserverServer( acceptor ); server.on( "dispose", function() { - const self = server; + const self:any = server; self.debug( "Disposed in-worker in {} IMA loop {}", threadInfo.threadDescription(), workerData.url ); } ); diff --git a/src/main.ts b/src/main.ts index 03f9bb2c..ff5580ac 100644 --- a/src/main.ts +++ b/src/main.ts @@ -41,13 +41,13 @@ import * as skaleObserver from "./observer"; import * as state from "./state"; // allow self-signed wss and https -process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; +process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; -process.on( "unhandledRejection", function( reason, p ) { +process.on( "unhandledRejection", function( reason: any, p: any ) { log.fatal( "CRITICAL ERROR: unhandled rejection with reason {} and promise {}", reason, p ); -} ).on( "uncaughtException", function( err ) { +} ).on( "uncaughtException", function( err: any ) { log.fatal( "CRITICAL ERROR: uncaught exception: {err}, stack is:\n{stack}", err, err.stack ); @@ -137,9 +137,9 @@ function parseCommandLine() { } } -let gServerMonitoringWS = null; +let gServerMonitoringWS: any = null; -function initMonitoringServer() { +function initMonitoringServer() : void { const imaState = state.get(); if( imaState.nMonitoringPort <= 0 ) return; @@ -149,7 +149,7 @@ function initMonitoringServer() { strLogPrefix, imaState.nMonitoringPort ); } gServerMonitoringWS = new ws.WebSocketServer( { port: 0 + imaState.nMonitoringPort } ); - gServerMonitoringWS.on( "connection", function( wsPeer, req ) { + gServerMonitoringWS.on( "connection", function( wsPeer: any, req: any ) { let ip = req.socket.remoteAddress; if( "headers" in req && req.headers && typeof req.headers == "object" && "x-forwarded-for" in req.headers && req.headers["x-forwarded-for"] ) @@ -161,13 +161,13 @@ function initMonitoringServer() { if( imaState.bLogMonitoringServer ) log.debug( "{p}New connection from {}", strLogPrefix, ip ); wsPeer.on( "message", function( message ) { - const joAnswer = { + const joAnswer: any = { "method": null, "id": null, "error": null }; try { - const joMessage = JSON.parse( message ); + const joMessage: any = JSON.parse( message ); if( imaState.bLogMonitoringServer ) log.trace( "{p}<<< message from {}: {}", strLogPrefix, ip, joMessage ); @@ -251,9 +251,9 @@ function initMonitoringServer() { } ); } -let gExpressJsonRpcAppIMA = null; +let gExpressJsonRpcAppIMA: any = null; -function initJsonRpcServer() { +function initJsonRpcServer() : void { const imaState = state.get(); if( imaState.nJsonRpcPort <= 0 ) return; @@ -275,13 +275,13 @@ function initJsonRpcServer() { strLogPrefix, joAnswer, ip, err, err.stack ); } }; - let joAnswer = { + let joAnswer: any = { "method": null, "id": null, "error": null }; try { - const joMessage = JSON.parse( message ); + const joMessage: any = JSON.parse( message ); log.trace( "{p}<<< Peer message from {}: ", strLogPrefix, ip, joMessage ); if( ! ( "method" in joMessage ) ) throw new Error( "\"method\" field was not specified" ); @@ -379,7 +379,8 @@ async function doTheJob() { } function handleFirstSChainDiscoveryAttemptDone( - err, joSChainNetworkInfo, isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ) { + err: any, joSChainNetworkInfo: any, + isSilentReDiscovery: boolean, fnOnPeriodicDiscoveryResultAvailable: any ) : void { if( err ) { // error information is printed by discoveryTools.discoverSChainNetwork() process.exit( 166 ); diff --git a/src/observer.ts b/src/observer.ts index cede7401..9a3896d0 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -28,7 +28,7 @@ import * as imaUtils from "./utils"; import * as log from "./log"; import * as threadInfo from "./threadInfo"; -export function findSChainIndexInArrayByName( arrSChains, strSChainName ) { +export function findSChainIndexInArrayByName( arrSChains: any[], strSChainName: string ) { for( let idxSChain = 0; idxSChain < arrSChains.length; ++ idxSChain ) { const joSChain = arrSChains[idxSChain]; if( joSChain.name.toString() == strSChainName.toString() ) @@ -37,9 +37,9 @@ export function findSChainIndexInArrayByName( arrSChains, strSChainName ) { return -1; } -let gConnectedChainsData = null; +let gConnectedChainsData: any = null; -export function autoUpdateLastCachedSChains() { +export function autoUpdateLastCachedSChains() : boolean { const imaState = state.get(); if( ! imaState.optsS2S.strNetworkBrowserPath ) return false; @@ -52,7 +52,6 @@ export function autoUpdateLastCachedSChains() { } if( gConnectedChainsData && gConnectedChainsData.updatedAt == jo.updatedAt ) return false; // assume data is same - gConnectedChainsData = jo; log.debug( "Connected S-chains cache in thread {} was updated from file {} with data: {}", @@ -61,26 +60,26 @@ export function autoUpdateLastCachedSChains() { return true; } -export function getLastCachedSChains() { +export function getLastCachedSChains() : any[] { autoUpdateLastCachedSChains(); if( ! gConnectedChainsData ) return []; return JSON.parse( JSON.stringify( gConnectedChainsData.schains ) ); } -export function pickRandomSChainNodeIndex( joSChain ) { +export function pickRandomSChainNodeIndex( joSChain: any ) : number { let min = 0, max = joSChain.nodes.length - 1; min = Math.ceil( min ); max = Math.floor( max ); const idxNode = Math.floor( Math.random() * ( max - min + 1 ) ) + min; return idxNode; } -export function pickRandomSChainNode( joSChain ) { +export function pickRandomSChainNode( joSChain: any ) : any { const idxNode = pickRandomSChainNodeIndex( joSChain ); return joSChain.nodes[idxNode]; } -export function pickRandomSChainUrl( joSChain ) { +export function pickRandomSChainUrl( joSChain: any ) : string { const joNode = pickRandomSChainNode( joSChain ); return "" + joNode.endpoints.ip.http; } diff --git a/src/oracle.ts b/src/oracle.ts index db603973..a867d78d 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -26,26 +26,27 @@ import * as log from "./log"; import * as rpcCall from "./rpcCall"; import * as threadInfo from "./threadInfo"; +import * as owaspUtils from "./owaspUtils"; import numberToBN from "number-to-bn"; import * as sha3Module from "sha3"; -const Keccak = sha3Module.Keccak; -export const gConstMinPowResultLimit = 10000; -export const gConstMaxPowResultLimit = 100000; +const Keccak: any = sha3Module.Keccak; +export const gConstMinPowResultLimit: number = 10000; +export const gConstMaxPowResultLimit: any = 100000; -const gBigNumMinPowResult = numberToBN( gConstMinPowResultLimit ); -const gBigNum1 = numberToBN( 1 ); -const gBigNum2 = numberToBN( 2 ); -const gBigNum256 = numberToBN( 256 ); -const gBigNumUpperPart = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); +const gBigNumMinPowResult: any = numberToBN( gConstMinPowResultLimit ); +const gBigNum1: any = numberToBN( 1 ); +const gBigNum2: any = numberToBN( 2 ); +const gBigNum256: any = numberToBN( 256 ); +const gBigNumUpperPart: any = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); -function getUtcTimestampString( d ) { +function getUtcTimestampString( d?: Date ) : string { d = d || new Date(); // use now time if d is not specified const nUtcUnixTimeStampWithMilliseconds = d.getTime(); const t = "" + nUtcUnixTimeStampWithMilliseconds; return t; } -export function findPowNumber( strRequestPart, details, isVerbose ) { +export function findPowNumber( strRequestPart: string, details: any, isVerbose?: boolean ) { details = details || log; if( isVerbose ) details.debug( "source part of request to find PoW number is {}", strRequestPart ); @@ -55,7 +56,7 @@ export function findPowNumber( strRequestPart, details, isVerbose ) { if( isVerbose ) details.debug( "source t={}, this is UTC timestamp", t ); for( ; i < gConstMaxPowResultLimit; ++ i ) { - n = "" + i; + n = 0 + i; s = "{" + strRequestPart + ",\"time\":" + t + ",\"pow\":" + n + "}"; const hash = new Keccak( 256 ); @@ -81,7 +82,8 @@ export function findPowNumber( strRequestPart, details, isVerbose ) { } async function handleOracleCheckResultResult( - oracleOpts, details, isVerboseTraceDetails, joCall, joIn, joOut + oracleOpts: any, details: any, isVerboseTraceDetails: boolean, + joCall: any, joIn: any, joOut: any ) { if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_checkResult) result is: {}", joOut ); @@ -92,11 +94,11 @@ async function handleOracleCheckResultResult( await joCall.disconnect(); return; } - const joResult = JSON.parse( joOut.result ); + const joResult: any = JSON.parse( joOut.result ); if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_checkResult) parsed result field is: {}", joResult ); const gp = numberToBN( joResult.rslts[0] ); - if( isVerbose ) { + if( isVerboseTraceDetails ) { details.success( "success, computed Gas Price={}={}", gp.toString(), owaspUtils.ensureStartsWith0x( gp.toString( 16 ) ) ); } @@ -105,7 +107,8 @@ async function handleOracleCheckResultResult( } async function handleOracleSubmitRequestResult( - oracleOpts, details, isVerboseTraceDetails, joCall, joIn, joOut + oracleOpts: any, details: any, isVerboseTraceDetails: boolean, + joCall: any, joIn: any, joOut: any ) { const nMillisecondsSleepBefore = "nMillisecondsSleepBefore" in oracleOpts ? oracleOpts.nMillisecondsSleepBefore : 1000; @@ -130,14 +133,14 @@ async function handleOracleSubmitRequestResult( if( nMillisecondsToSleep > 0 ) await threadInfo.sleep( nMillisecondsToSleep ); try { - const joIn = { "method": "oracle_checkResult", "params": [ joOut.result ] }; + const joIn: any = { "method": "oracle_checkResult", "params": [ joOut.result ] }; if( isVerboseTraceDetails ) { details.debug( "RPC call oracle_checkResult attempt {} " + "of {}...", idxAttempt, cntAttempts ); details.debug( "RPC call(oracle_checkResult) is {}", joIn ); } gp = null; - const joOut = await joCall.call( joIn ); + joOut= await joCall.call( joIn ); gp = await handleOracleCheckResultResult( oracleOpts, details, isVerboseTraceDetails, joCall, joIn, joOut ); if( gp ) @@ -155,15 +158,15 @@ async function handleOracleSubmitRequestResult( throw new Error( "RPC call(oracle_checkResult) all attempts timed out" ); } -export async function oracleGetGasPrice( oracleOpts, details ) { +export async function oracleGetGasPrice( oracleOpts: any, details: any ) { details = details || log; - let gp = null, joCall = null; + const url: string = oracleOpts.url; + let gp: any = null, joCall: any = null; try { - const url = oracleOpts.url; const isVerbose = "isVerbose" in oracleOpts ? oracleOpts.isVerbose : false; let isVerboseTraceDetails = "isVerboseTraceDetails" in oracleOpts ? oracleOpts.isVerboseTraceDetails : false; - if( ! ( log.verboseGet() >= log.verboseReversed().trace ) ) + if( ! ( log.verboseGet() >= log.verboseReversed()["trace"] ) ) isVerboseTraceDetails = false; const callOpts = "callOpts" in oracleOpts ? oracleOpts.callOpts : { }; joCall = await rpcCall.create( url, callOpts || { } ); @@ -174,10 +177,10 @@ export async function oracleGetGasPrice( oracleOpts, details ) { "\"post\":\"{\\\"jsonrpc\\\":\\\"2.0\\\"," + "\\\"method\\\":\\\"eth_gasPrice\\\",\\\"params\\\":[],\\\"id\\\":1}\"", details, isVerbose ); - const joIn = { "method": "oracle_submitRequest", "params": [ s ] }; + const joIn: any = { "method": "oracle_submitRequest", "params": [ s ] }; if( isVerboseTraceDetails ) details.debug( "RPC call {} is {}", "oracle_submitRequest", joIn ); - const joOut = await joCall.call( joIn ); + const joOut: any = await joCall.call( joIn ); gp = await handleOracleSubmitRequestResult( oracleOpts, details, isVerboseTraceDetails, joCall, joIn, joOut ); await joCall.disconnect(); diff --git a/src/pwa.ts b/src/pwa.ts index 858f168c..19376ff7 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -28,7 +28,7 @@ import * as rpcCall from "./rpcCall"; import * as imaBLS from "./bls"; import * as imaUtils from "./utils"; -function computeWalkNodeIndices( nNodeNumber, nNodesCount ) { +function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ) : number[] { if( nNodesCount <= 1 ) return []; // PWA is N/A if( !( nNodeNumber >= 0 && nNodeNumber < nNodesCount ) ) @@ -36,7 +36,7 @@ function computeWalkNodeIndices( nNodeNumber, nNodesCount ) { let i = nNodeNumber - 1; if( i < 0 ) i = nNodesCount - 1; - const arrWalkNodeIndices = []; + const arrWalkNodeIndices: number[] = []; for( ; true; ) { if( i == nNodeNumber ) break; @@ -48,7 +48,7 @@ function computeWalkNodeIndices( nNodeNumber, nNodesCount ) { return arrWalkNodeIndices; } -export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) { +export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType: string ) : boolean { if( ! strLoopWorkType ) return false; switch ( strLoopWorkType.toString().toLowerCase() ) { @@ -61,7 +61,7 @@ export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) { return false; } -function composeEmptyStateForPendingWorkAnalysis() { +function composeEmptyStateForPendingWorkAnalysis() : any { return { "oracle": { "isInProgress": false, "ts": 0 }, "m2s": { "isInProgress": false, "ts": 0 }, @@ -70,7 +70,7 @@ function composeEmptyStateForPendingWorkAnalysis() { }; } -function getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ) { +function getNodeProgressAndTimestamp( joNode: any, strLoopWorkType: string, nIndexS2S: number ) { if( ! ( "pwaState" in joNode ) ) joNode.pwaState = composeEmptyStateForPendingWorkAnalysis(); strLoopWorkType = strLoopWorkType.toLowerCase(); @@ -86,7 +86,8 @@ function getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ) { return joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S]; } -export async function checkOnLoopStart( imaState, strLoopWorkType, nIndexS2S ) { +export async function checkOnLoopStart( + imaState: any, strLoopWorkType: string, nIndexS2S: number ) { try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) @@ -102,8 +103,8 @@ export async function checkOnLoopStart( imaState, strLoopWorkType, nIndexS2S ) { const jarrNodes = imaState.joSChainNetworkInfo.network; if( ! jarrNodes ) throw new Error( "S-Chain network info is not available yet to PWA" ); - const arrBusyNodeIndices = []; - const arrWalkNodeIndices = + const arrBusyNodeIndices: number[] = []; + const arrWalkNodeIndices: number[] = computeWalkNodeIndices( imaState.nNodeNumber, imaState.nNodesCount ); if( imaState.isPrintPWA ) { log.debug( "PWA will check loop start condition via node(s) sequence {}...", @@ -112,8 +113,8 @@ export async function checkOnLoopStart( imaState, strLoopWorkType, nIndexS2S ) { const nUtcUnixTimeStamp = Math.floor( ( new Date() ).getTime() / 1000 ); for( let i = 0; i < arrWalkNodeIndices.length; ++i ) { const walk_node_index = arrWalkNodeIndices[i]; - const joNode = jarrNodes[walk_node_index]; - const joProps = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); + const joNode: any = jarrNodes[walk_node_index]; + const joProps: any = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); if( joProps && typeof joProps == "object" && "isInProgress" in joProps && joProps.isInProgress && joProps.ts != 0 && nUtcUnixTimeStamp >= joProps.ts @@ -152,11 +153,12 @@ export async function checkOnLoopStart( imaState, strLoopWorkType, nIndexS2S ) { } export async function handleLoopStateArrived( - imaState, nNodeNumber, strLoopWorkType, nIndexS2S, isStart, ts, signature + imaState: any, nNodeNumber: number, strLoopWorkType: string, nIndexS2S: number, + isStart: boolean, ts: any, signature: any ) { const se = isStart ? "start" : "end"; let isSuccess = false; - let joNode = null; + let joNode: any = null; try { if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type` ); @@ -172,7 +174,7 @@ export async function handleLoopStateArrived( if( ! jarrNodes ) throw new Error( "S-Chain network info is not available yet to PWA" ); joNode = jarrNodes[nNodeNumber]; - const joProps = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); + const joProps: any = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); if( imaState.isPrintPWA ) { log.trace( "PWA loop-{} state arrived for node {}, PWA state {}, arrived " + "signature is {}", se, nNodeNumber, joNode.pwaState, signature ); @@ -202,7 +204,8 @@ export async function handleLoopStateArrived( return isSuccess; } -async function notifyOnLoopImpl( imaState, strLoopWorkType, nIndexS2S, isStart ) { +async function notifyOnLoopImpl( + imaState: any, strLoopWorkType: string, nIndexS2S: number, isStart: boolean ) { const se = isStart ? "start" : "end"; try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined @@ -233,10 +236,10 @@ async function notifyOnLoopImpl( imaState, strLoopWorkType, nIndexS2S, isStart ) const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; if( isThisNode ) continue; // skip this node - const joNode = jarrNodes[i]; + const joNode: any = jarrNodes[i]; const strNodeURL = imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ); const rpcCallOpts = null; - let joCall = await rpcCall.create( strNodeURL, rpcCallOpts ) + let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) .catch( async function( err ) { log.error( "PWA failed to perform] loop-{} notification RPC call to node #{} with " + @@ -247,7 +250,7 @@ async function notifyOnLoopImpl( imaState, strLoopWorkType, nIndexS2S, isStart ) } ); if( ! joCall ) return false; - const joIn = { + const joIn: any = { "method": "skale_imaNotifyLoopWork", "params": { "nNodeNumber": 0 + imaState.nNodeNumber, diff --git a/src/rpcCall.ts b/src/rpcCall.ts index bec5a656..ec60ff11 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -32,7 +32,7 @@ import * as log from "./log"; const gSecondsConnectionTimeout = 60; -export async function waitWebSocketIsOpen( socket, fnDone, fnStep ) { +export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any ) { fnDone = fnDone || async function( nStep ) {}; fnDone = fnStep || async function( nStep ) { return true; }; let nStep = 0; @@ -47,7 +47,7 @@ export async function waitWebSocketIsOpen( socket, fnDone, fnStep ) { // Notice, connection is made if we are here clearInterval( iv ); await fnDone( nStep ); - resolve(); + resolve( true ); } else { if( ! await fnStep( nStep ) ) { clearInterval( iv ); @@ -66,14 +66,14 @@ export async function waitWebSocketIsOpen( socket, fnDone, fnStep ) { await promiseComplete; } -export async function doConnect( joCall, opts, fn ) { +export async function doConnect( joCall: any, opts: any, fn?: any ) { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + `to invalid URL: ${joCall.url}` ); } if( isUrlWS( joCall.url ) ) { - let strWsError = null; + let strWsError: string = ""; joCall.wsConn = new ws.WebSocket( joCall.url ); joCall.wsConn.on( "open", async function() { if( fn ) @@ -151,7 +151,7 @@ export async function doConnect( joCall, opts, fn ) { return joCall; } -export async function doConnectIfNeeded( joCall, opts, fn ) { +export async function doConnectIfNeeded( joCall: any, opts: any, fn: any ) { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -170,7 +170,7 @@ export async function doConnectIfNeeded( joCall, opts, fn ) { return joCall; } -async function doReconnectWsStep( joCall, opts, fn ) { +async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { if( ! joCall.isAutoReconnect ) return; if( joCall.isDisconnectMode ) @@ -185,7 +185,7 @@ async function doReconnectWsStep( joCall, opts, fn ) { } ); } -async function doDisconnect( joCall, fn ) { +async function doDisconnect( joCall: any, fn: any ) { try { joCall.isDisconnectMode = true; const wsConn = joCall.wsConn ? joCall.wsConn : null; @@ -204,10 +204,10 @@ async function doDisconnect( joCall, fn ) { } } -export async function doCall( joCall, joIn, fn ) { +export async function doCall( joCall: any, joIn: any, fn: any ) { joIn = enrichTopLevelFieldsInJSON( joIn ); if( joCall.wsConn ) { - const entry = { + const entry: any = { joIn: joIn, fn: fn, out: null @@ -228,7 +228,7 @@ export async function doCall( joCall, joIn, fn ) { return; } const strBody = JSON.stringify( joIn ); - let errCall = null, joOut = null; + let errCall: string|null = null, joOut: any = null; if( joCall.joRpcOptions && joCall.joRpcOptions.cert && typeof joCall.joRpcOptions.cert == "string" && joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" @@ -255,7 +255,7 @@ export async function doCall( joCall, joIn, fn ) { let accumulatedBody = ""; const promiseComplete = new Promise( ( resolve, reject ) => { try { - const req = https.request( options, res => { + const req = https.request( options, ( res: any ) => { res.setEncoding( "utf8" ); res.on( "data", body => { accumulatedBody += body; @@ -341,7 +341,7 @@ export async function doCall( joCall, joIn, fn ) { } } -export async function rpcCallCreate( strURL, opts ) { +export async function rpcCallCreate( strURL: string, opts: any ) { if( !validateURL( strURL ) ) throw new Error( `JSON RPC CALLER cannot create a call object invalid URL: ${strURL}` ); if( !( strURL && typeof strURL == "string" && strURL.length > 0 ) ) { @@ -400,7 +400,7 @@ export async function rpcCallCreate( strURL, opts ) { export { rpcCallCreate as create }; -export function generateRandomIntegerInRange( min, max ) { +export function generateRandomIntegerInRange( min: any, max: any ) { min = Math.ceil( min ); max = Math.floor( max ); return Math.floor( Math.random() * ( max - min + 1 ) ) + min; @@ -410,7 +410,7 @@ export function generateRandomRpcCallId() { return generateRandomIntegerInRange( 1, Number.MAX_SAFE_INTEGER ); } -export function enrichTopLevelFieldsInJSON( jo ) { +export function enrichTopLevelFieldsInJSON( jo: any ) { if( ( !( "jsonrpc" in jo ) ) || ( typeof jo.jsonrpc !== "string" ) || jo.jsonrpc.length === 0 @@ -421,7 +421,7 @@ export function enrichTopLevelFieldsInJSON( jo ) { return jo; } -export function isValidUrl( s ) { +export function isValidUrl( s: any ) { if( ! s ) return false; try { @@ -433,7 +433,7 @@ export function isValidUrl( s ) { return false; } -export function getValidUrl( s ) { +export function getValidUrl( s: any ) { if( ! s ) return null; try { @@ -443,7 +443,7 @@ export function getValidUrl( s ) { return null; } -export function getDefaultPort( strProtocol ) { +export function getDefaultPort( strProtocol: any ) { if( ! strProtocol ) return 80; switch ( strProtocol.toString().toLowerCase() ) { @@ -457,7 +457,7 @@ export function getDefaultPort( strProtocol ) { return 80; } -export function getValidHostAndPort( s ) { +export function getValidHostAndPort( s: any ) { const u = getValidUrl( s ); if( ! u ) return null; @@ -468,9 +468,10 @@ export function getValidHostAndPort( s ) { return jo; } -const gStrTcpConnectionHeader = "TCP connection checker: "; +const gStrTcpConnectionHeader: string = "TCP connection checker: "; -export function checkTcpPromise( strHost, nPort, nTimeoutMilliseconds, isLog ) { +export function checkTcpPromise( strHost: string, nPort: number, nTimeoutMilliseconds: number, + isLog?: boolean ) { return new Promise( ( resolve, reject ) => { if( isLog ) { console.log( @@ -484,7 +485,7 @@ export function checkTcpPromise( strHost, nPort, nTimeoutMilliseconds, isLog ) { `TCP connection to ${strHost}:${nPort} established` ); } conn.end(); - resolve(); + resolve( true ); } ); if( isLog ) { console.log( @@ -533,7 +534,8 @@ export function checkTcpPromise( strHost, nPort, nTimeoutMilliseconds, isLog ) { } ); } -export async function checkTcp( strHost, nPort, nTimeoutMilliseconds, isLog ) { +export async function checkTcp( strHost: string, nPort: number, nTimeoutMilliseconds: number, + isLog?: boolean ) { let isOnline = false; try { const promiseCompleteTcpCheck = checkTcpPromise( @@ -561,7 +563,7 @@ export async function checkTcp( strHost, nPort, nTimeoutMilliseconds, isLog ) { return isOnline; } -export async function checkUrl( u, nTimeoutMilliseconds, isLog ) { +export async function checkUrl( u: string, nTimeoutMilliseconds: number, isLog?: boolean ) { if( ! u ) return false; const jo: any = getValidHostAndPort( u ); From 15c40d25927a5999834e8421c946532cbf525c29 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Mon, 11 Dec 2023 15:50:04 +0000 Subject: [PATCH 04/53] code porting to TypeScript --- src/bls.ts | 357 ++++++++++--------- src/cc.ts | 6 +- src/cli.ts | 23 +- src/clpTools.ts | 55 +-- src/discoveryTools.ts | 66 ++-- src/eventDispatcher.ts | 18 +- src/imaCore.ts | 44 +-- src/imaEthOperations.ts | 72 ++-- src/imaEventLogScan.ts | 49 +-- src/imaGasUsageOperations.ts | 9 +- src/imaHelperAPIs.ts | 2 +- src/imaOracleOperations.ts | 47 +-- src/imaRegistrationOperations.ts | 74 ++-- src/imaReimbursementOperations.ts | 92 ++--- src/imaSgxExternalSigner.ts | 14 +- src/imaTokenOperations.ts | 563 +++++++++++++++--------------- src/imaTransferErrorHandling.ts | 26 +- src/imaTx.ts | 134 +++---- src/log.ts | 10 +- src/loop.ts | 55 +-- src/loopWorker.ts | 16 +- src/main.ts | 2 +- src/observer.ts | 2 +- src/oracle.ts | 2 +- src/owaspUtils.ts | 6 +- src/pwa.ts | 16 +- src/rpcCall.ts | 10 +- src/socket.ts | 32 +- src/socketServer.ts | 3 +- src/socketSettings.ts | 2 +- src/socketUtils.ts | 6 +- src/state.ts | 2 +- src/threadInfo.ts | 2 +- src/utils.ts | 6 +- 34 files changed, 920 insertions(+), 903 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index d8fc16d4..d0f7e186 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -7,7 +7,7 @@ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file bls.mjs + * @file bls.ts * @copyright SKALE Labs 2019-Present */ @@ -42,7 +42,7 @@ const shell = shellModule.default; const Keccak = sha3Module.Keccak; -function discoverBlsThreshold( joSChainNetworkInfo ) { +function discoverBlsThreshold( joSChainNetworkInfo: any ) : number { const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) @@ -56,7 +56,7 @@ function discoverBlsThreshold( joSChainNetworkInfo ) { return -1; } -function discoverBlsParticipants( joSChainNetworkInfo ) { +function discoverBlsParticipants( joSChainNetworkInfo: any ) : number { const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) @@ -71,7 +71,8 @@ function discoverBlsParticipants( joSChainNetworkInfo ) { } function checkBlsThresholdAndBlsParticipants( - nThreshold, nParticipants, strOperation, details ) { + nThreshold: number, nParticipants: number, strOperation: string, details: any + ) : boolean { details = details || log; if( nThreshold <= 0 ) { details.fatal( "Operation {} will fail because discovered BLS threshold {}" + @@ -91,7 +92,9 @@ function checkBlsThresholdAndBlsParticipants( return true; } -function discoverPublicKeyByIndex( nNodeIndex, joSChainNetworkInfo, details, isThrowException ) { +function discoverPublicKeyByIndex( + nNodeIndex: number, joSChainNetworkInfo: any, details: any, isThrowException: boolean + ) : any { details = details || log; const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; @@ -114,7 +117,8 @@ function discoverPublicKeyByIndex( nNodeIndex, joSChainNetworkInfo, details, isT return null; } -function discoverCommonPublicKey( joSChainNetworkInfo, isThrowException ) { +function discoverCommonPublicKey( + details: any, joSChainNetworkInfo: any, isThrowException: boolean ) : any { const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; const jarrNodes = joSChainNetworkInfo.network; @@ -136,7 +140,9 @@ function discoverCommonPublicKey( joSChainNetworkInfo, isThrowException ) { return null; } -function hexPrepare( strHex, isInvertBefore, isInvertAfter ) { +function hexPrepare( + strHex: string, isInvertBefore: boolean, isInvertAfter: boolean + ) : Uint8Array { if( isInvertBefore == undefined ) isInvertBefore = true; if( isInvertAfter == undefined ) @@ -150,27 +156,27 @@ function hexPrepare( strHex, isInvertBefore, isInvertAfter ) { return arrBytes; } -function stringToKeccak256( s ) { +function stringToKeccak256( s: string ) : Uint8Array { const strU256 = owaspUtils.ethersMod.ethers.utils.id( s ); return hexPrepare( strU256, true, true ); } -function arrayToKeccak256( arrBytes ) { +function arrayToKeccak256( arrBytes: Uint8Array ) : Uint8Array { const k = new Keccak( 256 ); k.update( imaUtils.toBuffer( arrBytes ) ); const h = k.digest( "hex" ); return imaUtils.hexToBytes( "0x" + h ); } -function keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) { +function keccak256Message( + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string + ) : string { let arrBytes = stringToKeccak256( strFromChainName ); arrBytes = imaUtils.bytesConcat( arrBytes, hexPrepare( owaspUtils.ensureStartsWith0x( nIdxCurrentMsgBlockStart.toString( 16 ) ), - false, - false - ) + false, false ) ); arrBytes = arrayToKeccak256( arrBytes ); const cnt = jarrMessages.length; @@ -194,7 +200,7 @@ function keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainN return owaspUtils.ensureStartsWith0x( imaUtils.bytesToHex( arrBytes, false ) ); } -export function keccak256U256( u256, isHash ) { +export function keccak256U256( u256: any, isHash: boolean ) : string { let arrBytes = new Uint8Array(); let bytesU256 = imaUtils.hexToBytes( u256 ); @@ -213,7 +219,9 @@ export function keccak256U256( u256, isHash ) { return strMessageHash; } -export function keccak256ForPendingWorkAnalysis( nNodeNumber, strLoopWorkType, isStart, ts ) { +export function keccak256ForPendingWorkAnalysis( + nNodeNumber: number, strLoopWorkType: string, isStart: boolean, ts: any + ) : string { let arrBytes = new Uint8Array(); let bytesU256 = imaUtils.hexToBytes( nNodeNumber ); @@ -242,33 +250,33 @@ export function keccak256ForPendingWorkAnalysis( nNodeNumber, strLoopWorkType, i return strMessageHash; } -function splitSignatureShare( signatureShare ) { +function splitSignatureShare( signatureShare: any ) : any { const jarr = signatureShare.split( ":" ); if( jarr.length < 2 ) throw new Error( `Failed to split signatureShare=${signatureShare.toString()}` ); return { X: jarr[0], Y: jarr[1] }; } -function getBlsGlueTmpDir() { +function getBlsGlueTmpDir() : string { const strTmpDir = "/tmp/ima-bls-glue"; shell.mkdir( "-p", strTmpDir ); return strTmpDir; } -function allocBlsTmpActionDir() { - const strActionDir = - getBlsGlueTmpDir() + "/" + imaUtils.replaceAll( imaUtils.uuid(), "-", "" ); +function allocBlsTmpActionDir() : string { + const strActionDir = getBlsGlueTmpDir() + "/" + imaUtils.replaceAll( imaUtils.uuid(), "-", "" ); if( ! fs.existsSync( strActionDir ) ) fs.mkdirSync( strActionDir , { recursive: true } ); return strActionDir; } function performBlsGlue( - details, strDirection, jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, arrSignResults -) { + details: any, strDirection: string, jarrMessages: any[], + nIdxCurrentMsgBlockStart: number, strFromChainName: string, arrSignResults: any[] + ) : any { const imaState = state.get(); const strLogPrefix = `${strDirection}/BLS/Glue: `; - let joGlueResult = null; + let joGlueResult: any = null; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); details.debug( "{p}Discovered BLS threshold is {}.", strLogPrefix, nThreshold ); @@ -306,11 +314,11 @@ function performBlsGlue( strInput + " --output " + strActionDir + "/glue-result.json"; details.trace( "{p}Will execute BLS glue command: {}", strLogPrefix, strGlueCommand ); - strOutput = childProcessModule.execSync( strGlueCommand, { cwd: strActionDir } ); + let strOutput = childProcessModule.execSync( strGlueCommand, { cwd: strActionDir } ); details.trace( "{p}BLS glue output is:\n{raw}", strLogPrefix, strOutput || "<>" ); joGlueResult = imaUtils.jsonFileLoad( path.join( strActionDir, "glue-result.json" ) ); details.trace( "{p}BLS glue result is: {}", strLogPrefix, joGlueResult ); - if( "X" in joGlueResult.signature && "Y" in joGlueResult.signature ) { + if( joGlueResult && "X" in joGlueResult.signature && "Y" in joGlueResult.signature ) { details.success( "{p}BLS glue success", strLogPrefix ); joGlueResult.hashSrc = strMessageHash; details.trace( "{p}Computing G1 hash point...", strLogPrefix ); @@ -354,10 +362,10 @@ function performBlsGlue( return joGlueResult; } -function performBlsGlueU256( details, u256, arrSignResults ) { +function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ) : any { const imaState = state.get(); const strLogPrefix = "BLS/Glue: "; - let joGlueResult = null; + let joGlueResult: any = null; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); details.debug( "{p}Discovered BLS threshold is {}.", strLogPrefix, nThreshold ); @@ -394,11 +402,12 @@ function performBlsGlueU256( details, u256, arrSignResults ) { strInput + " --output " + strActionDir + "/glue-result.json"; details.trace( "{p}Will execute BLS glue command: {}", strLogPrefix, strGlueCommand ); - strOutput = childProcessModule.execSync( strGlueCommand, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strGlueCommand, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}BLS glue output is:\n{raw}", strLogPrefix, strOutput || "<>" ); joGlueResult = imaUtils.jsonFileLoad( path.join( strActionDir, "glue-result.json" ) ); details.trace( "{p}BLS glue result is:\n{}", strLogPrefix, joGlueResult ); - if( "X" in joGlueResult.signature && "Y" in joGlueResult.signature ) { + if( joGlueResult && "X" in joGlueResult.signature && "Y" in joGlueResult.signature ) { details.success( "{p}BLS glue success", strLogPrefix ); joGlueResult.hashSrc = strMessageHash; details.trace( "{p}Computing G1 hash point...", strLogPrefix ); @@ -410,7 +419,8 @@ function performBlsGlueU256( details, u256, arrSignResults ) { " --t " + nThreshold + " --n " + nParticipants; details.trace( "{p}Will execute HashG1 command: {}", strLogPrefix, strHasG1Command ); - strOutput = childProcessModule.execSync( strHasG1Command, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strHasG1Command, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}HashG1 output is:\n{raw}", strLogPrefix, strOutput || "<>" ); const joResultHashG1 = imaUtils.jsonFileLoad( path.join( strActionDir, "g1.json" ) ); details.trace( "{p}HashG1 result is: {}", strLogPrefix, joResultHashG1 ); @@ -443,13 +453,11 @@ function performBlsGlueU256( details, u256, arrSignResults ) { } function performBlsVerifyI( - details, - strDirection, - nZeroBasedNodeIndex, - joResultFromNode, - jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joPublicKey -) { + details: any, strDirection: string, nZeroBasedNodeIndex: number, + joResultFromNode: any, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joPublicKey: any +) : boolean { if( !joResultFromNode ) return true; const imaState = state.get(); @@ -475,7 +483,7 @@ function performBlsVerifyI( keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.trace( "{p}BLS node #{} - hashed verify message is {}", strLogPrefix, nZeroBasedNodeIndex, strMessageHash ); - const joMsg = { "message": strMessageHash }; + const joMsg: any = { "message": strMessageHash }; details.debug( "{p}BLS node #{} - composed {} composed from {} using glue {} and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, jarrMessages, joResultFromNode, joPublicKey ); @@ -493,7 +501,8 @@ function performBlsVerifyI( ; details.trace( "{p}Will execute node #{} BLS verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); - strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -510,12 +519,8 @@ function performBlsVerifyI( } function performBlsVerifyIU256( - details, - nZeroBasedNodeIndex, - joResultFromNode, - u256, - joPublicKey -) { + details: any, nZeroBasedNodeIndex: number, joResultFromNode: any, u256: any, joPublicKey: any +) : boolean { if( ! joResultFromNode ) return true; const imaState = state.get(); @@ -531,7 +536,7 @@ function performBlsVerifyIU256( }; let strOutput = ""; try { - const joMsg = { "message": keccak256U256( u256, true ) }; + const joMsg: any = { "message": keccak256U256( u256, true ) }; details.debug( "{p}BLS u256 node #{} verify message {} composed from {} using glue {} " + "and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, u256, joResultFromNode, joPublicKey ); @@ -549,7 +554,8 @@ function performBlsVerifyIU256( ; details.trace( "{p}Will execute node #{} BLS u256 verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); - strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}BLS u256 node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS u256 node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -566,12 +572,10 @@ function performBlsVerifyIU256( } function performBlsVerify( - details, - strDirection, - joGlueResult, - jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joCommonPublicKey -) { + details: any, strDirection: string, joGlueResult: any, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joCommonPublicKey: any +) : boolean { if( !joGlueResult ) return true; const imaState = state.get(); @@ -597,14 +601,14 @@ function performBlsVerify( keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.trace( "{p}BLS/summary verify message - hashed verify message is {}", strLogPrefix, strMessageHash ); - const joMsg = { "message": strMessageHash }; + const joMsg: any = { "message": strMessageHash }; details.debug( "{p}BLS/summary verify message - composed JSON {} from messages array {}" + " using glue {} and common public key {}", strLogPrefix, joMsg, jarrMessages, joGlueResult, joCommonPublicKey ); imaUtils.jsonFileSave( strActionDir + "/glue-result.json", joGlueResult ); imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); - const joCommonPublicKeyToSave = { + const joCommonPublicKeyToSave: any = { commonBLSPublicKey0: joCommonPublicKey.commonBLSPublicKey0, commonBLSPublicKey1: joCommonPublicKey.commonBLSPublicKey1, commonBLSPublicKey2: joCommonPublicKey.commonBLSPublicKey2, @@ -621,7 +625,8 @@ function performBlsVerify( ; details.trace( "{p}Will execute BLS/summary verify command: {}", strLogPrefix, strVerifyCommand ); - strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}BLS/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); details.success( "{p}BLS/summary verify success", strLogPrefix ); @@ -636,7 +641,9 @@ function performBlsVerify( return false; } -function performBlsVerifyU256( details, joGlueResult, u256, joCommonPublicKey ) { +function performBlsVerifyU256( + details: any, joGlueResult: any, u256: any, joCommonPublicKey: any + ) : boolean { if( !joGlueResult ) return true; const imaState = state.get(); @@ -652,14 +659,14 @@ function performBlsVerifyU256( details, joGlueResult, u256, joCommonPublicKey ) let strOutput = ""; const strLogPrefix = "BLS u256/Summary: "; try { - const joMsg = { "message": keccak256U256( u256, true ) }; + const joMsg: any = { "message": keccak256U256( u256, true ) }; details.debug( "{p}BLS u256/summary verify message {} composed from {} using glue {}" + " and common public key {}", strLogPrefix, joMsg, u256, joGlueResult, joCommonPublicKey ); imaUtils.jsonFileSave( strActionDir + "/glue-result.json", joGlueResult ); imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); - const joCommonPublicKeyToSave = { + const joCommonPublicKeyToSave: any = { commonBLSPublicKey0: joCommonPublicKey.commonBLSPublicKey0, commonBLSPublicKey1: joCommonPublicKey.commonBLSPublicKey1, commonBLSPublicKey2: joCommonPublicKey.commonBLSPublicKey2, @@ -676,7 +683,8 @@ function performBlsVerifyU256( details, joGlueResult, u256, joCommonPublicKey ) ; details.trace( "{p}Will execute BLS u256/summary verify command: {}", strLogPrefix, strVerifyCommand ); - strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}BLS u256/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); details.success( "{p}BLS u256/summary verify success", strLogPrefix ); @@ -693,15 +701,11 @@ function performBlsVerifyU256( details, joGlueResult, u256, joCommonPublicKey ) } async function checkCorrectnessOfMessagesToSign( - details, - strLogPrefix, - strDirection, - jarrMessages, - nIdxCurrentMsgBlockStart, - joExtraSignOpts + details: any, strLogPrefix: string, strDirection: string, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, joExtraSignOpts: any ) { const imaState = state.get(); - let joMessageProxy = null, joAccount = null, joChainName = null; + let joMessageProxy: any = null, joAccount: any = null, joChainName: any = null; if( strDirection == "M2S" ) { joMessageProxy = imaState.joMessageProxyMainNet; joAccount = imaState.chainProperties.mn.joAccount; @@ -753,7 +757,7 @@ async function checkCorrectnessOfMessagesToSign( "source contract is {}, destination contract is {}, message data is {}", strLogPrefix, strDirection, i, cnt, idxMessage, joMessage.sender, joMessage.destinationContract, joMessage.data ); - const outgoingMessageData = { + const outgoingMessageData: any = { "dstChainHash": owaspUtils.ethersMod.ethers.utils.id( joChainName ), "msgCounter": 0 + idxMessage, "srcContract": joMessage.sender, @@ -789,7 +793,7 @@ async function checkCorrectnessOfMessagesToSign( } -async function prepareSignMessagesImpl( optsSignOperation ) { +async function prepareSignMessagesImpl( optsSignOperation: any ) { optsSignOperation.fn = optsSignOperation.fn || function() {}; optsSignOperation.sequenceId = owaspUtils.removeStarting0x( @@ -872,7 +876,7 @@ async function prepareSignMessagesImpl( optsSignOperation ) { return true; } -async function gatherSigningCheckFinish( optsSignOperation ) { +async function gatherSigningCheckFinish( optsSignOperation: any ) { const cntSuccess = optsSignOperation.arrSignResults.length; if( optsSignOperation.joGatheringTracker.nCountReceivedPrevious != optsSignOperation.joGatheringTracker.nCountReceived ) { @@ -890,7 +894,7 @@ async function gatherSigningCheckFinish( optsSignOperation ) { return false; optsSignOperation.strLogPrefixB = `${optsSignOperation.strDirection} /# ` + `${optsSignOperation.nTransferLoopCounter}/BLS/Summary: `; - let strError = null, strSuccessfulResultDescription = null; + let strError: string|null = null, strSuccessfulResultDescription: string|null = null; const joGlueResult = performBlsGlue( optsSignOperation.details, optsSignOperation.strDirection, optsSignOperation.jarrMessages, optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.strFromChainName, @@ -900,7 +904,7 @@ async function gatherSigningCheckFinish( optsSignOperation ) { optsSignOperation.strLogPrefixB, joGlueResult ); if( optsSignOperation.imaState.strPathBlsVerify.length > 0 ) { const joCommonPublicKey = discoverCommonPublicKey( - optsSignOperation.imaState.joSChainNetworkInfo, false ); + optsSignOperation.details, optsSignOperation.imaState.joSChainNetworkInfo, false ); if( ! joCommonPublicKey ) { strError = "No BLS common public key"; optsSignOperation.details.error( "{p}{err}", @@ -943,7 +947,7 @@ async function gatherSigningCheckFinish( optsSignOperation ) { return true; } -async function gatherSigningCheckOverflow( optsSignOperation ) { +async function gatherSigningCheckOverflow( optsSignOperation: any ) { if( optsSignOperation.joGatheringTracker.nCountReceived < optsSignOperation.jarrNodes.length ) return false; optsSignOperation.fn( @@ -963,7 +967,7 @@ async function gatherSigningCheckOverflow( optsSignOperation ) { return true; } -async function gatherSigningStartImpl( optsSignOperation ) { +async function gatherSigningStartImpl( optsSignOperation: any ) { optsSignOperation.details.debug( "{p}Waiting for BLS glue result...", optsSignOperation.strLogPrefix ); optsSignOperation.errGathering = null; @@ -993,7 +997,7 @@ async function gatherSigningStartImpl( optsSignOperation ) { optsSignOperation.bHaveResultReportCalled = true; } -async function gatherSigningFinishImpl( optsSignOperation ) { +async function gatherSigningFinishImpl( optsSignOperation: any ) { optsSignOperation.details.trace( "{p}Will await for message BLS verification and sending...", optsSignOperation.strLogPrefix ); if( optsSignOperation.errGathering ) { @@ -1030,6 +1034,7 @@ async function gatherSigningFinishImpl( optsSignOperation ) { `tracker data is: ${JSON.stringify( optsSignOperation.joGatheringTracker )}`, optsSignOperation.jarrMessages ).catch( function( err ) { + const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(6) in BLS sign result handler, not enough successful BLS signature " + "parts({}) and timeout reached, error details: {err}", cntSuccess, err ); @@ -1041,7 +1046,7 @@ async function gatherSigningFinishImpl( optsSignOperation ) { } } -async function doSignConfigureChainAccessParams( optsSignOperation ) { +async function doSignConfigureChainAccessParams( optsSignOperation: any ) { optsSignOperation.targetChainName = ""; optsSignOperation.fromChainName = ""; optsSignOperation.targetChainID = -4; @@ -1075,13 +1080,13 @@ async function doSignConfigureChainAccessParams( optsSignOperation ) { optsSignOperation.targetChainID = optsSignOperation.joExtraSignOpts.chainIdDst; optsSignOperation.fromChainID = optsSignOperation.joExtraSignOpts.chainIdSrc; } else { - await joCall.disconnect(); throw new Error( "CRITICAL ERROR: Failed doSignMessagesImpl() with " + `unknown direction ${optsSignOperation.strDirection}` ); } } -async function doSignProcessHandleCall( optsSignOperation, joParams, joCall, joIn, joOut, i ) { +async function doSignProcessHandleCall( + optsSignOperation: any, joParams: any, joCall: any, joIn: any, joOut: any, i: number ) { const imaState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignOperation.jarrNodes[i]; @@ -1133,7 +1138,7 @@ async function doSignProcessHandleCall( optsSignOperation, joParams, joCall, joI return; } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); - const joResultFromNode = { + const joResultFromNode: any = { index: "" + nZeroBasedNodeIndex, signature: { X: arrTmp[0], @@ -1189,7 +1194,7 @@ async function doSignProcessHandleCall( optsSignOperation, joParams, joCall, joI await joCall.disconnect(); } -async function doSignProcessOneImpl( i, optsSignOperation ) { +async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { const imaState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignOperation.jarrNodes[i]; @@ -1199,8 +1204,8 @@ async function doSignProcessOneImpl( i, optsSignOperation ) { const strNodeDescColorized = log.fmtDebug( "{url} ({}/{}, ID {}), sequence ID is {}", strNodeURL, i, optsSignOperation.jarrNodes.length, joNode.nodeID, optsSignOperation.sequenceId ); - const rpcCallOpts = null; - let joCall = await rpcCall.create( strNodeURL, rpcCallOpts ).catch( function( err ) { + const rpcCallOpts: any = null; + let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ).catch( function( err ) { ++optsSignOperation.joGatheringTracker.nCountReceived; ++optsSignOperation.joGatheringTracker.nCountErrors; optsSignOperation.details.error( @@ -1214,7 +1219,7 @@ async function doSignProcessOneImpl( i, optsSignOperation ) { if( ! joCall ) return; await doSignConfigureChainAccessParams( optsSignOperation ); - const joParams = { + const joParams: any = { "direction": "" + optsSignOperation.strDirection, "startMessageIdx": optsSignOperation.nIdxCurrentMsgBlockStart, "dstChainName": optsSignOperation.targetChainName, @@ -1234,17 +1239,17 @@ async function doSignProcessOneImpl( i, optsSignOperation ) { log.generateTimestampString( null, true ), "skale_imaVerifyAndSign", i, strNodeURL, optsSignOperation.fromChainName, optsSignOperation.targetChainName, joParams, optsSignOperation.sequenceId ); - const joIn = { "method": "skale_imaVerifyAndSign", "params": joParams }; + const joIn: any = { "method": "skale_imaVerifyAndSign", "params": joParams }; const joOut = await joCall.call( joIn ); await doSignProcessHandleCall( optsSignOperation, joParams, joCall, joIn, joOut, i ); } async function doSignMessagesImpl( - nTransferLoopCounter, strDirection, - jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn + nTransferLoopCounter: number, strDirection: string, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joExtraSignOpts: any, fn: any ) { - const optsSignOperation = { + const optsSignOperation: any = { imaState: state.get(), nTransferLoopCounter: nTransferLoopCounter, strDirection: strDirection, @@ -1285,7 +1290,7 @@ async function doSignMessagesImpl( }; optsSignOperation.details = optsSignOperation.imaState.isDynamicLogInBlsSigner - ? log : log.createMemoryStream( true ); + ? log : log.createMemoryStream(); optsSignOperation.strGatheredDetailsName = optsSignOperation.strDirection + "-" + "doSignMessagesImpl-#" + optsSignOperation.nTransferLoopCounter + "-" + optsSignOperation.strFromChainName + "-msg#" + @@ -1300,7 +1305,7 @@ async function doSignMessagesImpl( "{p}{} Stop invoking {bright} for transfer from chain {} at #{} because " + "successfully gathered count is reached ", optsSignOperation.strLogPrefix, log.generateTimestampString( null, true ), "skale_imaVerifyAndSign", - fromChainName, i, cntSuccess ); + strFromChainName, i, cntSuccess ); break; } doSignProcessOneImpl( i, optsSignOperation ); @@ -1339,51 +1344,36 @@ async function doSignMessagesImpl( } export async function doSignMessagesM2S( - nTransferLoopCounter, - jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, - fn -) { + nTransferLoopCounter: number, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joExtraSignOpts: any, fn: any ) { return await doSignMessagesImpl( - nTransferLoopCounter, - "M2S", + nTransferLoopCounter, "M2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, - fn - ); + joExtraSignOpts, fn ); } export async function doSignMessagesS2M( - nTransferLoopCounter, - jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, - fn -) { + nTransferLoopCounter: number, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joExtraSignOpts: any, fn: any ) { return await doSignMessagesImpl( - nTransferLoopCounter, - "S2M", + nTransferLoopCounter, "S2M", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, - fn - ); + joExtraSignOpts, fn ); } export async function doSignMessagesS2S( - nTransferLoopCounter, - jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, - fn -) { + nTransferLoopCounter: number, + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joExtraSignOpts: any, fn: any ) { return await doSignMessagesImpl( - nTransferLoopCounter, - "S2S", + nTransferLoopCounter, "S2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, - fn - ); + joExtraSignOpts, fn ); } -async function prepareSignU256( optsSignU256 ) { +async function prepareSignU256( optsSignU256: any ) { optsSignU256.details.debug( "{p}Will sign {} value...", optsSignU256.strLogPrefix, optsSignU256.u256 ); optsSignU256.details.trace( "{p}Will query to sign {} skaled node(s)...", @@ -1413,7 +1403,8 @@ async function prepareSignU256( optsSignU256 ) { return true; } -async function doSignU256OneImplHandleCallResult( i, optsSignU256, joCall, joIn, joOut ) { +async function doSignU256OneImplHandleCallResult( + i: number, optsSignU256: any, joCall: any, joIn: any, joOut: any ) { const imaState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignU256.jarrNodes[i]; @@ -1460,7 +1451,7 @@ async function doSignU256OneImplHandleCallResult( i, optsSignU256, joCall, joIn, return; } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); - const joResultFromNode = { + const joResultFromNode: any = { index: "" + nZeroBasedNodeIndex, signature: { X: arrTmp[0], Y: arrTmp[1] } }; @@ -1509,7 +1500,7 @@ async function doSignU256OneImplHandleCallResult( i, optsSignU256, joCall, joIn, await joCall.disconnect(); } -async function doSignU256OneImpl( i, optsSignU256 ) { +async function doSignU256OneImpl( i: number, optsSignU256: any ) { const imaState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignU256.jarrNodes[i]; @@ -1518,15 +1509,15 @@ async function doSignU256OneImpl( i, optsSignU256 ) { : imaUtils.composeSChainNodeUrl( joNode ); const strNodeDescColorized = log.fmtDebug( "{url} ({}/{}, ID {})", strNodeURL, i, optsSignU256.jarrNodes.length, joNode.nodeID ); - const rpcCallOpts = null; - let joCall = null; + const rpcCallOpts: any = null; + let joCall: any = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); optsSignU256.details.trace( "{p}Will invoke skale_imaBSU256 for to sign value {}", - optsSignU256.strLogPrefix, ptsSignU256.u256.toString() ); - const joIn = { + optsSignU256.strLogPrefix, optsSignU256.u256.toString() ); + const joIn: any = { "method": "skale_imaBSU256", "params": { "valueToSign": optsSignU256.u256 // must be 0x string, came from outside 0x string @@ -1547,7 +1538,7 @@ async function doSignU256OneImpl( i, optsSignU256 ) { } } -async function gatherSigningCheckFinish256( optsSignOperation ) { +async function gatherSigningCheckFinish256( optsSignU256: any ) { const cntSuccess = optsSignU256.arrSignResults.length; if( optsSignU256.joGatheringTracker.nCountReceivedPrevious != optsSignU256.joGatheringTracker.nCountReceived ) { @@ -1571,32 +1562,32 @@ async function gatherSigningCheckFinish256( optsSignOperation ) { strLogPrefixB, joGlueResult ); if( optsSignU256.imaState.strPathBlsVerify.length > 0 ) { const joCommonPublicKey = discoverCommonPublicKey( - optsSignU256.imaState.joSChainNetworkInfo, false ); + optsSignU256.details, optsSignU256.imaState.joSChainNetworkInfo, false ); if( ! joCommonPublicKey ) { - strError = "No BLS common public key"; - optsSignOperation.details.error( "{p}{}", - optsSignOperation.strLogPrefixB, strError ); + const strError = "No BLS common public key"; + optsSignU256.details.error( "{p}{}", + optsSignU256.strLogPrefixB, strError ); } else if( performBlsVerifyU256( optsSignU256.details, joGlueResult, optsSignU256.u256, joCommonPublicKey ) ) { - strSuccessfulResultDescription = + const strSuccessfulResultDescription = "Got successful summary BLS u256 verification result"; optsSignU256.details.success( "{p}{}", strLogPrefixB, strSuccessfulResultDescription ); } else { - strError = "BLS verification failed"; + const strError = "BLS verification failed"; optsSignU256.details.error( "{p}BLS verification failure:{}", strLogPrefixB, strError ); } } } else { - strError = "BLS u256 glue failed, no glue result arrived"; + const strError = "BLS u256 glue failed, no glue result arrived"; optsSignU256.details.error( "{p}Problem(1) in BLS u256 sign result handler: {err}", strLogPrefixB, strError ); } optsSignU256.details.trace( "Will call signed-256 answer-sending callback {}, u256 is {}, " + - "glue result is {}", strError ? ( " with error " + log.fmtError( { em }, strError ) ) : "", + "glue result is {}", strError ? ( " with error " + log.fmtError( "{err}", strError ) ) : "", optsSignU256.u256, joGlueResult ); optsSignU256.fn( strError, optsSignU256.u256, joGlueResult ).catch( function( err ) { optsSignU256.details.critical( @@ -1607,7 +1598,7 @@ async function gatherSigningCheckFinish256( optsSignOperation ) { return true; } -async function gatherSigningCheckOverflow256( optsSignOperation ) { +async function gatherSigningCheckOverflow256( optsSignU256: any ) { if( optsSignU256.joGatheringTracker.nCountReceived < optsSignU256.jarrNodes.length ) return false; optsSignU256.fn( @@ -1615,6 +1606,7 @@ async function gatherSigningCheckOverflow256( optsSignOperation ) { `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 ).catch( function( err ) { + const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.critical( "Problem(3) in BLS u256 sign result handler, not enough successful BLS " + "signature parts({} when all attempts done, error details: {err}", @@ -1626,13 +1618,13 @@ async function gatherSigningCheckOverflow256( optsSignOperation ) { return true; } -async function doSignU256Gathering( optsSignU256 ) { +async function doSignU256Gathering( optsSignU256: any ) { optsSignU256.details.debug( "{p}Waiting for BLS glue result ", optsSignU256.strLogPrefix ); optsSignU256.errGathering = null; - for( let idxStep = 0; idxStep < optsSignOperation.joGatheringTracker.nWaitIntervalMaxSteps; + for( let idxStep = 0; idxStep < optsSignU256.joGatheringTracker.nWaitIntervalMaxSteps; ++ idxStep ) { await threadInfo.sleep( - optsSignOperation.joGatheringTracker.nWaitIntervalStepMilliseconds ); + optsSignU256.joGatheringTracker.nWaitIntervalStepMilliseconds ); if( await gatherSigningCheckFinish256( optsSignU256 ) ) return; if( await gatherSigningCheckOverflow256( optsSignU256 ) ) @@ -1645,6 +1637,7 @@ async function doSignU256Gathering( optsSignU256 ) { `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 ).catch( function( err ) { + const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.error( "Problem(4) in BLS u256 sign result handler, not enough successful BLS " + "signature parts({}) and timeout reached, error details: {err", @@ -1655,8 +1648,8 @@ async function doSignU256Gathering( optsSignU256 ) { } ); } -export async function doSignU256( u256, details, fn ) { - const optsSignU256 = { +export async function doSignU256( u256: any, details: any, fn: any ) { + const optsSignU256: any = { u256: u256, fn: fn, details: details, @@ -1706,10 +1699,8 @@ export async function doSignU256( u256, details, fn ) { } export async function doVerifyReadyHash( - strMessageHash, - nZeroBasedNodeIndex, - signature, - isExposeOutput + strMessageHash: string, nZeroBasedNodeIndex: number, + signature: any, isExposeOutput: boolean ) { const imaState = state.get(); const strDirection = "RAW"; @@ -1717,7 +1708,7 @@ export async function doVerifyReadyHash( const details = log.createMemoryStream(); let isSuccess = false; const arrTmp = signature.signatureShare.split( ":" ); - const joResultFromNode = { + const joResultFromNode: any = { index: "" + nZeroBasedNodeIndex, signature: { X: arrTmp[0], @@ -1739,7 +1730,7 @@ export async function doVerifyReadyHash( nZeroBasedNodeIndex, imaState.joSChainNetworkInfo, details, true ); details.trace( "{p}BLS node #{} - hashed verify message is {}", strLogPrefix, nZeroBasedNodeIndex, strMessageHash ); - const joMsg = { + const joMsg: any = { "message": strMessageHash }; details.debug( "{p}BLS node #{} - composed {} using hash {} and glue {} and public key {}", @@ -1760,7 +1751,8 @@ export async function doVerifyReadyHash( ; details.trace( "{p}Will execute node #{} BLS verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); - strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ); + strOutput = + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); details.trace( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -1781,7 +1773,8 @@ export async function doVerifyReadyHash( } async function doSignReadyHashHandleCallResult( - strLogPrefix, details, strMessageHash, isExposeOutput, joCall, joIn, joOut + strLogPrefix: string, details: any, + strMessageHash: string, isExposeOutput: any, joCall: any, joIn: any, joOut: any ) { details.trace( "{p}Call to ", "SGX done, answer is: {}", strLogPrefix, joOut ); let joSignResult = joOut; @@ -1793,7 +1786,6 @@ async function doSignReadyHashHandleCallResult( joSignResult = joOut.signResult; if( !joSignResult ) { const strError = "No signature arrived"; - joRetVal.error = strError; details.error( "{p}BLS-sign(1) finished with error: {err}", strLogPrefix, strError ); await joCall.disconnect(); throw new Error( strError ); @@ -1803,7 +1795,6 @@ async function doSignReadyHashHandleCallResult( joSignResult.errorMessage.length > 0 ) { const strError = `BLS-sign finished with error: ${joSignResult.errorMessage};`; - joRetVal.error = strError; details.error( "{p}BLS-sign(2) finished with error: {err}", strLogPrefix, joSignResult.errorMessage ); await joCall.disconnect(); @@ -1814,11 +1805,11 @@ async function doSignReadyHashHandleCallResult( return joSignResult; } -export async function doSignReadyHash( strMessageHash, isExposeOutput ) { +export async function doSignReadyHash( strMessageHash: string, isExposeOutput: any ) { const imaState = state.get(); const strLogPrefix = ""; - const details = log.createMemoryStream(); - let joSignResult = null, joCall = null; + const details: any = log.createMemoryStream(); + let joSignResult: any = null, joCall: any = null; try { const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -1838,7 +1829,7 @@ export async function doSignReadyHash( strMessageHash, isExposeOutput ) { if( ! joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign U256" ); } - let rpcCallOpts = null; + let rpcCallOpts: any = null; if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey == "string" && joAccount.strPathSslKey.length > 0 && "strPathSslCert" in joAccount && typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 @@ -1853,7 +1844,7 @@ export async function doSignReadyHash( strMessageHash, isExposeOutput ) { joCall = await rpcCall.create( joAccount.strSgxURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); - const joIn = { + const joIn: any = { "jsonrpc": "2.0", "id": utils.randomCallID(), "method": "blsSignMessageHash", @@ -1887,7 +1878,7 @@ export async function doSignReadyHash( strMessageHash, isExposeOutput ) { return joSignResult; } -async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) { +async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) { optsHandleVerifyAndSign.details.debug( "{p}Will verify and sign {}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.joCallData ); optsHandleVerifyAndSign.nIdxCurrentMsgBlockStart = @@ -1941,7 +1932,7 @@ async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) return true; } -async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) { +async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) { const strSChainNameSrc = optsHandleVerifyAndSign.joCallData.params.srcChainName; const strSChainNameDst = optsHandleVerifyAndSign.joCallData.params.dstChainName; optsHandleVerifyAndSign.details.trace( @@ -1955,7 +1946,7 @@ async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) { "try again later" ); } - let joSChainSrc = null, strUrlSrcSChain = null; + let joSChainSrc: any = null, strUrlSrcSChain: string|null = null; for( let idxSChain = 0; idxSChain < arrSChainsCached.length; ++ idxSChain ) { const joSChain = arrSChainsCached[idxSChain]; if( joSChain.name.toString() == strSChainNameSrc.toString() ) { @@ -1984,7 +1975,8 @@ async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) { } async function handleBlsSignMessageHashResult( - optsHandleVerifyAndSign, joCallData, joAccount, joCall, joIn, joOut + optsHandleVerifyAndSign: any, joCallData: any, joAccount: any, + joCall: any, joIn: any, joOut: any ) { optsHandleVerifyAndSign.details.trace( "{p}{bright} Call to SGX done, " + "answer is: {}", optsHandleVerifyAndSign.strLogPrefix, @@ -2000,8 +1992,10 @@ async function handleBlsSignMessageHashResult( optsHandleVerifyAndSign.joRetVal.qa = optsHandleVerifyAndSign.joCallData.qa; if( !joSignResult ) { const strError = "No signature arrived"; - joRetVal.error = strError; - details.error( "{p}BLS-sign(1) finished with error: {err}", strLogPrefix, strError ); + optsHandleVerifyAndSign.joRetVal.error = strError; + optsHandleVerifyAndSign.details.error( + "{p}BLS-sign(1) finished with error: {err}", + optsHandleVerifyAndSign.strLogPrefix, strError ); await joCall.disconnect(); throw new Error( strError ); } @@ -2026,8 +2020,8 @@ async function handleBlsSignMessageHashResult( return joSignResult; } -export async function handleSkaleImaVerifyAndSign( joCallData ) { - const optsHandleVerifyAndSign = { +export async function handleSkaleImaVerifyAndSign( joCallData: any ) { + const optsHandleVerifyAndSign: any = { joCallData: joCallData, imaState: state.get(), strLogPrefix: "", @@ -2046,7 +2040,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData ) { nThreshold: 1, nParticipants: 1 }; - let joCall = null; + let joCall: any = null; try { if( ! ( await prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) ) ) return null; @@ -2070,7 +2064,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData ) { if( ! joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign IMA message(s)" ); } - let rpcCallOpts = null; + let rpcCallOpts: any = null; if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey == "string" && joAccount.strPathSslKey.length > 0 && "strPathSslCert" in joAccount && typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 @@ -2119,7 +2113,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData ) { return optsHandleVerifyAndSign.joRetVal; } -async function handleSkaleImaBSU256Prepare( optsBSU256 ) { +async function handleSkaleImaBSU256Prepare( optsBSU256: any ) { optsBSU256.details.debug( "{p}Will U256-BLS-sign {}", optsBSU256.strLogPrefix, optsBSU256.joCallData ); optsBSU256.nThreshold = discoverBlsThreshold( optsBSU256.imaState.joSChainNetworkInfo ); @@ -2129,15 +2123,15 @@ async function handleSkaleImaBSU256Prepare( optsBSU256 ) { optsBSU256.details.trace( "{p}Discovered number of BLS participants is {}.", optsBSU256.strLogPrefix, optsBSU256.nParticipants ); if( ! checkBlsThresholdAndBlsParticipants( - optsHandleVerifyAndSign.nThreshold, - optsHandleVerifyAndSign.nParticipants, + optsBSU256.nThreshold, + optsBSU256.nParticipants, "handle BSU256Prepare", optsBSU256.details ) ) return false; optsBSU256.u256 = optsBSU256.joCallData.params.valueToSign; optsBSU256.details.trace( "{p}U256 original value is {}", optsBSU256.strLogPrefix, optsBSU256.u256 ); - optsBSU256.strMessageHash = keccak256U256.u256( optsBSU256.u256, true ); + optsBSU256.strMessageHash = keccak256U256( optsBSU256.u256, true ); optsBSU256.details.trace( "{p}hash of U256 value to sign is {}", optsBSU256.strLogPrefix, optsBSU256.strMessageHash ); optsBSU256.details.trace( "{p}Will BLS-sign U256.", optsBSU256.strLogPrefix ); @@ -2152,7 +2146,9 @@ async function handleSkaleImaBSU256Prepare( optsBSU256 ) { return true; } -async function handleBlsSignMessageHash256Result( optsBSU256, joCallData, joCall, joIn, joOut ) { +async function handleBlsSignMessageHash256Result( + optsBSU256: any, joCallData: any, joCall: any, joIn: any, joOut: any +) { optsBSU256.details.trace( "{p}Call to SGX done, answer is: {}", optsBSU256.strLogPrefix, joOut ); let joSignResult = joOut; @@ -2164,8 +2160,9 @@ async function handleBlsSignMessageHash256Result( optsBSU256, joCallData, joCall joSignResult = joOut.signResult; if( !joSignResult ) { const strError = "No signature arrived"; - joRetVal.error = strError; - details.error( "{p}U256/BLS-sign(1) finished with error: {err}", strLogPrefix, strError ); + optsBSU256.joRetVal.error = strError; + optsBSU256.details.error( + "{p}U256/BLS-sign(1) finished with error: {err}", optsBSU256.strLogPrefix, strError ); await joCall.disconnect(); throw new Error( strError ); } @@ -2189,8 +2186,8 @@ async function handleBlsSignMessageHash256Result( optsBSU256, joCallData, joCall return joSignResult; } -export async function handleSkaleImaBSU256( joCallData ) { - const optsBSU256 = { +export async function handleSkaleImaBSU256( joCallData: any ) { + const optsBSU256: any = { joCallData: joCallData, imaState: state.get(), strLogPrefix: "", @@ -2203,11 +2200,11 @@ export async function handleSkaleImaBSU256( joCallData ) { strMessageHash: "", joAccount: null }; - let joCall = null; + let joCall: any = null; try { if( ! ( await handleSkaleImaBSU256Prepare( optsBSU256 ) ) ) return null; - let rpcCallOpts = null; + let rpcCallOpts: any = null; if( "strPathSslKey" in optsBSU256.joAccount && typeof optsBSU256.joAccount.strPathSslKey == "string" && optsBSU256.joAccount.strPathSslKey.length > 0 && diff --git a/src/cc.ts b/src/cc.ts index 8883d53d..38b2a7bc 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file cc.mjs + * @file cc.ts * @copyright SKALE Labs 2019-Present */ @@ -425,7 +425,7 @@ export const getCircularReplacerForJsonStringify = () : any => { }; }; -export const jsonColorizer = { // see http://jsfiddle.net/unLSJ/ +export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ cntCensoredMax: 30000, // zero to disable censoring censor: ( censor: any ) : any => { let i = 0; diff --git a/src/cli.ts b/src/cli.ts index 62eb90fc..af14c099 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -19,7 +19,7 @@ */ /** - * @file cli.mjs + * @file cli.ts * @copyright SKALE Labs 2019-Present */ @@ -36,7 +36,7 @@ import * as imaOracleOperations from "./imaOracleOperations"; import * as imaTx from "./imaTx"; import * as state from "./state"; -const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); +const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); const gStrAppName = "IMA AGENT"; const gStrVersion = @@ -54,7 +54,7 @@ export function printAbout( isLog?: boolean ) { return true; } -export function parseCommandLineArgument( s ) { +export function parseCommandLineArgument( s: string ) { const joArg = { name: "", value: "" @@ -1317,11 +1317,16 @@ function commonInitPrintSysInfo() { log.debug( "This process {sunny} is {}", "versions", process.versions ); log.debug( "This process {sunny} is {}", "PID", process.pid ); log.debug( "This process {sunny} is {}", "PPID", process.ppid ); - log.debug( "This process {sunny} is {}", "EGID", process.getegid() ); - log.debug( "This process {sunny} is {}", "EUID", process.geteuid() ); - log.debug( "This process {sunny} is {}", "GID", process.getgid() ); - log.debug( "This process {sunny} is {}", "UID", process.getuid() ); - log.debug( "This process {sunny} are {}", "groups", process.getgroups() ); + log.debug( "This process {sunny} is {}", "EGID", + process.getegid ? process.getegid() : "N/A" ); + log.debug( "This process {sunny} is {}", "EUID", + process.geteuid ? process.geteuid() : "N/A" ); + log.debug( "This process {sunny} is {}", "GID", + process.getgid ? process.getgid() : "N/A" ); + log.debug( "This process {sunny} is {}", "UID", + process.getuid ? process.getuid() : "N/A" ); + log.debug( "This process {sunny} are {}", "groups", + process.getgroups ? process.getgroups() : "N/A" ); log.debug( "This process {sunny} is {}", "CWD", process.cwd() ); log.debug( "This process {sunny} is {}", "architecture", process.arch ); log.debug( "This process {sunny} is {}", "execPath", process.execPath ); @@ -2091,7 +2096,7 @@ function commonInitCheckGeneralArgs() { } ensureHaveValue( "App path", - path.join( __dirname, "main.mjs" ), false, isPrintGathered, null, ( x ) => { + path.join( __dirname, "main.ts" ), false, isPrintGathered, null, ( x ) => { return att( x ); } ); ensureHaveValue( diff --git a/src/clpTools.ts b/src/clpTools.ts index e4ec11dd..313c4495 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -7,7 +7,7 @@ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file clpTools.mjs + * @file clpTools.ts * @copyright SKALE Labs 2019-Present */ @@ -40,12 +40,13 @@ import * as discoveryTools from "./discoveryTools"; import * as loop from "./loop"; import * as imaUtils from "./utils"; import * as imaBLS from "./bls"; +import * as imaTx from "./imaTx"; -export async function registerAll( isPrintSummaryRegistrationCosts ) { +export async function registerAll( isPrintSummaryRegistrationCosts: boolean ) { if( !await registerStep1( false ) ) return false; if( isPrintSummaryRegistrationCosts ) - printSummaryRegistrationCosts(); + printSummaryRegistrationCosts( log ); return true; } @@ -54,12 +55,12 @@ export async function checkRegistrationAll() { return b1; } -const gInfoRegistrationCost = { +const gInfoRegistrationCost: any = { mn: [], sc: [] }; -export async function registerStep1( isPrintSummaryRegistrationCosts ) { +export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) { const imaState = state.get(); imaCLI.initContracts(); const strLogPrefix = "Reg 1: "; @@ -74,7 +75,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts ) { log.posNeg( bSuccess, "already registered", "not registered yet" ) ); if( bSuccess ) return true; - const jarrReceipts = + const jarrReceipts: any = await imaReg.registerSChainInDepositBoxes( // step 1 imaState.chainProperties.mn.ethersProvider, imaState.joLinker, @@ -98,7 +99,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts ) { gInfoRegistrationCost.mn.concat( gInfoRegistrationCost.mn, jarrReceipts ); } if( isPrintSummaryRegistrationCosts ) - clpTools.printSummaryRegistrationCosts(); + printSummaryRegistrationCosts(); if( !bSuccess ) { const nRetCode = 163; log.fatal( "{p}failed to register S-Chain in deposit box, will return code {}", @@ -120,7 +121,9 @@ export async function checkRegistrationStep1() { return bRetVal; } -export function printSummaryRegistrationCosts( details ) { +export function printSummaryRegistrationCosts( details?: any ) { + if( ! details ) + details = log; imaGasUsage.printGasUsageReportFromArray( "Main Net REGISTRATION", gInfoRegistrationCost.mn, details ); imaGasUsage.printGasUsageReportFromArray( @@ -1086,7 +1089,7 @@ export function commandLineTaskPaymentS2S() { ? strAddrErc721ExplicitTarget : strAddrErc721Explicit; const strAddrErc1155Dst = isForward ? strAddrErc1155ExplicitTarget : strAddrErc1155Explicit; - const tx_customizer = isForward ? sc.transactionCustomizer : tc.transactionCustomizer; + const tx_customizer: imaTx.TransactionCustomizer = isForward ? sc.transactionCustomizer : tc.transactionCustomizer; if( strCoinNameErc721Src.length > 0 ) { // ERC721 payment log.information( "one S->S single ERC721 payment: {}", imaState.idToken ); @@ -1193,7 +1196,7 @@ export function commandLineTaskPaymentS2S() { } // ETH payment log.information( "one S->S single ETH payment: {}", imaState.nAmountOfWei ); - lop.fatal( "S->S ETH payment(s) are neither supported nor allowed" ); + log.fatal( "S->S ETH payment(s) are neither supported nor allowed" ); process.exit( 154 ); } } ); @@ -1244,7 +1247,7 @@ export function commandLineTaskTransferM2S() { "fn": async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // main-net --> s-chain transfer - const joRuntimeOpts = { + const joRuntimeOpts: any = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 @@ -1284,7 +1287,7 @@ export function commandLineTaskTransferS2M() { "fn": async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer - const joRuntimeOpts = { + const joRuntimeOpts: any = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 @@ -1326,7 +1329,7 @@ export function commandLineTaskTransferS2S() { return; if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer - const joRuntimeOpts = { + const joRuntimeOpts: any = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 @@ -1360,12 +1363,12 @@ export function commandLineTaskTransfer() { "fn": async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); - const joRuntimeOpts = { + const joRuntimeOpts: any = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - const optsLoop = { + const optsLoop: any = { joRuntimeOpts: joRuntimeOpts, isDelayFirstRun: false, enableStepOracle: true, @@ -1373,7 +1376,7 @@ export function commandLineTaskTransfer() { enableStepS2M: true, enableStepS2S: true }; - return await singleTransferLoop( optsLoop ); + return await loop.singleTransferLoop( optsLoop ); } } ); } @@ -1394,7 +1397,7 @@ export function commandLineTaskLoop() { } if( isPrintSummaryRegistrationCosts ) printSummaryRegistrationCosts(); - const opts = { + const opts: any = { imaState: imaState, "details": log }; @@ -1421,12 +1424,12 @@ export function commandLineTaskLoopSimple() { } if( isPrintSummaryRegistrationCosts ) printSummaryRegistrationCosts(); - const joRuntimeOpts = { + const joRuntimeOpts: any = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - const optsLoop = { + const optsLoop: any = { joRuntimeOpts: joRuntimeOpts, isDelayFirstRun: false, enableStepOracle: true, @@ -1453,13 +1456,13 @@ async function handleBrowseSkaleModesRpcInfoResult( strLogPrefix, joCall, joIn, continue; } const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); - const rpcCallOpts = null; - let joCall = null; + const rpcCallOpts: any = null; + let joCall: any = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); - const jIn = { "method": "skale_imaInfo", "params": { } }; + const jIn: any = { "method": "skale_imaInfo", "params": { } }; if( discoveryTools.isSendImaAgentIndex() ) jIn.params.fromImaAgentIndex = imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -1495,15 +1498,15 @@ export function commandLineTaskBrowseSChain() { process.exit( 155 ); } log.information( "{p}Downloading S-Chain network information...", strLogPrefix ); - const rpcCallOpts = null; - let joCall = null; + const rpcCallOpts: any = null; + let joCall: any = null; try { joCall = await rpcCall.create( imaState.chainProperties.sc.strURL, rpcCallOpts ); if( ! joCall ) { throw new Error( "Failed to create JSON RPC call object " + `to ${imaState.chainProperties.sc.strURL}` ); } - const joIn = { "method": "skale_nodesRpcInfo", "params": { } }; + const joIn: any = { "method": "skale_nodesRpcInfo", "params": { } }; if( discoveryTools.isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = imaState.nNodeNumber; const joOut = await joCall.call( joIn ); diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index ad1ee23d..b132861c 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -7,7 +7,7 @@ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file discoveryTools.mjs + * @file discoveryTools.ts * @copyright SKALE Labs 2019-Present */ @@ -29,7 +29,7 @@ import * as state from "./state"; import * as imaUtils from "./utils"; import * as threadInfo from "./threadInfo"; -export function formatBalanceInfo( bi, strAddress ) { +export function formatBalanceInfo( bi: any, strAddress: string ) : string { let s = ""; s += log.fmtInformation( "{p}", bi.assetName ); if( "assetAddress" in bi && @@ -53,7 +53,7 @@ export function formatBalanceInfo( bi, strAddress ) { return s; } -function getSChainNodesCount( joSChainNetworkInfo ) { +function getSChainNodesCount( joSChainNetworkInfo: any ) : number { try { if( ! joSChainNetworkInfo ) return 0; @@ -65,7 +65,7 @@ function getSChainNodesCount( joSChainNetworkInfo ) { } } -export function isSChainNodeFullyDiscovered( joNode ) { +export function isSChainNodeFullyDiscovered( joNode: any ) : boolean { if( ! joNode ) return false; if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo == "object" && @@ -102,7 +102,7 @@ export function isSChainNodeFullyDiscovered( joNode ) { return false; } -export function getSChainDiscoveredNodesCount( joSChainNetworkInfo ) { +export function getSChainDiscoveredNodesCount( joSChainNetworkInfo: any ) : number { try { if( ! joSChainNetworkInfo ) return 0; @@ -170,14 +170,15 @@ export async function waitUntilSChainStarted() { log.success( "Done, S-Chain is accessible and sane." ); } -export function isSendImaAgentIndex() { +export function isSendImaAgentIndex() : boolean { return true; } -let gTimerSChainDiscovery = null; -let gFlagIsInSChainDiscovery = false; +let gTimerSChainDiscovery: any = null; +let gFlagIsInSChainDiscovery: boolean = false; -function composeStillUnknownNodesMessage( joSChainNetworkInfo, cntStillUnknown, cntNodesOnChain ) { +function composeStillUnknownNodesMessage( + joSChainNetworkInfo: any, cntStillUnknown: number, cntNodesOnChain: number ) : string { let strMessage = log.fmtSuccess( ", {} of {} still unknown (", cntStillUnknown, cntNodesOnChain ); try { @@ -201,12 +202,12 @@ function composeStillUnknownNodesMessage( joSChainNetworkInfo, cntStillUnknown, return strMessage; } -async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery, fnAfter ) { +async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boolean, fnAfter: any ) { if( gFlagIsInSChainDiscovery ) { - isInsideAsyncHandler = false; log.information( "Notice: long this S-Chain re-discovery is in progress now..." ); return; } + const imaState = state.get(); fnAfter = fnAfter || function() {}; gFlagIsInSChainDiscovery = true; const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); @@ -276,7 +277,8 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery, fnAft continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, fnAfter ); } -export async function continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, fnAfter ) { +export async function continueSChainDiscoveryInBackgroundIfNeeded( + isSilentReDiscovery: boolean, fnAfter: any ) { if( gTimerSChainDiscovery != null ) return; fnAfter = fnAfter || function() {}; @@ -321,8 +323,9 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDis } function handleDiscoverSkaleImaInfoResult( - optsDiscover, strNodeDescColorized, joNode, joCall, joIn, joOut -) { + optsDiscover: any, strNodeDescColorized: string, + joNode: any, joCall: any, joIn: any, joOut: any +) : void { joNode.imaInfo = joOut.result; if( isSChainNodeFullyDiscovered( joNode ) ) ++ optsDiscover.nCountReceivedImaDescriptions; @@ -333,7 +336,7 @@ function handleDiscoverSkaleImaInfoResult( } } -async function discoverSChainWalkNodes( optsDiscover ) { +async function discoverSChainWalkNodes( optsDiscover: any ) { optsDiscover.cntFailed = 0; for( let i = 0; i < optsDiscover.cntNodes; ++ i ) { const nCurrentNodeIdx = 0 + i; @@ -361,13 +364,13 @@ async function discoverSChainWalkNodes( optsDiscover ) { } } } catch ( err ) { } - const rpcCallOpts = null; - let joCall = null; + const rpcCallOpts: any = null; + let joCall: any = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); - const joIn = { "method": "skale_imaInfo", "params": { } }; + const joIn: any = { "method": "skale_imaInfo", "params": { } }; if( isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = optsDiscover.imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -386,7 +389,7 @@ async function discoverSChainWalkNodes( optsDiscover ) { } } -async function discoverSChainWait( optsDiscover ) { +async function discoverSChainWait( optsDiscover: any ) { if( ! optsDiscover.isSilentReDiscovery ) { log.debug( "{p}Waiting for response from at least {} node(s)...", optsDiscover.strLogPrefix, optsDiscover.nCountToWait ); @@ -454,7 +457,8 @@ async function discoverSChainWait( optsDiscover ) { }, nWaitStepMilliseconds ); } -async function handleDiscoverSkaleNodesRpcInfoResult( optsDiscover, scURL, joCall, joIn, joOut ) { +async function handleDiscoverSkaleNodesRpcInfoResult( + optsDiscover: any, scURL: string, joCall: any, joIn: any, joOut: any ) { if( ! optsDiscover.isSilentReDiscovery ) { log.trace( "{p}OK, got (own) S-Chain network information: {}", optsDiscover.strLogPrefix, joOut.result ); @@ -522,8 +526,9 @@ async function handleDiscoverSkaleNodesRpcInfoResult( optsDiscover, scURL, joCal } export async function discoverSChainNetwork( - fnAfter, isSilentReDiscovery, joPrevSChainNetworkInfo, nCountToWait ) { - const optsDiscover = { + fnAfter: any, isSilentReDiscovery: boolean, + joPrevSChainNetworkInfo: any, nCountToWait: number ) { + const optsDiscover: any = { fnAfter: fnAfter, isSilentReDiscovery: ( !!isSilentReDiscovery ), joPrevSChainNetworkInfo: joPrevSChainNetworkInfo || null, @@ -543,14 +548,14 @@ export async function discoverSChainNetwork( optsDiscover.nCountToWait = 0; if( !optsDiscover.isSilentReDiscovery ) log.information( "{p}This S-Chain discovery will start...", optsDiscover.strLogPrefix ); - let joCall = null; + let joCall: any = null; try { const scURL = optsDiscover.imaState.chainProperties.sc.strURL; - const rpcCallOpts = null; + const rpcCallOpts: any = null; joCall = await rpcCall.create( scURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${scURL}` ); - const joIn = { "method": "skale_nodesRpcInfo", "params": { } }; + const joIn: any = { "method": "skale_nodesRpcInfo", "params": { } }; if( isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = optsDiscover.imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -578,9 +583,10 @@ export async function discoverSChainNetwork( return optsDiscover.joSChainNetworkInfo; } -let gIntervalPeriodicDiscovery = null; +let gIntervalPeriodicDiscovery: any = null; -function checkPeriodicDiscoveryNoLongerNeeded( joSChainNetworkInfo, isSilentReDiscovery ) { +function checkPeriodicDiscoveryNoLongerNeeded( + joSChainNetworkInfo: any, isSilentReDiscovery: boolean ) { if( ! joSChainNetworkInfo ) return false; const imaState = state.get(); @@ -601,7 +607,7 @@ function checkPeriodicDiscoveryNoLongerNeeded( joSChainNetworkInfo, isSilentReDi } export async function doPeriodicSChainNetworkDiscoveryIfNeeded( - isSilentReDiscovery, fnAfterRediscover + isSilentReDiscovery: boolean, fnAfterRediscover: any ) { if( gIntervalPeriodicDiscovery ) return; // already started @@ -633,7 +639,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( await discoverSChainNetwork( null, isSilentReDiscovery, joPrevSChainNetworkInfo, nCountToWait ); joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; - imaState.joSChainNetworkInfo = joSChainNetworkInfo; + imaState.joSChainNetworkInfo = imaState.joSChainNetworkInfo; if( checkPeriodicDiscoveryNoLongerNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { if( ! isSilentReDiscovery ) diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index c28e5965..d0381a6b 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -19,11 +19,12 @@ */ /** - * @file eventDispatcher.mjs + * @file eventDispatcher.ts * @copyright SKALE Labs 2019-Present */ export class UniversalDispatcherEvent { + type: any; constructor( type, jo ) { this.type = type; for( const [ key, value ] of Object.entries( jo ) ) { @@ -38,6 +39,9 @@ export class UniversalDispatcherEvent { export class EventDispatcher { // see https://stackoverflow.com/questions/36675693/eventtarget-interface-in-safari + _listeners: any[]; + isDisposing: boolean; + isDisposed: boolean; constructor() { this._listeners = []; this.isDisposed = false; @@ -53,10 +57,10 @@ export class EventDispatcher { ); this.removeAllEventListeners(); } - hasEventListener( type, listener ) { + hasEventListener( type: any, listener: any ) { return this._listeners.some( item => item.type === type && item.listener === listener ); } - addEventListener( type, listener ) { + addEventListener( type: any, listener: any ) { if( ! this.hasEventListener( type, listener ) ) { this._listeners.push( { type, @@ -66,7 +70,7 @@ export class EventDispatcher { } return this; } - removeEventListener( type, listener ) { + removeEventListener( type: any, listener: any ) { while( true ) { const index = ( listener != undefined ) ? this._listeners.findIndex( @@ -85,16 +89,16 @@ export class EventDispatcher { this._listeners = []; return this; } - on( type, listener ) { + on( type: any, listener: any ) { return this.addEventListener( type, listener ); } - off( type, listener ) { + off( type: any, listener: any ) { return this.removeEventListener( type, listener ); } offAll() { return this.removeAllEventListeners(); } - dispatchEvent( evt ) { + dispatchEvent( evt: any ) { const a = this._listeners.filter( item => item.type === evt.type ); for( const item of a ) { const { diff --git a/src/imaCore.ts b/src/imaCore.ts index 8639ab25..af3d47c3 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file index.mjs + * @file index.ts * @copyright SKALE Labs 2019-Present */ @@ -43,8 +43,8 @@ const perMessageGasForTransfer = 1000000; const additionalS2MTransferOverhead = 200000; async function findOutReferenceLogRecord( - details, strLogPrefix, ethersProvider, joMessageProxy, - bnBlockId, nMessageNumberToFind, isVerbose + details: any, strLogPrefix: string, ethersProvider: any, joMessageProxy: any, + bnBlockId: any, nMessageNumberToFind: any, isVerbose: boolean ) { const bnMessageNumberToFind = owaspUtils.toBN( nMessageNumberToFind.toString() ); const strEventName = "PreviousMessageReference"; @@ -58,11 +58,11 @@ async function findOutReferenceLogRecord( } for( let idxLogRecord = 0; idxLogRecord < cntLogRecord; ++ idxLogRecord ) { const joEvent = arrLogRecords[idxLogRecord]; - const ev = { + const ev: any = { "currentMessage": joEvent.args[0], "previousOutgoingMessageBlockId": joEvent.args[1] }; - const joReferenceLogRecord = { + const joReferenceLogRecord: any = { "currentMessage": ev.currentMessage, "previousOutgoingMessageBlockId": ev.previousOutgoingMessageBlockId, "currentBlockId": bnBlockId @@ -95,7 +95,7 @@ async function findOutAllReferenceLogRecords( "message counter {}", strLogPrefix, bnBlockId.toString(), nOutMsgCnt.toString(), nIncMsgCnt.toString() ); } - const arrLogRecordReferences = []; + const arrLogRecordReferences: any = []; const cntExpected = nOutMsgCnt - nIncMsgCnt; if( cntExpected <= 0 ) { if( isVerbose ) { @@ -259,7 +259,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer ) { } async function analyzeGatheredRecords( optsTransfer, r ) { - let joValues = ""; + let joValues: any = null; const strChainHashWeAreLookingFor = owaspUtils.ethersMod.ethers.utils.id( optsTransfer.chainNameDst ); optsTransfer.details.debug( @@ -270,7 +270,7 @@ async function analyzeGatheredRecords( optsTransfer, r ) { const joEvent = r[i]; optsTransfer.details.debug( "{p}Will review found event record {} with data {}", optsTransfer.strLogPrefix, i, joEvent ); - const ev = { + const ev: any = { "dstChainHash": joEvent.args[0], "msgCounter": joEvent.args[1], "srcContract": joEvent.args[2], @@ -439,7 +439,7 @@ async function gatherMessages( optsTransfer ) { optsTransfer.details.debug( "{p}Will process message counter value {}", optsTransfer.strLogPrefix, optsTransfer.nIdxCurrentMsg ); optsTransfer.arrMessageCounters.push( optsTransfer.nIdxCurrentMsg ); - const joMessage = { + const joMessage: any = { "sender": joValues.srcContract, "destinationContract": joValues.dstContract, "to": joValues.to, @@ -494,7 +494,7 @@ async function callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueR let hint = joGlueResult ? joGlueResult.hint : null; if( !hint ) hint = "0"; - const sign = { + const sign: any = { blsSignature: [ signature.X, signature.Y ], // BLS glue of signatures hashA: hashPoint.X, // G1.X from joGlueResult.hashSrc hashB: hashPoint.Y, // G1.Y from joGlueResult.hashSrc @@ -545,7 +545,7 @@ async function callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueR weiHowMuchPostIncomingMessages, null ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { + const opts: any = { isCheckTransactionToSchain: ( optsTransfer.chainNameDst !== "Mainnet" ) ? true : false }; @@ -681,7 +681,7 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer, optsOutgoingMes optsOutgoingMessageAnalysis.joNode.name, node_r ); for( let idxEvent = 0; idxEvent < cntEvents; ++ idxEvent ) { const joEvent = node_r[idxEvent]; - const eventValuesByName = { + const eventValuesByName: any = { "dstChainHash": joEvent.args[0], "msgCounter": joEvent.args[1], "srcContract": joEvent.args[2], @@ -745,7 +745,7 @@ async function checkOutgoingMessageEvent( optsTransfer, joSChain ) { "{p}{bright} message analysis for message {} of {} with IMA message index {} and " + "message envelope data: {}", optsTransfer.strLogPrefix, optsTransfer.strDirection, idxMessage + 1, cntMessages, idxImaMessage, joMessage ); - const optsOutgoingMessageAnalysis = { + const optsOutgoingMessageAnalysis: any = { idxMessage: idxMessage, idxImaMessage: idxImaMessage, joMessage: joMessage, @@ -896,7 +896,7 @@ async function doMainTransferLoopActions( optsTransfer ) { optsTransfer.details.close(); optsTransfer.details = optsTransfer.imaState.isDynamicLogInDoTransfer - ? log : log.createMemoryStream( true ); + ? log : log.createMemoryStream(); optsTransfer.strGatheredDetailsName = `${optsTransfer.strDirection}/#` + `${optsTransfer.nTransferLoopCounter}-doTransfer-B-${optsTransfer.chainNameSrc}` + `-->${optsTransfer.chainNameDst}`; @@ -926,9 +926,10 @@ export async function doTransfer( joTokenManagerSChain, // for logs validation on s-chain nTransactionsCountInBlock, nTransferSteps, nMaxTransactionsCount, nBlockAwaitDepth, nBlockAge, - fnSignMessages, joExtraSignOpts, transactionCustomizerDst + fnSignMessages, joExtraSignOpts, + transactionCustomizerDst: imaTx.TransactionCustomizer ) { - const optsTransfer = { + const optsTransfer: any = { strDirection: strDirection, joRuntimeOpts: joRuntimeOpts, ethersProviderSrc: ethersProviderSrc, @@ -977,7 +978,7 @@ export async function doTransfer( `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter}-doTransfer-A-` + `${optsTransfer.chainNameSrc}-->${optsTransfer.chainNameDst}`; optsTransfer.details = optsTransfer.imaState.isDynamicLogInDoTransfer - ? log : log.createMemoryStream( true ); + ? log : log.createMemoryStream(); optsTransfer.strLogPrefixShort = `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter} `; optsTransfer.strLogPrefix = `${optsTransfer.strLogPrefixShort}transfer loop from ` + @@ -1091,7 +1092,7 @@ export async function doAllS2S( // s-chain --> s-chain nBlockAwaitDepth, nBlockAge, fnSignMessages, - transactionCustomizerDst + transactionCustomizerDst: imaTx.TransactionCustomizer ) { let cntOK = 0, cntFail = 0, nIndexS2S = 0; const sc = imaState.chainProperties.sc; @@ -1127,7 +1128,7 @@ export async function doAllS2S( // s-chain --> s-chain sc.joAbiIMA.message_proxy_chain_address, sc.joAbiIMA.message_proxy_chain_abi, ethersProviderSrc ); - const joExtraSignOpts = { + const joExtraSignOpts: any = { chainNameSrc: chainNameSrc, chainIdSrc: chainIdSrc, chainNameDst: chainNameDst, @@ -1166,8 +1167,7 @@ export async function doAllS2S( // s-chain --> s-chain nBlockAge, fnSignMessages, joExtraSignOpts, - transactionCustomizerDst - ); + transactionCustomizerDst ); imaState.loopState.s2s.isInProgress = false; await pwa.notifyOnLoopEnd( imaState, "s2s", nIndexS2S ); } else { diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 767a251a..23ed9078 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaEthOperations.mjs + * @file imaEthOperations.ts * @copyright SKALE Labs 2019-Present */ @@ -32,11 +32,11 @@ import * as imaEventLogScan from "./imaEventLogScan"; import * as threadInfo from "./threadInfo"; export async function getBalanceEth( - isMainNet, - ethersProvider, - chainId, - joAccount, - contractERC20 + isMainNet: any, + ethersProvider: any, + chainId: string, + joAccount?: any, + contractERC20?: any ) { const strLogPrefix = "getBalanceEth() call "; try { @@ -67,18 +67,18 @@ export async function getBalanceEth( // money is sent from caller // "value" JSON arg is used to specify amount of money to sent export async function doEthPaymentFromMainNet( - ethersProviderMainNet, - chainIdMainNet, - joAccountSrc, - joAccountDst, - joDepositBox, - joMessageProxyMainNet, // for checking logs - chainIdSChain, - weiHowMuch, // how much WEI money to send - transactionCustomizerMainNet + ethersProviderMainNet: any, + chainIdMainNet: string, + joAccountSrc: any, + joAccountDst: any, + joDepositBox: any, + joMessageProxyMainNet: any, // for checking logs + chainIdSChain: string, + weiHowMuch: any, // how much WEI money to send + transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any[] = []; let strActionName = ""; const strLogPrefix = "M2S ETH Payment: "; try { @@ -164,17 +164,17 @@ export async function doEthPaymentFromMainNet( // money is sent from caller // "value" JSON arg is used to specify amount of money to sent export async function doEthPaymentFromSChain( - ethersProviderSChain, - chainIdSChain, - joAccountSrc, - joAccountDst, - joTokenManagerETH, - joMessageProxySChain, // for checking logs - weiHowMuch, // how much WEI money to send - transactionCustomizerSChain + ethersProviderSChain: any, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joTokenManagerETH: any, + joMessageProxySChain: any, // for checking logs + weiHowMuch: any, // how much WEI money to send + transactionCustomizerSChain: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "S2M ETH Payment: "; try { @@ -200,7 +200,7 @@ export async function doEthPaymentFromSChain( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { + const opts: any = { isCheckTransactionToSchain: true }; const joReceipt = await imaTx.payedCall( @@ -253,14 +253,14 @@ export async function doEthPaymentFromSChain( } export async function receiveEthPaymentFromSchainOnMainNet( - ethersProviderMainNet, - chainIdMainNet, - joAccountMN, - joDepositBoxETH, - transactionCustomizerMainNet + ethersProviderMainNet: any, + chainIdMainNet: string, + joAccountMN: any, + joDepositBoxETH: any, + transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "M2S ETH Receive: "; try { @@ -313,9 +313,9 @@ export async function receiveEthPaymentFromSchainOnMainNet( } export async function viewEthPaymentFromSchainOnMainNet( - ethersProviderMainNet, - joAccountMN, - joDepositBoxETH + ethersProviderMainNet: any, + joAccountMN: any, + joDepositBoxETH: any ) { const details = log.createMemoryStream(); const strActionName = ""; diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index f3852418..2728faf3 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaEventLogScan.mjs + * @file imaEventLogScan.ts * @copyright SKALE Labs 2019-Present */ @@ -29,7 +29,7 @@ import * as rpcCall from "./rpcCall"; import * as imaHelperAPIs from "./imaHelperAPIs"; import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -export function createProgressiveEventsScanPlan( details, nLatestBlockNumber ) { +export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumber: any ) { // assume Main Net mines 6 blocks per minute const blocksInOneMinute = 6; const blocksInOneHour = blocksInOneMinute * 60; @@ -64,7 +64,7 @@ export function createProgressiveEventsScanPlan( details, nLatestBlockNumber ) { "nBlockTo": "latest", "type": "3 years" } ]; - const arrProgressiveEventsScanPlan = []; + const arrProgressiveEventsScanPlan: any[] = []; for( let idxPlan = 0; idxPlan < arrProgressiveEventsScanPlanA.length; ++idxPlan ) { const joPlan = arrProgressiveEventsScanPlanA[idxPlan]; if( joPlan.nBlockFrom >= 0 ) @@ -85,9 +85,9 @@ export function createProgressiveEventsScanPlan( details, nLatestBlockNumber ) { } export async function safeGetPastEventsProgressive( - details, strLogPrefix, - ethersProvider, attempts, joContract, strEventName, - nBlockFrom, nBlockTo, joFilter + details: any, strLogPrefix: string, + ethersProvider: any, attempts: number, joContract: any, strEventName: string, + nBlockFrom: any, nBlockTo: any, joFilter: any ) { const strURL = owaspUtils.ethersProviderToUrl( ethersProvider ); details.information( "{p}Will run progressive logs search for event {} via URL {url}, " + @@ -131,7 +131,7 @@ export async function safeGetPastEventsProgressive( createProgressiveEventsScanPlan( details, nLatestBlockNumberPlus1 ); details.trace( "Composed progressive event log records scan plan is: {}", arrProgressiveEventsScanPlan ); - let joLastPlan = { "nBlockFrom": 0, "nBlockTo": "latest", "type": "entire block range" }; + let joLastPlan: any = { "nBlockFrom": 0, "nBlockTo": "latest", "type": "entire block range" }; for( let idxPlan = 0; idxPlan < arrProgressiveEventsScanPlan.length; ++idxPlan ) { const joPlan = arrProgressiveEventsScanPlan[idxPlan]; if( joPlan.nBlockFrom < 0 ) @@ -164,9 +164,9 @@ export async function safeGetPastEventsProgressive( } export async function getContractCallEvents( - details, strLogPrefix, - ethersProvider, joContract, strEventName, - nBlockNumber, strTxHash, joFilter + details: any, strLogPrefix: string, + ethersProvider: any, joContract: any, strEventName: string, + nBlockNumber: any, strTxHash: string, joFilter: any ) { joFilter = joFilter || {}; nBlockNumber = owaspUtils.toBN( nBlockNumber ); @@ -184,7 +184,8 @@ export async function getContractCallEvents( await safeGetPastEventsIterative( details, strLogPrefix, ethersProvider, 10, joContract, strEventName, nBlockFrom, nBlockTo, joFilter ); - const joAllTransactionEvents = []; let i; + const joAllTransactionEvents: any = []; + let i: number; for( i = 0; i < joAllEventsInBlock.length; ++i ) { const joEvent = joAllEventsInBlock[i]; if( "transactionHash" in joEvent && joEvent.transactionHash == strTxHash ) @@ -194,7 +195,9 @@ export async function getContractCallEvents( } export async function safeGetTransactionCount( - details, cntAttempts, ethersProvider, address, param, retValOnFail, throwIfServerOffline + details: any, cntAttempts: number, + ethersProvider: any, address: string, param: any, + retValOnFail: any, throwIfServerOffline: boolean ) { const strFnName = "getTransactionCount"; const u = owaspUtils.ethersProviderToUrl( ethersProvider ); @@ -248,7 +251,8 @@ export async function safeGetTransactionCount( } export async function safeGetTransactionReceipt( - details, cntAttempts, ethersProvider, txHash, retValOnFail, throwIfServerOffline + details: any, cntAttempts: number, + ethersProvider: any, txHash: string, retValOnFail?: any, throwIfServerOffline?: boolean ) { const strFnName = "getTransactionReceipt"; const u = owaspUtils.ethersProviderToUrl( ethersProvider ); @@ -272,7 +276,7 @@ export async function safeGetTransactionReceipt( "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err.stack ); } ++ idxAttempt; - while( txReceipt === "" && idxAttempt <= cntAttempts ) { + while( idxAttempt <= cntAttempts ) { const isOnLine = rpcCall.checkUrl( u, nWaitStepMilliseconds ); if( ! isOnLine ) { ret = retValOnFail; @@ -293,7 +297,7 @@ export async function safeGetTransactionReceipt( } ++ idxAttempt; } - if( ( idxAttempt + 1 ) > cntAttempts && ( txReceipt === "" || txReceipt === undefined ) ) { + if( ( idxAttempt + 1 ) > cntAttempts ) { details.error( "Failed call to {} via {url} after {} attempts", strFnName + "()", u, cntAttempts ); throw new Error( `Failed call to ${strFnName}() via ${u} after ${cntAttempts} attempts` ); @@ -302,9 +306,10 @@ export async function safeGetTransactionReceipt( } export async function safeGetPastEvents( - details, strLogPrefix, - ethersProvider, cntAttempts, joContract, strEventName, - nBlockFrom, nBlockTo, joFilter, retValOnFail, throwIfServerOffline + details: any, strLogPrefix: string, + ethersProvider: any, cntAttempts: number, joContract: any, strEventName: string, + nBlockFrom: any, nBlockTo: any, joFilter: any, + retValOnFail?: any, throwIfServerOffline?: boolean ) { const u = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; @@ -404,9 +409,9 @@ export async function safeGetPastEvents( } export async function safeGetPastEventsIterative( - details, strLogPrefix, - ethersProvider, attempts, joContract, strEventName, - nBlockFrom, nBlockTo, joFilter + details: any, strLogPrefix: string, + ethersProvider: any, attempts: number, joContract: any, strEventName: string, + nBlockFrom: any, nBlockTo: any, joFilter: any ) { if( imaHelperAPIs.getBlocksCountInInIterativeStepOfEventsScan() <= 0 || imaHelperAPIs.getMaxIterationsInAllRangeEventsScan() <= 0 ) { diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 6783134f..7ea0f931 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -19,16 +19,16 @@ */ /** - * @file imaGasUsageOperations.mjs + * @file imaGasUsageOperations.ts * @copyright SKALE Labs 2019-Present */ import * as log from "./log"; import * as owaspUtils from "./owaspUtils"; -export function composeGasUsageReportFromArray( strName, jarrReceipts ) { +export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ) : any { if( ! ( strName && typeof strName == "string" && jarrReceipts ) ) - return ""; + return { "sumGasUsed": 0, "strReport": "N/A" }; let i, sumGasUsed = owaspUtils.toBN( "0" ), s = "\n" + log.fmtInformation( "Gas usage report for " ) + log.fmtInformation( "{p}\n", strName ); @@ -45,7 +45,8 @@ export function composeGasUsageReportFromArray( strName, jarrReceipts ) { return { "sumGasUsed": sumGasUsed, "strReport": s }; } -export function printGasUsageReportFromArray( strName, jarrReceipts, details ) { +export function printGasUsageReportFromArray( + strName: string, jarrReceipts: any[], details?: any ) { details = details || log; const jo: any = composeGasUsageReportFromArray( strName, jarrReceipts ); if( jo.strReport && typeof jo.strReport == "string" && jo.strReport.length > 0 && diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 7ff36837..9107e88b 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -19,7 +19,7 @@ */ /** - * @file imaHelperAPIs.mjs + * @file imaHelperAPIs.ts * @copyright SKALE Labs 2019-Present */ diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index b0bcc700..ddf2c8d9 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaOracleOperations.mjs + * @file imaOracleOperations.ts * @copyright SKALE Labs 2019-Present */ @@ -30,16 +30,16 @@ import * as imaTx from "./imaTx"; import * as imaGasUsage from "./imaGasUsageOperations"; import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -let gFlagIsEnabledOracle = false; +let gFlagIsEnabledOracle: boolean = false; export function getEnabledOracle() : boolean { return ( !!gFlagIsEnabledOracle ); } -export function setEnabledOracle( isEnabled ) { +export function setEnabledOracle( isEnabled: boolean ) : void { gFlagIsEnabledOracle = ( !!isEnabled ); } -async function prepareOracleGasPriceSetup( optsGasPriseSetup ) { +async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { optsGasPriseSetup.strActionName = "prepareOracleGasPriceSetup.optsGasPriseSetup.latestBlockNumber()"; optsGasPriseSetup.latestBlockNumber = @@ -56,8 +56,8 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup ) { optsGasPriseSetup.details.trace( "Local timestamp on Main Net is {}={} (original)", optsGasPriseSetup.bnTimestampOfBlock.toString(), owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimestampOfBlock.toHexString() ) ); - optsGasPriseSetup.bnTimeZoneOffset = owaspUtils.toBN( parseInt( new Date( parseInt( - optsGasPriseSetup.bnTimestampOfBlock.toString(), 10 ) ).getTimezoneOffset(), 10 ) ); + optsGasPriseSetup.bnTimeZoneOffset = owaspUtils.toBN( new Date( parseInt( + optsGasPriseSetup.bnTimestampOfBlock.toString(), 10 ) ).getTimezoneOffset() ); optsGasPriseSetup.details.trace( "Local time zone offset is {}={} (original)", optsGasPriseSetup.bnTimeZoneOffset.toString(), owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimeZoneOffset.toHexString() ) ); @@ -79,15 +79,15 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup ) { optsGasPriseSetup.strActionName = "prepareOracleGasPriceSetup.getGasPrice()"; optsGasPriseSetup.gasPriceOnMainNet = null; if( getEnabledOracle() ) { - const oracleOpts = { + const oracleOpts: any = { url: owaspUtils.ethersProviderToUrl( optsGasPriseSetup.ethersProviderSChain ), callOpts: { }, nMillisecondsSleepBefore: 1000, nMillisecondsSleepPeriod: 3000, cntAttempts: 40, - isVerbose: ( log.verboseGet() >= log.verboseReversed().information ) ? true : false, + isVerbose: ( log.verboseGet() >= log.verboseReversed()["information"] ) ? true : false, isVerboseTraceDetails: - ( log.verboseGet() >= log.verboseReversed().debug ) ? true : false + ( log.verboseGet() >= log.verboseReversed()["debug"] ) ? true : false }; optsGasPriseSetup.details.debug( "Will fetch Main Net gas price via call to Oracle with options {}...", oracleOpts ); @@ -127,7 +127,8 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup ) { } } -async function handleOracleSigned( optsGasPriseSetup, strError, u256, joGlueResult ) { +async function handleOracleSigned( + optsGasPriseSetup: any, strError: string, u256: any, joGlueResult: any ) { if( strError ) { optsGasPriseSetup.details.critical( "{p}Error in doOracleGasPriceSetup() during {bright}: {err}", @@ -148,7 +149,7 @@ async function handleOracleSigned( optsGasPriseSetup, strError, u256, joGlueResu let hint = joGlueResult ? joGlueResult.hint : null; if( ! hint ) hint = "0"; - const sign = { + const sign: any = { blsSignature: [ signature.X, signature.Y ], // BLS glue of signatures hashA: hashPoint.X, // G1.X from joGlueResult.hashSrc hashB: hashPoint.Y, // G1.Y from joGlueResult.hashSrc @@ -190,7 +191,7 @@ async function handleOracleSigned( optsGasPriseSetup, strError, u256, joGlueResu isIgnoreSetGasPrice, gasPrice, estimatedGasSetGasPrice, weiHowMuch ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { + const opts: any = { isCheckTransactionToSchain: ( optsGasPriseSetup.chainIdSChain !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( optsGasPriseSetup.details, @@ -212,18 +213,18 @@ async function handleOracleSigned( optsGasPriseSetup, strError, u256, joGlueResu } export async function doOracleGasPriceSetup( - ethersProviderMainNet, - ethersProviderSChain, - transactionCustomizerSChain, - joCommunityLocker, - joAccountSC, - chainIdMainNet, - chainIdSChain, - fnSignMsgOracle + ethersProviderMainNet: any, + ethersProviderSChain: any, + transactionCustomizerSChain: imaTx.TransactionCustomizer, + joCommunityLocker: any, + joAccountSC: any, + chainIdMainNet: string, + chainIdSChain: string, + fnSignMsgOracle: any ) { if( ! getEnabledOracle() ) - return; - const optsGasPriseSetup = { + return true; + const optsGasPriseSetup: any = { ethersProviderMainNet: ethersProviderMainNet, ethersProviderSChain: ethersProviderSChain, transactionCustomizerSChain: transactionCustomizerSChain, diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 65152754..41060c08 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -19,7 +19,7 @@ */ /** - * @file imaRegistrationOperations.mjs + * @file imaRegistrationOperations.ts * @copyright SKALE Labs 2019-Present */ @@ -29,11 +29,11 @@ import * as imaTx from "./imaTx"; import * as threadInfo from "./threadInfo"; export async function invokeHasChain( - details, - ethersProvider, // Main-Net or S-Chin - joLinker, // Main-Net or S-Chin - joAccount, // Main-Net or S-Chin - chainIdSChain + details: any, + ethersProvider: any, // Main-Net or S-Chin + joLinker: any, // Main-Net or S-Chin + joAccount: any, // Main-Net or S-Chin + chainIdSChain: string ) { const strLogPrefix = "Wait for added chain status: "; const strActionName = "invokeHasChain(hasSchain): joLinker.hasSchain"; @@ -52,22 +52,20 @@ export async function invokeHasChain( } export async function waitForHasChain( - details, - ethersProvider, // Main-Net or S-Chin - joLinker, // Main-Net or S-Chin - joAccount, // Main-Net or S-Chin - chainIdSChain, - cntWaitAttempts, - nSleepMilliseconds + details: any, + ethersProvider: any, // Main-Net or S-Chin + joLinker: any, // Main-Net or S-Chin + joAccount: any, // Main-Net or S-Chin + chainIdSChain: string, + cntWaitAttempts?: number, + nSleepMilliseconds?: number ) { - if( cntWaitAttempts == null || cntWaitAttempts == undefined ) + if( ! cntWaitAttempts ) cntWaitAttempts = 100; - if( nSleepMilliseconds == null || nSleepMilliseconds == undefined ) + if( ! nSleepMilliseconds ) nSleepMilliseconds = 5; for( let idxWaitAttempts = 0; idxWaitAttempts < cntWaitAttempts; ++ idxWaitAttempts ) { - if( await invokeHasChain( - details, ethersProvider, joLinker, joAccount, chainIdSChain - ) ) + if( await invokeHasChain( details, ethersProvider, joLinker, joAccount, chainIdSChain ) ) return true; details.trace( "Sleeping {} milliseconds...", nSleepMilliseconds ); await threadInfo.sleep( nSleepMilliseconds ); @@ -80,10 +78,10 @@ export async function waitForHasChain( // main-net.DepositBox call: function addSchain(string schainName, address tokenManagerAddress) // export async function checkIsRegisteredSChainInDepositBoxes( // step 1 - ethersProviderMainNet, - joLinker, - joAccountMN, - chainIdSChain + ethersProviderMainNet: any, + joLinker: any, + joAccountMN: any, + chainIdSChain: string ) { const details = log.createMemoryStream(); details.debug( "Main-net Linker address is...........{}", joLinker.address ); @@ -115,24 +113,24 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 } export async function registerSChainInDepositBoxes( // step 1 - ethersProviderMainNet, - joLinker, - joAccountMN, - joTokenManagerETH, // only s-chain - joTokenManagerERC20, // only s-chain - joTokenManagerERC721, // only s-chain - joTokenManagerERC1155, // only s-chain - joTokenManagerERC721WithMetadata, // only s-chain - joCommunityLocker, // only s-chain - joTokenManagerLinker, - chainNameSChain, - chainNameMainNet, - transactionCustomizerMainNet, - cntWaitAttempts, - nSleepMilliseconds + ethersProviderMainNet: any, + joLinker: any, + joAccountMN: any, + joTokenManagerETH: any, // only s-chain + joTokenManagerERC20: any, // only s-chain + joTokenManagerERC721: any, // only s-chain + joTokenManagerERC1155: any, // only s-chain + joTokenManagerERC721WithMetadata: any, // only s-chain + joCommunityLocker: any, // only s-chain + joTokenManagerLinker: any, + chainNameSChain: string, + chainNameMainNet: string, + transactionCustomizerMainNet: imaTx.TransactionCustomizer, + cntWaitAttempts?: number, + nSleepMilliseconds?: number ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any[] = []; details.debug( "Main-net Linker address is..........{}", joLinker.address ); details.debug( "S-Chain ID is.......................{}", chainNameSChain ); const strLogPrefix = "Reg S in depositBoxes: "; diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index 71fce684..a5a51206 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaReimbursementOperations.mjs + * @file imaReimbursementOperations.ts * @copyright SKALE Labs 2019-Present */ @@ -29,14 +29,14 @@ import * as imaTx from "./imaTx"; import * as imaGasUsage from "./imaGasUsageOperations"; export async function reimbursementShowBalance( - ethersProviderMainNet, - joCommunityPool, - joReceiverMainNet, - strChainNameMainNet, - chainIdMainNet, - transactionCustomizerMainNet, - strReimbursementChain, - isForcePrintOut + ethersProviderMainNet: any, + joCommunityPool: any, + joReceiverMainNet: any, + strChainNameMainNet: any, + chainIdMainNet: string, + transactionCustomizerMainNet: imaTx.TransactionCustomizer, + strReimbursementChain: string, + isForcePrintOut: boolean ) { const details = log.createMemoryStream(); let s = ""; @@ -70,14 +70,14 @@ export async function reimbursementShowBalance( } export async function reimbursementEstimateAmount( - ethersProviderMainNet, - joCommunityPool, - joReceiverMainNet, - strChainNameMainNet, - chainIdMainNet, - transactionCustomizerMainNet, - strReimbursementChain, - isForcePrintOut + ethersProviderMainNet: any, + joCommunityPool: any, + joReceiverMainNet: any, + strChainNameMainNet: string, + chainIdMainNet: string, + transactionCustomizerMainNet: imaTx.TransactionCustomizer, + strReimbursementChain: string, + isForcePrintOut: boolean ) { const details = log.createMemoryStream(); let s = ""; @@ -153,17 +153,17 @@ export async function reimbursementEstimateAmount( } export async function reimbursementWalletRecharge( - ethersProviderMainNet, - joCommunityPool, - joAccountMN, - strChainNameMainNet, - chainIdMainNet, - transactionCustomizerMainNet, - strReimbursementChain, - nReimbursementRecharge + ethersProviderMainNet: any, + joCommunityPool: any, + joAccountMN: any, + strChainNameMainNet: string, + chainIdMainNet: any, + transactionCustomizerMainNet: imaTx.TransactionCustomizer, + strReimbursementChain: string, + nReimbursementRecharge: any ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "Gas Reimbursement - Wallet Recharge "; try { @@ -215,17 +215,17 @@ export async function reimbursementWalletRecharge( } export async function reimbursementWalletWithdraw( - ethersProviderMainNet, - joCommunityPool, - joAccountMN, - strChainNameMainNet, - chainIdMainNet, - transactionCustomizerMainNet, - strReimbursementChain, - nReimbursementWithdraw + ethersProviderMainNet: any, + joCommunityPool: any, + joAccountMN: any, + strChainNameMainNet: string, + chainIdMainNet: string, + transactionCustomizerMainNet: imaTx.TransactionCustomizer, + strReimbursementChain: string, + nReimbursementWithdraw: any ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "Gas Reimbursement - Wallet Withdraw "; try { @@ -282,17 +282,17 @@ export async function reimbursementWalletWithdraw( } export async function reimbursementSetRange( - ethersProviderSChain, - joCommunityLocker, - joAccountSC, - strChainNameSChain, - chainIdSChain, - transactionCustomizerSChain, - strChainNameOriginChain, - nReimbursementRange + ethersProviderSChain: any, + joCommunityLocker: any, + joAccountSC: any, + strChainNameSChain: string, + chainIdSChain: string, + transactionCustomizerSChain: imaTx.TransactionCustomizer, + strChainNameOriginChain: string, + nReimbursementRange: any ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "Gas Reimbursement - Set Minimal time interval from S2M transfers "; try { @@ -320,7 +320,7 @@ export async function reimbursementSetRange( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: true }; + const opts: any = { isCheckTransactionToSchain: true }; const joReceipt = await imaTx.payedCall( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 070ad4f5..5e362a84 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -9,13 +9,13 @@ log.addStdout(); // allow self-signed wss and https process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; -function finalizeOutput( jo ) { +function finalizeOutput( jo: any ) { if( ! jo ) return; process.stdout.write( log.fmtInformation( "{}", jo ) ); } -function postConvertBN( jo, name ) { +function postConvertBN( jo: any, name: any ) { if( ! jo ) return; if( ! ( name in jo ) ) @@ -70,7 +70,7 @@ async function run() { const ethersProvider = owaspUtils.getEthersProviderFromURL( strURL ); - const tx = { + const tx: any = { data: tcData, to: txTo, value: owaspUtils.toBN( txValue ), @@ -88,15 +88,15 @@ async function run() { if( gIsDebugLogging ) log.debug( "--- TX hash ---> {}", txHash ); - const rpcCallOpts = { + const rpcCallOpts: any = { "cert": fs.readFileSync( strPathCert, "utf8" ), "key": fs.readFileSync( strPathKey, "utf8" ) }; - const joCall = await rpcCall.create( strSgxWalletURL, rpcCallOpts ); + const joCall: any = await rpcCall.create( strSgxWalletURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strSgxWalletURL}` ); - const joIn = { + const joIn: any = { "method": "ecdsaSignMessageHash", "params": { "keyName": "" + strSgxKeyName, @@ -104,7 +104,7 @@ async function run() { "base": 16 } }; - const joOut = await joCall.call( joIn ); + const joOut: any = await joCall.call( joIn ); try { if( gIsDebugLogging ) log.debug( "SGX wallet ECDSA sign result is: {}", joOut ); diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 8382ab50..b3bf9af2 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaTokenOperations.mjs + * @file imaTokenOperations.ts * @copyright SKALE Labs 2019-Present */ @@ -32,12 +32,12 @@ import * as imaEventLogScan from "./imaEventLogScan"; import * as threadInfo from "./threadInfo"; export async function getBalanceErc20( - isMainNet, - ethersProvider, - chainId, - joAccount, - strCoinName, - joABI + isMainNet: boolean, + ethersProvider: any, + chainId: string, + joAccount: any, + strCoinName: string, + joABI: any ) { const strLogPrefix = "getBalanceErc20() call "; try { @@ -61,13 +61,13 @@ export async function getBalanceErc20( } export async function getOwnerOfErc721( - isMainNet, - ethersProvider, - chainId, - joAccount, - strCoinName, - joABI, - idToken + isMainNet: boolean, + ethersProvider: any, + chainId: string, + joAccount: any, + strCoinName: string, + joABI: any, + idToken: any ) { const strLogPrefix = "getOwnerOfErc721() call "; try { @@ -75,7 +75,7 @@ export async function getOwnerOfErc721( joABI && ( strCoinName + "_address" ) in joABI ) ) return ""; const strAddress = joAccount.address(); - const contractERC721 = owaspUtils.ethersMod.ethers.Contract( + const contractERC721: any = new owaspUtils.ethersMod.ethers.Contract( joABI[strCoinName + "_address"], joABI[strCoinName + "_abi"], ethersProvider @@ -90,13 +90,13 @@ export async function getOwnerOfErc721( } export async function getBalanceErc1155( - isMainNet, - ethersProvider, - chainId, - joAccount, - strCoinName, - joABI, - idToken + isMainNet: boolean, + ethersProvider: any, + chainId: string, + joAccount: any, + strCoinName: string, + joABI: any, + idToken: any ) { const strLogPrefix = "getBalanceErc1155() call "; try { @@ -120,26 +120,26 @@ export async function getBalanceErc1155( } export async function doErc721PaymentFromMainNet( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joDepositBoxERC721, - joMessageProxyMainNet, // for checking logs - chainNameSChain, - tokenId, // which ERC721 token id to send - weiHowMuch, // how much ETH - joTokenManagerERC721, // only s-chain - strCoinNameErc721MainNet, - erc721PrivateTestnetJsonMainNet, - strCoinNameErc721SChain, - erc721PrivateTestnetJsonSChain, - transactionCustomizerMainNet + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joDepositBoxERC721: any, + joMessageProxyMainNet: any, // for checking logs + chainNameSChain: string, + tokenId: any, // which ERC721 token id to send + weiHowMuch: any, // how much ETH + joTokenManagerERC721: any, // only s-chain + strCoinNameErc721MainNet: string, + erc721PrivateTestnetJsonMainNet: any, + strCoinNameErc721SChain: string, + erc721PrivateTestnetJsonSChain: any, + transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "M2S ERC721 Payment: "; try { @@ -258,26 +258,26 @@ export async function doErc721PaymentFromMainNet( } export async function doErc20PaymentFromMainNet( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joDepositBoxERC20, - joMessageProxyMainNet, // for checking logs - chainNameSChain, - tokenAmount, // how much ERC20 tokens to send - weiHowMuch, // how much ETH - joTokenManagerERC20, // only s-chain - strCoinNameErc20MainNet, - erc20MainNet, - strCoinNameErc20SChain, - erc20SChain, - transactionCustomizerMainNet + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joDepositBoxERC20: any, + joMessageProxyMainNet: any, // for checking logs + chainNameSChain: string, + tokenAmount: any, // how much ERC20 tokens to send + weiHowMuch: any, // how much ETH + joTokenManagerERC20: any, // only s-chain + strCoinNameErc20MainNet: string, + erc20MainNet: any, + strCoinNameErc20SChain: string, + erc20SChain: any, + transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "M2S ERC20 Payment: "; try { @@ -395,27 +395,27 @@ export async function doErc20PaymentFromMainNet( } export async function doErc1155PaymentFromMainNet( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joDepositBoxERC1155, - joMessageProxyMainNet, // for checking logs - chainNameSChain, - tokenId, // which ERC1155 token id to send - tokenAmount, // which ERC1155 token id to send - weiHowMuch, // how much ETH - joTokenManagerERC1155, // only s-chain - strCoinNameErc1155SMainNet, - erc1155PrivateTestnetJsonMainNet, - strCoinNameErc1155SChain, - erc1155PrivateTestnetJsonSChain, - transactionCustomizerMainNet + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joDepositBoxERC1155: any, + joMessageProxyMainNet: any, // for checking logs + chainNameSChain: string, + tokenId: any, // which ERC1155 token id to send + tokenAmount: any, // which ERC1155 token id to send + weiHowMuch: any, // how much ETH + joTokenManagerERC1155: any, // only s-chain + strCoinNameErc1155SMainNet: string, + erc1155PrivateTestnetJsonMainNet: any, + strCoinNameErc1155SChain: string, + erc1155PrivateTestnetJsonSChain: any, + transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "M2S ERC1155 Payment: "; try { @@ -542,22 +542,23 @@ export async function doErc1155PaymentFromMainNet( } export async function doErc1155BatchPaymentFromMainNet( - ethersProviderMainNet, ethersProviderSChain, - chainIdMainNet, chainIdSChain, - joAccountSrc, joAccountDst, - joDepositBoxERC1155, - joMessageProxyMainNet, // for checking logs - chainNameSChain, - arrTokenIds, // which ERC1155 token id to send - arrTokenAmounts, // which ERC1155 token id to send - weiHowMuch, // how much ETH - joTokenManagerERC1155, // only s-chain - strCoinNameErc1155SMainNet, - erc1155PrivateTestnetJsonMainNet, strCoinNameErc1155SChain, - erc1155PrivateTestnetJsonSChain, transactionCustomizerMainNet + ethersProviderMainNet: any, ethersProviderSChain: any, + chainIdMainNet: string, chainIdSChain: string, + joAccountSrc: any, joAccountDst: any, + joDepositBoxERC1155: any, + joMessageProxyMainNet: any, // for checking logs + chainNameSChain: string, + arrTokenIds: any[], // which ERC1155 token id to send + arrTokenAmounts: any[], // which ERC1155 token id to send + weiHowMuch: any, // how much ETH + joTokenManagerERC1155: any, // only s-chain + strCoinNameErc1155SMainNet: string, + erc1155PrivateTestnetJsonMainNet: any, strCoinNameErc1155SChain: string, + erc1155PrivateTestnetJsonSChain: any, + transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "M2S ERC1155 Batch Payment: "; try { @@ -669,25 +670,25 @@ export async function doErc1155BatchPaymentFromMainNet( } export async function doErc20PaymentFromSChain( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joTokenManagerERC20, // only s-chain - joMessageProxySChain, // for checking logs - joDepositBox, // only main net - tokenAmount, // how much ERC20 tokens to send - weiHowMuch, // how much ETH - strCoinNameErc20MainNet, - joErc20MainNet, - strCoinNameErc20SChain, - joErc20SChain, - transactionCustomizerSChain + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joTokenManagerERC20: any, // only s-chain + joMessageProxySChain: any, // for checking logs + joDepositBox: any, // only main net + tokenAmount: any, // how much ERC20 tokens to send + weiHowMuch: any, // how much ETH + strCoinNameErc20MainNet: string, + joErc20MainNet: any, + strCoinNameErc20SChain: string, + joErc20SChain: any, + transactionCustomizerSChain: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "S2M ERC20 Payment: "; try { @@ -723,7 +724,7 @@ export async function doErc20PaymentFromSChain( weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts = { isCheckTransactionToSchain: true }; + const opts: any = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC20", contractERC20, "approve", arrArgumentsApprove, @@ -813,25 +814,25 @@ export async function doErc20PaymentFromSChain( } export async function doErc721PaymentFromSChain( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joTokenManagerERC721, // only s-chain - joMessageProxySChain, // for checking logs - joDepositBox, // only main net - tokenId, // which ERC721 token id to send - weiHowMuch, // how much ETH - strCoinNameErc721MainNet, - joErc721MainNet, - strCoinNameErc721SChain, - joErc721SChain, - transactionCustomizerSChain + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joTokenManagerERC721: any, // only s-chain + joMessageProxySChain: any, // for checking logs + joDepositBox: any, // only main net + tokenId: any, // which ERC721 token id to send + weiHowMuch: any, // how much ETH + strCoinNameErc721MainNet: string, + joErc721MainNet: any, + strCoinNameErc721SChain: string, + joErc721SChain: any, + transactionCustomizerSChain: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "S2M ERC721 Payment: "; try { @@ -869,7 +870,7 @@ export async function doErc721PaymentFromSChain( gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts = { isCheckTransactionToSchain: true }; + const opts: any = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC721", contractERC721, "approve", arrArgumentsApprove, @@ -961,26 +962,26 @@ export async function doErc721PaymentFromSChain( } export async function doErc1155PaymentFromSChain( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joTokenManagerERC1155, // only s-chain - joMessageProxySChain, // for checking logs - joDepositBox, // only main net - tokenId, // which ERC1155 token id to send - tokenAmount, // which ERC1155 token id to send - weiHowMuch, // how much ETH - strCoinNameErc1155SMainNet, - joErc1155MainNet, - strCoinNameErc1155SChain, - joErc1155Chain, - transactionCustomizerSChain + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joTokenManagerERC1155: any, // only s-chain + joMessageProxySChain: any, // for checking logs + joDepositBox: any, // only main net + tokenId: any, // which ERC1155 token id to send + tokenAmount: any, // which ERC1155 token id to send + weiHowMuch: any, // how much ETH + strCoinNameErc1155SMainNet: string, + joErc1155MainNet: any, + strCoinNameErc1155SChain: string, + joErc1155Chain: any, + transactionCustomizerSChain: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "S2M ERC1155 Payment: "; try { @@ -1017,7 +1018,7 @@ export async function doErc1155PaymentFromSChain( gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts = { isCheckTransactionToSchain: true }; + const opts: any = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, @@ -1108,26 +1109,26 @@ export async function doErc1155PaymentFromSChain( } export async function doErc1155BatchPaymentFromSChain( - ethersProviderMainNet, - ethersProviderSChain, - chainIdMainNet, - chainIdSChain, - joAccountSrc, - joAccountDst, - joTokenManagerERC1155, // only s-chain - joMessageProxySChain, // for checking logs - joDepositBox, // only main net - arrTokenIds, // which ERC1155 token ids to send - arrTokenAmounts, // which ERC1155 token amounts to send - weiHowMuch, // how much ETH - strCoinNameErc1155SMainNet, - joErc1155MainNet, - strCoinNameErc1155SChain, - joErc1155Chain, - transactionCustomizerSChain + ethersProviderMainNet: any, + ethersProviderSChain: any, + chainIdMainNet: string, + chainIdSChain: string, + joAccountSrc: any, + joAccountDst: any, + joTokenManagerERC1155: any, // only s-chain + joMessageProxySChain: any, // for checking logs + joDepositBox: any, // only main net + arrTokenIds: any[], // which ERC1155 token ids to send + arrTokenAmounts: any[], // which ERC1155 token amounts to send + weiHowMuch: any, // how much ETH + strCoinNameErc1155SMainNet: string, + joErc1155MainNet: any, + strCoinNameErc1155SChain: string, + joErc1155Chain: any, + transactionCustomizerSChain: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = "S2M ERC1155 Batch Payment: "; try { @@ -1160,7 +1161,7 @@ export async function doErc1155BatchPaymentFromSChain( gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts = { isCheckTransactionToSchain: true }; + const opts: any = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, @@ -1254,22 +1255,22 @@ export async function doErc1155BatchPaymentFromSChain( } export async function doErc20PaymentS2S( - isForward, - ethersProviderSrc, - chainIdSrc, - strChainNameDst, - joAccountSrc, - joTokenManagerERC20Src, - nAmountOfToken, // how much ERC20 tokens to send - nAmountOfWei, // how much to send - strCoinNameErc20Src, - joSrcErc20, - ercDstAddress20, // only reverse payment needs it - tc + isForward: boolean, + ethersProviderSrc: any, + chainIdSrc: string, + strChainNameDst: string, + joAccountSrc: any, + joTokenManagerERC20Src: any, + nAmountOfToken: any, // how much ERC20 tokens to send + nAmountOfWei: any, // how much to send + strCoinNameErc20Src: string, + joSrcErc20: any, + ercDstAddress20: any, // only reverse payment needs it + tc: imaTx.TransactionCustomizer ) { const isReverse = isForward ? false : true; const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = `S2S ERC20 Payment(${( isForward ? "forward" : "reverse" )}:): `; try { @@ -1394,22 +1395,22 @@ export async function doErc20PaymentS2S( } export async function doErc721PaymentS2S( - isForward, - ethersProviderSrc, - chainIdSrc, - strChainNameDst, - joAccountSrc, - joTokenManagerERC721Src, - tokenId, // which ERC721 token id to send - nAmountOfWei, // how much to send - strCoinNameErc721Src, - joSrcErc721, - ercDstAddress721, // only reverse payment needs it - tc + isForward: boolean, + ethersProviderSrc: any, + chainIdSrc: string, + strChainNameDst: string, + joAccountSrc: any, + joTokenManagerERC721Src: any, + tokenId: any, // which ERC721 token id to send + nAmountOfWei: any, // how much to send + strCoinNameErc721Src: string, + joSrcErc721: any, + ercDstAddress721: any, // only reverse payment needs it + tc: imaTx.TransactionCustomizer ) { const isReverse = isForward ? false : true; const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = `S2S ERC721 Payment(${( isForward ? "forward" : "reverse" )}: `; try { @@ -1538,23 +1539,23 @@ export async function doErc721PaymentS2S( } export async function doErc1155PaymentS2S( - isForward, - ethersProviderSrc, - chainIdSrc, - strChainNameDst, - joAccountSrc, - joTokenManagerERC1155Src, - tokenId, // which ERC721 token id to send - nAmountOfToken, // how much ERC1155 tokens to send - nAmountOfWei, // how much to send - strCoinNameErc1155Src, - joSrcErc1155, - ercDstAddress1155, // only reverse payment needs it - tc + isForward: boolean, + ethersProviderSrc: any, + chainIdSrc: string, + strChainNameDst: string, + joAccountSrc: any, + joTokenManagerERC1155Src: any, + tokenId: any, // which ERC721 token id to send + nAmountOfToken: any, // how much ERC1155 tokens to send + nAmountOfWei: any, // how much to send + strCoinNameErc1155Src: string, + joSrcErc1155: any, + ercDstAddress1155: any, // only reverse payment needs it + tc: imaTx.TransactionCustomizer ) { const isReverse = isForward ? false : true; const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = `S2S ERC1155 Payment(${( isForward ? "forward" : "reverse" )}): `; try { @@ -1683,23 +1684,23 @@ export async function doErc1155PaymentS2S( } export async function doErc1155BatchPaymentS2S( - isForward, - ethersProviderSrc, - chainIdSrc, - strChainNameDst, - joAccountSrc, - joTokenManagerERC1155Src, - arrTokenIds, // which ERC1155 token id to send - arrTokenAmounts, // which ERC1155 token id to send - nAmountOfWei, // how much to send - strCoinNameErc1155Src, - joSrcErc1155, - ercDstAddress1155, // only reverse payment needs it - tc + isForward: boolean, + ethersProviderSrc: any, + chainIdSrc: string, + strChainNameDst: string, + joAccountSrc: any, + joTokenManagerERC1155Src: any, + arrTokenIds: any[], // which ERC1155 token id to send + arrTokenAmounts: any[], // which ERC1155 token id to send + nAmountOfWei: any, // how much to send + strCoinNameErc1155Src: string, + joSrcErc1155: any, + ercDstAddress1155: any, // only reverse payment needs it + tc: imaTx.TransactionCustomizer ) { const isReverse = isForward ? false : true; const details = log.createMemoryStream(); - const jarrReceipts = []; + const jarrReceipts: any = []; let strActionName = ""; const strLogPrefix = `S2S Batch ERC1155 Payment(${( isForward ? "forward" : "reverse" )}: `; try { @@ -1830,15 +1831,15 @@ export async function doErc1155BatchPaymentS2S( } export async function mintErc20( - ethersProvider, - chainId, - chainName, - joAccount, - strAddressMintTo, - nAmount, - strTokenContractAddress, - joTokenContractABI, - tc + ethersProvider: any, + chainId: string, + chainName: string, + joAccount: any, + strAddressMintTo: string, + nAmount: any, + strTokenContractAddress: string, + joTokenContractABI: any, + tc: imaTx.TransactionCustomizer ) { let strActionName = "mintErc20() init"; const strLogPrefix = "mintErc20() call "; @@ -1876,7 +1877,7 @@ export async function mintErc20( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: ( chainNameDst !== "Mainnet" ) ? true : false }; + const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC20", contract, "mint", arrArgumentsMint, @@ -1899,15 +1900,15 @@ export async function mintErc20( } export async function mintErc721( - ethersProvider, - chainId, - chainName, - joAccount, - strAddressMintTo, - idToken, - strTokenContractAddress, - joTokenContractABI, - tc + ethersProvider: any, + chainId: string, + chainName: string, + joAccount: any, + strAddressMintTo: string, + idToken: any, + strTokenContractAddress: string, + joTokenContractABI: any, + tc: imaTx.TransactionCustomizer ) { let strActionName = "mintErc721() init"; const strLogPrefix = "mintErc721() call "; @@ -1945,7 +1946,7 @@ export async function mintErc721( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: ( chainNameDst !== "Mainnet" ) ? true : false }; + const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC721", contract, "mint", arrArgumentsMint, @@ -1968,16 +1969,16 @@ export async function mintErc721( } export async function mintErc1155( - ethersProvider, - chainId, - chainName, - joAccount, - strAddressMintTo, - idToken, - nAmount, - strTokenContractAddress, - joTokenContractABI, - tc + ethersProvider: any, + chainId: string, + chainName: any, + joAccount: any, + strAddressMintTo: string, + idToken: any, + nAmount: any, + strTokenContractAddress: string, + joTokenContractABI: any, + tc: imaTx.TransactionCustomizer ) { let strActionName = "mintErc1155() init"; const strLogPrefix = "mintErc1155() call "; @@ -2018,7 +2019,7 @@ export async function mintErc1155( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: ( chainNameDst !== "Mainnet" ) ? true : false }; + const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC1155", contract, "mint", arrArgumentsMint, @@ -2041,15 +2042,15 @@ export async function mintErc1155( } export async function burnErc20( - ethersProvider, - chainId, - chainName, - joAccount, - strAddressBurnFrom, - nAmount, - strTokenContractAddress, - joTokenContractABI, - tc + ethersProvider: any, + chainId: string, + chainName: string, + joAccount: any, + strAddressBurnFrom: string, + nAmount: any, + strTokenContractAddress: string, + joTokenContractABI: any, + tc: imaTx.TransactionCustomizer ) { let strActionName = "burnErc20() init"; const strLogPrefix = "burnErc20() call "; @@ -2087,7 +2088,7 @@ export async function burnErc20( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: ( chainNameDst !== "Mainnet" ) ? true : false }; + const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC20", contract, "burnFrom", arrArgumentsBurn, @@ -2110,14 +2111,14 @@ export async function burnErc20( } export async function burnErc721( - ethersProvider, - chainId, - chainName, - joAccount, - idToken, - strTokenContractAddress, - joTokenContractABI, - tc + ethersProvider: any, + chainId: string, + chainName: string, + joAccount: any, + idToken: any, + strTokenContractAddress: string, + joTokenContractABI: any, + tc: imaTx.TransactionCustomizer ) { let strActionName = "burnErc721() init"; const strLogPrefix = "burnErc721() call "; @@ -2153,7 +2154,7 @@ export async function burnErc721( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: ( chainNameDst !== "Mainnet" ) ? true : false }; + const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC721", contract, "burn", arrArgumentsBurn, @@ -2176,16 +2177,16 @@ export async function burnErc721( } export async function burnErc1155( - ethersProvider, - chainId, - chainName, - joAccount, - strAddressBurnFrom, - idToken, - nAmount, - strTokenContractAddress, - joTokenContractABI, - tc + ethersProvider: any, + chainId: string, + chainName: string, + joAccount: any, + strAddressBurnFrom: string, + idToken: any, + nAmount: any, + strTokenContractAddress: string, + joTokenContractABI: any, + tc: imaTx.TransactionCustomizer ) { let strActionName = "burnErc1155() init"; const strLogPrefix = "burnErc1155() call "; @@ -2225,7 +2226,7 @@ export async function burnErc1155( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts = { isCheckTransactionToSchain: ( chainNameDst !== "Mainnet" ) ? true : false }; + const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC1155", contract, "burn", arrArgumentsBurn, diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index df4e3d1d..28a4c619 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaTransferErrorHandling.mjs + * @file imaTransferErrorHandling.ts * @copyright SKALE Labs 2019-Present */ @@ -30,16 +30,16 @@ export function verifyTransferErrorCategoryName( strCategory ) { return "" + ( strCategory ? strCategory : "default" ); } -const gMaxLastTransferErrors = 20; -const gArrLastTransferErrors = []; -let gMapTransferErrorCategories = { }; +const gMaxLastTransferErrors: number = 20; +const gArrLastTransferErrors: any = []; +let gMapTransferErrorCategories: any = { }; export const saveTransferEvents = new EventDispatcher(); -export function saveTransferError( strCategory, textLog, ts ) { +export function saveTransferError( strCategory: string, textLog: any, ts?: any ) : void { ts = ts || Math.round( ( new Date() ).getTime() / 1000 ); const c = verifyTransferErrorCategoryName( strCategory ); - const joTransferEventError = { + const joTransferEventError: any = { "ts": ts, "category": "" + c, "textLog": "" + textLog.toString() @@ -54,7 +54,7 @@ export function saveTransferError( strCategory, textLog, ts ) { { "detail": joTransferEventError } ) ); } -export function saveTransferSuccess( strCategory ) { +export function saveTransferSuccess( strCategory: string ) : void { const c = verifyTransferErrorCategoryName( strCategory ); try { delete gMapTransferErrorCategories["" + c]; } catch ( err ) { } saveTransferEvents.dispatchEvent( @@ -63,12 +63,12 @@ export function saveTransferSuccess( strCategory ) { { "detail": { "category": strCategory } } ) ); } -export function saveTransferSuccessAll() { +export function saveTransferSuccessAll() : void { // clear all transfer error categories, out of time frame gMapTransferErrorCategories = { }; } -export function getLastTransferErrors( isIncludeTextLog ) { +export function getLastTransferErrors( isIncludeTextLog: boolean ) : any[] { if( typeof isIncludeTextLog == "undefined" ) isIncludeTextLog = true; const jarr = JSON.parse( JSON.stringify( gArrLastTransferErrors ) ); @@ -82,15 +82,15 @@ export function getLastTransferErrors( isIncludeTextLog ) { return jarr; } -export function getLastErrorCategories() { +export function getLastErrorCategories() : string[] { return Object.keys( gMapTransferErrorCategories ); } let gFlagIsEnabledProgressiveEventsScan = true; -export function getEnabledProgressiveEventsScan() { +export function getEnabledProgressiveEventsScan() : boolean { return ( !!gFlagIsEnabledProgressiveEventsScan ); } -export function setEnabledProgressiveEventsScan( isEnabled ) { +export function setEnabledProgressiveEventsScan( isEnabled: boolean ) : void { gFlagIsEnabledProgressiveEventsScan = ( !!isEnabled ); } diff --git a/src/imaTx.ts b/src/imaTx.ts index 15c8ab5d..1c4576ce 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file imaTx.mjs + * @file imaTx.ts * @copyright SKALE Labs 2019-Present */ @@ -39,16 +39,16 @@ import * as imaEventLogScan from "./imaEventLogScan"; import * as threadInfo from "./threadInfo"; -const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); +const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); -let redis = null; +let redis: any = null; -let gFlagDryRunIsEnabled = true; +let gFlagDryRunIsEnabled: boolean = true; -export function dryRunIsEnabled() { +export function dryRunIsEnabled() : boolean { return ( !!gFlagDryRunIsEnabled ); } -export function dryRunEnable( isEnable ) { +export function dryRunEnable( isEnable: any ) : boolean { gFlagDryRunIsEnabled = ( isEnable != null && isEnable != undefined ) ? ( !!isEnable ) : true; return ( !!gFlagDryRunIsEnabled ); @@ -56,23 +56,23 @@ export function dryRunEnable( isEnable ) { let gFlagDryRunIsIgnored = true; -export function dryRunIsIgnored() { +export function dryRunIsIgnored() : boolean { return ( !!gFlagDryRunIsIgnored ); } -export function dryRunIgnore( isIgnored ) { +export function dryRunIgnore( isIgnored: boolean ) : boolean { gFlagDryRunIsIgnored = ( isIgnored != null && isIgnored != undefined ) ? ( !!isIgnored ) : true; return ( !!gFlagDryRunIsIgnored ); } export async function dryRunCall( - details, - ethersProvider, - strContractName, joContract, strMethodName, arrArguments, - joAccount, strActionName, isDryRunResultIgnore, - gasPrice, gasValue, weiHowMuch, - opts + details: any, + ethersProvider: any, + strContractName: string, joContract: any, strMethodName: string, arrArguments: any[], + joAccount: any, strActionName: string, isDryRunResultIgnore: boolean, + gasPrice: any, gasValue: any, weiHowMuch: any, + opts?: any ) { if( ! dryRunIsEnabled() ) return null; // success @@ -97,7 +97,7 @@ export async function dryRunCall( details.trace( "Dry-run of action {bright}...", strActionName ); details.trace( "Will dry-run {}...", strContractCallDescription ); const strAccountWalletAddress = joAccount.address(); - const callOpts = { + const callOpts: any = { from: strAccountWalletAddress }; if( gasPrice ) @@ -119,7 +119,7 @@ export async function dryRunCall( } } -async function payedCallPrepare( optsPayedCall ) { +async function payedCallPrepare( optsPayedCall: any ) { optsPayedCall.joACI = getAccountConnectivityInfo( optsPayedCall.joAccount ); if( optsPayedCall.gasPrice ) { optsPayedCall.callOpts.gasPrice = @@ -160,8 +160,8 @@ async function payedCallPrepare( optsPayedCall ) { optsPayedCall.txHash ); } -async function payedCallTM( optsPayedCall ) { - const txAdjusted = +async function payedCallTM( optsPayedCall: any ) { + const txAdjusted: any = optsPayedCall.unsignedTx; // JSON.parse( JSON.stringify( optsPayedCall.rawTx ) ); const arrNamesConvertToHex = [ "gas", "gasLimit", "optsPayedCall.gasPrice", "value" ]; for( let idxName = 0; idxName < arrNamesConvertToHex.length; ++ idxName ) { @@ -200,14 +200,14 @@ async function payedCallTM( optsPayedCall ) { } } -async function payedCallSGX( optsPayedCall ) { +async function payedCallSGX( optsPayedCall: any ) { const tx = optsPayedCall.unsignedTx; let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); if( chainId == "string" ) chainId = owaspUtils.parseIntOrHex( chainId ); optsPayedCall.details.trace( "{p}Chain ID is: {}", optsPayedCall.strLogPrefix, chainId ); - const strCmd = "" + process.argv[0] + " --no-warnings ./imaSgxExternalSigner.mjs " + + const strCmd = "" + process.argv[0] + " --no-warnings ./imaSgxExternalSigner.ts " + ( log.isEnabledColorization() ? "true" : "false" ) + " " + "\"" + optsPayedCall.joAccount.strSgxURL + "\" " + "\"" + optsPayedCall.joAccount.strSgxKeyName + "\" " + @@ -224,15 +224,15 @@ async function payedCallSGX( optsPayedCall ) { "\"" + ( optsPayedCall.joAccount.strPathSslKey ? optsPayedCall.joAccount.strPathSslKey : "" ) + "\" " + ""; - const joSpawnOptions = { + const joSpawnOptions: any = { shell: true, cwd: __dirname, env: {}, encoding: "utf-8" }; const rv = childProcessModule.spawnSync( strCmd, joSpawnOptions ); - const strStdOutFromExternalInvocation = rv.stdout.toString( "utf8" ); - optsPayedCall.joReceipt = JSON.parse( strStdOutFromExternalInvocation.toString( "utf8" ) ); + const strStdOutFromExternalInvocation = rv.stdout.toString(); + optsPayedCall.joReceipt = JSON.parse( strStdOutFromExternalInvocation.toString() ); optsPayedCall.details.trace( "{p}Result from external SGX signer is: {}", optsPayedCall.strLogPrefix, optsPayedCall.joReceipt ); postConvertBN( optsPayedCall.joReceipt, "gasUsed" ); @@ -240,7 +240,7 @@ async function payedCallSGX( optsPayedCall ) { postConvertBN( optsPayedCall.joReceipt, "effectiveGasPrice" ); } -function postConvertBN( jo, name ) { +function postConvertBN( jo: any, name: any ) { if( ! jo ) return; if( ! ( name in jo ) ) @@ -250,7 +250,7 @@ function postConvertBN( jo, name ) { jo[name] = owaspUtils.toBN( jo[name] ); } -async function payedCallDirect( optsPayedCall ) { +async function payedCallDirect( optsPayedCall: any ) { const ethersWallet = new owaspUtils.ethersMod.ethers.Wallet( owaspUtils.ensureStartsWith0x( @@ -282,14 +282,13 @@ async function payedCallDirect( optsPayedCall ) { } export async function payedCall( - details, - ethersProvider, - strContractName, joContract, strMethodName, arrArguments, + details: any, ethersProvider: any, + strContractName: string, joContract: any, strMethodName: any, arrArguments: any[], joAccount, strActionName, - gasPrice, estimatedGas, weiHowMuch, - opts + gasPrice: any, estimatedGas: any, weiHowMuch: any, + opts?: any ) { - const optsPayedCall = { + const optsPayedCall: any = { details: details, ethersProvider: ethersProvider, strContractName: strContractName, @@ -381,10 +380,10 @@ export async function payedCall( } export async function checkTransactionToSchain( - unsignedTx, - details, - ethersProvider, - joAccount + unsignedTx: any, + details: any, + ethersProvider: any, + joAccount: any ) { const strLogPrefix = "PoW-mining: "; try { @@ -401,11 +400,11 @@ export async function checkTransactionToSchain( if( balance.lt( requiredBalance ) ) { details.warning( "{p}Insufficient funds for {}, will run PoW-mining to get {} of gas", strLogPrefix, strFromAddress, owaspUtils.toHexStringSafe( unsignedTx.gasLimit ) ); - let powNumber = await calculatePowNumber( + let powNumberBuffer = await calculatePowNumber( strFromAddress, owaspUtils.toBN( unsignedTx.nonce ).toHexString(), owaspUtils.toHexStringSafe( unsignedTx.gasLimit ), details, strLogPrefix ); - details.debug( "{p}Returned PoW-mining number {}", strLogPrefix, powNumber ); - powNumber = powNumber.toString().trim(); + details.debug( "{p}Returned PoW-mining number {}", strLogPrefix, powNumberBuffer ); + let powNumber: string = powNumberBuffer.toString( "utf8" ).trim(); powNumber = imaUtils.replaceAll( powNumber, "\r", "" ); powNumber = imaUtils.replaceAll( powNumber, "\n", "" ); powNumber = imaUtils.replaceAll( powNumber, "\t", "" ); @@ -415,9 +414,10 @@ export async function checkTransactionToSchain( throw new Error( "Failed to compute gas price with PoW-mining(1), got empty text" ); powNumber = owaspUtils.toBN( owaspUtils.ensureStartsWith0x( powNumber ) ); details.trace( "{p}BN PoW-mining number is {}", strLogPrefix, powNumber ); - if( powNumber.eq( owaspUtils.toBN( "0" ) ) ) + let powNumberBN = owaspUtils.toBN( powNumber); + if( powNumberBN.eq( owaspUtils.toBN( "0" ) ) ) throw new Error( "Failed to compute gas price with PoW-mining(2), got zero value" ); - unsignedTx.gasPrice = owaspUtils.toBN( powNumber.toHexString() ); + unsignedTx.gasPrice = owaspUtils.toBN( powNumberBN.toHexString() ); details.success( "{p}Success, finally (after PoW-mining) modified unsigned " + "transaction is {}", strLogPrefix, unsignedTx ); } else { @@ -431,7 +431,8 @@ export async function checkTransactionToSchain( return unsignedTx; } -export async function calculatePowNumber( address, nonce, gas, details, strLogPrefix ) { +export async function calculatePowNumber( + address: string, nonce: any, gas: any, details: any, strLogPrefix: string ) { try { let _address = owaspUtils.ensureStartsWith0x( address ); _address = ethereumJsUtilModule.toChecksumAddress( _address ); @@ -451,8 +452,8 @@ export async function calculatePowNumber( address, nonce, gas, details, strLogPr } } -export function getAccountConnectivityInfo( joAccount ) { - const joACI = { +export function getAccountConnectivityInfo( joAccount: any ) { + const joACI: any = { "isBad": true, "strType": "bad", "isAutoSend": false @@ -499,7 +500,7 @@ function tmMakeId( details ) { return id; } -function tmMakeRecord( tx = {}, score ) { +function tmMakeRecord( tx: any = {}, score ) { const status = "PROPOSED"; return JSON.stringify( { "score": score, @@ -527,7 +528,7 @@ async function tmSend( details, tx, priority = 5 ) { return id; } -function tmIsFinished( record ) { +function tmIsFinished( record: any ) { if( record == null ) return null; return [ "SUCCESS", "FAILED", "DROPPED" ].includes( record.status ); @@ -540,7 +541,7 @@ async function tmGetRecord( txId ) { return null; } -async function tmWait( details, txId, ethersProvider, nWaitSeconds = 36000 ) { +async function tmWait( details: any, txId: any, ethersProvider: any, nWaitSeconds: number = 36000 ) { const strLogPrefix = log.fmtDebug( "(gathered details)" ) + " "; details.debug( "{p}TM - will wait TX {} to complete for {} second(s) maximum", strLogPrefix, txId, nWaitSeconds ); @@ -561,7 +562,7 @@ async function tmWait( details, txId, ethersProvider, nWaitSeconds = 36000 ) { details.error( "{p}TM - TX {} was unsuccessful, wait failed", strLogPrefix, txId ); return null; } - const joReceipt = await imaEventLogScan.safeGetTransactionReceipt( + const joReceipt: any = await imaEventLogScan.safeGetTransactionReceipt( details, 10, ethersProvider, r.tx_hash ); if( !joReceipt ) { details.error( "{p}TM - TX {} was unsuccessful, failed to fetch transaction receipt", @@ -572,7 +573,8 @@ async function tmWait( details, txId, ethersProvider, nWaitSeconds = 36000 ) { } async function tmEnsureTransaction( - details, ethersProvider, priority, txAdjusted, cntAttempts, sleepMilliseconds + details: any, ethersProvider: any, priority: any, txAdjusted: any, + cntAttempts?: number, sleepMilliseconds?: number ) { cntAttempts = cntAttempts || 1; sleepMilliseconds = sleepMilliseconds || ( 30 * 1000 ); @@ -600,13 +602,15 @@ async function tmEnsureTransaction( } export class TransactionCustomizer { - constructor( gasPriceMultiplier, gasMultiplier ) { + gasPriceMultiplier: any; + gasMultiplier: any; + constructor( gasPriceMultiplier: any, gasMultiplier: any ) { this.gasPriceMultiplier = gasPriceMultiplier ? ( 0.0 + gasPriceMultiplier ) : null; // null means use current gasPrice or recommendedGasPrice this.gasMultiplier = gasMultiplier ? ( 0.0 + gasMultiplier ) : 1.25; } - async computeGasPrice( ethersProvider, maxGasPrice ) { + async computeGasPrice( ethersProvider: any, maxGasPrice: any ) { const gasPrice = owaspUtils.parseIntOrHex( owaspUtils.toBN( @@ -632,14 +636,14 @@ export class TransactionCustomizer { return gasPrice; } async computeGas( - details, - ethersProvider, - strContractName, joContract, strMethodName, arrArguments, - joAccount, strActionName, - gasPrice, gasValueRecommended, weiHowMuch, - opts + details: any, + ethersProvider: any, + strContractName: string, joContract: any, strMethodName: string, arrArguments: any[], + joAccount: any, strActionName: string, + gasPrice: any, gasValueRecommended: any, weiHowMuch: any, + opts?: any ) { - let estimatedGas = 0; + let estimatedGas: any = 0; const strContractMethodDescription = log.fmtDebug( "{p}({}).{sunny}", strContractName, joContract.address, strMethodName ); let strArgumentsDescription = ""; @@ -660,7 +664,7 @@ export class TransactionCustomizer { details.trace( "Estimate-gas of action {bright}...", strActionName ); details.trace( "Will estimate-gas {}...", strContractCallDescription ); const strAccountWalletAddress = joAccount.address(); - const callOpts = { from: strAccountWalletAddress }; + const callOpts: any = { from: strAccountWalletAddress }; if( gasPrice ) callOpts.gasPrice = owaspUtils.toBN( gasPrice ).toHexString(); if( gasValueRecommended ) @@ -690,25 +694,25 @@ export class TransactionCustomizer { } }; -let gTransactionCustomizerMainNet = null; -let gTransactionCustomizerSChain = null; -let gTransactionCustomizerSChainTarget = null; +let gTransactionCustomizerMainNet: TransactionCustomizer|null = null; +let gTransactionCustomizerSChain: TransactionCustomizer|null = null; +let gTransactionCustomizerSChainTarget: TransactionCustomizer|null = null; -export function getTransactionCustomizerForMainNet() { +export function getTransactionCustomizerForMainNet() : TransactionCustomizer { if( gTransactionCustomizerMainNet ) return gTransactionCustomizerMainNet; gTransactionCustomizerMainNet = new TransactionCustomizer( 1.25, 1.25 ); return gTransactionCustomizerMainNet; } -export function getTransactionCustomizerForSChain() { +export function getTransactionCustomizerForSChain() : TransactionCustomizer { if( gTransactionCustomizerSChain ) return gTransactionCustomizerSChain; gTransactionCustomizerSChain = new TransactionCustomizer( null, 1.25 ); return gTransactionCustomizerSChain; } -export function getTransactionCustomizerForSChainTarget() { +export function getTransactionCustomizerForSChainTarget() : TransactionCustomizer { if( gTransactionCustomizerSChainTarget ) return gTransactionCustomizerSChainTarget; gTransactionCustomizerSChainTarget = new TransactionCustomizer( null, 1.25 ); diff --git a/src/log.ts b/src/log.ts index c952270e..57e40663 100644 --- a/src/log.ts +++ b/src/log.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file log.mjs + * @file log.ts * @copyright SKALE Labs 2019-Present */ @@ -124,7 +124,7 @@ export function getStreamWithFilePath( strFilePath: string ) : any { export function createStandardOutputStream() : any { try { - const objEntry = { + const objEntry: any = { "id": gIdentifierAllocatorCounter ++, "strPath": "stdout", "nMaxSizeBeforeRotation": -1, @@ -235,7 +235,7 @@ export function insertStandardOutputStream() : boolean { export function createMemoryOutputStream() : any { try { - const objEntry = { + const objEntry: any = { "id": gIdentifierAllocatorCounter ++, "strPath": "memory", "nMaxSizeBeforeRotation": -1, @@ -410,7 +410,7 @@ export function insertMemoryOutputStream() : boolean { export function createFileOutput( strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : any { try { - const objEntry = { + const objEntry: any = { "id": gIdentifierAllocatorCounter ++, "strPath": "" + strFilePath, "nMaxSizeBeforeRotation": 0 + ( nMaxSizeBeforeRotation || 0 ), diff --git a/src/loop.ts b/src/loop.ts index 4b29b687..26e7fb70 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file loop.mjs + * @file loop.ts * @copyright SKALE Labs 2019-Present */ @@ -38,11 +38,12 @@ import * as skaleObserver from "./observer"; import * as pwa from "./pwa"; import * as state from "./state"; -const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); +const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); // Run transfer loop -export function checkTimeFraming( d, strDirection, joRuntimeOpts ) { +export function checkTimeFraming( + d: Date|null, strDirection: string, joRuntimeOpts: any ) : boolean { try { const imaState = state.get(); if( imaState.nTimeFrameSeconds <= 0 || imaState.nNodesCount <= 1 ) @@ -127,7 +128,7 @@ export function checkTimeFraming( d, strDirection, joRuntimeOpts ) { return true; }; -async function singleTransferLoopPartOracle( optsLoop, strLogPrefix ) { +async function singleTransferLoopPartOracle( optsLoop: any, strLogPrefix: string ) { const imaState = state.get(); let b0 = true; if( optsLoop.enableStepOracle && imaOracleOperations.getEnabledOracle() ) { @@ -142,7 +143,7 @@ async function singleTransferLoopPartOracle( optsLoop, strLogPrefix ) { if( checkTimeFraming( null, "oracle", optsLoop.joRuntimeOpts ) ) { imaState.loopState.oracle.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "oracle" ); - b0 = imaOracleOperations.doOracleGasPriceSetup( + b0 = await imaOracleOperations.doOracleGasPriceSetup( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.transactionCustomizer, @@ -172,7 +173,7 @@ async function singleTransferLoopPartOracle( optsLoop, strLogPrefix ) { return b0; } -async function singleTransferLoopPartM2S( optsLoop, strLogPrefix ) { +async function singleTransferLoopPartM2S( optsLoop: any, strLogPrefix: string ) { const imaState = state.get(); let b1 = true; if( optsLoop.enableStepM2S ) { @@ -233,7 +234,7 @@ async function singleTransferLoopPartM2S( optsLoop, strLogPrefix ) { return b1; } -async function singleTransferLoopPartS2M( optsLoop, strLogPrefix ) { +async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) { const imaState = state.get(); let b2 = true; if( optsLoop.enableStepS2M ) { @@ -295,7 +296,7 @@ async function singleTransferLoopPartS2M( optsLoop, strLogPrefix ) { return b2; } -async function singleTransferLoopPartS2S( optsLoop, strLogPrefix ) { +async function singleTransferLoopPartS2S( optsLoop: any, strLogPrefix: string ) { const imaState = state.get(); let b3 = true; if( optsLoop.enableStepS2S && imaState.optsS2S.isEnabled ) { @@ -333,12 +334,12 @@ async function singleTransferLoopPartS2S( optsLoop, strLogPrefix ) { return b3; } -function printLoopPartSkippedWarning( strLoopPartName ) { - log.warning( "{p}Skipped {} transfer loop part due to other single transfer loop is in " + - "progress right now", strLogPrefix, strLoopPartName ); +function printLoopPartSkippedWarning( strLoopPartName: string ) { + log.warning( "Skipped {} transfer loop part due to other single transfer loop is in " + + "progress right now", strLoopPartName ); } -export async function singleTransferLoop( optsLoop ) { +export async function singleTransferLoop( optsLoop: any ) { const imaState = state.get(); const strLogPrefix = `Single Loop in ${threadInfo.threadDescription( false )} `; try { @@ -399,14 +400,14 @@ export async function singleTransferLoop( optsLoop ) { imaState.loopState.s2s.isInProgress = false; return false; } -export async function singleTransferLoopWithRepeat( optsLoop ) { +export async function singleTransferLoopWithRepeat( optsLoop: any ) { const imaState = state.get(); await singleTransferLoop( optsLoop ); setTimeout( async function() { await singleTransferLoopWithRepeat( optsLoop ); }, imaState.nLoopPeriodSeconds * 1000 ); }; -export async function runTransferLoop( optsLoop ) { +export async function runTransferLoop( optsLoop: any ) { const imaState = state.get(); const isDelayFirstRun = owaspUtils.toBoolean( optsLoop.isDelayFirstRun ); if( isDelayFirstRun ) { @@ -420,10 +421,10 @@ export async function runTransferLoop( optsLoop ) { // Parallel thread based loop -const gArrWorkers = []; -const gArrClients = []; +const gArrWorkers: any[] = []; +const gArrClients: any[] = []; -function constructChainProperties( opts ) { +function constructChainProperties( opts: any ) { return { "mn": { "joAccount": { @@ -488,8 +489,8 @@ function constructChainProperties( opts ) { }; } -function getDefaultOptsLoop( idxWorker ) { - const optsLoop = { +function getDefaultOptsLoop( idxWorker: number ) { + const optsLoop: any = { joRuntimeOpts: { isInsideWorker: true, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }, @@ -502,19 +503,19 @@ function getDefaultOptsLoop( idxWorker ) { return optsLoop; } -export async function ensureHaveWorkers( opts ) { +export async function ensureHaveWorkers( opts: any ) { if( gArrWorkers.length > 0 ) return gArrWorkers; const cntWorkers = 2; log.debug( "Loop module will create its ", cntWorkers, " worker(s) in ", threadInfo.threadDescription(), "..." ); for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) { - const workerData = { + const workerData: any = { "url": "ima_loop_server" + idxWorker, "colorization": { isEnabled: log.isEnabledColorization() } }; gArrWorkers.push( new threadInfo.Worker( - path.join( __dirname, "loopWorker.mjs" ), + path.join( __dirname, "loopWorker.ts" ), { "type": "module", "workerData": workerData } ) ); gArrWorkers[idxWorker].on( "message", jo => { @@ -664,7 +665,7 @@ export async function ensureHaveWorkers( opts ) { gArrWorkers.length, " worker(s) in ", threadInfo.threadDescription() ); } -export async function runParallelLoops( opts ) { +export async function runParallelLoops( opts: any ) { log.notice( "Will start parallel IMA transfer loops in {}...", threadInfo.threadDescription() ); await ensureHaveWorkers( opts ); log.success( "Done, did started parallel IMA transfer loops in {}, have {} worker(s) and {} " + @@ -672,7 +673,7 @@ export async function runParallelLoops( opts ) { return true; } -export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage ) { +export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) { if( ! ( joMessage && typeof joMessage == "object" && "method" in joMessage && joMessage.method == "skale_imaNotifyLoopWork" ) ) @@ -683,9 +684,9 @@ export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage ) { } -export async function spreadUpdatedSChainNetwork( isFinal ) { +export async function spreadUpdatedSChainNetwork( isFinal: boolean ) { const imaState = state.get(); - const joMessage = { + const joMessage: any = { "method": "spreadUpdatedSChainNetwork", "isFinal": ( !!isFinal ), "joSChainNetworkInfo": imaState.joSChainNetworkInfo diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 49c424a8..6c7d8701 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file loopWorker.mjs + * @file loopWorker.ts * @copyright SKALE Labs 2019-Present */ @@ -45,9 +45,9 @@ if( parentPort ) { } ); } -function doSendMessage( type, endpoint, workerUUID, data ) { +function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = networkLayer.socketReceivedDataReverseMarshall( data ); - const joSend = { + const joSend: any = { "workerMessageType": ( type && typeof type == "string" && type.length > 0 ) ? type @@ -65,7 +65,7 @@ class ObserverServer extends SocketServer { opts: any; intervalPeriodicSchainsCaching: number|null; bIsPeriodicCachingStepInProgress: boolean; - constructor( acceptor ) { + constructor( acceptor: any ) { super( acceptor ); const self: any = this; self.initComplete = false; @@ -211,7 +211,7 @@ class ObserverServer extends SocketServer { workerData.url, threadInfo.threadDescription() ); } dispose() { - const self:any = this; + const self: any = this; self.isDisposing = true; if( self.intervalPeriodicSchainsCaching ) { clearInterval( self.intervalPeriodicSchainsCaching ); @@ -220,7 +220,7 @@ class ObserverServer extends SocketServer { super.dispose(); } initLogMethods() { - const self:any = this; + const self: any = this; if( "fatal" in self && self.fatal && typeof self.fatal == "function" ) return; self.fatal = function( ...args: any[] ) { @@ -301,7 +301,7 @@ class ObserverServer extends SocketServer { const acceptor = new networkLayer.InWorkerSocketServerAcceptor( workerData.url, doSendMessage ); const server = new ObserverServer( acceptor ); server.on( "dispose", function() { - const self:any = server; + const self: any = server; self.debug( "Disposed in-worker in {} IMA loop {}", threadInfo.threadDescription(), workerData.url ); } ); diff --git a/src/main.ts b/src/main.ts index ff5580ac..48bccb93 100644 --- a/src/main.ts +++ b/src/main.ts @@ -19,7 +19,7 @@ */ /** - * @file main.mjs + * @file main.ts * @copyright SKALE Labs 2019-Present */ diff --git a/src/observer.ts b/src/observer.ts index 9a3896d0..c9fade2a 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -19,7 +19,7 @@ */ /** - * @file observer.mjs + * @file observer.ts * @copyright SKALE Labs 2019-Present */ diff --git a/src/oracle.ts b/src/oracle.ts index a867d78d..84b868a8 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -19,7 +19,7 @@ */ /** - * @file oracle.mjs + * @file oracle.ts * @copyright SKALE Labs 2019-Present */ diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index db87b61a..962c377e 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -7,7 +7,7 @@ * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file owaspUtils.mjs + * @file owaspUtils.ts * @copyright SKALE Labs 2019-Present */ @@ -456,7 +456,7 @@ export function ipFromHex( hex?: any ) : string { } export function cloneObjectByRootKeys( joIn?: any ) : any { - const joOut = { }, arrKeys = Object.keys( joIn ); + const joOut: any = { }, arrKeys = Object.keys( joIn ); for( let i = 0; i < arrKeys.length; ++ i ) { const key = arrKeys[i]; const value = joIn[key]; diff --git a/src/pwa.ts b/src/pwa.ts index 19376ff7..420ff6b4 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -19,7 +19,7 @@ */ /** - * @file pwa.mjs + * @file pwa.ts * @copyright SKALE Labs 2019-Present */ @@ -87,7 +87,7 @@ function getNodeProgressAndTimestamp( joNode: any, strLoopWorkType: string, nInd } export async function checkOnLoopStart( - imaState: any, strLoopWorkType: string, nIndexS2S: number ) { + imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) @@ -205,7 +205,7 @@ export async function handleLoopStateArrived( } async function notifyOnLoopImpl( - imaState: any, strLoopWorkType: string, nIndexS2S: number, isStart: boolean ) { + imaState: any, strLoopWorkType: string, isStart: boolean, nIndexS2S?: number ) { const se = isStart ? "start" : "end"; try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined @@ -238,7 +238,7 @@ async function notifyOnLoopImpl( continue; // skip this node const joNode: any = jarrNodes[i]; const strNodeURL = imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ); - const rpcCallOpts = null; + const rpcCallOpts: any = null; let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) .catch( async function( err ) { log.error( @@ -275,10 +275,10 @@ async function notifyOnLoopImpl( return true; } -export async function notifyOnLoopStart( imaState, strLoopWorkType, nIndexS2S ) { - return await notifyOnLoopImpl( imaState, strLoopWorkType, nIndexS2S, true ); +export async function notifyOnLoopStart( imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { + return await notifyOnLoopImpl( imaState, strLoopWorkType, true, nIndexS2S ); } -export async function notifyOnLoopEnd( imaState, strLoopWorkType, nIndexS2S ) { - return await notifyOnLoopImpl( imaState, strLoopWorkType, nIndexS2S, false ); +export async function notifyOnLoopEnd( imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { + return await notifyOnLoopImpl( imaState, strLoopWorkType, false, nIndexS2S ); } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index ec60ff11..208e4c19 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -7,7 +7,7 @@ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file rpcCall.mjs + * @file rpcCall.ts * @copyright SKALE Labs 2019-Present */ @@ -234,7 +234,7 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" ) { const u = new URL( joCall.url ); - const options = { + const options: any = { "hostname": u.hostname, "port": u.port, "path": "/", @@ -348,7 +348,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { throw new Error( "rpcCallCreate() was invoked with " + `bad parameters: ${JSON.stringify( arguments )}` ); } - const joCall = { + const joCall: any = { "url": "" + strURL, "joRpcOptions": opts ? opts : null, "mapPendingByCallID": { }, @@ -390,7 +390,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { "{url} JSON RPC call(awaiter) error: {err}", strURL, err ); } ); }, - "disconnect": async function( fnAfter ) { + "disconnect": async function( fnAfter?: any ) { await doDisconnect( joCall, fnAfter ); } }; diff --git a/src/socket.ts b/src/socket.ts index b25461a1..4ff604b4 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -7,7 +7,7 @@ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file socket.mjs + * @file socket.ts * @copyright SKALE Labs 2019-Present */ @@ -41,7 +41,7 @@ export function setWebRtcModule( mod: any ) : void { webRtcModule = mod ? mod : null; } -export const gMapLocalServers = { }; // used both for local and in-worker servers +export const gMapLocalServers: any = { }; // used both for local and in-worker servers export const socketSentDataMarshall = function( data?: any ) : void { const s = data @@ -83,7 +83,7 @@ export const updateSocketDataStatsForMessage = function( joMessage: any, joStats joStats[strMethod] = 1; }; export const generateSocketDataStatsJSON = function( jo: any ) { - const joStats = {}; + const joStats: any = {}; if( "arrPackedMessages" in jo && jo.arrPackedMessages && typeof jo.arrPackedMessages == "object" @@ -103,8 +103,6 @@ export class BasicServerAcceptor extends EventDispatcher { strEndPoint: string|null; nextClientNumber: number; mapClients: any; - isDisposing: boolean; - isDisposed: boolean; url: string; constructor() { super(); @@ -201,10 +199,10 @@ export class BasicSocketPipe extends EventDispatcher { maxAccumulatedMessagesCount: number; relayClientSocket: any; mapImpersonatedEntries: any; // for external in-app usage only - isDisposing: boolean; - isDisposed: boolean; acceptor: any; clientPort: any; + logicalInitComplete: any; // for external use + errorLogicalInit: any; // for external use constructor() { super(); this.socketType = "N/A"; @@ -260,7 +258,7 @@ export class BasicSocketPipe extends EventDispatcher { socketLoggingTextPrefix( strLogEventName: string ) { return "" + strLogEventName + " " + this.socketDescription() + " -"; } - send( data: any, isFlush: boolean ) { + send( data: any, isFlush?: boolean ) { if( this.isDisposed || ( !this.isConnected ) ) return; if( this.isAutoFlush() ) { @@ -389,7 +387,7 @@ export const gMapAwaitingInWorkerClients = { }; // in-worker clients in connecting state export const gMapConnectedInWorkerClients = { }; -export const outOfWorkerAPIs = { +export const outOfWorkerAPIs: any = { "onMessage": function( worker: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); if( ! ( "workerMessageType" in jo ) || @@ -428,7 +426,7 @@ export const outOfWorkerAPIs = { }, "onSendMessage": function( worker: any, type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); - const joSend = { + const joSend: any = { "workerMessageType": ( type && typeof type == "string" && type.length > 0 ) ? type : "inWorkerMessage", @@ -440,7 +438,7 @@ export const outOfWorkerAPIs = { worker.postMessage( socketSentDataMarshall( joSend ) ); } }; -export const inWorkerAPIs = { +export const inWorkerAPIs: any = { "onMessage": function( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); if( ! ( "workerMessageType" in jo ) || @@ -471,7 +469,7 @@ export const inWorkerAPIs = { }, "onSendMessage": function( type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); - const joSend = { + const joSend: any = { "workerMessageType": ( type && typeof type == "string" && type.length > 0 ) ? type : "inWorkerMessage", @@ -612,7 +610,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { worker: any; fnSend: any; strEndPoint: string; - constructor( strEndPoint: string, worker: any, fnSend: any ) { + constructor( strEndPoint: string, worker: any, fnSend?: any ) { super(); this.socketType = "InWorker"; this.socketSubtype = "client"; @@ -688,8 +686,6 @@ export class OutOfWorkerRelay extends EventDispatcher { acceptor: any; fnCreateClient: any; onConnection_: any; - isDisposing: any; - isDisposed: any; // eslint-disable-next-line max-lines-per-function constructor( strRelayName: string, acceptor: any, fnCreateClient: any, @@ -928,8 +924,6 @@ export class OneToOneRelay extends EventDispatcher { isAutoFlushOutgoing: boolean; pipeIncoming: any; pipeOutgoing: any; - isDisposing: boolean; - isDisposed: boolean; // eslint-disable-next-line max-lines-per-function constructor( strRelayName: string, pipeIncoming: any, pipeOutgoing: any, @@ -1703,8 +1697,6 @@ export class RTCConnection extends EventDispatcher { iceComplete: any; pc: any; dc: any; - isDisposing: boolean; - isDisposed: boolean; constructor( strSignalingServerURL?: string, idRtcParticipant?: string ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); diff --git a/src/socketServer.ts b/src/socketServer.ts index b282e004..ece5904d 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -19,7 +19,7 @@ */ /** - * @file socketServer.mjs + * @file socketServer.ts * @copyright SKALE Labs 2019-Present */ @@ -36,7 +36,6 @@ export class SocketServer extends EventDispatcher { isLogSocketErrors: boolean; isLogSocketTraffic: boolean; isLogSocketTrafficRaw: boolean; - isDisposing: boolean; constructor( acceptor: any ) { super(); if( acceptor == null || acceptor == undefined || typeof acceptor != "object" ) diff --git a/src/socketSettings.ts b/src/socketSettings.ts index 7826d084..107bf312 100644 --- a/src/socketSettings.ts +++ b/src/socketSettings.ts @@ -19,7 +19,7 @@ */ /** - * @file socketSettings.mjs + * @file socketSettings.ts * @copyright SKALE Labs 2019-Present */ diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 57878beb..6fb62c21 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -7,7 +7,7 @@ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ */ /** - * @file socketUtils.mjs + * @file socketUtils.ts * @copyright SKALE Labs 2019-Present */ @@ -124,7 +124,7 @@ export const randomDirectPipeID = function() : string { }; export const prepareAnswerJSON = function( joMessage: any ) : any { - const joAnswer = { + const joAnswer: any = { "id": "" + ( ( joMessage != null && joMessage != undefined && diff --git a/src/state.ts b/src/state.ts index 95f0e451..11e81873 100644 --- a/src/state.ts +++ b/src/state.ts @@ -1,7 +1,7 @@ import * as owaspUtils from "./owaspUtils"; import * as imaTx from "./imaTx"; -export const gDefaultValueForLoopState = { +export const gDefaultValueForLoopState: any = { "oracle": { "isInProgress": false, "wasInProgress": false diff --git a/src/threadInfo.ts b/src/threadInfo.ts index 38527dcf..73f1e7a2 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -19,7 +19,7 @@ */ /** - * @file loop.mjs + * @file loop.ts * @copyright SKALE Labs 2019-Present */ diff --git a/src/utils.ts b/src/utils.ts index 0d98733a..e5866f76 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -19,7 +19,7 @@ */ /** - * @file utils.mjs + * @file utils.ts * @copyright SKALE Labs 2019-Present */ @@ -84,7 +84,7 @@ export function fileSave( strPath: string, s: string ) : boolean { return false; } -export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boolean ) : boolean { +export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boolean ) : any { if( bLogOutput == undefined || bLogOutput == null ) bLogOutput = false; joDefault = joDefault || {}; @@ -112,7 +112,7 @@ export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boo return joDefault; } -export function jsonFileSave( strPath: string, jo?: any, bLogOutput?: boolean ) : boolean { +export function jsonFileSave( strPath: string, jo?: any, bLogOutput?: boolean ) : any { if( bLogOutput == undefined || bLogOutput == null ) bLogOutput = false; if( bLogOutput ) From 929ac583f359dfc9c6a6637d027a91b9e1ab940c Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Mon, 11 Dec 2023 17:48:28 +0000 Subject: [PATCH 05/53] code porting to TypeScript --- src/bls.ts | 54 ++++----- src/cc.ts | 22 ++-- src/cli.ts | 178 ++++++++++++++--------------- src/clpTools.ts | 13 ++- src/discoveryTools.ts | 14 +-- src/eventDispatcher.ts | 5 +- src/imaCore.ts | 103 ++++++++--------- src/imaEthOperations.ts | 12 +- src/imaEventLogScan.ts | 14 +-- src/imaHelperAPIs.ts | 6 +- src/imaOracleOperations.ts | 21 ++-- src/imaRegistrationOperations.ts | 6 +- src/imaReimbursementOperations.ts | 10 +- src/imaTokenOperations.ts | 42 +++---- src/imaTransferErrorHandling.ts | 2 +- src/imaTx.ts | 28 ++--- src/log.ts | 127 +++++++++++---------- src/loop.ts | 19 ++-- src/loopWorker.ts | 41 +++---- src/main.ts | 25 +++-- src/oracle.ts | 4 +- src/owaspUtils.ts | 32 +++--- src/package.json | 12 +- src/pwa.ts | 8 +- src/rpcCall.ts | 56 +++++----- src/socket.ts | 106 +++++++++--------- src/socketServer.ts | 18 +-- src/state.ts | 6 +- src/tsconfig.json | 18 +++ src/utils.ts | 6 +- src/yarn.lock | 179 ++++++++++++++++++++++++------ 31 files changed, 671 insertions(+), 516 deletions(-) create mode 100644 src/tsconfig.json diff --git a/src/bls.ts b/src/bls.ts index d0f7e186..5a10b221 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -29,7 +29,7 @@ import * as log from "./log"; import * as owaspUtils from "./owaspUtils"; import * as childProcessModule from "child_process"; import * as rpcCall from "./rpcCall"; -import * as shellModule from "shelljs"; +import * as shell from "shelljs"; import * as imaUtils from "./utils"; import * as sha3Module from "sha3"; import * as skaleObserver from "./observer"; @@ -38,8 +38,6 @@ import * as threadInfo from "./threadInfo"; import * as utils from "./socketUtils"; import * as state from "./state"; -const shell = shellModule.default; - const Keccak = sha3Module.Keccak; function discoverBlsThreshold( joSChainNetworkInfo: any ) : number { @@ -354,7 +352,7 @@ function performBlsGlue( fnShellRestore(); } catch ( err ) { details.critical( "{p}BLS glue error description is: {err}, stack is: \n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); details.critical( "{p}BLS glue output is:\n{raw}", strLogPrefix, strOutput || "<>" ); fnShellRestore(); joGlueResult = null; @@ -444,7 +442,7 @@ function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ) : fnShellRestore(); } catch ( err ) { details.critical( "BLS glue error description is: {err}, stack is: \n{stack}", - err, err.stack ); + err, err ); details.critical( "BLS glue output is:\n{raw}", strOutput || "<>" ); fnShellRestore(); joGlueResult = null; @@ -510,7 +508,7 @@ function performBlsVerifyI( return true; } catch ( err ) { details.critical( "{p}BLS node #{} verify error:, error description is: {err}, " + - "stack is: \n{stack}", strLogPrefix, nZeroBasedNodeIndex, err, err.stack ); + "stack is: \n{stack}", strLogPrefix, nZeroBasedNodeIndex, err, err ); details.critical( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); fnShellRestore(); @@ -563,7 +561,7 @@ function performBlsVerifyIU256( return true; } catch ( err ) { details.error( "{p}BLS u256 node #{} verify error, error description is: {err}, " + - "stack is: \n{stack}", strLogPrefix, nZeroBasedNodeIndex, err, err.stack ); + "stack is: \n{stack}", strLogPrefix, nZeroBasedNodeIndex, err, err ); details.error( "{p}BLS u256 node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); fnShellRestore(); @@ -634,7 +632,7 @@ function performBlsVerify( return true; } catch ( err ) { details.error( "{p}BLS/summary verify error description is: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); details.error( "BLS/summary verify output is:\n{raw}", strOutput || "<>" ); fnShellRestore(); } @@ -692,7 +690,7 @@ function performBlsVerifyU256( return true; } catch ( err ) { details.error( "{p}BLS u256/summary error description is: {err}, stack is: \n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); details.error( "{p}BLS u256/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); fnShellRestore(); @@ -780,7 +778,7 @@ async function checkCorrectnessOfMessagesToSign( "{p}{bright} Correctness validation failed for message {} sent to {}, " + "message is: {}, error information: {err}, stack is:\n{stack}", strLogPrefix, strDirection, idxMessage, joChainName, joMessage, - err, err.stack ); + err, err ); } } } @@ -937,7 +935,7 @@ async function gatherSigningCheckFinish( optsSignOperation: any ) { optsSignOperation.jarrMessages, joGlueResult ); optsSignOperation.fn( strError, optsSignOperation.jarrMessages, joGlueResult ) - .catch( function( err ) { + .catch( function( err: Error|string ) { optsSignOperation.details.critical( "Problem(2) in BLS sign result handler: {err}", err ); optsSignOperation.errGathering = "Problem(2) in BLS sign " + @@ -954,7 +952,7 @@ async function gatherSigningCheckOverflow( optsSignOperation: any ) { `signature error(2), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, optsSignOperation.jarrMessages - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(3) in BLS sign result handler, not enough successful BLS signature " + @@ -985,7 +983,7 @@ async function gatherSigningStartImpl( optsSignOperation: any ) { `signature error(3), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, optsSignOperation.jarrMessages - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.critical( "Problem(4) in BLS sign result handler, not enough successful BLS signature " + @@ -1011,7 +1009,7 @@ async function gatherSigningFinishImpl( optsSignOperation: any ) { `${JSON.stringify( optsSignOperation.joGatheringTracker )} , ` + `error is: ${optsSignOperation.errGathering.toString()}`, optsSignOperation.jarrMessages - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(5) in BLS sign result handler, not enough successful BLS " + @@ -1033,7 +1031,7 @@ async function gatherSigningFinishImpl( optsSignOperation: any ) { `Failed to gather BLS signatures in ${optsSignOperation.jarrNodes.length} node(s), ` + `tracker data is: ${JSON.stringify( optsSignOperation.joGatheringTracker )}`, optsSignOperation.jarrMessages - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(6) in BLS sign result handler, not enough successful BLS signature " + @@ -1171,7 +1169,7 @@ async function doSignProcessHandleCall( "{p}S-Chain node {} partial signature fail from with index {}" + ", error is {err}, sequence ID is {}, stack is:\n{stack}", optsSignOperation.strLogPrefixA, strNodeDescColorized, nZeroBasedNodeIndex, - err, optsSignOperation.sequenceId, err.stack ); + err, optsSignOperation.sequenceId, err ); } if( bNodeSignatureOKay ) { optsSignOperation.arrSignResults.push( { @@ -1189,7 +1187,7 @@ async function doSignProcessHandleCall( "{p}S-Chain node {} signature fail from node {}, error is {err}" + ", sequence ID is {}, stack is:\n{stack}", optsSignOperation.strLogPrefix, strNodeDescColorized, joNode.nodeID, - err, optsSignOperation.sequenceId, err.stack ); + err, optsSignOperation.sequenceId, err ); } await joCall.disconnect(); } @@ -1205,7 +1203,8 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { strNodeURL, i, optsSignOperation.jarrNodes.length, joNode.nodeID, optsSignOperation.sequenceId ); const rpcCallOpts: any = null; - let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ).catch( function( err ) { + let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) + .catch( function( err: Error|string ) { ++optsSignOperation.joGatheringTracker.nCountReceived; ++optsSignOperation.joGatheringTracker.nCountErrors; optsSignOperation.details.error( @@ -1315,13 +1314,13 @@ async function doSignMessagesImpl( } catch ( err ) { if( optsSignOperation.details ) { optsSignOperation.details.critical( "Failed BLS sign due to generic " + - "flow exception: {err}, stack is:\n{stack}", err, err.stack ); + "flow exception: {err}, stack is:\n{stack}", err, err ); } if( ! optsSignOperation.bHaveResultReportCalled ) { optsSignOperation.bHaveResultReportCalled = true; await optsSignOperation.fn( "Failed BLS sign due to exception: " + `${owaspUtils.extractErrorMessage( err )}`, optsSignOperation.jarrMessages - ).catch( function( err ) { + ).catch( function( err: Error|string ) { log.critical( "Failed BLS sign due to error-reporting callback exception: {err}", err ); if( optsSignOperation.details ) { @@ -1477,7 +1476,7 @@ async function doSignU256OneImplHandleCallResult( "{p}S-Chain node {} sign CRITICAL ERROR: partial signature fail from " + "with index {}, error is {err}, stack is:\n{stack}", strLogPrefixA, strNodeDescColorized, nZeroBasedNodeIndex, - err, err.stack ); + err, err ); } if( bNodeSignatureOKay ) { optsSignU256.arrSignResults.push( { @@ -1495,7 +1494,7 @@ async function doSignU256OneImplHandleCallResult( optsSignU256.details.critical( "{p}S-Chain node {} signature fail from node {}, error is {err}, " + "stack is:\n{stack}", optsSignU256.strLogPrefix, - strNodeDescColorized, joNode.nodeID, err, err.stack ); + strNodeDescColorized, joNode.nodeID, err, err ); } await joCall.disconnect(); } @@ -1589,7 +1588,8 @@ async function gatherSigningCheckFinish256( optsSignU256: any ) { "Will call signed-256 answer-sending callback {}, u256 is {}, " + "glue result is {}", strError ? ( " with error " + log.fmtError( "{err}", strError ) ) : "", optsSignU256.u256, joGlueResult ); - optsSignU256.fn( strError, optsSignU256.u256, joGlueResult ).catch( function( err ) { + optsSignU256.fn( strError, optsSignU256.u256, joGlueResult ) + .catch( function( err: Error|string ) { optsSignU256.details.critical( "Problem(2) in BLS u256 sign result handler: {err}", err ); optsSignU256.errGathering = "Problem(2) in BLS u256 sign result " + @@ -1605,7 +1605,7 @@ async function gatherSigningCheckOverflow256( optsSignU256: any ) { "signature error(2, u256), got " + `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.critical( "Problem(3) in BLS u256 sign result handler, not enough successful BLS " + @@ -1636,7 +1636,7 @@ async function doSignU256Gathering( optsSignU256: any ) { `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.error( "Problem(4) in BLS u256 sign result handler, not enough successful BLS " + @@ -1760,7 +1760,7 @@ export async function doVerifyReadyHash( isSuccess = true; } catch ( err ) { details.critical( "{p}BLS node #{} verify error, error description is: {err}" + - ", stack is:\n{stack}", strLogPrefix, nZeroBasedNodeIndex, err, err.stack ); + ", stack is:\n{stack}", strLogPrefix, nZeroBasedNodeIndex, err, err ); details.critical( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); fnShellRestore(); @@ -1865,7 +1865,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a joSignResult = { }; joSignResult.error = strError; details.error( "{p}JSON RPC call to SGX failed, error is: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); if( joCall ) await joCall.disconnect(); } diff --git a/src/cc.ts b/src/cc.ts index 38b2a7bc..a1875bf7 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -269,8 +269,10 @@ export function safeURL( arg?: any ) : URL|null { if( arg[cnt - 1] == sc ) { const ss = arg.substring( 1, cnt - 1 ); const objURL = safeURL( ss ); - if( objURL != null && objURL != undefined ) - objURL["strStrippedStringComma"] = sc; + if( objURL != null && objURL != undefined ) { + const anyURL: any = objURL; + anyURL["strStrippedStringComma"] = sc; + } return objURL; } @@ -283,7 +285,8 @@ export function safeURL( arg?: any ) : URL|null { if( objURL.hostname.length === 0 ) return null; - objURL["strStrippedStringComma"] = null; + const anyURL: any = objURL; + anyURL["strStrippedStringComma"] = null; return objURL; } catch ( err ) { return null; @@ -354,8 +357,9 @@ export function logArgToString( ...args: any[] ) : string { const objURL = safeURL( arg ); if( objURL != null && objURL != undefined ) { let strURL = ""; - if( objURL["strStrippedStringComma"] ) - strURL += normal( objURL["strStrippedStringComma"] ); + const anyURL: any = objURL; + if( anyURL["strStrippedStringComma"] ) + strURL += normal( anyURL["strStrippedStringComma"] ); if( objURL.protocol ) strURL += "" + yellow( objURL.protocol ) + normal( "//" ); @@ -379,8 +383,8 @@ export function logArgToString( ...args: any[] ) : string { if( objURL.search ) strURL += "" + magenta( objURL.search ); - if( objURL["strStrippedStringComma"] ) - strURL += normal( objURL["strStrippedStringComma"] ); + if( anyURL["strStrippedStringComma"] ) + strURL += normal( anyURL["strStrippedStringComma"] ); s += strURL; continue; @@ -429,7 +433,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ cntCensoredMax: 30000, // zero to disable censoring censor: ( censor: any ) : any => { let i = 0; - return ( key, value ) => { + return ( key: any, value: any ) => { if( i !== 0 && typeof ( censor ) === "object" && typeof ( value ) === "object" && censor == value ) @@ -528,7 +532,7 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ) : str return jo.replace( // eslint-disable-next-line max-len /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, - function( match ) { + function( match: any ) { if( ! gFlagIsEnabled ) return match; let cls = "number"; diff --git a/src/cli.ts b/src/cli.ts index af14c099..7034c435 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -83,10 +83,10 @@ export function ensureHaveValue( ) { isExitIfEmpty = isExitIfEmpty || false; isPrintValue = isPrintValue || false; - fnNameColorizer = fnNameColorizer || ( ( x ) => { + fnNameColorizer = fnNameColorizer || ( ( x: any ) => { return log.fmtInformation( x ); } ); - fnValueColorizer = fnValueColorizer || ( ( x ) => { + fnValueColorizer = fnValueColorizer || ( ( x: any ) => { return log.fmtNotice( x ); } ); let retVal = true; @@ -108,7 +108,7 @@ export function ensureHaveValue( } export function ensureHaveCredentials( - strFriendlyChainName, joAccount, isExitIfEmpty, isPrintValue + strFriendlyChainName: string, joAccount: any, isExitIfEmpty: boolean, isPrintValue: boolean ) { strFriendlyChainName = strFriendlyChainName || ""; if( ! ( typeof joAccount == "object" ) ) { @@ -196,7 +196,7 @@ export function ensureHaveCredentials( return true; } -export function findNodeIndex( joSChainNodeConfiguration ) { +export function findNodeIndex( joSChainNodeConfiguration: any ) { try { const searchID = joSChainNodeConfiguration.skaleConfig.nodeInfo.nodeID; const cnt = joSChainNodeConfiguration.skaleConfig.sChain.nodes.length; @@ -209,7 +209,7 @@ export function findNodeIndex( joSChainNodeConfiguration ) { return 0; } -function parseHelp( imaState, joArg ) { // exits process on "--help" +function parseHelp( imaState: any, joArg: any ) { // exits process on "--help" if( joArg.name != "help" ) return false; printAbout(); @@ -218,14 +218,14 @@ function parseHelp( imaState, joArg ) { // exits process on "--help" process.exit( 0 ); } -function parseVersion( imaState, joArg ) { // exits process on "--version" +function parseVersion( imaState: any, joArg: any ) { // exits process on "--version" if( joArg.name != "version" ) return false; printAbout(); process.exit( 0 ); } -function parseBasicArgs( imaState, joArg ) { +function parseBasicArgs( imaState: any, joArg: any ) { if( joArg.name == "colors" ) { log.enableColorization( true ); return true; @@ -253,7 +253,7 @@ function parseBasicArgs( imaState, joArg ) { return false; } -function parseChainAccessArgs( imaState, joArg ) { +function parseChainAccessArgs( imaState: any, joArg: any ) { if( joArg.name == "url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); imaState.chainProperties.mn.strURL = joArg.value; @@ -307,7 +307,7 @@ function parseChainAccessArgs( imaState, joArg ) { return false; } -function parseTransactionManagerArgs( imaState, joArg ) { +function parseTransactionManagerArgs( imaState: any, joArg: any ) { if( joArg.name == "tm-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); const strURL = "" + joArg.value; @@ -347,7 +347,7 @@ function parseTransactionManagerArgs( imaState, joArg ) { return false; } -function parseSgxArgs( imaState, joArg ) { +function parseSgxArgs( imaState: any, joArg: any ) { if( joArg.name == "sgx-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); imaState.chainProperties.mn.joAccount.strSgxURL = joArg.value; @@ -472,7 +472,7 @@ function parseSgxArgs( imaState, joArg ) { return false; } -function parseCredentialsArgs( imaState, joArg ) { +function parseCredentialsArgs( imaState: any, joArg: any ) { if( joArg.name == "address-main-net" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.chainProperties.mn.joAccount.address_ = joArg.value; @@ -511,7 +511,7 @@ function parseCredentialsArgs( imaState, joArg ) { return false; } -function parseAbiArgs( imaState, joArg ) { +function parseAbiArgs( imaState: any, joArg: any ) { if( joArg.name == "abi-skale-manager" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); imaState.strPathAbiJsonSkaleManager = imaUtils.normalizePath( joArg.value ); @@ -535,7 +535,7 @@ function parseAbiArgs( imaState, joArg ) { return false; } -function parseErcArgs( imaState, joArg ) { +function parseErcArgs( imaState: any, joArg: any ) { if( joArg.name == "erc20-main-net" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); imaState.chainProperties.mn.strPathJsonErc20 = imaUtils.normalizePath( joArg.value ); @@ -620,7 +620,7 @@ function parseErcArgs( imaState, joArg ) { return false; } -function parseTransactionArgs( imaState, joArg ) { +function parseTransactionArgs( imaState: any, joArg: any ) { if( joArg.name == "sleep-between-tx" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaHelperAPIs.setSleepBetweenTransactionsOnSChainMilliseconds( joArg.value ); @@ -718,7 +718,7 @@ function parseTransactionArgs( imaState, joArg ) { return false; } -function parsePaymentAmountArgs( imaState, joArg ) { +function parsePaymentAmountArgs( imaState: any, joArg: any ) { if( joArg.name == "value" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = owaspUtils.parseMoneySpecToWei( "" + joArg.value, true ); @@ -789,7 +789,7 @@ function parsePaymentAmountArgs( imaState, joArg ) { return false; } -function parseTransferArgs( imaState, joArg ) { +function parseTransferArgs( imaState: any, joArg: any ) { if( joArg.name == "s2s-forward" ) { imaHelperAPIs.setForwardS2S(); return true; @@ -957,7 +957,7 @@ function parseTransferArgs( imaState, joArg ) { return false; } -function parseMulticallArgs( imaState, joArg ) { +function parseMulticallArgs( imaState: any, joArg: any ) { if( joArg.name == "enable-multicall" ) { imaState.isEnabledMultiCall = true; return true; @@ -969,7 +969,7 @@ function parseMulticallArgs( imaState, joArg ) { return false; } -function parsePendingWorkAnalysisArgs( imaState, joArg ) { +function parsePendingWorkAnalysisArgs( imaState: any, joArg: any ) { if( joArg.name == "pwa" ) { imaState.isPWA = true; return true; @@ -994,7 +994,7 @@ function parsePendingWorkAnalysisArgs( imaState, joArg ) { return false; } -function parseLoggingArgs( imaState, joArg ) { +function parseLoggingArgs( imaState: any, joArg: any ) { if( joArg.name == "gathered" ) { imaState.isPrintGathered = true; return true; @@ -1045,7 +1045,7 @@ function parseLoggingArgs( imaState, joArg ) { return false; } -function parseBlsArgs( imaState, joArg ) { +function parseBlsArgs( imaState: any, joArg: any ) { if( joArg.name == "sign-messages" ) { imaState.bSignMessages = true; return true; @@ -1068,7 +1068,7 @@ function parseBlsArgs( imaState, joArg ) { return false; } -function parseMonitoringArgs( imaState, joArg ) { +function parseMonitoringArgs( imaState: any, joArg: any ) { if( joArg.name == "monitoring-port" ) { owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nMonitoringPort = owaspUtils.toInteger( joArg.value ); @@ -1082,7 +1082,7 @@ function parseMonitoringArgs( imaState, joArg ) { return false; } -function parseReimbursementArgs( imaState, joArg ) { +function parseReimbursementArgs( imaState: any, joArg: any ) { if( joArg.name == "reimbursement-chain" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.strReimbursementChain = joArg.value.trim(); @@ -1116,7 +1116,7 @@ function parseReimbursementArgs( imaState, joArg ) { return false; } -function parseOracleArgs( imaState, joArg ) { +function parseOracleArgs( imaState: any, joArg: any ) { if( joArg.name == "enable-oracle" ) { imaOracleOperations.setEnabledOracle( true ); return true; @@ -1128,7 +1128,7 @@ function parseOracleArgs( imaState, joArg ) { return false; } -function parseNetworkDiscoveryArgs( imaState, joArg ) { +function parseNetworkDiscoveryArgs( imaState: any, joArg: any ) { if( joArg.name == "network-browser-path" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.optsS2S.strNetworkBrowserPath = "" + joArg.value; @@ -1137,7 +1137,7 @@ function parseNetworkDiscoveryArgs( imaState, joArg ) { return false; } -function parseBlockScannerArgs( imaState, joArg ) { +function parseBlockScannerArgs( imaState: any, joArg: any ) { if( joArg.name == "bs-step-size" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaHelperAPIs.setBlocksCountInInIterativeStepOfEventsScan( @@ -1160,7 +1160,7 @@ function parseBlockScannerArgs( imaState, joArg ) { return false; } -function parseJsonRpcServerArgs( imaState, joArg ) { +function parseJsonRpcServerArgs( imaState: any, joArg: any ) { if( joArg.name == "json-rpc-port" ) { owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nJsonRpcPort = owaspUtils.toInteger( joArg.value ); @@ -1169,7 +1169,7 @@ function parseJsonRpcServerArgs( imaState, joArg ) { return false; } -function parseCrossImaCommunicationArgs( imaState, joArg ) { +function parseCrossImaCommunicationArgs( imaState: any, joArg: any ) { if( joArg.name == "cross-ima" ) { imaState.isCrossImaBlsMode = true; return true; @@ -1181,7 +1181,7 @@ function parseCrossImaCommunicationArgs( imaState, joArg ) { return false; } -function parseShowConfigArgs( imaState, joArg ) { +function parseShowConfigArgs( imaState: any, joArg: any ) { if( joArg.name == "show-config" ) { imaState.bShowConfigMode = true; return true; @@ -1189,7 +1189,7 @@ function parseShowConfigArgs( imaState, joArg ) { return false; } -function parseOtherArgs( imaState, joArg ) { +function parseOtherArgs( imaState: any, joArg: any ) { if( joArg.name == "auto-exit" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaState.nAutoExitAfterSeconds = owaspUtils.toInteger( joArg.value ); @@ -1288,7 +1288,7 @@ export function parse( joExternalHandlers: any ) { return 0; } -async function asyncCheckUrlAtStartup( u, name ) { +async function asyncCheckUrlAtStartup( u: URL|string, name: string ) { const details = log.createMemoryStream(); const nTimeoutMilliseconds = 10 * 1000; try { @@ -1305,7 +1305,7 @@ async function asyncCheckUrlAtStartup( u, name ) { return isOnLine; } catch ( err ) { details.error( "Failed to check URL {url} connectivity for {} at start-up, " + - "error is: {err}, stack is:\n{stack}", u, name, err, err.stack ); + "error is: {err}, stack is:\n{stack}", u, name, err, err ); } return false; } @@ -1526,7 +1526,7 @@ function commonInitPrintFoundContracts() { // message_proxy_mainnet_address --> message_proxy_mainnet_abi // message_proxy_chain_address --> message_proxy_chain_abi - const oct = function( joContract ) { // optional contract address + const oct = function( joContract: any ) { // optional contract address if( joContract && "address" in joContract && joContract.address ) return log.fmtInformation( "{}", joContract.address ); return log.fmtError( "contract is not available" ); @@ -2096,92 +2096,92 @@ function commonInitCheckGeneralArgs() { } ensureHaveValue( "App path", - path.join( __dirname, "main.ts" ), false, isPrintGathered, null, ( x ) => { + path.join( __dirname, "main.ts" ), false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "Verbose level", log.verboseLevelAsTextForLog( log.verboseGet() ), - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "Multi-call optimizations", - imaState.isEnabledMultiCall, false, isPrintGathered, null, ( x ) => { + imaState.isEnabledMultiCall, false, isPrintGathered, null, ( x: any ) => { return log.yn( x ); } ); ensureHaveValue( "Main-net URL", imaState.chainProperties.mn.strURL, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.u( x ); } ); ensureHaveValue( "S-chain URL", imaState.chainProperties.sc.strURL, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.u( x ); } ); ensureHaveValue( "S<->S Target S-chain URL", imaState.chainProperties.tc.strURL, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.u( x ); } ); ensureHaveValue( "Main-net Ethereum network name", imaState.chainProperties.mn.strChainName, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S-Chain Ethereum network name", imaState.chainProperties.sc.strChainName, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S<->S Target S-Chain Ethereum network name", imaState.chainProperties.tc.strChainName, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "Main-net Ethereum chain ID", imaState.chainProperties.mn.chainId, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S-Chain Ethereum chain ID", imaState.chainProperties.sc.chainId, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S<->S Target S-Chain Ethereum chain ID", imaState.chainProperties.tc.chainId, false, - isPrintGathered && isPrintSecurityValues, null, ( x ) => { + isPrintGathered && isPrintSecurityValues, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "Skale Manager ABI JSON file path", - imaState.strPathAbiJsonSkaleManager, false, isPrintGathered, null, ( x ) => { + imaState.strPathAbiJsonSkaleManager, false, isPrintGathered, null, ( x: any ) => { return log.fmtWarning( x ); } ); ensureHaveValue( "Main-net ABI JSON file path", - imaState.chainProperties.mn.strPathAbiJson, false, isPrintGathered, null, ( x ) => { + imaState.chainProperties.mn.strPathAbiJson, false, isPrintGathered, null, ( x: any ) => { return log.fmtWarning( x ); } ); ensureHaveValue( "S-Chain ABI JSON file path", - imaState.chainProperties.sc.strPathAbiJson, false, isPrintGathered, null, ( x ) => { + imaState.chainProperties.sc.strPathAbiJson, false, isPrintGathered, null, ( x: any ) => { return log.fmtWarning( x ); } ); ensureHaveValue( "S<->S Target S-Chain ABI JSON file path", - imaState.chainProperties.tc.strPathAbiJson, false, isPrintGathered, null, ( x ) => { + imaState.chainProperties.tc.strPathAbiJson, false, isPrintGathered, null, ( x: any ) => { return log.fmtWarning( x ); } ); @@ -2231,7 +2231,7 @@ function commonInitCheckCredentialsArgs() { ensureHaveValue( "BLS/Main Net key name", imaState.chainProperties.mn.joAccount.strBlsKeyName, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); } @@ -2239,7 +2239,7 @@ function commonInitCheckCredentialsArgs() { ensureHaveValue( "BLS/S-Chain key name", imaState.chainProperties.sc.joAccount.strBlsKeyName, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); } @@ -2247,7 +2247,7 @@ function commonInitCheckCredentialsArgs() { ensureHaveValue( "BLS/Target S-Chain key name", imaState.chainProperties.tc.joAccount.strBlsKeyName, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); } @@ -2259,7 +2259,7 @@ function commonInitCheckTransferAmountArgs() { const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( "Amount of wei to transfer", imaState.nAmountOfWei, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); } @@ -2269,92 +2269,92 @@ function commonInitTransferringArgs() { const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( "M->S transfer block size", imaState.nTransferBlockSizeM2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S->M transfer block size", imaState.nTransferBlockSizeS2M, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); if( imaState.bHaveSkaleManagerABI ) { ensureHaveValue( "S->S transfer block size", imaState.nTransferBlockSizeS2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); } ensureHaveValue( "M->S transfer job steps", imaState.nTransferStepsM2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S->M transfer job steps", imaState.nTransferStepsS2M, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); if( imaState.bHaveSkaleManagerABI ) { ensureHaveValue( "S->S transfer job steps", imaState.nTransferStepsS2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); } ensureHaveValue( "M->S transactions limit", imaState.nMaxTransactionsM2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S->M transactions limit", imaState.nMaxTransactionsS2M, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); if( imaState.bHaveSkaleManagerABI ) { ensureHaveValue( "S->S transactions limit", imaState.nMaxTransactionsS2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); } ensureHaveValue( "M->S await blocks", imaState.nBlockAwaitDepthM2S, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S->M await blocks", imaState.nBlockAwaitDepthS2M, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); if( imaState.bHaveSkaleManagerABI ) { ensureHaveValue( "S->S await blocks", imaState.nBlockAwaitDepthS2S, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); } ensureHaveValue( "M->S minimal block age", imaState.nBlockAgeM2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); ensureHaveValue( "S->M minimal block age", imaState.nBlockAgeS2M, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); if( imaState.bHaveSkaleManagerABI ) { ensureHaveValue( "S->S minimal block age", imaState.nBlockAgeS2S, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtNote( x ); } ); } ensureHaveValue( "Transfer loop period(seconds)", imaState.nLoopPeriodSeconds, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtSuccess( x ); } ); if( imaState.nTimeFrameSeconds > 0 ) { @@ -2377,12 +2377,12 @@ function commonInitCheckAccessArgs() { const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( "S-Chain node number(zero based)", - imaState.nNodeNumber, false, isPrintGathered, null, ( x ) => { + imaState.nNodeNumber, false, isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); ensureHaveValue( "S-Chain nodes count", - imaState.nNodesCount, false, isPrintGathered, null, ( x ) => { + imaState.nNodesCount, false, isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); } @@ -2394,19 +2394,19 @@ function commonInitErcTokensArgs() { ensureHaveValue( "Loaded Main-net ERC20 ABI ", imaState.chainProperties.tc.strCoinNameErc20, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "Loaded S-Chain ERC20 ABI ", imaState.chainProperties.sc.strCoinNameErc20, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "Amount of tokens to transfer", imaState.nAmountOfToken, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); if( isPrintGathered ) { @@ -2418,7 +2418,7 @@ function commonInitErcTokensArgs() { ensureHaveValue( "Loaded S<->S Target S-Chain ERC20 ABI ", imaState.chainProperties.tc.strCoinNameErc20, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); } @@ -2426,19 +2426,19 @@ function commonInitErcTokensArgs() { ensureHaveValue( "Loaded Main-net ERC721 ABI ", imaState.chainProperties.mn.strCoinNameErc721, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "Loaded S-Chain ERC721 ABI ", imaState.chainProperties.sc.strCoinNameErc721, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "ERC721 token id ", imaState.idToken, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); if( isPrintGathered ) { @@ -2450,28 +2450,28 @@ function commonInitErcTokensArgs() { ensureHaveValue( "Loaded S<->S Target S-Chain ERC721 ABI ", imaState.chainProperties.tc.strCoinNameErc721, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); } if( imaState.chainProperties.mn.strCoinNameErc1155.length > 0 ) { ensureHaveValue( "Loaded Main-net ERC1155 ABI ", imaState.chainProperties.mn.strCoinNameErc1155, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( "Loaded S-Chain ERC1155 ABI ", imaState.chainProperties.sc.strCoinNameErc1155, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); try { ensureHaveValue( "ERC1155 token id ", - imaState.idToken, false, isPrintGathered, null, ( x ) => { + imaState.idToken, false, isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); ensureHaveValue( "ERC1155 token amount ", - imaState.nAmountOfToken, false, isPrintGathered, null, ( x ) => { + imaState.nAmountOfToken, false, isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); } catch ( e1 ) { @@ -2479,13 +2479,13 @@ function commonInitErcTokensArgs() { ensureHaveValue( "ERC1155 batch of token ids ", imaState.idTokens, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); ensureHaveValue( "ERC1155 batch of token amounts ", imaState.arrAmountsOfTokens, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); } catch ( e2 ) { @@ -2504,7 +2504,7 @@ function commonInitErcTokensArgs() { ensureHaveValue( "Loaded S<->S Target S-Chain ERC1155 ABI ", imaState.chainProperties.tc.strCoinNameErc1155, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); } @@ -2596,19 +2596,19 @@ function commonInitLoggingArgs() { ensureHaveValue( "Log file path", imaState.strLogFilePath, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return log.fmtInformation( x ); } ); ensureHaveValue( "Max size of log file path", imaState.nLogMaxSizeBeforeRotation, false, - isPrintGathered, null, ( x ) => { + isPrintGathered, null, ( x: any ) => { return ( x <= 0 ) ? log.fmtWarning( "unlimited" ) : log.fmtNote( x ); } ); ensureHaveValue( "Max rotated count of log files", imaState.nLogMaxFilesCount, - false, isPrintGathered, null, ( x ) => { + false, isPrintGathered, null, ( x: any ) => { return ( x <= 1 ) ? log.fmtWarning( "not set" ) : log.fmtNote( x ); } ); } @@ -2632,7 +2632,7 @@ export function commonInit() { commonInitCheckErc20(); commonInitCheckErc721(); commonInitCheckErc1155(); - if( log.verboseGet() > log.verboseReversed()["debug"] || imaState.bShowConfigMode ) { + if( log.verboseGet() > log.verboseName2Number( "debug" ) || imaState.bShowConfigMode ) { commonInitCheckGeneralArgs(); commonInitCheckCredentialsArgs(); commonInitCheckTransferAmountArgs(); diff --git a/src/clpTools.ts b/src/clpTools.ts index 313c4495..7ee89f4f 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -424,7 +424,7 @@ export function commandLineTaskBurnErc1155() { } export async function commandLineTaskShowBalanceEth( - arrBalancesMN, arrBalancesSC, arrBalancesTC + arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[] ) { const imaState = state.get(); let assetAddress = null; @@ -480,7 +480,7 @@ export async function commandLineTaskShowBalanceEth( } export async function commandLineTaskShowBalanceErc20( - arrBalancesMN, arrBalancesSC, arrBalancesTC + arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[] ) { const imaState = state.get(); let assetAddress = null; @@ -538,7 +538,7 @@ export async function commandLineTaskShowBalanceErc20( } export async function commandLineTaskShowBalanceErc721( - arrBalancesMN, arrBalancesSC, arrBalancesTC, idTokens + arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[], idTokens: any[] ) { const imaState = state.get(); let assetAddress = null; @@ -611,7 +611,7 @@ export async function commandLineTaskShowBalanceErc721( } export async function commandLineTaskShowBalanceErc1155( - arrBalancesMN, arrBalancesSC, arrBalancesTC, idTokens + arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[], idTokens: any[] ) { const imaState = state.get(); let assetAddress = null; @@ -688,7 +688,7 @@ export function commandLineTaskShowBalance() { imaState.arrActions.push( { "name": "show balance", "fn": async function() { - const arrBalancesMN = [], arrBalancesSC = [], arrBalancesTC = []; + const arrBalancesMN: any = [], arrBalancesSC: any = [], arrBalancesTC: any = []; await commandLineTaskShowBalanceEth( arrBalancesMN, arrBalancesSC, arrBalancesTC ); await commandLineTaskShowBalanceErc20( @@ -1442,7 +1442,8 @@ export function commandLineTaskLoopSimple() { } ); } -async function handleBrowseSkaleModesRpcInfoResult( strLogPrefix, joCall, joIn, joOut ) { +async function handleBrowseSkaleModesRpcInfoResult( + strLogPrefix: string, joCall: any, joIn: any, joOut: any ) { const imaState = state.get(); log.information( "{p}S-Chain network information: {}", strLogPrefix, joOut.result ); diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index b132861c..baa7e435 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -147,7 +147,7 @@ export async function waitUntilSChainStarted() { let isError = false; const joSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, null, nCountToWait - ).catch( function( err ) { + ).catch( function( err: Error|string ) { log.critical( "S-Chain network discovery attempt failed: {err}", err ); isError = true; } ); @@ -248,7 +248,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole let isError = false; const joSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait - ).catch( function( err ) { + ).catch( function( err: Error|string ) { isError = true; log.critical( "S-Chain network re-discovery failed: {err}", err ); } ); @@ -380,7 +380,7 @@ async function discoverSChainWalkNodes( optsDiscover: any ) { if( ! optsDiscover.isSilentReDiscovery ) { log.critical( "{p}JSON RPC call(err) to S-Chain node {} failed: {err}, stack is:\n{stack}", - optsDiscover.strLogPrefix, strNodeDescColorized, err, err.stack ); + optsDiscover.strLogPrefix, strNodeDescColorized, err, err ); } ++ optsDiscover.cntFailed; if( joCall ) @@ -518,7 +518,7 @@ async function handleDiscoverSkaleNodesRpcInfoResult( if( optsDiscover.fnAfter ) optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); rv = true; - } ).catch( function( err ) { + } ).catch( function( err: Error|string ) { if( optsDiscover.fnAfter ) optsDiscover.fnAfter( err, null ); } ); @@ -561,17 +561,17 @@ export async function discoverSChainNetwork( const joOut = await joCall.call( joIn ); await handleDiscoverSkaleNodesRpcInfoResult( optsDiscover, scURL, joCall, joIn, joOut - ).catch( function( err ) { + ).catch( function( err: Error|string ) { log.critical( "{p}JSON RPC call(in discoverSChainNetwork) error: {err}, stack is:\n{stack}", - optsDiscover.strLogPrefix, err, err.stack ); + optsDiscover.strLogPrefix, err, err ); } ); } catch ( err ) { if( ! optsDiscover.isSilentReDiscovery ) { log.critical( "{p}JSON RPC call(discoverSChainNetwork) to S-Chain failed: " + "{err}, stack is:\n{stack}", optsDiscover.strLogPrefix, - err, err.stack ); + err, err ); } optsDiscover.joSChainNetworkInfo = null; if( optsDiscover.fnAfter ) diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index d0381a6b..56155eac 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -25,14 +25,15 @@ export class UniversalDispatcherEvent { type: any; - constructor( type, jo ) { + constructor( type: any, jo: any ) { this.type = type; for( const [ key, value ] of Object.entries( jo ) ) { if( key in this ) { console.warn( "UniversalDispatcherEvent will skip", key, "data field" ); continue; } - this[key] = value; + let anyThis: any = this; + anyThis[key] = value; } } }; diff --git a/src/imaCore.ts b/src/imaCore.ts index af3d47c3..69ca1513 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -44,7 +44,7 @@ const additionalS2MTransferOverhead = 200000; async function findOutReferenceLogRecord( details: any, strLogPrefix: string, ethersProvider: any, joMessageProxy: any, - bnBlockId: any, nMessageNumberToFind: any, isVerbose: boolean + bnBlockId: any, nMessageNumberToFind: any, isVerbose?: boolean ) { const bnMessageNumberToFind = owaspUtils.toBN( nMessageNumberToFind.toString() ); const strEventName = "PreviousMessageReference"; @@ -85,8 +85,8 @@ async function findOutReferenceLogRecord( } async function findOutAllReferenceLogRecords( - details, strLogPrefix, ethersProvider, joMessageProxy, - bnBlockId, nIncMsgCnt, nOutMsgCnt, isVerbose + details: any, strLogPrefix: string, ethersProvider: any, joMessageProxy: any, + bnBlockId: any, nIncMsgCnt: number, nOutMsgCnt: number, isVerbose?: boolean ) { if( isVerbose ) { details.debug( @@ -150,7 +150,7 @@ let gTransferLoopCounter = 0; // [to] // address[] memory to // [amount] // uint256[] memory amount / *uint256[2] memory blsSignature* / // ) -async function doQueryOutgoingMessageCounter( optsTransfer ) { +async function doQueryOutgoingMessageCounter( optsTransfer: any ) { let nPossibleIntegerValue = 0; optsTransfer.details.debug( "{p}SRC MessageProxy address is.....{}", optsTransfer.strLogPrefixShort,optsTransfer.joMessageProxySrc.address ); @@ -174,7 +174,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer ) { } catch ( err ) { optsTransfer.details.critical( "(IMMEDIATE) error caught during {bright}, error details: {err}, stack is:\n{stack}", - optsTransfer.strActionName, err, err.stack ); + optsTransfer.strActionName, err, err ); } optsTransfer.strActionName = "dst-chain.MessageProxy.getIncomingMessagesCounter()"; @@ -227,7 +227,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer ) { optsTransfer.details.error( "{p}Optimized log search is off. Running old IMA smart contracts? " + "Please upgrade, if possible. Error is: {err}, stack is:\n{stack}", - optsTransfer.strLogPrefix, err, err.stack ); + optsTransfer.strLogPrefix, err, err ); } } catch ( err ) { optsTransfer.arrLogRecordReferences = []; @@ -258,7 +258,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer ) { return true; } -async function analyzeGatheredRecords( optsTransfer, r ) { +async function analyzeGatheredRecords( optsTransfer: any, r: any ) { let joValues: any = null; const strChainHashWeAreLookingFor = owaspUtils.ethersMod.ethers.utils.id( optsTransfer.chainNameDst ); @@ -303,7 +303,7 @@ async function analyzeGatheredRecords( optsTransfer, r ) { return joValues; } -async function gatherMessages( optsTransfer ) { +async function gatherMessages( optsTransfer: any ) { optsTransfer.arrMessageCounters = []; optsTransfer.jarrMessages = []; optsTransfer.nIdxCurrentMsgBlockStart = 0 + optsTransfer.nIdxCurrentMsg; @@ -365,7 +365,7 @@ async function gatherMessages( optsTransfer ) { optsTransfer.details.critical( "{p}Exception(evaluate block depth) while getting transaction hash and " + "block number during {bright}: {err}, stack is:\n{stack}", - optsTransfer.strLogPrefix, optsTransfer.strActionName, err, err.stack ); + optsTransfer.strLogPrefix, optsTransfer.strActionName, err, err ); optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( @@ -417,7 +417,7 @@ async function gatherMessages( optsTransfer ) { optsTransfer.details.critical( "{p}Exception(evaluate block age) while getting block number and timestamp " + "during {bright}: {err}, stack is:\n{stack}", optsTransfer.strLogPrefix, - optsTransfer.strActionName, err, err.stack ); + optsTransfer.strActionName, err, err ); optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( @@ -451,7 +451,8 @@ async function gatherMessages( optsTransfer ) { } } -async function preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) { +async function preCheckAllMessagesSign( + optsTransfer: any, err: Error|string, jarrMessages: any[], joGlueResult: any ) { const strDidInvokedSigningCallbackMessage = log.fmtDebug( "{p}Did invoked message signing callback, first real message index is: {}, have {} " + "message(s) to process {}", optsTransfer.strLogPrefix, @@ -475,7 +476,8 @@ async function preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueR return true; } -async function callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) { +async function callbackAllMessagesSign( + optsTransfer: any, err: Error|string, jarrMessages: any[], joGlueResult: any ) { if( ! await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) return; const nBlockSize = optsTransfer.arrMessageCounters.length; @@ -619,16 +621,16 @@ async function callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueR } } -async function handleAllMessagesSigning( optsTransfer ) { +async function handleAllMessagesSigning( optsTransfer: any ) { try { let errFinal = null; await optsTransfer.fnSignMessages( optsTransfer.nTransferLoopCounter, optsTransfer.jarrMessages, optsTransfer.nIdxCurrentMsgBlockStart, optsTransfer.chainNameSrc, optsTransfer.joExtraSignOpts, - async function( err, jarrMessages, joGlueResult ) { + async function( err: Error|string, jarrMessages: any[], joGlueResult: any ) { await callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ); return; - } ).catch( function( err ) { + } ).catch( function( err: Error|string ) { // callback fn as argument of optsTransfer.fnSignMessages optsTransfer.bErrorInSigningMessages = true; optsTransfer.details.error( "{p}Problem in transfer handler(in signer): {err}", @@ -649,7 +651,7 @@ async function handleAllMessagesSigning( optsTransfer ) { } } -async function checkOutgoingMessageEventInOneNode( optsTransfer, optsOutgoingMessageAnalysis ) { +async function checkOutgoingMessageEventInOneNode( optsTransfer: any, optsOutgoingMessageAnalysis: any ) { const sc = optsTransfer.imaState.chainProperties.sc; const strUrlHttp = optsOutgoingMessageAnalysis.joNode.endpoints.ip.http; optsTransfer.details.trace( @@ -704,7 +706,7 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer, optsOutgoingMes "detailed node description is: {}, error is: {err}, stack is: ", optsTransfer.strLogPrefix, optsTransfer.strDirection, optsOutgoingMessageAnalysis.joNode.name, optsOutgoingMessageAnalysis.joNode, - err, err.stack ); + err, err ); return true; // continue nodes analysis } if( bEventIsFound ) { @@ -735,7 +737,7 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer, optsOutgoingMes return true; } -async function checkOutgoingMessageEvent( optsTransfer, joSChain ) { +async function checkOutgoingMessageEvent( optsTransfer: any, joSChain: any ) { const cntNodes = joSChain.nodes.length; const cntMessages = optsTransfer.jarrMessages.length; for( let idxMessage = 0; idxMessage < cntMessages; ++ idxMessage ) { @@ -780,7 +782,7 @@ async function checkOutgoingMessageEvent( optsTransfer, joSChain ) { idxMessage + 1, strNodeName, log.posNeg( optsOutgoingMessageAnalysis.joNode, log.u( strUrlHttp ), "<>" ), - err, err.stack ); + err, err ); } if( optsOutgoingMessageAnalysis.cntFailedNodes > optsTransfer.cntNodesMayFail ) { optsTransfer.details.critical( @@ -811,7 +813,7 @@ async function checkOutgoingMessageEvent( optsTransfer, joSChain ) { return true; } -async function doMainTransferLoopActions( optsTransfer ) { +async function doMainTransferLoopActions( optsTransfer: any ) { // classic scanner with optional usage of optimized IMA messages search algorithm // outer loop is block former/creator, then transfer optsTransfer.nIdxCurrentMsg = optsTransfer.nIncMsgCnt; @@ -906,7 +908,7 @@ async function doMainTransferLoopActions( optsTransfer ) { } catch ( err ) { optsTransfer.details.critical( "{p}Exception from signing messages function: {err}, stack is:\n{stack}", - optsTransfer.strLogPrefix, err, err.stack ); + optsTransfer.strLogPrefix, err, err ); } if( optsTransfer.bErrorInSigningMessages ) break; @@ -918,15 +920,15 @@ async function doMainTransferLoopActions( optsTransfer ) { let gIsOneTransferInProgressInThisThread = false; export async function doTransfer( - strDirection, joRuntimeOpts, - ethersProviderSrc, joMessageProxySrc, joAccountSrc, - ethersProviderDst, joMessageProxyDst, joAccountDst, - chainNameSrc, chainNameDst, chainIdSrc, chainIdDst, - joDepositBoxMainNet, // for logs validation on mainnet - joTokenManagerSChain, // for logs validation on s-chain - nTransactionsCountInBlock, - nTransferSteps, nMaxTransactionsCount, nBlockAwaitDepth, nBlockAge, - fnSignMessages, joExtraSignOpts, + strDirection: string, joRuntimeOpts: any, + ethersProviderSrc: any, joMessageProxySrc: any, joAccountSrc: any, + ethersProviderDst: any, joMessageProxyDst: any, joAccountDst: any, + chainNameSrc: string, chainNameDst: string, chainIdSrc: string, chainIdDst: string, + joDepositBoxMainNet: any, // for logs validation on mainnet + joTokenManagerSChain: any, // for logs validation on s-chain + nTransactionsCountInBlock: number, + nTransferSteps: number, nMaxTransactionsCount: number, nBlockAwaitDepth: number, nBlockAge: number, + fnSignMessages: any, joExtraSignOpts: any, transactionCustomizerDst: imaTx.TransactionCustomizer ) { const optsTransfer: any = { @@ -1002,8 +1004,9 @@ export async function doTransfer( optsTransfer.details.debug( "{p}Using internal signing stub function", optsTransfer.strLogPrefix ); optsTransfer.fnSignMessages = async function( - nTransferLoopCounter, jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fnAfter + nTransferLoopCounter: number, jarrMessages: any[], + nIdxCurrentMsgBlockStart: number, strFromChainName: string, + joExtraSignOpts: any, fnAfter: any ) { optsTransfer.details.debug( "{p}Message signing callback was not provided to IMA, first real message " + @@ -1038,7 +1041,7 @@ export async function doTransfer( } catch ( err ) { optsTransfer.details.critical( "{p}Error in {} during {bright}: {err}, " + "stack is:\n{stack}", optsTransfer.strLogPrefix, - optsTransfer.strGatheredDetailsName, optsTransfer.strActionName,err, err.stack ); + optsTransfer.strGatheredDetailsName, optsTransfer.strActionName,err, err ); optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( @@ -1066,7 +1069,7 @@ export async function doTransfer( gIsOneTransferInProgressInThisThread = false; optsTransfer.details.error( "{p}Transfer loop step failed with error: {err} in {}, stack is:\n{stack}", - optsTransfer.strLogPrefix, err, threadInfo.threadDescription(), err.stack ); + optsTransfer.strLogPrefix, err, threadInfo.threadDescription(), err ); if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) { optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, true ); @@ -1077,21 +1080,21 @@ export async function doTransfer( } export async function doAllS2S( // s-chain --> s-chain - joRuntimeOpts, - imaState, - skaleObserver, - ethersProviderDst, - joMessageProxyDst, - joAccountDst, - chainNameDst, - chainIdDst, - joTokenManagerSChain, // for logs validation on s-chain - nTransactionsCountInBlock, - nTransferSteps, - nMaxTransactionsCount, - nBlockAwaitDepth, - nBlockAge, - fnSignMessages, + joRuntimeOpts: any, + imaState: any, + skaleObserver: any, + ethersProviderDst: any, + joMessageProxyDst: any, + joAccountDst: any, + chainNameDst: string, + chainIdDst: string, + joTokenManagerSChain: any, // for logs validation on s-chain + nTransactionsCountInBlock: number, + nTransferSteps: number, + nMaxTransactionsCount: number, + nBlockAwaitDepth: number, + nBlockAge: number, + fnSignMessages: any, transactionCustomizerDst: imaTx.TransactionCustomizer ) { let cntOK = 0, cntFail = 0, nIndexS2S = 0; @@ -1180,7 +1183,7 @@ export async function doAllS2S( // s-chain --> s-chain } catch ( err ) { bOK = false; log.error( "S2S step error from S-Chain {}, error is: {err} in {}, stack is:\n{stack}", - chainNameSrc, err, threadInfo.threadDescription(), err.stack ); + chainNameSrc, err, threadInfo.threadDescription(), err ); imaState.loopState.s2s.isInProgress = false; await pwa.notifyOnLoopEnd( imaState, "s2s", nIndexS2S ); } diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 23ed9078..697c1ccf 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -52,7 +52,7 @@ export async function getBalanceEth( return balance; } catch ( err ) { log.error( "{p}balance fetching error details: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); } return ""; } @@ -143,7 +143,7 @@ export async function doEthPaymentFromMainNet( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doEthPaymentFromMainNet", false ); details.close(); return false; @@ -240,7 +240,7 @@ export async function doEthPaymentFromSChain( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doEthPaymentFromSChain", false ); details.close(); return false; @@ -265,7 +265,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( const strLogPrefix = "M2S ETH Receive: "; try { strActionName = "Receive ETH payment from S-Chain on Main Met, getMyEth"; - const arrArguments = []; + const arrArguments: any = []; const weiHowMuch = undefined; const gasPrice = await transactionCustomizerMainNet.computeGasPrice( ethersProviderMainNet, 200000000000 ); @@ -300,7 +300,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( } } catch ( err ) { details.critical( "{p}Receive payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "receiveEthPaymentFromSchainOnMainNet", false ); details.close(); return false; @@ -337,7 +337,7 @@ export async function viewEthPaymentFromSchainOnMainNet( return xWei; } catch ( err ) { details.critical( "{p}View payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "viewEthPaymentFromSchainOnMainNet", false ); details.close(); return null; diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 2728faf3..b0da3687 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -218,7 +218,7 @@ export async function safeGetTransactionCount( } catch ( err ) { ret = retValOnFail; details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err.stack ); + "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); } ++ idxAttempt; while( ret === "" && idxAttempt <= cntAttempts ) { @@ -238,7 +238,7 @@ export async function safeGetTransactionCount( } catch ( err ) { ret = retValOnFail; details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err.stack ); + "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); } ++ idxAttempt; } @@ -273,7 +273,7 @@ export async function safeGetTransactionReceipt( } catch ( err ) { ret = retValOnFail; details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err.stack ); + "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); } ++ idxAttempt; while( idxAttempt <= cntAttempts ) { @@ -293,7 +293,7 @@ export async function safeGetTransactionReceipt( } catch ( err ) { ret = retValOnFail; details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err.stack ); + "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); } ++ idxAttempt; } @@ -347,7 +347,7 @@ export async function safeGetPastEvents( details.error( "{p}Failed filtering attempt {} for event {} via {url}, from block {}, to block {}, " + "error is: {err}, stack is:\n{stack}", strLogPrefix, idxAttempt, strEventName, u, - nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err.stack ); + nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err ); if( owaspUtils.extractErrorMessage( err ) .indexOf( strErrorTextAboutNotExistingEvent ) >= 0 ) { details.error( "{p}Did stopped filtering of {} event because no such event exist " + @@ -385,7 +385,7 @@ export async function safeGetPastEvents( "{p}Failed filtering attempt {} for event {} via {url}, from block {}" + ", to block{}, error is: {err}, stack is:\n{stack}", strLogPrefix, idxAttempt, strEventName, u, nBlockFrom.toHexString(), nBlockTo.toHexString(), - err, err.stack ); + err, err ); if( owaspUtils.extractErrorMessage( err ) .indexOf( strErrorTextAboutNotExistingEvent ) >= 0 ) { @@ -476,7 +476,7 @@ export async function safeGetPastEventsIterative( "{p}Got scan error during interactive scan of {}/{} block sub-range in {}/{} " + "block range, error is: {err}, stack is:\n{stack}", strLogPrefix, idxBlockSubRangeFrom.toHexString(), idxBlockSubRangeTo.toHexString(), - nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err.stack ); + nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err ); } idxBlockSubRangeTo = idxBlockSubRangeFrom; if( idxBlockSubRangeTo.lte( nBlockFrom ) ) diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 9107e88b..e363abcc 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -53,7 +53,7 @@ export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ) export function getWaitForNextBlockOnSChain() : boolean { return ( !!gFlagWaitForNextBlockOnSChain ); } -export function setWaitForNextBlockOnSChain( val ) { +export function setWaitForNextBlockOnSChain( val: any ) { gFlagWaitForNextBlockOnSChain = ( !!val ); } @@ -99,7 +99,7 @@ export async function safeGetBlockNumber( ret = retValOnFail; details.error( "Failed call attempt {} to {} via {url}, error is: {err}, stack is:\n{stack}", - idxAttempt, strFnName + "()", u, err, err.stack ); + idxAttempt, strFnName + "()", u, err, err ); } ++ idxAttempt; while( ret === "" && idxAttempt <= cntAttempts ) { @@ -119,7 +119,7 @@ export async function safeGetBlockNumber( } catch ( err ) { ret = retValOnFail; details.error( "Failed call attempt {} to via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err.stack ); + "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); } ++ idxAttempt; } diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index ddf2c8d9..faa8edb4 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -85,9 +85,9 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { nMillisecondsSleepBefore: 1000, nMillisecondsSleepPeriod: 3000, cntAttempts: 40, - isVerbose: ( log.verboseGet() >= log.verboseReversed()["information"] ) ? true : false, + isVerbose: ( log.verboseGet() >= log.verboseName2Number( "information" ) ) ? true : false, isVerboseTraceDetails: - ( log.verboseGet() >= log.verboseReversed()["debug"] ) ? true : false + ( log.verboseGet() >= log.verboseName2Number( "debug" ) ) ? true : false }; optsGasPriseSetup.details.debug( "Will fetch Main Net gas price via call to Oracle with options {}...", oracleOpts ); @@ -98,7 +98,7 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { } catch ( err ) { optsGasPriseSetup.gasPriceOnMainNet = null; optsGasPriseSetup.details.error( "Failed to fetch Main Net gas price via call " + - "to Oracle, error is: {err}, stack is:\n{stack}", err, err.stack ); + "to Oracle, error is: {err}, stack is:\n{stack}", err, err ); } } if( optsGasPriseSetup.gasPriceOnMainNet === null ) { @@ -247,11 +247,12 @@ export async function doOracleGasPriceSetup( optsGasPriseSetup.fnSignMsgOracle == undefined ) { optsGasPriseSetup.details.trace( "{p}Using internal u256 signing stub function", optsGasPriseSetup.strLogPrefix ); - optsGasPriseSetup.fnSignMsgOracle = async function( u256, details, fnAfter ) { - details.trace( "{p}u256 signing callback was not provided", - optsGasPriseSetup.strLogPrefix ); - await fnAfter( null, u256, null ); // null - no error, null - no signatures - }; + optsGasPriseSetup.fnSignMsgOracle = + async function( u256: any, details: any, fnAfter: any ) { + details.trace( "{p}u256 signing callback was not provided", + optsGasPriseSetup.strLogPrefix ); + await fnAfter( null, u256, null ); // null - no error, null - no signatures + }; } else { optsGasPriseSetup.details.trace( "{p}Using externally provided u256 signing function", optsGasPriseSetup.strLogPrefix ); @@ -262,14 +263,14 @@ export async function doOracleGasPriceSetup( "doOracleGasPriceSetup.optsGasPriseSetup.fnSignMsgOracle()"; await optsGasPriseSetup.fnSignMsgOracle( optsGasPriseSetup.gasPriceOnMainNet, optsGasPriseSetup.details, - async function( strError, u256, joGlueResult ) { + async function( strError: string, u256: any, joGlueResult: any ) { await handleOracleSigned( optsGasPriseSetup, strError, u256, joGlueResult ); } ); } catch ( err ) { optsGasPriseSetup.details.critical( "{p}Error in doOracleGasPriceSetup() during {bright}: {err}, stack is:\n{stack}", optsGasPriseSetup.strLogPrefix, optsGasPriseSetup.strActionName, - err, err.stack ); + err, err ); optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", false ); imaTransferErrorHandling.saveTransferError( "oracle", optsGasPriseSetup.details.toString() ); diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 41060c08..46d7d133 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -46,7 +46,7 @@ export async function invokeHasChain( return bHasSchain; } catch ( err ) { details.critical( "{p}Error in invokeHasChain() during {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); } return false; } @@ -105,7 +105,7 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 } catch ( err ) { details.critical( "{p}Error in checkIsRegisteredSChainInDepositBoxes(reg-step1)() during {bright}: " + - "{err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err.stack ); + "{err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "checkIsRegisteredSChainInDepositBoxes", false ); details.close(); } @@ -186,7 +186,7 @@ export async function registerSChainInDepositBoxes( // step 1 throw new Error( "S-Chain ownership status check timeout" ); } catch ( err ) { details.critical( "{p}Error in registerSChainInDepositBoxes() during {bright}: {err}" + - ", stack is:\n{stack}", strLogPrefix, strActionName, err, err.stack ); + ", stack is:\n{stack}", strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "registerSChainInDepositBoxes", false ); details.close(); return null; diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index a5a51206..c9b0ef98 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -62,7 +62,7 @@ export async function reimbursementShowBalance( return xWei; } catch ( err ) { details.critical( "{p}Payment error in reimbursementShowBalance(): {err}, " + - "stack is:\n{stack}", strLogPrefix, err, err.stack ); + "stack is:\n{stack}", strLogPrefix, err, err ); details.exposeDetailsTo( log, "reimbursementShowBalance", false ); details.close(); return 0; @@ -145,7 +145,7 @@ export async function reimbursementEstimateAmount( return amountToRecharge; } catch ( err ) { details.critical( "{p} Payment error in reimbursementEstimateAmount(): {err}, " + - "stack is:\n{stack}", strLogPrefix, err, err.stack ); + "stack is:\n{stack}", strLogPrefix, err, err ); details.exposeDetailsTo( log, "reimbursementEstimateAmount", false ); details.close(); return 0; @@ -201,7 +201,7 @@ export async function reimbursementWalletRecharge( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "reimbursementWalletRecharge", false ); details.close(); return false; @@ -268,7 +268,7 @@ export async function reimbursementWalletWithdraw( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "reimbursementWalletWithdraw", false ); details.close(); return false; @@ -333,7 +333,7 @@ export async function reimbursementSetRange( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "reimbursementSetRange", false ); details.close(); return false; diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index b3bf9af2..5091c532 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -55,7 +55,7 @@ export async function getBalanceErc20( return balance; } catch ( err ) { log.error( "{p}ERC20 balance fetching error: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); } return ""; } @@ -84,7 +84,7 @@ export async function getOwnerOfErc721( return owner; } catch ( err ) { log.error( "{p}ERC721 owner fetching error: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); } return ""; } @@ -114,7 +114,7 @@ export async function getBalanceErc1155( return balance; } catch ( err ) { log.error( "{p}ERC1155 balance fetching error: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); } return ""; } @@ -244,7 +244,7 @@ export async function doErc721PaymentFromMainNet( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc721PaymentFromMainNet", false ); details.close(); return false; @@ -381,7 +381,7 @@ export async function doErc20PaymentFromMainNet( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc20PaymentFromMainNet", false ); details.close(); return false; @@ -528,7 +528,7 @@ export async function doErc1155PaymentFromMainNet( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc1155PaymentFromMainNet", false ); details.close(); return false; @@ -656,7 +656,7 @@ export async function doErc1155BatchPaymentFromMainNet( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc1155BatchPaymentFromMainNet", false ); details.close(); return false; @@ -800,7 +800,7 @@ export async function doErc20PaymentFromSChain( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc20PaymentFromSChain", false ); details.close(); return false; @@ -948,7 +948,7 @@ export async function doErc721PaymentFromSChain( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc721PaymentFromSChain", false ); details.close(); return false; @@ -1095,7 +1095,7 @@ export async function doErc1155PaymentFromSChain( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc1155PaymentFromSChain", false ); details.close(); return false; @@ -1241,7 +1241,7 @@ export async function doErc1155BatchPaymentFromSChain( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "doErc1155BatchPaymentFromSChain", false ); details.close(); return false; @@ -1378,7 +1378,7 @@ export async function doErc20PaymentS2S( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, `doErc20PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); @@ -1521,7 +1521,7 @@ export async function doErc721PaymentS2S( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, `doErc721PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); @@ -1666,7 +1666,7 @@ export async function doErc1155PaymentS2S( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, `doErc1155PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); @@ -1813,7 +1813,7 @@ export async function doErc1155BatchPaymentS2S( } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, `doErc1155BatchPaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); @@ -1892,7 +1892,7 @@ export async function mintErc20( return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "mintErc20()", false ); details.close(); return false; @@ -1961,7 +1961,7 @@ export async function mintErc721( return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "mintErc721()", false ); details.close(); return false; @@ -2034,7 +2034,7 @@ export async function mintErc1155( return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "mintErc1155()", false ); details.close(); return false; @@ -2103,7 +2103,7 @@ export async function burnErc20( return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "burnErc20()", false ); details.close(); return false; @@ -2169,7 +2169,7 @@ export async function burnErc721( return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "burnErc721()", false ); details.close(); return false; @@ -2242,7 +2242,7 @@ export async function burnErc1155( return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", - strLogPrefix, strActionName, err, err.stack ); + strLogPrefix, strActionName, err, err ); details.exposeDetailsTo( log, "burnErc1155()", false ); details.close(); return false; diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 28a4c619..ae253cd7 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -26,7 +26,7 @@ import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher"; -export function verifyTransferErrorCategoryName( strCategory ) { +export function verifyTransferErrorCategoryName( strCategory: string ) { return "" + ( strCategory ? strCategory : "default" ); } diff --git a/src/imaTx.ts b/src/imaTx.ts index 1c4576ce..105cee3d 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -195,7 +195,7 @@ async function payedCallTM( optsPayedCall: any ) { } catch ( err ) { optsPayedCall.details.critical( "{p}TM-transaction was not sent, underlying error is: {err}", - optsPayedCall.strLogPrefix, err.toString() ); + optsPayedCall.strLogPrefix, err ); throw err; } } @@ -284,7 +284,7 @@ async function payedCallDirect( optsPayedCall: any ) { export async function payedCall( details: any, ethersProvider: any, strContractName: string, joContract: any, strMethodName: any, arrArguments: any[], - joAccount, strActionName, + joAccount: any, strActionName: string, gasPrice: any, estimatedGas: any, weiHowMuch: any, opts?: any ) { @@ -352,7 +352,7 @@ export async function payedCall( } catch ( err ) { const strErrorPrefix = "Transaction sign and send error(outer flow):"; optsPayedCall.details.critical( "{p}{} {err}, stack is:\n{stack}", - optsPayedCall.strLogPrefix, strErrorPrefix, err, err.stack ); + optsPayedCall.strLogPrefix, strErrorPrefix, err, err ); throw new Error( `${strErrorPrefix} invoking ` + `the ${optsPayedCall.strContractCallDescription}, ` + `error is: ${owaspUtils.extractErrorMessage( err )}` ); @@ -374,7 +374,7 @@ export async function payedCall( optsPayedCall.details.trace( "{p}ETH spent: {}", optsPayedCall.strLogPrefix, ethSpent ); } catch ( err ) { optsPayedCall.details.warning( "{p}TX stats computation error {err}, stack is:\n{stack}", - optsPayedCall.strLogPrefix, err, err.stack ); + optsPayedCall.strLogPrefix, err, err ); } return optsPayedCall.joReceipt; } @@ -426,7 +426,7 @@ export async function checkTransactionToSchain( } } catch ( err ) { details.critical( "{p}PoW-mining error(checkTransactionToSchain): exception occur before " + - "PoW-mining, error is: {err}, stack is:\n{stack}", strLogPrefix, err, err.stack ); + "PoW-mining, error is: {err}, stack is:\n{stack}", strLogPrefix, err, err ); } return unsignedTx; } @@ -447,7 +447,7 @@ export async function calculatePowNumber( return res; } catch ( err ) { details.critical( "{p}PoW-mining error(calculatePowNumber): exception occur during " + - "PoW-mining, error is: {err}, stack is:\n{stack}", strLogPrefix, err, err.stack ); + "PoW-mining, error is: {err}, stack is:\n{stack}", strLogPrefix, err, err ); throw err; } } @@ -489,10 +489,10 @@ export function getAccountConnectivityInfo( joAccount: any ) { const gTransactionManagerPool = "transactions"; const tmGenerateRandomHex = - size => [ ...Array( size ) ] - .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ); + function( size: number ) { [ ...Array( size ) ] + .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ) }; -function tmMakeId( details ) { +function tmMakeId( details: any ) { const prefix = "tx-"; const unique = tmGenerateRandomHex( 16 ); const id = prefix + unique + "js"; @@ -500,7 +500,7 @@ function tmMakeId( details ) { return id; } -function tmMakeRecord( tx: any = {}, score ) { +function tmMakeRecord( tx: any = {}, score: any ) { const status = "PROPOSED"; return JSON.stringify( { "score": score, @@ -509,12 +509,12 @@ function tmMakeRecord( tx: any = {}, score ) { } ); } -function tmMakeScore( priority ) { +function tmMakeScore( priority: number ) { const ts = imaHelperAPIs.currentTimestamp(); return priority * Math.pow( 10, ts.toString().length ) + ts; } -async function tmSend( details, tx, priority = 5 ) { +async function tmSend( details: any, tx: any, priority: number = 5 ) { details.trace( "TM - sending tx {} ts: {}", tx, imaHelperAPIs.currentTimestamp() ); const id = tmMakeId( details ); const score = tmMakeScore( priority ); @@ -534,7 +534,7 @@ function tmIsFinished( record: any ) { return [ "SUCCESS", "FAILED", "DROPPED" ].includes( record.status ); } -async function tmGetRecord( txId ) { +async function tmGetRecord( txId: any ) { const r = await redis.get( txId ); if( r != null ) return JSON.parse( r ); @@ -677,7 +677,7 @@ export class TransactionCustomizer { } catch ( err ) { details.error( "{p}Estimate-gas error: {err}, default recommended gas value will be used " + - "instead of estimated, stack is:\n{stack}", strLogPrefix, err, err.stack ); + "instead of estimated, stack is:\n{stack}", strLogPrefix, err, err ); } estimatedGas = owaspUtils.parseIntOrHex( owaspUtils.toBN( estimatedGas ).toString() ); if( estimatedGas == 0 ) { diff --git a/src/log.ts b/src/log.ts index 57e40663..e8482bf2 100644 --- a/src/log.ts +++ b/src/log.ts @@ -153,65 +153,65 @@ export function createStandardOutputStream() : any { "close": function() { this.objStream = null; }, "open": function() { try { this.objStream = process.stdout; } catch ( err ) { } }, "size": function() { return 0; }, - "rotate": function( nBytesToWrite ) { }, + "rotate": function( nBytesToWrite: number ) { }, "toString": function() : string { return "" + this.strFilePath; }, "exposeDetailsTo": function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { }, // high-level formatters "fatal": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["fatal"] ) + if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, "critical": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["critical"] ) { + if( verboseGet() >= verboseName2Number( "critical" ) ) { this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, "error": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["error"] ) + if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, "warning": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["warning"] ) + if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, "attention": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["attention"] ) { + if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, "information": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) { + if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, "info": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) { + if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, "notice": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, "note": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, "debug": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["debug"] ) + if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, "trace": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["trace"] ) + if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, "success": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) + if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } }; @@ -287,7 +287,7 @@ export function createMemoryOutputStream() : any { "close": function() { this.clear(); }, "open": function() { this.clear(); }, "size": function() { return 0; }, - "rotate": function( nBytesToWrite ) { this.this.arrAccumulatedLogTextLines = []; }, + "rotate": function( nBytesToWrite: number ) { this.this.arrAccumulatedLogTextLines = []; }, "toString": function() : string { let s = ""; for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) @@ -335,57 +335,57 @@ export function createMemoryOutputStream() : any { }, // high-level formatters "fatal": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["fatal"] ) + if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, "critical": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["critical"] ) + if( verboseGet() >= verboseName2Number( "critical" ) ) this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); }, "error": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["error"] ) + if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, "warning": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["warning"] ) + if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, "attention": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["attention"] ) { + if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, "information": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) { + if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, "info": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) { + if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, "notice": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, "note": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, "debug": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["debug"] ) + if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, "trace": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["trace"] ) + if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, "success": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) + if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } }; @@ -453,7 +453,7 @@ export function createFileOutput( "size": function() { try { return fs.lstatSync( this.strPath ).size; } catch ( err ) { return 0; } }, - "rotate": function( nBytesToWrite ) { + "rotate": function( nBytesToWrite: number ) { try { if( this.nMaxSizeBeforeRotation <= 0 || this.nMaxFilesCount <= 1 ) return; @@ -488,59 +488,59 @@ export function createFileOutput( function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { }, // high-level formatters "fatal": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["fatal"] ) + if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, "critical": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["critical"] ) { + if( verboseGet() >= verboseName2Number( "critical" ) ) { this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, "error": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["error"] ) + if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, "warning": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["warning"] ) + if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, "attention": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["attention"] ) { + if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, "information": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) { + if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, "info": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) { + if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, "notice": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, "note": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, "debug": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["debug"] ) + if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, "trace": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["trace"] ) + if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, "success": function( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) + if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } }; @@ -571,8 +571,8 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ) : if( ! jo ) return strDefaultErrorText; try { - const isError = function( err ) { - return err && err.stack && err.message; + const isError = function( err: Error|string ) { + return err && err instanceof Error && err.stack && err.message; }; if( ! isError( jo ) ) { if( "error" in jo ) { @@ -587,8 +587,8 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ) : return strDefaultErrorText; } if( typeof jo.message == "string" && jo.message.length > 0 ) - return jo.message; // + jo.stack; - strDefaultErrorText += "(" + jo.toString() + ")"; // + jo.stack; + return jo.message; + strDefaultErrorText += "(" + jo.toString() + ")"; } catch ( err ) { } return strDefaultErrorText; @@ -628,7 +628,7 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ) : any } export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string { - fnFormatter = fnFormatter || function( arg ) { return arg; }; + fnFormatter = fnFormatter || function( arg: any ) { return arg; }; const arrParts = ( arrArgs && arrArgs.length > 0 ) ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; let s = "", isValueMode = false; @@ -811,51 +811,51 @@ export function fmtSuccess( ...args: any[] ) : string { // high-level formatted output export function fatal( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["fatal"] ) + if( verboseGet() >= verboseName2Number( "fatal" ) ) write( getLogLinePrefixFatal() + fmtFatal( ...args ) + "\n" ); } export function critical( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["critical"] ) + if( verboseGet() >= verboseName2Number( "critical" ) ) write( getLogLinePrefixCritical() + fmtCritical( ...args ) + "\n" ); } export function error( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["error"] ) + if( verboseGet() >= verboseName2Number( "error" ) ) write( getLogLinePrefixError() + fmtError( ...args ) + "\n" ); } export function warning( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["warning"] ) + if( verboseGet() >= verboseName2Number( "warning" ) ) write( getLogLinePrefixWarning() + fmtWarning( ...args ) + "\n" ); } export function attention( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["attention"] ) + if( verboseGet() >= verboseName2Number( "attention" ) ) write( getLogLinePrefixAttention() + fmtAttention( ...args ) + "\n" ); } export function information( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) + if( verboseGet() >= verboseName2Number( "information" ) ) write( getLogLinePrefixInformation() + fmtInformation( ...args ) + "\n" ); } export function info( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) + if( verboseGet() >= verboseName2Number( "information" ) ) write( getLogLinePrefixInformation() + fmtInformation( ...args ) + "\n" ); } export function notice( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) write( getLogLinePrefixNotice() + fmtNotice( ...args ) + "\n" ); } export function note( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["notice"] ) + if( verboseGet() >= verboseName2Number( "notice" ) ) write( getLogLinePrefixNote() + fmtNote( ...args ) + "\n" ); } export function debug( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["debug"] ) + if( verboseGet() >= verboseName2Number( "debug" ) ) write( getLogLinePrefixDebug() + fmtDebug( ...args ) + "\n" ); } export function trace( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["trace"] ) + if( verboseGet() >= verboseName2Number( "trace" ) ) write( getLogLinePrefixTrace() + fmtTrace( ...args ) + "\n" ); } export function success( ...args: any[] ) : void { - if( verboseGet() >= verboseReversed()["information"] ) + if( verboseGet() >= verboseName2Number( "information" ) ) write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) + "\n" ); } @@ -943,7 +943,7 @@ export function verboseReversed() : Map < string, number > { gMapReversedVerbose = computeVerboseAlias(); return gMapReversedVerbose; } -export function verboseLevelAsTextForLog( vl ) { +export function verboseLevelAsTextForLog( vl: any ) { if( typeof vl == "undefined" ) vl = verboseGet(); if( vl in gMapVerbose ) { @@ -952,14 +952,21 @@ export function verboseLevelAsTextForLog( vl ) { } return "unknown(" + JSON.stringify( vl ) + ")"; } +export function verboseName2Number( s: string ) : number { + const mapReversedVerbose: Map < string, number > = verboseReversed(); + let n = mapReversedVerbose.get( s ); + if( typeof n == "undefined" ) + return 9; + return n; +} let gFlagIsExposeDetails = false; -let gVerboseLevel = 0 + verboseReversed()["information"]; +let gVerboseLevel = 0 + verboseName2Number( "information" ); export function exposeDetailsGet() { return ( !!gFlagIsExposeDetails ); } -export function exposeDetailsSet( isExpose ) { +export function exposeDetailsSet( isExpose: any ) { gFlagIsExposeDetails = ( !!isExpose ); } @@ -1015,6 +1022,8 @@ export function em( x?: any ) : string { } export function stack( x?: any ) : string { + if( x && "stack" in x && x.stack ) + return stack( x.stack ); return cc.isStringAlreadyColorized( x ) ? x : cc.stack( x ); } diff --git a/src/loop.ts b/src/loop.ts index 26e7fb70..0f5d43bb 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -123,7 +123,7 @@ export function checkTimeFraming( return false; } catch ( err ) { log.error( "Exception in time framing check in {}: {err}, stack is:{}{stack}", - threadInfo.threadDescription(), err, "\n", err.stack ); + threadInfo.threadDescription(), err, "\n", err ); } return true; }; @@ -162,7 +162,7 @@ async function singleTransferLoopPartOracle( optsLoop: any, strLogPrefix: string } } catch ( err ) { log.error( "{p}Oracle operation exception: {} in {err}, stack is:{}{stack}", - strLogPrefix, err, threadInfo.threadDescription(), "\n", err.stack ); + strLogPrefix, err, threadInfo.threadDescription(), "\n", err ); imaState.loopState.oracle.isInProgress = false; await pwa.notifyOnLoopEnd( imaState, "oracle" ); throw err; @@ -221,7 +221,7 @@ async function singleTransferLoopPartM2S( optsLoop: any, strLogPrefix: string ) } } catch ( err ) { log.error( "{p}M2S transfer exception in {}: {err}, stack is:{}{stack}", - strLogPrefix, threadInfo.threadDescription(), err, "\n", err.stack ); + strLogPrefix, threadInfo.threadDescription(), err, "\n", err ); imaState.loopState.m2s.isInProgress = false; await pwa.notifyOnLoopEnd( imaState, "m2s" ); throw err; @@ -282,7 +282,7 @@ async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) } } catch ( err ) { log.error( "{p}S2M transfer exception in {err}: , stack is:{}{stack}", - strLogPrefix, threadInfo.threadDescription(), err, "\n", err.stack ); + strLogPrefix, threadInfo.threadDescription(), err, "\n", err ); imaState.loopState.s2m.isInProgress = false; await pwa.notifyOnLoopEnd( imaState, "s2m" ); throw err; @@ -322,7 +322,7 @@ async function singleTransferLoopPartS2S( optsLoop: any, strLogPrefix: string ) ); } catch ( err ) { log.error( "{p}S2S transfer exception in {}: {err}, stack is:{}{stack}", - strLogPrefix, threadInfo.threadDescription(), err, "\n", err.stack ); + strLogPrefix, threadInfo.threadDescription(), err, "\n", err ); throw err; } log.information( "{p}All S2S transfers done in {}: {}", @@ -392,7 +392,7 @@ export async function singleTransferLoop( optsLoop: any ) { return bResult; } catch ( err ) { log.error( "{p}Exception in transfer loop: {err}, stack is:{}{stack}", strLogPrefix, - err, "\n", err.stack ); + err, "\n", err ); } imaState.loopState.oracle.isInProgress = false; imaState.loopState.m2s.isInProgress = false; @@ -516,9 +516,10 @@ export async function ensureHaveWorkers( opts: any ) { }; gArrWorkers.push( new threadInfo.Worker( path.join( __dirname, "loopWorker.ts" ), - { "type": "module", "workerData": workerData } + { // "type": "module", + "workerData": workerData } ) ); - gArrWorkers[idxWorker].on( "message", jo => { + gArrWorkers[idxWorker].on( "message", function( jo: any ) { if( networkLayer.outOfWorkerAPIs.onMessage( gArrWorkers[idxWorker], jo ) ) return; } ); @@ -527,7 +528,7 @@ export async function ensureHaveWorkers( opts: any ) { gArrClients.push( aClient ); aClient.logicalInitComplete = false; aClient.errorLogicalInit = null; - aClient.on( "message", async function( eventData ) { + aClient.on( "message", async function( eventData: any ) { const joMessage = eventData.message; switch ( joMessage.method ) { case "init": diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 6c7d8701..4c53d4a0 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -61,10 +61,10 @@ function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { } class ObserverServer extends SocketServer { - initComplete: boolean; + initComplete?: boolean; opts: any; - intervalPeriodicSchainsCaching: number|null; - bIsPeriodicCachingStepInProgress: boolean; + intervalPeriodicSchainsCaching?: number|null; + bIsPeriodicCachingStepInProgress?: boolean; constructor( acceptor: any ) { super( acceptor ); const self: any = this; @@ -73,7 +73,8 @@ class ObserverServer extends SocketServer { self.opts = null; self.intervalPeriodicSchainsCaching = null; self.bIsPeriodicCachingStepInProgress = false; - self.mapApiHandlers.init = function( joMessage, joAnswer, eventData, socket ) { + self.mapApiHandlers.init = + function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { joAnswer.message = { "method": "" + joMessage.method, "error": null @@ -110,7 +111,7 @@ class ObserverServer extends SocketServer { log.enableColorization( joMessage.message.colorization.isEnabled ); log.verboseSet( self.opts.imaState.verbose_ ); log.exposeDetailsSet( self.opts.imaState.expose_details_ ); - imaTransferErrorHandling.saveTransferEvents.on( "error", function( eventData ) { + imaTransferErrorHandling.saveTransferEvents.on( "error", function( eventData: any ) { const jo: any = { "method": "saveTransferError", "message": eventData.detail @@ -118,7 +119,7 @@ class ObserverServer extends SocketServer { const isFlush = true; socket.send( jo, isFlush ); } ); - imaTransferErrorHandling.saveTransferEvents.on( "success", function( eventData ) { + imaTransferErrorHandling.saveTransferEvents.on( "success", function( eventData: any ) { const jo: any = { "method": "saveTransferSuccess", "message": eventData.detail @@ -184,7 +185,7 @@ class ObserverServer extends SocketServer { return joAnswer; }; self.mapApiHandlers.spreadUpdatedSChainNetwork = - function( joMessage, joAnswer, eventData, socket ) { + function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { self.initLogMethods(); self.debug( "New own S-Chains network information is arrived to {} loop worker " + @@ -195,7 +196,7 @@ class ObserverServer extends SocketServer { }; // eslint-disable-next-line dot-notation self.mapApiHandlers["skale_imaNotifyLoopWork"] = - function( joMessage, joAnswer, eventData, socket ) { + function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { self.initLogMethods(); pwa.handleLoopStateArrived( // NOTICE: no await here, executed async imaState, @@ -224,73 +225,73 @@ class ObserverServer extends SocketServer { if( "fatal" in self && self.fatal && typeof self.fatal == "function" ) return; self.fatal = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["fatal"] ) { + if( log.verboseGet() >= log.verboseName2Number( "fatal" ) ) { self.log( log.getLogLinePrefixFatal() + log.fmtFatal( ...args ) ); } }; self.critical = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["critical"] ) { + if( log.verboseGet() >= log.verboseName2Number( "critical" ) ) { self.log( log.getLogLinePrefixCritical() + log.fmtCritical( ...args ) ); } }; self.error = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["error"] ) { + if( log.verboseGet() >= log.verboseName2Number( "error" ) ) { self.log( log.getLogLinePrefixError() + log.fmtError( ...args ) ); } }; self.warning = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["warning"] ) { + if( log.verboseGet() >= log.verboseName2Number( "warning" ) ) { self.log( log.getLogLinePrefixWarning() + log.fmtWarning( ...args ) ); } }; self.attention = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["attention"] ) { + if( log.verboseGet() >= log.verboseName2Number( "attention" ) ) { self.log( log.getLogLinePrefixAttention() + log.fmtAttention( ...args ) ); } }; self.information = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["information"] ) { + if( log.verboseGet() >= log.verboseName2Number( "information" ) ) { self.log( log.getLogLinePrefixInformation() + log.fmtInformation( ...args ) ); } }; self.info = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["information"] ) { + if( log.verboseGet() >= log.verboseName2Number( "information" ) ) { self.log( log.getLogLinePrefixInformation() + log.fmtInformation( ...args ) ); } }; self.notice = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["notice"] ) { + if( log.verboseGet() >= log.verboseName2Number( "notice" ) ) { self.log( log.getLogLinePrefixNotice() + log.fmtNotice( ...args ) ); } }; self.note = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["notice"] ) { + if( log.verboseGet() >= log.verboseName2Number( "notice" ) ) { self.log( log.getLogLinePrefixNote() + log.fmtNote( ...args ) ); } }; self.debug = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["debug"] ) { + if( log.verboseGet() >= log.verboseName2Number( "debug" ) ) { self.log( log.getLogLinePrefixDebug() + log.fmtDebug( ...args ) ); } }; self.trace = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["trace"] ) { + if( log.verboseGet() >= log.verboseName2Number( "trace" ) ) { self.log( log.getLogLinePrefixTrace() + log.fmtTrace( ...args ) ); } }; self.success = function( ...args: any[] ) { - if( log.verboseGet() >= log.verboseReversed()["information"] ) { + if( log.verboseGet() >= log.verboseName2Number( "information" ) ) { self.log( log.getLogLinePrefixSuccess() + log.fmtSuccess( ...args ) ); } diff --git a/src/main.ts b/src/main.ts index 48bccb93..f1db1c24 100644 --- a/src/main.ts +++ b/src/main.ts @@ -50,7 +50,7 @@ process.on( "unhandledRejection", function( reason: any, p: any ) { } ).on( "uncaughtException", function( err: any ) { log.fatal( "CRITICAL ERROR: uncaught exception: {err}, stack is:\n{stack}", - err, err.stack ); + err, err ); process.exit( 1 ); } ); @@ -160,7 +160,7 @@ function initMonitoringServer() : void { ip = "N/A"; if( imaState.bLogMonitoringServer ) log.debug( "{p}New connection from {}", strLogPrefix, ip ); - wsPeer.on( "message", function( message ) { + wsPeer.on( "message", function( message: any ) { const joAnswer: any = { "method": null, "id": null, @@ -237,7 +237,7 @@ function initMonitoringServer() : void { } // switch( joMessage.method ) } catch ( err ) { log.error( "{p}Bad message from {}: {}, error is: {err}, stack is:\n{stack}", - strLogPrefix, ip, message, err, err.stack ); + strLogPrefix, ip, message, err, err ); } try { if( imaState.bLogMonitoringServer ) @@ -245,7 +245,7 @@ function initMonitoringServer() : void { wsPeer.send( JSON.stringify( joAnswer ) ); } catch ( err ) { log.error( "{p}Failed to sent answer to {}, error is: {err}, stack is:\n{stack}", - strLogPrefix, ip, err, err.stack ); + strLogPrefix, ip, err, err ); } } ); } ); @@ -261,18 +261,18 @@ function initJsonRpcServer() : void { gExpressJsonRpcAppIMA = express(); gExpressJsonRpcAppIMA.use( bodyParser.urlencoded( { extended: true } ) ); gExpressJsonRpcAppIMA.use( bodyParser.json() ); - gExpressJsonRpcAppIMA.post( "/", async function( req, res ) { + gExpressJsonRpcAppIMA.post( "/", async function( req: any, res: any ) { const isSkipMode = false; const message = JSON.stringify( req.body ); const ip = req.connection.remoteAddress.split( ":" ).pop(); - const fnSendAnswer: any = function( joAnswer ) { + const fnSendAnswer: any = function( joAnswer: any ) { try { res.header( "Content-Type", "application/json" ); res.status( 200 ).send( JSON.stringify( joAnswer ) ); log.trace( "{p}>>> did sent answer to {}: ", strLogPrefix, ip, joAnswer ); } catch ( err ) { log.error( "{p}Failed to sent answer {} to {}, error is: {err}, stack is:\n{stack}", - strLogPrefix, joAnswer, ip, err, err.stack ); + strLogPrefix, joAnswer, ip, err, err ); } }; let joAnswer: any = { @@ -333,7 +333,7 @@ function initJsonRpcServer() : void { } } catch ( err ) { log.error( "{p}Bad message from {}: {}, error is: {err}, stack is:\n{stack}", - strLogPrefix, ip, message, err, err.stack ); + strLogPrefix, ip, message, err, err ); } if( ! isSkipMode ) fnSendAnswer( joAnswer ); @@ -364,7 +364,7 @@ async function doTheJob() { } catch ( err ) { ++cntFalse; log.critical( "{p}Exception occurred while executing action: {err}, stack is:\n{stack}", - strLogPrefix, err, err.stack ); + strLogPrefix, err, err ); } } log.information( "{p}{p}", strLogPrefix, imaHelperAPIs.longSeparator ); @@ -422,7 +422,7 @@ async function main() { initJsonRpcServer(); const isSilentReDiscovery = imaState.isPrintSecurityValues ? false : imaState.joSChainDiscovery.isSilentReDiscovery; - const fnOnPeriodicDiscoveryResultAvailable = function( isFinal ) { + const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ) { loop.spreadUpdatedSChainNetwork( isFinal ); }; if( imaState.bSignMessages ) { @@ -444,7 +444,8 @@ async function main() { "This S-Chain discovery will be done for command line task handler" ); } const nCountToWait = -1; - discoveryTools.discoverSChainNetwork( function( err, joSChainNetworkInfo ) { + discoveryTools.discoverSChainNetwork( + function( err: Error|string, joSChainNetworkInfo: any ) { handleFirstSChainDiscoveryAttemptDone( err, joSChainNetworkInfo, isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ); @@ -453,7 +454,7 @@ async function main() { // everything else is in async calls executed later return 0; }, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait - ).catch( function( err ) { + ).catch( function( err: Error|string ) { const strError = owaspUtils.extractErrorMessage( err ); log.critical( "S-Chain network discovery failed: {err}", strError ); doTheJob(); diff --git a/src/oracle.ts b/src/oracle.ts index 84b868a8..d1966c6f 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -148,7 +148,7 @@ async function handleOracleSubmitRequestResult( } catch ( err ) { details.critical( "RPC call {} exception is: {err},stack is:\n{stack}", - "oracle_checkResult", err, err.stack ); + "oracle_checkResult", err, err ); await joCall.disconnect(); throw err; } @@ -166,7 +166,7 @@ export async function oracleGetGasPrice( oracleOpts: any, details: any ) { const isVerbose = "isVerbose" in oracleOpts ? oracleOpts.isVerbose : false; let isVerboseTraceDetails = "isVerboseTraceDetails" in oracleOpts ? oracleOpts.isVerboseTraceDetails : false; - if( ! ( log.verboseGet() >= log.verboseReversed()["trace"] ) ) + if( ! ( log.verboseGet() >= log.verboseName2Number( "trace" ) ) ) isVerboseTraceDetails = false; const callOpts = "callOpts" in oracleOpts ? oracleOpts.callOpts : { }; joCall = await rpcCall.create( url, callOpts || { } ); diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 962c377e..ac494b99 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -156,20 +156,23 @@ export function toURL( s: any ) : URL | null { const cnt = s.length; if( s[cnt - 1] == sc ) { const ss = s.substring( 1, cnt - 1 ); - const url = toURL( ss ); - if( url != null && url != undefined ) - url["strStrippedStringComma"] = sc; - return url; + const objURL = toURL( ss ); + if( objURL != null && objURL != undefined ) { + const anyURL: any = objURL; + anyURL["strStrippedStringComma"] = sc; + } + return objURL; } return null; } - const url = new URL( s ); - if( !url.hostname ) + const objURL = new URL( s ); + if( !objURL.hostname ) return null; - if( url.hostname.length === 0 ) + if( objURL.hostname.length === 0 ) return null; - url["strStrippedStringComma"] = null; - return url; + const anyURL: any = objURL; + anyURL["strStrippedStringComma"] = null; + return objURL; } catch ( err ) { return null; } @@ -631,7 +634,7 @@ export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ) : str } catch ( err ) { if( isThrowException ) { throw new Error( `Parse error in parseMoneySpecToWei( ${s} ), ` + - `error is: ${err.toString()}` ); + `error is: ${err}` ); } } return "0"; @@ -666,11 +669,12 @@ export function publicKeyToAccountAddress( keyPublic : string ) : string { } export function fnAddressImpl_() : string { - if( this.address_ == undefined || this.address_ == null || this.address_ == "" ) { - if( this.privateKey ) - this.address_ = "" + privateKeyToAccountAddress( this.privateKey ); + const anyThis: any = this; + if( anyThis.address_ == undefined || anyThis.address_ == null || anyThis.address_ == "" ) { + if( anyThis.privateKey ) + anyThis.address_ = "" + privateKeyToAccountAddress( anyThis.privateKey ); } - return this.address_; + return anyThis.address_; } export function getEthersProviderFromURL( strURL: string ) : any { diff --git a/src/package.json b/src/package.json index 0cb59ab7..d86cb8c9 100644 --- a/src/package.json +++ b/src/package.json @@ -14,17 +14,23 @@ "@ethersproject/experimental": "^5.7.0", "solc": "0.8.6", "uuid": "^9.0.0", + "@types/uuid": "^9.0.7", "express": "^4.18.2", + "@types/express": "^4.17.21", "body-parser": "^1.20.1", + "@types/body-parser": "^1.19.5", "jayson": "^4.0.0", - "ws": "^8.12.0", - "urllib": "^3.10.1", + "ws": "^8.15.0 ", + "@types/ws": "^8.5.10", + "urllib": "^3.21.0", "sha3": "2.1.4", "serve-static": "^1.15.0", "shelljs": "^0.8.5", + "@types/shelljs": "^0.8.15", "connect": "^3.7.0", "ethereum-multicall": "^2.16.1", - "ioredis": "^4.28.2", + "ioredis": "^5.0.0", + "@types/ioredis": "^4.28.2", "ethereumjs-util": "^7.1.5", "ethereumjs-wallet": "^1.0.2" }, diff --git a/src/pwa.ts b/src/pwa.ts index 420ff6b4..d9b31006 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -147,7 +147,7 @@ export async function checkOnLoopStart( log.success( "PWA loop start condition check passed" ); } catch ( err ) { log.critical( "Exception in PWA check on loop start: {err}, stack is:\n{stack}", - err, err.stack ); + err, err ); } return true; } @@ -199,7 +199,7 @@ export async function handleLoopStateArrived( "Exception in PWA handler for loop-{} for node {}, PWA state {}, arrived signature " + "is {}, error is: {err}, stack is:\n{stack}", se, nNodeNumber, ( joNode && "pwaState" in joNode ) ? joNode.pwaState : "N/A", signature, - err, err.stack ); + err, err ); } return isSuccess; } @@ -240,7 +240,7 @@ async function notifyOnLoopImpl( const strNodeURL = imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ); const rpcCallOpts: any = null; let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) - .catch( async function( err ) { + .catch( async function( err: Error|string ) { log.error( "PWA failed to perform] loop-{} notification RPC call to node #{} with " + "URL {url}, error is: {err}", se, i, strNodeURL, err ); @@ -270,7 +270,7 @@ async function notifyOnLoopImpl( } } catch ( err ) { log.error( "Exception in PWA notify on loop {}: {err}, stack is:\n{stack}", se, - err, err.stack ); + err, err ); } return true; } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 208e4c19..2c507640 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -33,8 +33,8 @@ import * as log from "./log"; const gSecondsConnectionTimeout = 60; export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any ) { - fnDone = fnDone || async function( nStep ) {}; - fnDone = fnStep || async function( nStep ) { return true; }; + fnDone = fnDone || async function( nStep: number ) {}; + fnDone = fnStep || async function( nStep: number ) { return true; }; let nStep = 0; const promiseComplete = new Promise( function( resolve, reject ) { let isInsideAsyncHandler = false; @@ -84,7 +84,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { "web socket was closed, please check provided URL is valid and accessible"; joCall.wsConn = null; } ); - joCall.wsConn.on( "error", async function( err ) { + joCall.wsConn.on( "error", async function( err: any ) { strWsError = err.toString() || "internal web socket error"; log.error( "{url} web socket error: {err}", joCall.url, err ); const wsConn = joCall.wsConn; @@ -92,7 +92,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { wsConn.close(); doReconnectWsStep( joCall, opts ); } ); - joCall.wsConn.on( "fail", async function( err ) { + joCall.wsConn.on( "fail", async function( err: any ) { strWsError = err.toString() || "internal web socket failure"; log.error( "{url} web socket fail: {err}", joCall.url, err ); const wsConn = joCall.wsConn; @@ -100,7 +100,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { wsConn.close(); doReconnectWsStep( joCall, opts ); } ); - joCall.wsConn.on( "message", async function incoming( data ) { + joCall.wsConn.on( "message", async function incoming( data: any ) { const joOut = JSON.parse( data ); if( joOut.id in joCall.mapPendingByCallID ) { const entry = joCall.mapPendingByCallID[joOut.id]; @@ -115,9 +115,9 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { } } ); await waitWebSocketIsOpen( joCall.wsConn, - async function( nStep ) { // work done handler + async function( nStep: number ) { // work done handler }, - async function( nStep ) { // step handler + async function( nStep: number ) { // step handler if( strWsError && typeof strWsError == "string" && strWsError.length > 0 ) { log.error( "{url} web socket wait error detected: {err}", joCall.url, strWsError ); @@ -175,7 +175,7 @@ async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { return; if( joCall.isDisconnectMode ) return; - doConnect( joCall, opts, async function( joCall, err ) { + doConnect( joCall, opts, async function( joCall: any, err: any ) { if( err ) { doReconnectWsStep( joCall, opts ); return; @@ -257,7 +257,7 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { try { const req = https.request( options, ( res: any ) => { res.setEncoding( "utf8" ); - res.on( "data", body => { + res.on( "data", function( body: any ) { accumulatedBody += body; } ); res.on( "end", function() { @@ -273,15 +273,15 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { resolve( joOut ); } catch ( err ) { joOut = null; - errCall = "Response body parse error: " + err.toString(); + errCall = "Response body parse error: " + err; reject( errCall ); } } ); } ); - req.on( "error", err => { + req.on( "error", function( err: any ) { log.error( "{url} REST error {err}", joCall.url, err ); joOut = null; - errCall = `HTTP(S)/RPC call(event) error: ${err.toString()}`; + errCall = `HTTP(S)/RPC call(event) error: ${err}`; reject( errCall ); } ); req.write( strBody ); @@ -289,14 +289,14 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { } catch ( err ) { log.error( "{url} REST error {err}", joCall.url, err ); joOut = null; - errCall = `HTTP(S)/RPC call(processing) error: ${err.toString()}`; + errCall = `HTTP(S)/RPC call(processing) error: ${err}`; reject( errCall ); } } ); - await promiseComplete.catch( function( err ) { + await promiseComplete.catch( function( err: Error|string ) { log.error( "{url} HTTP call error {err}", joCall.url, err ); if( ! errCall ) - errCall = `HTTP(S)/RPC call(catch) error: ${err.toString()}`; + errCall = `HTTP(S)/RPC call(catch) error: ${err}`; } ); } else { try { @@ -330,7 +330,7 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { } catch ( err ) { log.error( "{url} request error {err}", joCall.url, err ); joOut = null; - errCall = "request error: " + err.toString(); + errCall = "request error: " + err; } } try { @@ -356,36 +356,36 @@ export async function rpcCallCreate( strURL: string, opts: any ) { "isAutoReconnect": ( opts && "isAutoReconnect" in opts && opts.isAutoReconnect ) ? true : false, "isDisconnectMode": false, - "reconnect": async function( fnAfter ) { + "reconnect": async function( fnAfter: any ) { await doConnect( joCall, fnAfter ); }, - "reconnect_if_needed": async function( fnAfter ) { + "reconnect_if_needed": async function( fnAfter: any ) { await doConnectIfNeeded( joCall, opts, fnAfter ); }, - "call": function( joIn, fnAfter ) { + "call": function( joIn: any, fnAfter: any ) { const self = this; - const promiseComplete = new Promise( function( resolve, reject ) { - self.reconnect_if_needed( async function( joCall, err ) { + const promiseComplete = new Promise( function( resolve: any, reject: any ) { + self.reconnect_if_needed( async function( joCall: any, err: any ) { if( err ) { if( fnAfter ) await fnAfter( joIn, null, err ); reject( err ); return; } - await doCall( joCall, joIn, async function( joIn, joOut, err ) { + await doCall( joCall, joIn, async function( joIn: any, joOut: any, err: any ) { if( fnAfter ) await fnAfter( joIn, joOut, err ); if( err ) reject( err ); else resolve( joOut ); - } ).catch( function( err ) { + } ).catch( function( err: Error|string ) { log.error( "{url} JSON RPC call(performer) error: {err}", strURL, err ); } ); } ); } ); - return promiseComplete.catch( function( err ) { + return promiseComplete.catch( function( err: Error|string ) { log.error( "{url} JSON RPC call(awaiter) error: {err}", strURL, err ); } ); @@ -509,7 +509,7 @@ export function checkTcpPromise( strHost: string, nPort: number, nTimeoutMillise `default TCP connection to ${strHost}:${nPort} timeout...` ); } } - conn.on( "timeout", err => { + conn.on( "timeout", function( err: any ) { if( isLog ) { console.log( `${gStrTcpConnectionHeader}TCP connection ` + @@ -518,7 +518,7 @@ export function checkTcpPromise( strHost: string, nPort: number, nTimeoutMillise conn.destroy(); reject( err ); } ); - conn.on( "error", err => { + conn.on( "error", function( err: any ) { if( isLog ) { console.log( `${gStrTcpConnectionHeader}TCP connection ` + @@ -558,12 +558,12 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec isOnline = false; console.log( `${gStrTcpConnectionHeader}TCP connection ` + - `to ${strHost}:${nPort} check failed with error: ${err.toString()}` ); + `to ${strHost}:${nPort} check failed with error: ${err}` ); } return isOnline; } -export async function checkUrl( u: string, nTimeoutMilliseconds: number, isLog?: boolean ) { +export async function checkUrl( u: URL|string, nTimeoutMilliseconds: number, isLog?: boolean ) { if( ! u ) return false; const jo: any = getValidHostAndPort( u ); diff --git a/src/socket.ts b/src/socket.ts index 4ff604b4..42c77e47 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -103,7 +103,7 @@ export class BasicServerAcceptor extends EventDispatcher { strEndPoint: string|null; nextClientNumber: number; mapClients: any; - url: string; + url?: string; constructor() { super(); this.socketType = "BasicAcceptor"; @@ -383,9 +383,9 @@ export const isRunningInWorker = function() { }; // in-worker clients in connecting state -export const gMapAwaitingInWorkerClients = { }; +export const gMapAwaitingInWorkerClients: Record < string, any > = { }; // in-worker clients in connecting state -export const gMapConnectedInWorkerClients = { }; +export const gMapConnectedInWorkerClients: Record < string, any > = { }; export const outOfWorkerAPIs: any = { "onMessage": function( worker: any, data: any ) { @@ -405,19 +405,19 @@ export const outOfWorkerAPIs: any = { case "inWorkerConnect": { if( !( jo.workerUUID in gMapAwaitingInWorkerClients ) ) return false; - const pipe = gMapAwaitingInWorkerClients[jo.workerUUID]; + const pipe: any = gMapAwaitingInWorkerClients[ "" + jo.workerUUID ]; pipe.performSuccessfulConnection(); } return true; case "inWorkerDisconnect": { if( !( jo.workerUUID in gMapConnectedInWorkerClients ) ) return false; - const pipe = gMapConnectedInWorkerClients[jo.workerUUID]; + const pipe: any = gMapConnectedInWorkerClients[jo.workerUUID]; pipe.performDisconnect(); } return true; case "inWorkerMessage": { if( !( jo.workerUUID in gMapConnectedInWorkerClients ) ) return false; - const pipe = gMapConnectedInWorkerClients[jo.workerUUID]; + const pipe: any = gMapConnectedInWorkerClients[jo.workerUUID]; pipe.receive( jo.data ); } return true; default: @@ -680,9 +680,9 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { }; export class OutOfWorkerRelay extends EventDispatcher { - strRelayName: string; - isAutoFlushIncoming: boolean; - isAutoFlushOutgoing: boolean; + strRelayName?: string; + isAutoFlushIncoming?: boolean; + isAutoFlushOutgoing?: boolean; acceptor: any; fnCreateClient: any; onConnection_: any; @@ -919,9 +919,9 @@ export class OutOfWorkerRelay extends EventDispatcher { }; export class OneToOneRelay extends EventDispatcher { - strRelayName: string; - isAutoFlushIncoming: boolean; - isAutoFlushOutgoing: boolean; + strRelayName?: string; + isAutoFlushIncoming?: boolean; + isAutoFlushOutgoing?: boolean; pipeIncoming: any; pipeOutgoing: any; // eslint-disable-next-line max-lines-per-function @@ -1478,7 +1478,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { export class WebSocketServerAcceptor extends BasicServerAcceptor { wsServer: any; httpsModule: any; - constructor( nTcpPort, key, cert ) { + constructor( nTcpPort: null, key?: string, cert?: string ) { super(); this.socketType = "WS"; this.wsServer = null; @@ -1496,7 +1496,7 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { this.wsServer = new wsModule.WebSocketServer( { port: nTcpPort } ); const self = this; - self.wsServer.on( "connection", function( wsConnection, req ) { + self.wsServer.on( "connection", function( wsConnection: any, req: any ) { wsConnection.strSavedRemoteAddress = "" + req.connection.remoteAddress; wsConnection.serverPipe = new WebSocketServerPipe( self, wsConnection, req.connection.remoteAddress ); @@ -1784,7 +1784,7 @@ export class RTCConnection extends EventDispatcher { this.pc = null; } } - onError( err ) { + onError( err: any ) { this.dispatchEvent( new UniversalDispatcherEvent( "rtcParticipantError", { "detail": { "actor": this, "error": err } } ) ); @@ -1802,7 +1802,7 @@ export class RTCConnection extends EventDispatcher { try { this.dc.send( s ); } catch ( err ) { - this.onError( "Failed to send message to RTC data channel: " + err.toString() ); + this.onError( "Failed to send message to RTC data channel: " + err ); } } onDataChannelOpen( event: any ) { @@ -2193,7 +2193,7 @@ export class RTCActor extends RTCConnection { } onImpersonationComplete() { } // generic implementation should never be called - onOtherSideIdentified( idSomebodyOtherSide, idOffer ) { } + onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ) { } }; export class RTCServerPeer extends RTCConnection { @@ -2379,7 +2379,7 @@ export class RTCServerPeer extends RTCConnection { self.pc.onnegotiationneeded = function( event: any ) { self.onIceNegotiationNeeded( event ); }; self.pc.createOffer( self.offerOptions ).then( - function( offerDescription ) { + function( offerDescription: any ) { // success self.tsOfferCreated = new Date(); if( settings.logging.net.signaling.offer ) { @@ -2410,17 +2410,17 @@ export class RTCServerPeer extends RTCConnection { self.iceComplete = true; self.onIceComplete( event ); }; // onicecandidate - }, function( err ) { + }, function( err: any ) { // error of setLocalDescription self.publishCancel(); self.signalingNegotiationCancel(); - self.onError( "Failed to set local description: " + err.toString() ); + self.onError( "Failed to set local description: " + err ); } ); - }, function( err ) { + }, function( err: any ) { self.publishCancel(); self.signalingNegotiationCancel(); // error of createOffer - self.onError( "Failed to create offer:" + err.toString() ); + self.onError( "Failed to create offer:" + err ); } ); } onOtherSideIdentified( idSomebodyOtherSide: any ) { @@ -2439,7 +2439,7 @@ export class RTCServerPeer extends RTCConnection { } ) ); } - onError( err ) { + onError( err: any ) { if( this.rtcCreator ) { this.rtcCreator.onRtcPeerError( this, err ); if( this.idOffer && this.idOffer in this.rtcCreator.mapServerOffers ) { @@ -2541,13 +2541,13 @@ export class RTCServerPeer extends RTCConnection { } catch ( err ) { self.publishCancel(); self.signalingNegotiationCancel(); - self.onError( "Failed to process ICE candidate: " + err.toString() ); + self.onError( "Failed to process ICE candidate: " + err ); } } }; export class RTCCreator extends RTCActor { - idOfferNext: number; + idOfferNext?: number; mapServerOffers: any; mapServerPeers: any; constructor( @@ -2721,9 +2721,9 @@ export class RTCCreator extends RTCActor { ); self.onOtherSideIdentified( idSomebodyOtherSide, idOffer ); // server peer got result - }, function( err ) { + }, function( err: any ) { // error - self.onError( "Failed to set remote description: " + err.toString() ); + self.onError( "Failed to set remote description: " + err ); } ); } else { if( settings.logging.net.signaling.error ) { @@ -2890,7 +2890,7 @@ export class RTCJoiner extends RTCActor { } } catch ( err ) { self.onError( - "Failed to process ICE candidate: " + err.toString() + "Failed to process ICE candidate: " + err ); } }; // onicecandidate @@ -2951,7 +2951,7 @@ export class RTCJoiner extends RTCActor { onIceComplete( event: any ) { super.onIceComplete( event ); } - onOtherSideIdentified( idSomebodyOtherSide, idOffer ) { // client peer got result + onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ) { // client peer got result if( settings.logging.net.signaling.impersonate ) { console.log( this.describe() + " did identified other side RTC creator \"" + @@ -3018,7 +3018,7 @@ export class RTCJoiner extends RTCActor { "remoteDescriptionSet", { "detail": { "participant": self } } ) ); self.pc.createAnswer( self.offerOptions ).then( - function( answerDescription ) { + function( answerDescription: any ) { // success self.tsAnswerCreated = new Date(); if( settings.logging.net.signaling.answer ) { @@ -3046,7 +3046,7 @@ export class RTCJoiner extends RTCActor { self.onOtherSideIdentified( idSomebodyOtherSide, idOffer ); // client peer got result - }, function( err ) { + }, function( err: any ) { // error of setLocalDescription self.onError( "Failed to set local description " + @@ -3054,17 +3054,17 @@ export class RTCJoiner extends RTCActor { idSomebodyOtherSide + "\"): " + err.toString() ); } ); - }, function( err ) { + }, function( err: any ) { // error of createAnswer self.onError( "Failed to create answer (while fetching offer for \"" + - idSomebodyOtherSide + "\"): " + err.toString() ); + idSomebodyOtherSide + "\"): " + err ); } ); - }, function( err ) { + }, function( err: any ) { // error of setLocalDescription self.onError( "Failed to set remote description: (while fetching offer for \"" + - idSomebodyOtherSide + "\"): " + err.toString() ); + idSomebodyOtherSide + "\"): " + err ); } ); } else { if( settings.logging.net.signaling.error ) { @@ -3087,9 +3087,9 @@ export class RTCJoiner extends RTCActor { }; export class WebRTCServerPipe extends BasicSocketPipe { - clientNumber: number; + clientNumber?: number; rtcPeer: any; - strSignalingServerURL: string; + strSignalingServerURL?: string; constructor( acceptor: any, rtcPeer: any, strSignalingServerURL: string ) { super(); const self = this; @@ -3098,13 +3098,13 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.isConnected = true; self.acceptor = acceptor; self.clientNumber = 0 + acceptor.nextClientNumber; - self.clientPort = 0 + self.clientNumber; + self.clientPort = 0 + ( self.clientNumber || 0 ); ++ acceptor.nextClientNumber; self.rtcPeer = rtcPeer; self.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); self.url = "rtc_server_pipe(" + self.clientNumber + ")://" + strSignalingServerURL; - self.rtcPeer.on( "dataChannelOpen", function( jo ) { + self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { self.isConnected = true; self.acceptor.mapClients["" + self.clientPort] = self; self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); @@ -3113,25 +3113,25 @@ export class WebRTCServerPipe extends BasicSocketPipe { "connection", { "socket": self, strSignalingServerURL: "" + strSignalingServerURL } ) ); } ); - self.rtcPeer.on( "dataChannelMessage", function( jo ) { + self.rtcPeer.on( "dataChannelMessage", function( jo: any ) { self.receive( jo.detail.data ); } ); - self.rtcPeer.on( "rtcParticipantError", function( jo ) { + self.rtcPeer.on( "rtcParticipantError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": self, "message": jo } ) ); } ); - self.rtcPeer.on( "dataChannelError", function( jo ) { + self.rtcPeer.on( "dataChannelError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": self, "message": jo } ) ); } ); - self.rtcPeer.on( "dataChannelClose", function( jo ) { + self.rtcPeer.on( "dataChannelClose", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self, "message": jo } ) ); } ); - self.rtcPeer.on( "peerClose", function( jo ) { + self.rtcPeer.on( "peerClose", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self, "message": jo } ) ); @@ -3176,7 +3176,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); } - onError( err ) { + onError( err: any ) { } disconnect() { this.performDisconnect(); @@ -3201,7 +3201,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { timeToPublishMilliseconds: number; timeToSignalingNegotiationMilliseconds: number; rtcCreator: any; - isConnected: false; + isConnected?: false; constructor( strSignalingServerURL: string, idRtcParticipant: any, offerOptions: any, signalingOptions: any, maxActiveOfferCount?: number, timeToPublishMilliseconds?: number, @@ -3274,7 +3274,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { "close", { "detail": { "acceptor": self, "eventData": eventData } } ) ); } ); - self.rtcCreator.on( "signalingPipeError", function( jo ) { + self.rtcCreator.on( "signalingPipeError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( @@ -3485,7 +3485,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { ); } } ); - self.rtcPeer.on( "dataChannelOpen", function( jo ) { + self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { self.isConnected = true; self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) @@ -3501,10 +3501,10 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.rtcPeer.signalingPipeClose(); } } ); - self.rtcPeer.on( "dataChannelMessage", function( jo ) { + self.rtcPeer.on( "dataChannelMessage", function( jo: any ) { self.receive( jo.detail.data ); } ); - self.rtcPeer.on( "rtcParticipantError", function( jo ) { + self.rtcPeer.on( "rtcParticipantError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3515,7 +3515,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { } ) ); } ); - self.rtcPeer.on( "dataChannelError", function( jo ) { + self.rtcPeer.on( "dataChannelError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3526,13 +3526,13 @@ export class WebRTCClientPipe extends BasicSocketPipe { } ) ); } ); - self.rtcPeer.on( "dataChannelClose", function( jo ) { + self.rtcPeer.on( "dataChannelClose", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self, "message": jo } ) ); } ); - self.rtcPeer.on( "signalingPipeError", function( jo ) { + self.rtcPeer.on( "signalingPipeError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", diff --git a/src/socketServer.ts b/src/socketServer.ts index ece5904d..0f05b0a1 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -32,10 +32,10 @@ export class SocketServer extends EventDispatcher { acceptor: any; mapApiHandlers: any; mapAcceptedPipes: any; - isLogAcceptedSocket: boolean; - isLogSocketErrors: boolean; - isLogSocketTraffic: boolean; - isLogSocketTrafficRaw: boolean; + isLogAcceptedSocket?: boolean; + isLogSocketErrors?: boolean; + isLogSocketTraffic?: boolean; + isLogSocketTrafficRaw?: boolean; constructor( acceptor: any ) { super(); if( acceptor == null || acceptor == undefined || typeof acceptor != "object" ) @@ -49,7 +49,7 @@ export class SocketServer extends EventDispatcher { self.isLogSocketErrors = true; self.isLogSocketTraffic = false; self.isLogSocketTrafficRaw = false; - acceptor.on( "connection", function( eventData ) { + acceptor.on( "connection", function( eventData: any ) { const socket = eventData.socket; if( ( ! ( "remoteAddress" in eventData ) ) || eventData.remoteAddress == null || @@ -74,7 +74,7 @@ export class SocketServer extends EventDispatcher { } delete self.mapAcceptedPipes[socket]; }; - let _onPipeError: any = function( eventData ) { + let _onPipeError: any = function( eventData: any ) { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Socket {url} error {err}", socket.strSavedRemoteAddress, eventData ) ); @@ -85,7 +85,7 @@ export class SocketServer extends EventDispatcher { } delete self.mapAcceptedPipes[socket]; }; - let _onPipeMessage: any = function( eventData ) { + let _onPipeMessage: any = function( eventData: any ) { if( self.isLogSocketTrafficRaw ) { self.log( log.fmtInformation( "Socket {url} did received {sunny} {}", socket.strSavedRemoteAddress, "raw-message", eventData ) ); @@ -118,10 +118,10 @@ export class SocketServer extends EventDispatcher { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Server method {} RPC exception: {err}, stack is: {stack}", - joMessage.method, err, err.stack ) ); + joMessage.method, err, err ) ); } joAnswer = utils.prepareAnswerJSON( joMessage ); - joAnswer.error = "" + err.toString(); + joAnswer.error = "" + err; } if( joAnswer != null && joAnswer != undefined ) { diff --git a/src/state.ts b/src/state.ts index 11e81873..ec2ab1be 100644 --- a/src/state.ts +++ b/src/state.ts @@ -286,7 +286,7 @@ export function get() { return imaState; } -export function set( imaStateNew ) { +export function set( imaStateNew: any ) { imaState = imaStateNew; return imaState; } @@ -297,6 +297,6 @@ export function isPreventExitAfterLastAction() { return gFlagIsPreventExitAfterLastAction; } -export function setPreventExitAfterLastAction( isPrevent ) { - gFlagIsPreventExitAfterLastAction = isPrevent; +export function setPreventExitAfterLastAction( isPrevent: any ) { + gFlagIsPreventExitAfterLastAction = (!!isPrevent); } diff --git a/src/tsconfig.json b/src/tsconfig.json new file mode 100644 index 00000000..7fec2598 --- /dev/null +++ b/src/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + "target": "es2022" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "es2022" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "declaration": true /* Generates corresponding '.d.ts' file. */, + "outDir": "build" /* Redirect output structure to the directory. */, + /* Strict Type-Checking Options */ + "strict": true /* Enable all strict type-checking options. */, + "resolveJsonModule": true, + /* Module Resolution Options */ + "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + /* Advanced Options */ + "skipLibCheck": true /* Skip type checking of declaration files. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +} diff --git a/src/utils.ts b/src/utils.ts index e5866f76..c4705667 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -107,7 +107,7 @@ export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boo return jo; } catch ( err ) { log.error( "Failed to load JSON file {}, error is: {err}, stack is:\n{stack}", - strPath, err, err.stack ); + strPath, err, err ); } return joDefault; } @@ -125,7 +125,7 @@ export function jsonFileSave( strPath: string, jo?: any, bLogOutput?: boolean ) return true; } catch ( err ) { log.error( " failed to save JSON file {}, error is: {err}, stack is:\n{stack}", - strPath, err, err.stack ); + strPath, err, err ); } return false; } @@ -375,7 +375,7 @@ export function checkKeyExistInABI( } catch ( err ) { if( isExitOnError ) { log.fatal( "Loaded {} ABI JSON file {} does not contain needed key {}, stack is:\n{stack}", - strName, strFile, strKey, err.stack ); + strName, strFile, strKey, err ); process.exit( 126 ); } } diff --git a/src/yarn.lock b/src/yarn.lock index 13a25f53..0f8b595d 100644 --- a/src/yarn.lock +++ b/src/yarn.lock @@ -414,6 +414,11 @@ resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-2.0.1.tgz#e5211452df060fa8522b55c7b3c0c4d1981cb044" integrity sha512-dvuCeX5fC9dXgJn9t+X5atfmgQAzUOWqS1254Gh0m6i8wKd10ebXkfNKiRK+1GWi/yTvvLDHpoxLr0xxxeslWw== +"@ioredis/commands@^1.1.1": + version "1.2.0" + resolved "https://registry.yarnpkg.com/@ioredis/commands/-/commands-1.2.0.tgz#6d61b3097470af1fdbbe622795b8921d42018e11" + integrity sha512-Sx1pU8EM64o2BrqNpEO1CNLtKQwyhuXuqyfH7oGKCk+1a33d2r5saW8zNwm3j6BTExtjrv2BxTgzzkMwts6vGg== + "@nodelib/fs.scandir@2.1.5": version "2.1.5" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5" @@ -442,6 +447,21 @@ dependencies: "@types/node" "*" +"@types/body-parser@*", "@types/body-parser@^1.19.5": + version "1.19.5" + resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.5.tgz#04ce9a3b677dc8bd681a17da1ab9835dc9d3ede4" + integrity sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg== + dependencies: + "@types/connect" "*" + "@types/node" "*" + +"@types/connect@*": + version "3.4.38" + resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.38.tgz#5ba7f3bc4fbbdeaff8dded952e5ff2cc53f8d858" + integrity sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug== + dependencies: + "@types/node" "*" + "@types/connect@^3.4.33": version "3.4.36" resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.36.tgz#e511558c15a39cb29bd5357eebb57bd1459cd1ab" @@ -449,11 +469,66 @@ dependencies: "@types/node" "*" +"@types/express-serve-static-core@^4.17.33": + version "4.17.41" + resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.41.tgz#5077defa630c2e8d28aa9ffc2c01c157c305bef6" + integrity sha512-OaJ7XLaelTgrvlZD8/aa0vvvxZdUmlCn6MtWeB7TkiKW70BQLc9XEPpDLPdbo52ZhXUCrznlWdCHWxJWtdyajA== + dependencies: + "@types/node" "*" + "@types/qs" "*" + "@types/range-parser" "*" + "@types/send" "*" + +"@types/express@^4.17.21": + version "4.17.21" + resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.21.tgz#c26d4a151e60efe0084b23dc3369ebc631ed192d" + integrity sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ== + dependencies: + "@types/body-parser" "*" + "@types/express-serve-static-core" "^4.17.33" + "@types/qs" "*" + "@types/serve-static" "*" + +"@types/glob@~7.2.0": + version "7.2.0" + resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.2.0.tgz#bc1b5bf3aa92f25bd5dd39f35c57361bdce5b2eb" + integrity sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA== + dependencies: + "@types/minimatch" "*" + "@types/node" "*" + +"@types/http-errors@*": + version "2.0.4" + resolved "https://registry.yarnpkg.com/@types/http-errors/-/http-errors-2.0.4.tgz#7eb47726c391b7345a6ec35ad7f4de469cf5ba4f" + integrity sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA== + +"@types/ioredis@^4.28.2": + version "4.28.10" + resolved "https://registry.yarnpkg.com/@types/ioredis/-/ioredis-4.28.10.tgz#40ceb157a4141088d1394bb87c98ed09a75a06ff" + integrity sha512-69LyhUgrXdgcNDv7ogs1qXZomnfOEnSmrmMFqKgt1XMJxmoOSG/u3wYy13yACIfKuMJ8IhKgHafDO3sx19zVQQ== + dependencies: + "@types/node" "*" + "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ== +"@types/mime@*": + version "3.0.4" + resolved "https://registry.yarnpkg.com/@types/mime/-/mime-3.0.4.tgz#2198ac274de6017b44d941e00261d5bc6a0e0a45" + integrity sha512-iJt33IQnVRkqeqC7PzBHPTC6fDlRNRW8vjrgqtScAhrmMwe8c4Eo7+fUGTa+XdWrpEgpyKWMYmi2dIwMAYRzPw== + +"@types/mime@^1": + version "1.3.5" + resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.5.tgz#1ef302e01cf7d2b5a0fa526790c9123bf1d06690" + integrity sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w== + +"@types/minimatch@*": + version "5.1.2" + resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-5.1.2.tgz#07508b45797cb81ec3f273011b054cd0755eddca" + integrity sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA== + "@types/node@*": version "20.8.4" resolved "https://registry.yarnpkg.com/@types/node/-/node-20.8.4.tgz#0e9ebb2ff29d5c3302fc84477d066fa7c6b441aa" @@ -473,6 +548,16 @@ dependencies: "@types/node" "*" +"@types/qs@*": + version "6.9.10" + resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.10.tgz#0af26845b5067e1c9a622658a51f60a3934d51e8" + integrity sha512-3Gnx08Ns1sEoCrWssEgTSJs/rsT2vhGP+Ja9cnnk9k4ALxinORlQneLXFeFKOTJMOeZUFD1s7w+w2AphTpvzZw== + +"@types/range-parser@*": + version "1.2.7" + resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.7.tgz#50ae4353eaaddc04044279812f52c8c65857dbcb" + integrity sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ== + "@types/secp256k1@^4.0.1": version "4.0.4" resolved "https://registry.yarnpkg.com/@types/secp256k1/-/secp256k1-4.0.4.tgz#33c760de627fce1f449c2d4270da07e4da54c830" @@ -480,6 +565,36 @@ dependencies: "@types/node" "*" +"@types/send@*": + version "0.17.4" + resolved "https://registry.yarnpkg.com/@types/send/-/send-0.17.4.tgz#6619cd24e7270793702e4e6a4b958a9010cfc57a" + integrity sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA== + dependencies: + "@types/mime" "^1" + "@types/node" "*" + +"@types/serve-static@*": + version "1.15.5" + resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.15.5.tgz#15e67500ec40789a1e8c9defc2d32a896f05b033" + integrity sha512-PDRk21MnK70hja/YF8AHfC7yIsiQHn1rcXx7ijCFBX/k+XQJhQT/gw3xekXKJvx+5SXaMMS8oqQy09Mzvz2TuQ== + dependencies: + "@types/http-errors" "*" + "@types/mime" "*" + "@types/node" "*" + +"@types/shelljs@^0.8.15": + version "0.8.15" + resolved "https://registry.yarnpkg.com/@types/shelljs/-/shelljs-0.8.15.tgz#22c6ab9dfe05cec57d8e6cb1a95ea173aee9fcac" + integrity sha512-vzmnCHl6hViPu9GNLQJ+DZFd6BQI2DBTUeOvYHqkWQLMfKAAQYMb/xAmZkTogZI/vqXHCWkqDRymDI5p0QTi5Q== + dependencies: + "@types/glob" "~7.2.0" + "@types/node" "*" + +"@types/uuid@^9.0.7": + version "9.0.7" + resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.7.tgz#b14cebc75455eeeb160d5fe23c2fcc0c64f724d8" + integrity sha512-WUtIVRUZ9i5dYXefDEAI7sh9/O7jGvHg7Df/5O/gtH3Yabe5odI3UWopVR1qbPXQtvOxWu3mM4XxlYeZtMWF4g== + "@types/ws@^7.4.4": version "7.4.7" resolved "https://registry.yarnpkg.com/@types/ws/-/ws-7.4.7.tgz#f7c390a36f7a0679aa69de2d501319f4f8d9b702" @@ -487,6 +602,13 @@ dependencies: "@types/node" "*" +"@types/ws@^8.5.10": + version "8.5.10" + resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.10.tgz#4acfb517970853fa6574a3a6886791d04a396787" + integrity sha512-vmQSUcfalpIq0R9q7uTo2lXs6eGIpt9wtnLdMv9LVpIjCA/+ufZRozlVoVelIYixx1ugCBKDhn89vnsEGOCx9A== + dependencies: + "@types/node" "*" + "@ungap/structured-clone@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.2.0.tgz#756641adb587851b5ccb3e095daf27ae581c8406" @@ -916,7 +1038,7 @@ debug@^3.2.7: dependencies: ms "^2.1.1" -debug@^4.1.1, debug@^4.3.1, debug@^4.3.2: +debug@^4.1.1, debug@^4.3.2, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== @@ -958,10 +1080,10 @@ delay@^5.0.0: resolved "https://registry.yarnpkg.com/delay/-/delay-5.0.0.tgz#137045ef1b96e5071060dd5be60bf9334436bd1d" integrity sha512-ReEBKkIfe4ya47wlPYf/gu5ib6yUG0/Aez0JQZQz94kiWtRQvZIQbTiehsnwHvLSWJnQdhVeqYue7Id1dKr0qw== -denque@^1.1.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/denque/-/denque-1.5.1.tgz#07f670e29c9a78f8faecb2566a1e2c11929c5cbf" - integrity sha512-XwE+iZ4D6ZUB7mfYRMb5wByE8L74HCn30FBN7sWnXksWc1LO1bPDl67pBR9o/kC4z/xSNAwkMYcGgqDV3BE3Hw== +denque@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/denque/-/denque-2.1.0.tgz#e93e1a6569fb5e66f16a3c2a2964617d349d6ab1" + integrity sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw== depd@2.0.0: version "2.0.0" @@ -1835,19 +1957,17 @@ interpret@^1.0.0: resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e" integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== -ioredis@^4.28.2: - version "4.28.5" - resolved "https://registry.yarnpkg.com/ioredis/-/ioredis-4.28.5.tgz#5c149e6a8d76a7f8fa8a504ffc85b7d5b6797f9f" - integrity sha512-3GYo0GJtLqgNXj4YhrisLaNNvWSNwSS2wS4OELGfGxH8I69+XfNdnmV1AyN+ZqMh0i7eX+SWjrwFKDBDgfBC1A== +ioredis@^5.0.0: + version "5.3.2" + resolved "https://registry.yarnpkg.com/ioredis/-/ioredis-5.3.2.tgz#9139f596f62fc9c72d873353ac5395bcf05709f7" + integrity sha512-1DKMMzlIHM02eBBVOFQ1+AolGjs6+xEcM4PDL7NqOS6szq7H9jSaEkIUH6/a5Hl241LzW6JLSiAbNvTQjUupUA== dependencies: + "@ioredis/commands" "^1.1.1" cluster-key-slot "^1.1.0" - debug "^4.3.1" - denque "^1.1.0" + debug "^4.3.4" + denque "^2.1.0" lodash.defaults "^4.2.0" - lodash.flatten "^4.4.0" lodash.isarguments "^3.1.0" - p-map "^2.1.0" - redis-commands "1.7.0" redis-errors "^1.2.0" redis-parser "^3.0.0" standard-as-callback "^2.1.0" @@ -2111,11 +2231,6 @@ lodash.defaults@^4.2.0: resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-4.2.0.tgz#d09178716ffea4dde9e5fb7b37f6f0802274580c" integrity sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ== -lodash.flatten@^4.4.0: - version "4.4.0" - resolved "https://registry.yarnpkg.com/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f" - integrity sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g== - lodash.isarguments@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" @@ -2369,11 +2484,6 @@ p-locate@^5.0.0: dependencies: p-limit "^3.0.2" -p-map@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/p-map/-/p-map-2.1.0.tgz#310928feef9c9ecc65b68b17693018a665cea175" - integrity sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw== - parent-module@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" @@ -2522,11 +2632,6 @@ rechoir@^0.6.2: dependencies: resolve "^1.1.6" -redis-commands@1.7.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/redis-commands/-/redis-commands-1.7.0.tgz#15a6fea2d58281e27b1cd1acfb4b293e278c3a89" - integrity sha512-nJWqw3bTFy21hX/CPKHth6sfhZbdiHP6bTawSgQBlKOVRG7EZkfHbbHwQJnrE4vsQf0CMNE+3gJ4Fmm16vdVlQ== - redis-errors@^1.0.0, redis-errors@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/redis-errors/-/redis-errors-1.2.0.tgz#eb62d2adb15e4eaf4610c04afe1529384250abad" @@ -3001,10 +3106,10 @@ uri-js@^4.2.2: dependencies: punycode "^2.1.0" -urllib@^3.10.1: - version "3.19.3" - resolved "https://registry.yarnpkg.com/urllib/-/urllib-3.19.3.tgz#825084d388c2e442474a1b1e89adaa35e899bde7" - integrity sha512-QEEBgRN94uPoVatOmZttfJTVdPKc+U96i/JH1zXgUA+dw3I3k+3d9Dzr1YafI92/r0V/4ypDH75zll93RDrp3w== +urllib@^3.21.0: + version "3.21.0" + resolved "https://registry.yarnpkg.com/urllib/-/urllib-3.21.0.tgz#1a81541d00121bf0c4a2c463cf4d8218d01a3a49" + integrity sha512-xtgaQ4G2emUssoz3jZjMTL2g32rEL75PggNHg3EUYf1h0sdkLSaRGAFgxe5UtNdFNoxJtjWk9hwNrY5Ja9fGNA== dependencies: default-user-agent "^1.0.0" digest-header "^1.0.0" @@ -3104,10 +3209,10 @@ ws@^7.4.5: resolved "https://registry.yarnpkg.com/ws/-/ws-7.5.9.tgz#54fa7db29f4c7cec68b1ddd3a89de099942bb591" integrity sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q== -ws@^8.12.0: - version "8.14.2" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.14.2.tgz#6c249a806eb2db7a20d26d51e7709eab7b2e6c7f" - integrity sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g== +"ws@^8.15.0 ": + version "8.15.0" + resolved "https://registry.yarnpkg.com/ws/-/ws-8.15.0.tgz#db080a279260c5f532fc668d461b8346efdfcf86" + integrity sha512-H/Z3H55mrcrgjFwI+5jKavgXvwQLtfPCUEp6pi35VhoB0pfcHnSoyuTzkBEZpzq49g1193CUEwIvmsjcotenYw== yallist@^4.0.0: version "4.0.0" From af16e36229e0f8204dd8695e5d5ecce4ca791635 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 12 Dec 2023 17:25:26 +0000 Subject: [PATCH 06/53] code porting to TypeScript --- .gitignore | 4 +- package.json | 3 ++ src/bls.ts | 18 +++---- src/cli.ts | 20 ++++---- src/clpTools.ts | 36 ++++++------- src/discoveryTools.ts | 10 ++-- src/imaCore.ts | 24 ++++----- src/imaEthOperations.ts | 14 ++--- src/imaEventLogScan.ts | 10 ++-- src/imaGasUsageOperations.ts | 4 +- src/imaHelperAPIs.ts | 8 +-- src/imaOracleOperations.ts | 12 ++--- src/imaRegistrationOperations.ts | 8 +-- src/imaReimbursementOperations.ts | 8 +-- src/imaSgxExternalSigner.ts | 6 +-- src/imaTokenOperations.ts | 14 ++--- src/imaTransferErrorHandling.ts | 2 +- src/imaTx.ts | 12 ++--- src/log.ts | 85 +++++++++++++++---------------- src/loop.ts | 24 ++++----- src/loopWorker.ts | 26 +++++----- src/main.ts | 24 ++++----- src/observer.ts | 8 +-- src/oracle.ts | 21 ++++---- src/owaspUtils.ts | 62 +++++++++++++++++++--- src/package.json | 8 ++- src/pwa.ts | 8 +-- src/rpcCall.ts | 9 ++-- src/socket.ts | 6 +-- src/socketServer.ts | 6 +-- src/socketUtils.ts | 2 +- src/state.ts | 13 +++-- src/threadInfo.ts | 2 +- src/tsconfig.json | 27 ++++++++-- src/utils.ts | 6 +-- src/yarn.lock | 30 ++--------- 36 files changed, 317 insertions(+), 263 deletions(-) diff --git a/.gitignore b/.gitignore index 3c4c510b..0537a6e6 100644 --- a/.gitignore +++ b/.gitignore @@ -73,4 +73,6 @@ venv # network-browser network-browser/test*.json -network-browser.js \ No newline at end of file +network-browser.js + +src/build \ No newline at end of file diff --git a/package.json b/package.json index 1704b3e1..e9a68daf 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "license": "AGPL-3.0", "author": "SKALE Labs and contributors", "scripts": { + "build": "cd src && yarn build && cd ..", + "rebuild": "cd src && yarn rebuild && cd ..", + "clean-build": "cd src && yarn clean-build && cd ..", "lint-check": "cd src && yarn lint-check && cd ..", "lint-nb": "cd network-browser && yarn lint-check && cd ..", "install-nb": "cd network-browser && bun install && cd ..", diff --git a/src/bls.ts b/src/bls.ts index 5a10b221..b967804f 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -25,18 +25,18 @@ import * as fs from "fs"; import * as path from "path"; -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; import * as childProcessModule from "child_process"; -import * as rpcCall from "./rpcCall"; +import * as rpcCall from "./rpcCall.js"; import * as shell from "shelljs"; -import * as imaUtils from "./utils"; +import * as imaUtils from "./utils.js"; import * as sha3Module from "sha3"; -import * as skaleObserver from "./observer"; -import * as discoveryTools from "./discoveryTools"; -import * as threadInfo from "./threadInfo"; -import * as utils from "./socketUtils"; -import * as state from "./state"; +import * as skaleObserver from "./observer.js"; +import * as discoveryTools from "./discoveryTools.js"; +import * as threadInfo from "./threadInfo.js"; +import * as utils from "./socketUtils.js"; +import * as state from "./state.js"; const Keccak = sha3Module.Keccak; diff --git a/src/cli.ts b/src/cli.ts index 7034c435..53d0953c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -26,15 +26,15 @@ import * as path from "path"; import * as url from "url"; import * as os from "os"; -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as imaUtils from "./utils"; -import * as rpcCall from "./rpcCall"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -import * as imaOracleOperations from "./imaOracleOperations"; -import * as imaTx from "./imaTx"; -import * as state from "./state"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaUtils from "./utils.js"; +import * as rpcCall from "./rpcCall.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; +import * as imaOracleOperations from "./imaOracleOperations.js"; +import * as imaTx from "./imaTx.js"; +import * as state from "./state.js"; const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); @@ -213,7 +213,7 @@ function parseHelp( imaState: any, joArg: any ) { // exits process on "--help" if( joArg.name != "help" ) return false; printAbout(); - const strAboutText = imaUtils.fileLoad( path.join( __dirname, "about.txt" ), "N/A" ).toString(); + const strAboutText = imaUtils.fileLoad( path.join( __dirname, "../about.txt" ), "N/A" ).toString(); console.log( strAboutText ); process.exit( 0 ); } diff --git a/src/clpTools.ts b/src/clpTools.ts index 7ee89f4f..41a9735d 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -23,24 +23,24 @@ * @copyright SKALE Labs 2019-Present */ -import * as owaspUtils from "./owaspUtils"; -import * as log from "./log"; -import * as imaCLI from "./cli"; -import * as rpcCall from "./rpcCall"; -import * as state from "./state"; -import * as IMA from "./imaCore"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaGasUsage from "./imaGasUsageOperations"; -import * as imaReimbursement from "./imaReimbursementOperations"; -import * as imaReg from "./imaRegistrationOperations"; -import * as imaEth from "./imaEthOperations"; -import * as imaToken from "./imaTokenOperations"; -import * as skaleObserver from "./observer"; -import * as discoveryTools from "./discoveryTools"; -import * as loop from "./loop"; -import * as imaUtils from "./utils"; -import * as imaBLS from "./bls"; -import * as imaTx from "./imaTx"; +import * as owaspUtils from "./owaspUtils.js"; +import * as log from "./log.js"; +import * as imaCLI from "./cli.js"; +import * as rpcCall from "./rpcCall.js"; +import * as state from "./state.js"; +import * as IMA from "./imaCore.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaGasUsage from "./imaGasUsageOperations.js"; +import * as imaReimbursement from "./imaReimbursementOperations.js"; +import * as imaReg from "./imaRegistrationOperations.js"; +import * as imaEth from "./imaEthOperations.js"; +import * as imaToken from "./imaTokenOperations.js"; +import * as skaleObserver from "./observer.js"; +import * as discoveryTools from "./discoveryTools.js"; +import * as loop from "./loop.js"; +import * as imaUtils from "./utils.js"; +import * as imaBLS from "./bls.js"; +import * as imaTx from "./imaTx.js"; export async function registerAll( isPrintSummaryRegistrationCosts: boolean ) { if( !await registerStep1( false ) ) diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index baa7e435..df7d2c2c 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -23,11 +23,11 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as rpcCall from "./rpcCall"; -import * as state from "./state"; -import * as imaUtils from "./utils"; -import * as threadInfo from "./threadInfo"; +import * as log from "./log.js"; +import * as rpcCall from "./rpcCall.js"; +import * as state from "./state.js"; +import * as imaUtils from "./utils.js"; +import * as threadInfo from "./threadInfo.js"; export function formatBalanceInfo( bi: any, strAddress: string ) : string { let s = ""; diff --git a/src/imaCore.ts b/src/imaCore.ts index 69ca1513..93d01f98 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -23,18 +23,18 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as loop from "./loop"; -import * as pwa from "./pwa"; -import * as state from "./state"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTx from "./imaTx"; -import * as imaGasUsage from "./imaGasUsageOperations"; -import * as imaEventLogScan from "./imaEventLogScan"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -import * as skaleObserver from "./observer"; -import * as threadInfo from "./threadInfo"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as loop from "./loop.js"; +import * as pwa from "./pwa.js"; +import * as state from "./state.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTx from "./imaTx.js"; +import * as imaGasUsage from "./imaGasUsageOperations.js"; +import * as imaEventLogScan from "./imaEventLogScan.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; +import * as skaleObserver from "./observer.js"; +import * as threadInfo from "./threadInfo.js"; log.enableColorization( false ); log.addStdout(); diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 697c1ccf..8dcd071f 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -23,13 +23,13 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTx from "./imaTx"; -import * as imaGasUsage from "./imaGasUsageOperations"; -import * as imaEventLogScan from "./imaEventLogScan"; -import * as threadInfo from "./threadInfo"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTx from "./imaTx.js"; +import * as imaGasUsage from "./imaGasUsageOperations.js"; +import * as imaEventLogScan from "./imaEventLogScan.js"; +import * as threadInfo from "./threadInfo.js"; export async function getBalanceEth( isMainNet: any, diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index b0da3687..cdd726b5 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -23,11 +23,11 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as rpcCall from "./rpcCall"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as rpcCall from "./rpcCall.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumber: any ) { // assume Main Net mines 6 blocks per minute diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 7ea0f931..9d11e042 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -23,8 +23,8 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ) : any { if( ! ( strName && typeof strName == "string" && jarrReceipts ) ) diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index e363abcc..56505325 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as rpcCall from "./rpcCall"; -import * as threadInfo from "./threadInfo"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as rpcCall from "./rpcCall.js"; +import * as threadInfo from "./threadInfo.js"; export const longSeparator: string = "============================================================" + diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index faa8edb4..2d10d5d7 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -23,12 +23,12 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as imaOracle from "./oracle"; -import * as imaTx from "./imaTx"; -import * as imaGasUsage from "./imaGasUsageOperations"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaOracle from "./oracle.js"; +import * as imaTx from "./imaTx.js"; +import * as imaGasUsage from "./imaGasUsageOperations.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; let gFlagIsEnabledOracle: boolean = false; diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 46d7d133..adc2a658 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTx from "./imaTx"; -import * as threadInfo from "./threadInfo"; +import * as log from "./log.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTx from "./imaTx.js"; +import * as threadInfo from "./threadInfo.js"; export async function invokeHasChain( details: any, diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index c9b0ef98..0401d638 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as imaTx from "./imaTx"; -import * as imaGasUsage from "./imaGasUsageOperations"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaTx from "./imaTx.js"; +import * as imaGasUsage from "./imaGasUsageOperations.js"; export async function reimbursementShowBalance( ethersProviderMainNet: any, diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 5e362a84..c761e92c 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -1,7 +1,7 @@ import * as fs from "fs"; -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as rpcCall from "./rpcCall"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as rpcCall from "./rpcCall.js"; const gIsDebugLogging = false; // development option only, must be always false log.addStdout(); diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 5091c532..a02d21dd 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -23,13 +23,13 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTx from "./imaTx"; -import * as imaGasUsage from "./imaGasUsageOperations"; -import * as imaEventLogScan from "./imaEventLogScan"; -import * as threadInfo from "./threadInfo"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTx from "./imaTx.js"; +import * as imaGasUsage from "./imaGasUsageOperations.js"; +import * as imaEventLogScan from "./imaEventLogScan.js"; +import * as threadInfo from "./threadInfo.js"; export async function getBalanceErc20( isMainNet: boolean, diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index ae253cd7..a7c17cbf 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -24,7 +24,7 @@ */ import { UniversalDispatcherEvent, EventDispatcher } - from "./eventDispatcher"; + from "./eventDispatcher.js"; export function verifyTransferErrorCategoryName( strCategory: string ) { return "" + ( strCategory ? strCategory : "default" ); diff --git a/src/imaTx.ts b/src/imaTx.ts index 105cee3d..3d8a16a7 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -30,14 +30,14 @@ import * as childProcessModule from "child_process"; import Redis from "ioredis"; import * as ethereumJsUtilModule from "ethereumjs-util"; -import * as log from "./log"; +import * as log from "./log.js"; -import * as owaspUtils from "./owaspUtils"; -import * as imaUtils from "./utils"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaEventLogScan from "./imaEventLogScan"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaUtils from "./utils.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaEventLogScan from "./imaEventLogScan.js"; -import * as threadInfo from "./threadInfo"; +import * as threadInfo from "./threadInfo.js"; const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); diff --git a/src/log.ts b/src/log.ts index e8482bf2..2a6f9eb8 100644 --- a/src/log.ts +++ b/src/log.ts @@ -23,7 +23,7 @@ * @copyright SKALE Labs 2019-Present */ -import * as cc from "./cc"; +import * as cc from "./cc.js"; import * as fs from "fs"; let gArrStreams: any[] = []; @@ -901,41 +901,40 @@ export function toString() : string { return ""; } -const gMapVerbose : any = { - 0: "silent", - 1: "fatal", - 2: "critical", - 3: "error", - 4: "warning", - 5: "attention", - 6: "information", - 7: "notice", - 8: "debug", - 9: "trace" -}; +const gMapVerbose : Map < number, string > = new Map < number, string > (); +gMapVerbose.set( 0, "silent" ); +gMapVerbose.set( 1, "fatal" ); +gMapVerbose.set( 2, "critical" ); +gMapVerbose.set( 3, "error" ); +gMapVerbose.set( 4, "warning" ); +gMapVerbose.set( 5, "attention" ); +gMapVerbose.set( 6, "information" ); +gMapVerbose.set( 7, "notice" ); +gMapVerbose.set( 8, "debug" ); +gMapVerbose.set( 9, "trace" ); + function computeVerboseAlias() { - const m: any = {}; - for( const key in gMapVerbose ) { - if( !gMapVerbose.hasOwnProperty( key ) ) - continue; // skip loop if the property is from prototype - const name = gMapVerbose[key]; - m[name] = parseInt( key ); + const m: Map < string, number > = new Map < string, number > (); + for( const [ key, val ] of gMapVerbose ) { + const name = val; + if( name ) + m.set( name, key ); } - m.empty = 0 + parseInt( m.silent ); // alias - m.none = 0 + parseInt( m.silent ); // alias - m.stop = 0 + parseInt( m.fatal ); // alias - m.bad = 0 + parseInt( m.critical ); // alias - m.err = 0 + parseInt( m.error ); // alias - m.warn = 0 + parseInt( m.warning ); // alias - m.attn = 0 + parseInt( m.attention ); // alias - m.info = 0 + parseInt( m.information ); // alias - m.note = 0 + parseInt( m.notice ); // alias - m.dbg = 0 + parseInt( m.debug ); // alias - m.crazy = 0 + parseInt( m.trace ); // alias - m.detailed = 0 + parseInt( m.trace ); // alias + m.set( "empty", m.get( "silent" ) || 0 ); // alias + m.set( "none", m.get( "silent" ) || 0 ); // alias + m.set( "stop", m.get( "fatal" ) || 0 ); // alias + m.set( "bad", m.get( "critical" ) || 0 ); // alias + m.set( "err", m.get( "error" ) || 0 ); // alias + m.set( "warn", m.get( "warning" ) || 0 ); // alias + m.set( "attn", m.get( "attention" ) || 0 ); // alias + m.set( "info", m.get( "information" ) || 0 ); // alias + m.set( "note", m.get( "notice" ) || 0 ); // alias + m.set( "dbg", m.get( "debug" ) || 0 ); // alias + m.set( "crazy", m.get( "trace" ) || 0 ); // alias + m.set( "detailed", m.get( "trace" ) || 0 ); // alias return m; } -let gMapReversedVerbose: any = null; +let gMapReversedVerbose: Map < string, number > = new Map < string, number > (); export function verbose() : any { return gMapVerbose; } export function verboseReversed() : Map < string, number > { @@ -943,12 +942,12 @@ export function verboseReversed() : Map < string, number > { gMapReversedVerbose = computeVerboseAlias(); return gMapReversedVerbose; } -export function verboseLevelAsTextForLog( vl: any ) { +export function verboseLevelAsTextForLog( vl: any ) : string { if( typeof vl == "undefined" ) vl = verboseGet(); if( vl in gMapVerbose ) { - const tl = gMapVerbose[vl]; - return tl; + const tl = gMapVerbose.get( vl ) || 0; + return "" + tl; } return "unknown(" + JSON.stringify( vl ) + ")"; } @@ -985,13 +984,11 @@ export function verboseParse( s: string ) : number { n = cc.toInteger( s ); else { const ch0 = s[0].toLowerCase(); - for( const key in gMapVerbose ) { - if( !gMapVerbose.hasOwnProperty( key ) ) - continue; // skip loop if the property is from prototype - const name = gMapVerbose[key]; - const ch1 = name[0].toLowerCase(); + for( const [ key, val ] of gMapVerbose ) { + const name = val; + const ch1:string = name[0].toLowerCase(); if( ch0 == ch1 ) { - n = parseInt( key ); + n = key; return n; } } @@ -1001,10 +998,8 @@ export function verboseParse( s: string ) : number { } export function verboseList() : void { - for( const key in gMapVerbose ) { - if( !gMapVerbose.hasOwnProperty( key ) ) - continue; // skip loop if the property is from prototype - const name = gMapVerbose[key]; + for( const [ key, val ] of gMapVerbose ) { + const name = val; console.log( " " + cc.j( key ) + cc.sunny( "=" ) + cc.bright( name ) ); } } diff --git a/src/loop.ts b/src/loop.ts index 0f5d43bb..1c2e670d 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -23,20 +23,20 @@ * @copyright SKALE Labs 2019-Present */ -import * as networkLayer from "./socket"; +import * as networkLayer from "./socket.js"; import * as url from "url"; -import * as threadInfo from "./threadInfo"; +import * as threadInfo from "./threadInfo.js"; import * as path from "path"; -import * as log from "./log"; -import * as IMA from "./imaCore"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -import * as imaOracleOperations from "./imaOracleOperations"; -import * as owaspUtils from "./owaspUtils"; -import * as imaBLS from "./bls"; -import * as skaleObserver from "./observer"; -import * as pwa from "./pwa"; -import * as state from "./state"; +import * as log from "./log.js"; +import * as IMA from "./imaCore.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; +import * as imaOracleOperations from "./imaOracleOperations.js"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaBLS from "./bls.js"; +import * as skaleObserver from "./observer.js"; +import * as pwa from "./pwa.js"; +import * as state from "./state.js"; const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 4c53d4a0..4c93df3d 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -24,17 +24,17 @@ */ import { parentPort, workerData } from "worker_threads"; -import * as networkLayer from "./socket"; +import * as networkLayer from "./socket.js"; import { SocketServer } from "./socketServer"; -import * as owaspUtils from "./owaspUtils"; -import * as loop from "./loop"; -import * as imaTx from "./imaTx"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -import * as imaCLI from "./cli"; -import * as state from "./state"; -import * as pwa from "./pwa"; -import * as log from "./log"; -import * as threadInfo from "./threadInfo"; +import * as owaspUtils from "./owaspUtils.js"; +import * as loop from "./loop.js"; +import * as imaTx from "./imaTx.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; +import * as imaCLI from "./cli.js"; +import * as state from "./state.js"; +import * as pwa from "./pwa.js"; +import * as log from "./log.js"; +import * as threadInfo from "./threadInfo.js"; let imaState: any = state.get(); @@ -127,8 +127,10 @@ class ObserverServer extends SocketServer { const isFlush = true; socket.send( jo, isFlush ); } ); - self.opts.imaState.chainProperties.mn.joAccount.address = owaspUtils.fnAddressImpl_; - self.opts.imaState.chainProperties.sc.joAccount.address = owaspUtils.fnAddressImpl_; + self.opts.imaState.chainProperties.mn.joAccount.address = + function() { return owaspUtils.fnAddressImpl_( this ); }; + self.opts.imaState.chainProperties.sc.joAccount.address = + function() { return owaspUtils.fnAddressImpl_( this ); }; if( self.opts.imaState.chainProperties.mn.strURL && typeof self.opts.imaState.chainProperties.mn.strURL == "string" && self.opts.imaState.chainProperties.mn.strURL.length > 0 diff --git a/src/main.ts b/src/main.ts index f1db1c24..bb049ea8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -26,19 +26,19 @@ import express from "express"; import bodyParser from "body-parser"; import * as ws from "ws"; -import * as owaspUtils from "./owaspUtils"; -import * as log from "./log"; -import * as imaCLI from "./cli"; -import * as loop from "./loop"; -import * as imaHelperAPIs from "./imaHelperAPIs"; -import * as imaTransferErrorHandling from "./imaTransferErrorHandling"; -import * as imaBLS from "./bls"; -import * as pwa from "./pwa"; -import * as clpTools from "./clpTools"; -import * as discoveryTools from "./discoveryTools"; -import * as skaleObserver from "./observer"; +import * as owaspUtils from "./owaspUtils.js"; +import * as log from "./log.js"; +import * as imaCLI from "./cli.js"; +import * as loop from "./loop.js"; +import * as imaHelperAPIs from "./imaHelperAPIs.js"; +import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; +import * as imaBLS from "./bls.js"; +import * as pwa from "./pwa.js"; +import * as clpTools from "./clpTools.js"; +import * as discoveryTools from "./discoveryTools.js"; +import * as skaleObserver from "./observer.js"; -import * as state from "./state"; +import * as state from "./state.js"; // allow self-signed wss and https process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; diff --git a/src/observer.ts b/src/observer.ts index c9fade2a..6b91c955 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as state from "./state"; -import * as imaUtils from "./utils"; -import * as log from "./log"; -import * as threadInfo from "./threadInfo"; +import * as state from "./state.js"; +import * as imaUtils from "./utils.js"; +import * as log from "./log.js"; +import * as threadInfo from "./threadInfo.js"; export function findSChainIndexInArrayByName( arrSChains: any[], strSChainName: string ) { for( let idxSChain = 0; idxSChain < arrSChains.length; ++ idxSChain ) { diff --git a/src/oracle.ts b/src/oracle.ts index d1966c6f..eb9561ef 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -23,20 +23,19 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as rpcCall from "./rpcCall"; -import * as threadInfo from "./threadInfo"; -import * as owaspUtils from "./owaspUtils"; -import numberToBN from "number-to-bn"; +import * as log from "./log.js"; +import * as rpcCall from "./rpcCall.js"; +import * as threadInfo from "./threadInfo.js"; +import * as owaspUtils from "./owaspUtils.js"; import * as sha3Module from "sha3"; const Keccak: any = sha3Module.Keccak; export const gConstMinPowResultLimit: number = 10000; export const gConstMaxPowResultLimit: any = 100000; -const gBigNumMinPowResult: any = numberToBN( gConstMinPowResultLimit ); -const gBigNum1: any = numberToBN( 1 ); -const gBigNum2: any = numberToBN( 2 ); -const gBigNum256: any = numberToBN( 256 ); +const gBigNumMinPowResult: any = owaspUtils.toBN( gConstMinPowResultLimit ); +const gBigNum1: any = owaspUtils.toBN( 1 ); +const gBigNum2: any = owaspUtils.toBN( 2 ); +const gBigNum256: any = owaspUtils.toBN( 256 ); const gBigNumUpperPart: any = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); function getUtcTimestampString( d?: Date ) : string { @@ -64,7 +63,7 @@ export function findPowNumber( strRequestPart: string, details: any, isVerbose?: let strHash = hash.digest( "hex" ); strHash = owaspUtils.ensureStartsWith0x( strHash ); - const f = numberToBN( strHash ); + const f = owaspUtils.toBN( strHash ); const r = gBigNumUpperPart.div( f ); if( r.gt( gBigNumMinPowResult ) ) { if( isVerbose ) { @@ -97,7 +96,7 @@ async function handleOracleCheckResultResult( const joResult: any = JSON.parse( joOut.result ); if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_checkResult) parsed result field is: {}", joResult ); - const gp = numberToBN( joResult.rslts[0] ); + const gp = owaspUtils.toBN( joResult.rslts[0] ); if( isVerboseTraceDetails ) { details.success( "success, computed Gas Price={}={}", gp.toString(), owaspUtils.ensureStartsWith0x( gp.toString( 16 ) ) ); diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index ac494b99..289306c5 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -28,18 +28,20 @@ // https://www.gitbook.com/download/pdf/book/checkmarx/JS-SCP // top 10 hit parade: https://owasp.org/www-project-top-ten/ -import * as log from "./log"; +import * as log from "./log.js"; import * as ethersMod from "ethers"; import * as fs from "fs"; import * as ethereumJsUtilModule from "ethereumjs-util"; import * as ethereumJsWalletModule from "ethereumjs-wallet"; const Wallet = ethereumJsWalletModule.default; +const BN = ethereumJsUtilModule.BN; +const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; const replaceAll = log.replaceAll; const extractErrorMessage = log.extractErrorMessage; -export { ethersMod, safeURL, replaceAll, extractErrorMessage }; +export { ethersMod, safeURL, replaceAll, extractErrorMessage, BigNumber }; export function rxIsInt( val: any ) : boolean { try { @@ -668,8 +670,7 @@ export function publicKeyToAccountAddress( keyPublic : string ) : string { return strAddress; } -export function fnAddressImpl_() : string { - const anyThis: any = this; +export function fnAddressImpl_( anyThis: any ) : string { if( anyThis.address_ == undefined || anyThis.address_ == null || anyThis.address_ == "" ) { if( anyThis.privateKey ) anyThis.address_ = "" + privateKeyToAccountAddress( anyThis.privateKey ); @@ -710,9 +711,56 @@ export function ethersProviderToUrl( ethersProvider: any ) : string { return strURL || "N/A-URL"; } -export function toBN( x?: any ) : any { - const bn = ethersMod.ethers.BigNumber.from( x ); - return bn; +export function isHexPrefixed( s: any ) : boolean { + if( typeof s !== "string" ) + throw new Error( + "Parameter value of owaspUtils.isHexPrefixed() must be type 'string' but it's " + + `type ${typeof s}, while checking isHexPrefixed.` ); + return ( s.slice( 0, 2 ) === "0x" ) ? true : false; +} + +export function stripHexPrefix( s: any ) : string { + if( typeof s !== "string" ) + return s; + return isHexPrefixed( s ) ? s.slice( 2 ) : s; +} + +export function toBNbasic( x?: any, optionalRadix?: number ) : any { + try { + const bn = ethersMod.ethers.BigNumber.from( x ); + return bn; + } catch( err ) { + console.log( `CRITICAL ERROR: Failure in owaspUtils.toBNbasic( ${x} ): ${err}` ); + throw err; + } +} + +export function toBN( arg: any ) : any { + if( typeof arg === 'string' || typeof arg === "number" ) { + let multiplier = toBNbasic( 1 ); // eslint-disable-line + let formattedString = String( arg ).toLowerCase().trim(); + let isHexPrefixed = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x"; + let stringArg = stripHexPrefix(formattedString); // eslint-disable-line + if( stringArg.substr(0, 1) === "-" ) { + stringArg = stripHexPrefix(stringArg.slice(1)); + multiplier = toBNbasic( -1, 10 ); + } + stringArg = stringArg === "" ? "0" : stringArg; + if( ( ! stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/) ) + || stringArg.match(/^[a-fA-F]+$/) + || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/)) ) + return toBNbasic( stringArg, 16).mul(multiplier); + if( ( stringArg.match(/^-?[0-9]+$/) || stringArg === "" ) && isHexPrefixed === false ) + return toBNbasic( stringArg, 10).mul( multiplier ); + } else if( typeof arg === "object" && arg.toString && (!arg.pop && !arg.push) ) { + if( arg.toString( 10 ).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy) ) + return toBNbasic(arg.toString(10), 10); + } + throw new Error( + "Error in owaspUtils.toBN() while converting " + + `number ${JSON.stringify(arg)}to BN.js instance, error: ` + + "invalid number value. Value must be an integer, hex string, BN or BigNumber instance. " + + "Note, decimals are not supported." ); } export function isNumeric( s?: any ) : boolean { diff --git a/src/package.json b/src/package.json index d86cb8c9..e9469e5a 100644 --- a/src/package.json +++ b/src/package.json @@ -2,14 +2,17 @@ "name": "skale-ima-agent-app", "license": "AGPL-3.0", "author": "SKALE Labs and contributors", + "type": "module", "scripts": { + "build": "./node_modules/typescript/bin/tsc", + "rebuild": "yarn clean-build && yarn build", + "clean-build": "rm -rf ./src/build/* || true", "lint-check": "eslint ./*.*js", "lint-fix": "eslint ./*.*js --fix", "check-outdated": "yarn outdated", "upgrade-to-latest": "yarn upgrade --latest" }, "dependencies": { - "number-to-bn": "^1.7.0", "ethers": "^5.7.2", "@ethersproject/experimental": "^5.7.0", "solc": "0.8.6", @@ -41,7 +44,8 @@ "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^6.1.1", "eslint-plugin-standard": "^4.0.1", - "eslint-plugin-n": "^16.3.0" + "eslint-plugin-n": "^16.3.0", + "typescript": "^5.3.3" }, "resolutions": { } diff --git a/src/pwa.ts b/src/pwa.ts index d9b31006..f7ae8a33 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -23,10 +23,10 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as rpcCall from "./rpcCall"; -import * as imaBLS from "./bls"; -import * as imaUtils from "./utils"; +import * as log from "./log.js"; +import * as rpcCall from "./rpcCall.js"; +import * as imaBLS from "./bls.js"; +import * as imaUtils from "./utils.js"; function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ) : number[] { if( nNodesCount <= 1 ) diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 2c507640..9bc04939 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -27,8 +27,8 @@ import * as ws from "ws"; import * as urllib from "urllib"; import * as https from "https"; import * as net from "net"; -import { validateURL, isUrlWS } from "./owaspUtils"; -import * as log from "./log"; +import { validateURL, isUrlWS } from "./owaspUtils.js"; +import * as log from "./log.js"; const gSecondsConnectionTimeout = 60; @@ -300,7 +300,7 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { } ); } else { try { - const response = await urllib.request( joCall.url, { + const requestOpts = { "method": "POST", "timeout": gSecondsConnectionTimeout * 1000, // in milliseconds "headers": { @@ -320,7 +320,8 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { "key": ( joCall.joRpcOptions && joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" ) ? joCall.joRpcOptions.key : null - } ); + }; + const response = await urllib.request( joCall.url, requestOpts as urllib.RequestOptions ); const body = response.data.toString( "utf8" ); if( response && response.statusCode && response.statusCode !== 200 ) log.warning( "REST call status code is {}", response.statusCode ); diff --git a/src/socket.ts b/src/socket.ts index 42c77e47..920d8218 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -23,9 +23,9 @@ * @copyright SKALE Labs 2019-Present */ -import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher"; -import { settings } from "./socketSettings"; -import * as utils from "./socketUtils"; +import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher.js"; +import { settings } from "./socketSettings.js"; +import * as utils from "./socketUtils.js"; export let httpsModule: any = null; // server side only export let wsModule: any = null; // server side only diff --git a/src/socketServer.ts b/src/socketServer.ts index 0f05b0a1..1b2d2ae9 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -23,9 +23,9 @@ * @copyright SKALE Labs 2019-Present */ -import { EventDispatcher, UniversalDispatcherEvent } from "./eventDispatcher"; -import * as utils from "./socketUtils"; -import * as log from "./log"; +import { EventDispatcher, UniversalDispatcherEvent } from "./eventDispatcher.js"; +import * as utils from "./socketUtils.js"; +import * as log from "./log.js"; export class SocketServer extends EventDispatcher { log: any; diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 6fb62c21..3bb54045 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -23,7 +23,7 @@ * @copyright SKALE Labs 2019-Present */ -import { settings } from "./socketSettings"; +import { settings } from "./socketSettings.js"; export const UUIDv4 = function() : string { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( /[xy]/g, function( c ) { diff --git a/src/state.ts b/src/state.ts index ec2ab1be..a3924609 100644 --- a/src/state.ts +++ b/src/state.ts @@ -1,5 +1,5 @@ -import * as owaspUtils from "./owaspUtils"; -import * as imaTx from "./imaTx"; +import * as owaspUtils from "./owaspUtils.js"; +import * as imaTx from "./imaTx.js"; export const gDefaultValueForLoopState: any = { "oracle": { @@ -26,7 +26,8 @@ function constructChainProperties() { "joAccount": { "privateKey": owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_ETHEREUM ), - "address": owaspUtils.fnAddressImpl_, + "address": + function() { return owaspUtils.fnAddressImpl_( this ); }, "strTransactionManagerURL": owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_ETHEREUM ), @@ -64,7 +65,8 @@ function constructChainProperties() { "joAccount": { "privateKey": owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN ), - "address": owaspUtils.fnAddressImpl_, + "address": + function() { return owaspUtils.fnAddressImpl_( this ); }, "strTransactionManagerURL": owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN ), "nTmPriority": @@ -101,7 +103,8 @@ function constructChainProperties() { "joAccount": { "privateKey": owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN_TARGET ), - "address": owaspUtils.fnAddressImpl_, + "address": + function() { return owaspUtils.fnAddressImpl_( this ); }, "strTransactionManagerURL": owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN_TARGET ), diff --git a/src/threadInfo.ts b/src/threadInfo.ts index 73f1e7a2..d3fa44e1 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -24,7 +24,7 @@ */ import * as worker_threads from "worker_threads"; -import * as log from "./log"; +import * as log from "./log.js"; const Worker = worker_threads.Worker; export { Worker }; diff --git a/src/tsconfig.json b/src/tsconfig.json index 7fec2598..52358d07 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ - "target": "es2022" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, - "module": "es2022" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "target": "es2020", + "module": "es2020", "declaration": true /* Generates corresponding '.d.ts' file. */, "outDir": "build" /* Redirect output structure to the directory. */, /* Strict Type-Checking Options */ @@ -12,7 +12,24 @@ "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, /* Advanced Options */ - "skipLibCheck": true /* Skip type checking of declaration files. */, - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ - } + // "skipLibCheck": true /* Skip type checking of declaration files. */, + // "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ + + // "noImplicitAny": true, + // "alwaysStrict": true, + // "rootDir": ".", + // "baseUrl": ".", + + "allowArbitraryExtensions": true, + + "paths": { + "*": [ + "./*.ts" + ] + } + }, + "exclude": ["node_modules", "dist"], + "include": [ + "./*.ts" + ] } diff --git a/src/utils.ts b/src/utils.ts index c4705667..0952730e 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -23,12 +23,12 @@ * @copyright SKALE Labs 2019-Present */ -import * as log from "./log"; -import * as owaspUtils from "./owaspUtils"; +import * as log from "./log.js"; +import * as owaspUtils from "./owaspUtils.js"; import * as fs from "fs"; import * as path from "path"; import * as os from "os"; -import * as threadInfo from "./threadInfo"; +import * as threadInfo from "./threadInfo.js"; import { v4 as uuid } from "uuid"; export { uuid }; diff --git a/src/yarn.lock b/src/yarn.lock index 0f8b595d..95500c80 100644 --- a/src/yarn.lock +++ b/src/yarn.lock @@ -777,11 +777,6 @@ blakejs@^1.1.0: resolved "https://registry.yarnpkg.com/blakejs/-/blakejs-1.2.1.tgz#5057e4206eadb4a97f7c0b6e197a505042fc3814" integrity sha512-QXUSXI3QVc/gJME0dBpXrag1kbzOqCjCX8/b54ntNyW6sjtoqxqRk3LTmXzaJoh71zMsDCjM+47jS7XiwN/+fQ== -bn.js@4.11.6: - version "4.11.6" - resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.11.6.tgz#53344adb14617a13f6e8dd2ce28905d1c0ba3215" - integrity sha512-XWwnNNFCuuSQ0m3r3C4LE3EiORltHd9M05pq6FOlVeiophzRbMo50Sbz1ehl8K3Z+jw9+vmgnXefY1hz8X+2wA== - bn.js@^4.11.9: version "4.12.0" resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.12.0.tgz#775b3f278efbb9718eec7361f483fb36fbbfea88" @@ -2039,11 +2034,6 @@ is-glob@^4.0.0, is-glob@^4.0.3: dependencies: is-extglob "^2.1.1" -is-hex-prefixed@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-hex-prefixed/-/is-hex-prefixed-1.0.0.tgz#7d8d37e6ad77e5d127148913c573e082d777f554" - integrity sha512-WvtOiug1VFrE9v1Cydwm+FnXd3+w9GaeVUss5W4v/SLy3UW00vP+6iNF2SdnfiBoLy4bTqVdkftNGTUeOFVsbA== - is-negative-zero@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz#7bf6f03a28003b8b3965de3ac26f664d765f3150" @@ -2361,14 +2351,6 @@ node-gyp-build@^4.2.0: resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.6.1.tgz#24b6d075e5e391b8d5539d98c7fc5c210cac8a3e" integrity sha512-24vnklJmyRS8ViBNI8KbtK/r/DmXQMRiOMXTNz2nrTnAYUwjmEEbnnpB/+kt+yWRv73bPsSPRFddrcIbAxSiMQ== -number-to-bn@^1.7.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/number-to-bn/-/number-to-bn-1.7.0.tgz#bb3623592f7e5f9e0030b1977bd41a0c53fe1ea0" - integrity sha512-wsJ9gfSz1/s4ZsJN01lyonwuxA1tml6X1yBDnfpMglypcBRFZZkus26EdPSlqS5GJfYddVZa22p3VNb3z5m5Ig== - dependencies: - bn.js "4.11.6" - strip-hex-prefix "1.0.0" - object-inspect@^1.12.3, object-inspect@^1.9.0: version "1.12.3" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" @@ -2952,13 +2934,6 @@ strip-bom@^3.0.0: resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA== -strip-hex-prefix@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz#0c5f155fef1151373377de9dbb588da05500e36f" - integrity sha512-q8d4ue7JGEiVcypji1bALTos+0pWtyGlivAWyPuTkHzuTCJqrK9sWxYQZUq6Nq3cuyv3bm734IhHvHtGGURU6A== - dependencies: - is-hex-prefixed "1.0.0" - strip-json-comments@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" @@ -3072,6 +3047,11 @@ typed-array-length@^1.0.4: for-each "^0.3.3" is-typed-array "^1.1.9" +typescript@^5.3.3: + version "5.3.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.3.3.tgz#b3ce6ba258e72e6305ba66f5c9b452aaee3ffe37" + integrity sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw== + unbox-primitive@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/unbox-primitive/-/unbox-primitive-1.0.2.tgz#29032021057d5e6cdbd08c5129c226dff8ed6f9e" From f57c7f02cee69d17a52a98c24d200f819e6e264b Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 12 Dec 2023 18:33:48 +0000 Subject: [PATCH 07/53] code porting to TypeScript --- src/owaspUtils.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 289306c5..d8d74ee9 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -727,6 +727,8 @@ export function stripHexPrefix( s: any ) : string { export function toBNbasic( x?: any, optionalRadix?: number ) : any { try { + if( optionalRadix && typeof optionalRadix == "number" && optionalRadix == 16 ) + x = ensureStartsWith0x( x ); const bn = ethersMod.ethers.BigNumber.from( x ); return bn; } catch( err ) { @@ -753,8 +755,8 @@ export function toBN( arg: any ) : any { if( ( stringArg.match(/^-?[0-9]+$/) || stringArg === "" ) && isHexPrefixed === false ) return toBNbasic( stringArg, 10).mul( multiplier ); } else if( typeof arg === "object" && arg.toString && (!arg.pop && !arg.push) ) { - if( arg.toString( 10 ).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy) ) - return toBNbasic(arg.toString(10), 10); + if( arg.toString().match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy) ) + return toBNbasic(arg.toString(), 10); } throw new Error( "Error in owaspUtils.toBN() while converting " + From 07a2d696bcaa33470e0c9cdbb3dd8b687f6a7569 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 12 Dec 2023 18:42:37 +0000 Subject: [PATCH 08/53] code porting to TypeScript --- src/owaspUtils.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index d8d74ee9..c0fbf1f3 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -757,6 +757,8 @@ export function toBN( arg: any ) : any { } else if( typeof arg === "object" && arg.toString && (!arg.pop && !arg.push) ) { if( arg.toString().match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy) ) return toBNbasic(arg.toString(), 10); + } else if( arg ) { + return toBNbasic( arg ); // try to convert as is } throw new Error( "Error in owaspUtils.toBN() while converting " + From babba72127eaeccf22320745ddb84dac2f195e36 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 12 Dec 2023 18:42:57 +0000 Subject: [PATCH 09/53] code porting to TypeScript --- src/owaspUtils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index c0fbf1f3..baa1a195 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -753,10 +753,10 @@ export function toBN( arg: any ) : any { || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/)) ) return toBNbasic( stringArg, 16).mul(multiplier); if( ( stringArg.match(/^-?[0-9]+$/) || stringArg === "" ) && isHexPrefixed === false ) - return toBNbasic( stringArg, 10).mul( multiplier ); + return toBNbasic( stringArg, 10 ).mul( multiplier ); } else if( typeof arg === "object" && arg.toString && (!arg.pop && !arg.push) ) { if( arg.toString().match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy) ) - return toBNbasic(arg.toString(), 10); + return toBNbasic( arg.toString(), 10 ); } else if( arg ) { return toBNbasic( arg ); // try to convert as is } From 19535569801c98e2f98133657e4b62d568037060 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 12 Dec 2023 18:45:33 +0000 Subject: [PATCH 10/53] code porting to TypeScript --- src/cli.ts | 2 +- src/loop.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 53d0953c..31455f32 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2096,7 +2096,7 @@ function commonInitCheckGeneralArgs() { } ensureHaveValue( "App path", - path.join( __dirname, "main.ts" ), false, isPrintGathered, null, ( x: any ) => { + path.join( __dirname, "main.js" ), false, isPrintGathered, null, ( x: any ) => { return att( x ); } ); ensureHaveValue( diff --git a/src/loop.ts b/src/loop.ts index 1c2e670d..0ee05b4e 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -515,7 +515,7 @@ export async function ensureHaveWorkers( opts: any ) { "colorization": { isEnabled: log.isEnabledColorization() } }; gArrWorkers.push( new threadInfo.Worker( - path.join( __dirname, "loopWorker.ts" ), + path.join( __dirname, "loopWorker.js" ), { // "type": "module", "workerData": workerData } ) ); From 32631bb8a4070bf5e70ea5f6bf6b9c695eba52d0 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 12 Dec 2023 18:57:15 +0000 Subject: [PATCH 11/53] code porting to TypeScript --- src/bls.ts | 5 ++++- src/imaTx.ts | 2 +- src/loopWorker.ts | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index b967804f..1160c20d 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -29,7 +29,7 @@ import * as log from "./log.js"; import * as owaspUtils from "./owaspUtils.js"; import * as childProcessModule from "child_process"; import * as rpcCall from "./rpcCall.js"; -import * as shell from "shelljs"; +import * as shellMod from "shelljs"; import * as imaUtils from "./utils.js"; import * as sha3Module from "sha3"; import * as skaleObserver from "./observer.js"; @@ -38,6 +38,9 @@ import * as threadInfo from "./threadInfo.js"; import * as utils from "./socketUtils.js"; import * as state from "./state.js"; +const anyShellMod: any = shellMod as any; +const shell = anyShellMod[ "default" ]; + const Keccak = sha3Module.Keccak; function discoverBlsThreshold( joSChainNetworkInfo: any ) : number { diff --git a/src/imaTx.ts b/src/imaTx.ts index 3d8a16a7..143dd836 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -207,7 +207,7 @@ async function payedCallSGX( optsPayedCall: any ) { chainId = owaspUtils.parseIntOrHex( chainId ); optsPayedCall.details.trace( "{p}Chain ID is: {}", optsPayedCall.strLogPrefix, chainId ); - const strCmd = "" + process.argv[0] + " --no-warnings ./imaSgxExternalSigner.ts " + + const strCmd = "" + process.argv[0] + " --no-warnings ./imaSgxExternalSigner.js " + ( log.isEnabledColorization() ? "true" : "false" ) + " " + "\"" + optsPayedCall.joAccount.strSgxURL + "\" " + "\"" + optsPayedCall.joAccount.strSgxKeyName + "\" " + diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 4c93df3d..559cc9c7 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -25,7 +25,7 @@ import { parentPort, workerData } from "worker_threads"; import * as networkLayer from "./socket.js"; -import { SocketServer } from "./socketServer"; +import { SocketServer } from "./socketServer.js"; import * as owaspUtils from "./owaspUtils.js"; import * as loop from "./loop.js"; import * as imaTx from "./imaTx.js"; From ae127aaf630288504afbd9833afc235d16709ae8 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 13 Dec 2023 11:55:56 +0000 Subject: [PATCH 12/53] IMA/TypeScript support --- src/cc.ts | 19 ++++++++++++------- src/log.ts | 8 ++++---- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/cc.ts b/src/cc.ts index a1875bf7..46cddc95 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -964,7 +964,7 @@ function errLocLn( s: string, isWithBraces?: boolean ) : string { if( j == 1 ) s2 += info( arrCodePoint[j] ); else - s2 += notice( arrCodePoint[j] ); + s2 += attention( arrCodePoint[j] ); } } else s2 += trace( s ); @@ -973,11 +973,16 @@ function errLocLn( s: string, isWithBraces?: boolean ) : string { return s2; } -export function stack( strIn?: string ) : string { - if( ! strIn ) - return strIn || ""; +export function stack( err?: any ) : string { + if( ! err ) + return ""; + if( err && "stack" in err ) { + const st = err[ "stack" ]; + if( st && typeof st == "string" ) + err = st; + } try { - const arr = ( typeof strIn == "string" ) ? strIn.split( "\n" ) : strIn; + const arr = ( typeof err == "string" ) ? err.split( "\n" ) : err; const cnt = arr.length; let i; for( i = 0; i < cnt; ++ i ) { @@ -1008,7 +1013,7 @@ export function stack( strIn?: string ) : string { arr[i] = s; } return arr.join( "\n" ); - } catch ( err ) { - return strIn; + } catch ( errCaught ) { + return err.toString(); } } diff --git a/src/log.ts b/src/log.ts index 2a6f9eb8..26c3ba11 100644 --- a/src/log.ts +++ b/src/log.ts @@ -26,6 +26,8 @@ import * as cc from "./cc.js"; import * as fs from "fs"; +export { cc }; + let gArrStreams: any[] = []; let gFlagLogWithTimeStamps: boolean = true; @@ -1016,10 +1018,8 @@ export function em( x?: any ) : string { return cc.isStringAlreadyColorized( x ) ? x : cc.warning( x ); } -export function stack( x?: any ) : string { - if( x && "stack" in x && x.stack ) - return stack( x.stack ); - return cc.isStringAlreadyColorized( x ) ? x : cc.stack( x ); +export function stack( err?: any ) : string { + return cc.stack( err ); } export function onOff( x?: any ) : string { From 1acebb3c1eb28be05a69a997a0974407bfddfb10 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 13 Dec 2023 13:59:52 +0000 Subject: [PATCH 13/53] IMA/TypeScript support --- src/bls.ts | 17 ++-- src/cli.ts | 10 +- src/clpTools.ts | 9 +- src/imaCore.ts | 59 +++++++----- src/imaEthOperations.ts | 24 ++--- src/imaEventLogScan.ts | 146 +++++++++++------------------- src/imaHelperAPIs.ts | 28 ++---- src/imaOracleOperations.ts | 4 +- src/imaRegistrationOperations.ts | 25 ++--- src/imaReimbursementOperations.ts | 10 +- src/imaSgxExternalSigner.ts | 7 +- src/imaTokenOperations.ts | 113 +++++++++++------------ src/imaTx.ts | 38 ++++---- src/loop.ts | 4 + src/owaspUtils.ts | 12 ++- 15 files changed, 240 insertions(+), 266 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index 1160c20d..5b4fcd3f 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -706,7 +706,8 @@ async function checkCorrectnessOfMessagesToSign( jarrMessages: any[], nIdxCurrentMsgBlockStart: number, joExtraSignOpts: any ) { const imaState = state.get(); - let joMessageProxy: any = null, joAccount: any = null, joChainName: any = null; + let joMessageProxy: owaspUtils.ethersMod.ethers.Contract|null = null; + let joAccount: any = null, joChainName: any = null; if( strDirection == "M2S" ) { joMessageProxy = imaState.joMessageProxyMainNet; joAccount = imaState.chainProperties.mn.joAccount; @@ -718,12 +719,9 @@ async function checkCorrectnessOfMessagesToSign( } else if( strDirection == "S2S" ) { joAccount = imaState.chainProperties.sc.joAccount; joChainName = joExtraSignOpts.chainNameDst; - const ethersProvider = - ( "ethersProviderSrc" in joExtraSignOpts && - joExtraSignOpts.ethersProviderSrc ) - ? joExtraSignOpts.ethersProviderSrc - : null - ; + const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider|null = + ( "ethersProviderSrc" in joExtraSignOpts && joExtraSignOpts.ethersProviderSrc ) + ? joExtraSignOpts.ethersProviderSrc : null; if( ! ethersProvider ) { throw new Error( "CRITICAL ERROR: No provider specified in extra signing options " + `for checking messages of direction ${strDirection}` ); @@ -743,7 +741,8 @@ async function checkCorrectnessOfMessagesToSign( "MessageProxy contract with address {}, caller account address is {}, message(s) " + "count is {}, message(s) to process are {}, first real message index is {}, messages " + "will be sent to chain name {}", - strLogPrefix, strDirection, "verifyOutgoingMessageData", joMessageProxy.address, + strLogPrefix, strDirection, "verifyOutgoingMessageData", + joMessageProxy ? joMessageProxy.address : "", strCallerAccountAddress, jarrMessages.length, jarrMessages, nIdxCurrentMsgBlockStart, joChainName ); let cntBadMessages = 0, i = 0; @@ -765,6 +764,8 @@ async function checkCorrectnessOfMessagesToSign( "dstContract": joMessage.destinationContract, "data": joMessage.data }; + if( ! joMessageProxy ) + throw new Error( "No message proxy available" ); const isValidMessage = await joMessageProxy.callStatic.verifyOutgoingMessageData( outgoingMessageData, { from: strCallerAccountAddress } ); details.trace( diff --git a/src/cli.ts b/src/cli.ts index 31455f32..f3fe05db 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1526,7 +1526,7 @@ function commonInitPrintFoundContracts() { // message_proxy_mainnet_address --> message_proxy_mainnet_abi // message_proxy_chain_address --> message_proxy_chain_abi - const oct = function( joContract: any ) { // optional contract address + const oct = function( joContract: owaspUtils.ethersMod.ethers.Contract ) { // optional contract address if( joContract && "address" in joContract && joContract.address ) return log.fmtInformation( "{}", joContract.address ); return log.fmtError( "contract is not available" ); @@ -2689,7 +2689,7 @@ function initContractsIMA() { const imaState = state.get(); if( imaState.chainProperties.mn.bHaveAbiIMA ) { const cp = imaState.chainProperties.mn; - const ep = cp.ethersProvider; + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = cp.joAbiIMA; imaState.joDepositBoxETH = new owaspUtils.ethersMod.ethers.Contract( @@ -2736,7 +2736,7 @@ function initContractsIMA() { } if( imaState.chainProperties.sc.bHaveAbiIMA ) { const cp = imaState.chainProperties.sc; - const ep = cp.ethersProvider; + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = cp.joAbiIMA; imaState.joTokenManagerETH = new owaspUtils.ethersMod.ethers.Contract( @@ -2786,7 +2786,7 @@ function initContractsIMA() { } if( imaState.chainProperties.tc.bHaveAbiIMA ) { const cp = imaState.chainProperties.tc; - const ep = cp.ethersProvider; + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = cp.joAbiIMA; imaState.joTokenManagerETHTarget = new owaspUtils.ethersMod.ethers.Contract( @@ -2840,7 +2840,7 @@ function initContractsSkaleManager() { const imaState = state.get(); if( imaState.bHaveSkaleManagerABI ) { const cp = imaState.chainProperties.mn; - const ep = cp.ethersProvider; + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = imaState.joAbiSkaleManager; imaState.joConstantsHolder = new owaspUtils.ethersMod.ethers.Contract( diff --git a/src/clpTools.ts b/src/clpTools.ts index 41a9735d..07d2e97e 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -1042,12 +1042,13 @@ export function commandLineTaskPaymentS2S() { "fn": async function() { const isForward = imaHelperAPIs.isForwardS2S(); const sc = imaState.chainProperties.sc, tc = imaState.chainProperties.tc; - const ethersProviderSrc = isForward ? sc.ethersProvider : tc.ethersProvider; + const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = + isForward ? sc.ethersProvider : tc.ethersProvider; const chainIdSrc = isForward ? sc.chainId : tc.chainId; const joAccountSrc = isForward ? sc.joAccount : tc.joAccount; - const joTokenManagerERC20Src = isForward + const joTokenManagerERC20Src: owaspUtils.ethersMod.ethers.Contract = isForward ? imaState.joTokenManagerERC20 : imaState.joTokenManagerERC20Target; - const joTokenManagerERC721Src = isForward + const joTokenManagerERC721Src: owaspUtils.ethersMod.ethers.Contract = isForward ? ( imaState.isWithMetadata721 ? imaState.joTokenManagerERC721WithMetadata : imaState.joTokenManagerERC721 ) @@ -1055,7 +1056,7 @@ export function commandLineTaskPaymentS2S() { ? imaState.joTokenManagerERC721WithMetadataTarget : imaState.joTokenManagerERC721Target ) ; - const joTokenManagerERC1155Src = isForward + const joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract = isForward ? imaState.joTokenManagerERC1155 : imaState.joTokenManagerERC1155Target; const strChainNameDst = isForward ? tc.strChainName : sc.strChainName; const strCoinNameErc20Src = isForward ? sc.strCoinNameErc20 : tc.strCoinNameErc20; diff --git a/src/imaCore.ts b/src/imaCore.ts index 93d01f98..8c5d9b9b 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -43,7 +43,9 @@ const perMessageGasForTransfer = 1000000; const additionalS2MTransferOverhead = 200000; async function findOutReferenceLogRecord( - details: any, strLogPrefix: string, ethersProvider: any, joMessageProxy: any, + details: any, strLogPrefix: string, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joMessageProxy: owaspUtils.ethersMod.ethers.Contract, bnBlockId: any, nMessageNumberToFind: any, isVerbose?: boolean ) { const bnMessageNumberToFind = owaspUtils.toBN( nMessageNumberToFind.toString() ); @@ -85,7 +87,9 @@ async function findOutReferenceLogRecord( } async function findOutAllReferenceLogRecords( - details: any, strLogPrefix: string, ethersProvider: any, joMessageProxy: any, + details: any, strLogPrefix: string, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joMessageProxy: owaspUtils.ethersMod.ethers.Contract, bnBlockId: any, nIncMsgCnt: number, nOutMsgCnt: number, isVerbose?: boolean ) { if( isVerbose ) { @@ -516,9 +520,8 @@ async function callbackAllMessagesSign( optsTransfer.strLogPrefix, optsTransfer.nIdxCurrentMsgBlockStart, joDebugArgs ); optsTransfer.strActionName = optsTransfer.strDirection + " - Post incoming messages"; const weiHowMuchPostIncomingMessages = undefined; - const gasPrice = - await optsTransfer.transactionCustomizerDst.computeGasPrice( - optsTransfer.ethersProviderDst, 200000000000 ); + const gasPrice = await optsTransfer.transactionCustomizerDst.computeGasPrice( + optsTransfer.ethersProviderDst, 200000000000 ); optsTransfer.details.debug( "{p}Using computed gasPrice {}={}", optsTransfer.strLogPrefix, gasPrice ); let estimatedGasPostIncomingMessages = @@ -663,10 +666,11 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer: any, optsOutgoi let bEventIsFound = false; try { const ethersProviderNode = owaspUtils.getEthersProviderFromURL( strUrlHttp ); - const joMessageProxyNode = new owaspUtils.ethersMod.ethers.Contract( - sc.joAbiIMA.message_proxy_chain_address, - sc.joAbiIMA.message_proxy_chain_abi, - ethersProviderNode ); + const joMessageProxyNode: owaspUtils.ethersMod.ethers.Contract = + new owaspUtils.ethersMod.ethers.Contract( + sc.joAbiIMA.message_proxy_chain_address, + sc.joAbiIMA.message_proxy_chain_abi, + ethersProviderNode ); const strEventName = "OutgoingMessage"; const node_r = await imaEventLogScan.safeGetPastEventsProgressive( optsTransfer.details, optsTransfer.strLogPrefixShort, ethersProviderNode, @@ -921,11 +925,13 @@ let gIsOneTransferInProgressInThisThread = false; export async function doTransfer( strDirection: string, joRuntimeOpts: any, - ethersProviderSrc: any, joMessageProxySrc: any, joAccountSrc: any, - ethersProviderDst: any, joMessageProxyDst: any, joAccountDst: any, + ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joMessageProxySrc: owaspUtils.ethersMod.ethers.Contract, joAccountSrc: any, + ethersProviderDst: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joMessageProxyDst: owaspUtils.ethersMod.ethers.Contract, joAccountDst: any, chainNameSrc: string, chainNameDst: string, chainIdSrc: string, chainIdDst: string, - joDepositBoxMainNet: any, // for logs validation on mainnet - joTokenManagerSChain: any, // for logs validation on s-chain + joDepositBoxMainNet: owaspUtils.ethersMod.ethers.Contract|null, // for logs validation on mainnet + joTokenManagerSChain: owaspUtils.ethersMod.ethers.Contract|null, // for logs validation on s-chain nTransactionsCountInBlock: number, nTransferSteps: number, nMaxTransactionsCount: number, nBlockAwaitDepth: number, nBlockAge: number, fnSignMessages: any, joExtraSignOpts: any, @@ -1083,12 +1089,12 @@ export async function doAllS2S( // s-chain --> s-chain joRuntimeOpts: any, imaState: any, skaleObserver: any, - ethersProviderDst: any, - joMessageProxyDst: any, + ethersProviderDst: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joMessageProxyDst: owaspUtils.ethersMod.ethers.Contract, joAccountDst: any, chainNameDst: string, chainIdDst: string, - joTokenManagerSChain: any, // for logs validation on s-chain + joTokenManagerSChain: owaspUtils.ethersMod.ethers.Contract, // for logs validation on s-chain nTransactionsCountInBlock: number, nTransferSteps: number, nMaxTransactionsCount: number, @@ -1107,7 +1113,8 @@ export async function doAllS2S( // s-chain --> s-chain for( let idxSChain = 0; idxSChain < cntSChains; ++ idxSChain ) { const joSChain = arrSChainsCached[idxSChain]; const urlSrc = skaleObserver.pickRandomSChainUrl( joSChain ); - const ethersProviderSrc = owaspUtils.getEthersProviderFromURL( urlSrc ); + const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = + owaspUtils.getEthersProviderFromURL( urlSrc ); const joAccountSrc = joAccountDst; // ??? const chainNameSrc = "" + joSChain.name; const chainIdSrc = "" + joSChain.chainId; @@ -1123,14 +1130,16 @@ export async function doAllS2S( // s-chain --> s-chain } else { if( loop.checkTimeFraming( null, "s2s", joRuntimeOpts ) ) { // ??? assuming all S-Chains have same ABIs here - const joMessageProxySrc = new owaspUtils.ethersMod.ethers.Contract( - sc.joAbiIMA.message_proxy_chain_address, - sc.joAbiIMA.message_proxy_chain_abi, - ethersProviderSrc ); - const joDepositBoxSrc = new owaspUtils.ethersMod.ethers.Contract( - sc.joAbiIMA.message_proxy_chain_address, - sc.joAbiIMA.message_proxy_chain_abi, - ethersProviderSrc ); + const joMessageProxySrc: owaspUtils.ethersMod.ethers.Contract = + new owaspUtils.ethersMod.ethers.Contract( + sc.joAbiIMA.message_proxy_chain_address, + sc.joAbiIMA.message_proxy_chain_abi, + ethersProviderSrc ); + const joDepositBoxSrc: owaspUtils.ethersMod.ethers.Contract = + new owaspUtils.ethersMod.ethers.Contract( + sc.joAbiIMA.message_proxy_chain_address, + sc.joAbiIMA.message_proxy_chain_abi, + ethersProviderSrc ); const joExtraSignOpts: any = { chainNameSrc: chainNameSrc, chainIdSrc: chainIdSrc, diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 8dcd071f..5e164312 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -32,8 +32,8 @@ import * as imaEventLogScan from "./imaEventLogScan.js"; import * as threadInfo from "./threadInfo.js"; export async function getBalanceEth( - isMainNet: any, - ethersProvider: any, + isMainNet: boolean, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider|null, chainId: string, joAccount?: any, contractERC20?: any @@ -67,12 +67,12 @@ export async function getBalanceEth( // money is sent from caller // "value" JSON arg is used to specify amount of money to sent export async function doEthPaymentFromMainNet( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, joAccountSrc: any, joAccountDst: any, - joDepositBox: any, - joMessageProxyMainNet: any, // for checking logs + joDepositBox: owaspUtils.ethersMod.ethers.Contract, + joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainIdSChain: string, weiHowMuch: any, // how much WEI money to send transactionCustomizerMainNet: imaTx.TransactionCustomizer @@ -164,12 +164,12 @@ export async function doEthPaymentFromMainNet( // money is sent from caller // "value" JSON arg is used to specify amount of money to sent export async function doEthPaymentFromSChain( - ethersProviderSChain: any, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joTokenManagerETH: any, - joMessageProxySChain: any, // for checking logs + joTokenManagerETH: owaspUtils.ethersMod.ethers.Contract, + joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs weiHowMuch: any, // how much WEI money to send transactionCustomizerSChain: imaTx.TransactionCustomizer ) { @@ -253,10 +253,10 @@ export async function doEthPaymentFromSChain( } export async function receiveEthPaymentFromSchainOnMainNet( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, joAccountMN: any, - joDepositBoxETH: any, + joDepositBoxETH: owaspUtils.ethersMod.ethers.Contract, transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { const details = log.createMemoryStream(); @@ -313,9 +313,9 @@ export async function receiveEthPaymentFromSchainOnMainNet( } export async function viewEthPaymentFromSchainOnMainNet( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joAccountMN: any, - joDepositBoxETH: any + joDepositBoxETH: owaspUtils.ethersMod.ethers.Contract ) { const details = log.createMemoryStream(); const strActionName = ""; diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index cdd726b5..96f3ba1c 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -86,7 +86,8 @@ export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumbe export async function safeGetPastEventsProgressive( details: any, strLogPrefix: string, - ethersProvider: any, attempts: number, joContract: any, strEventName: string, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + attempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any ) { const strURL = owaspUtils.ethersProviderToUrl( ethersProvider ); @@ -165,7 +166,8 @@ export async function safeGetPastEventsProgressive( export async function getContractCallEvents( details: any, strLogPrefix: string, - ethersProvider: any, joContract: any, strEventName: string, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockNumber: any, strTxHash: string, joFilter: any ) { joFilter = joFilter || {}; @@ -180,10 +182,9 @@ export async function getContractCallEvents( nBlockFrom = nBlockZero; if( nBlockTo.gte( nLatestBlockNumber ) ) nBlockTo = nLatestBlockNumberPlus1; - const joAllEventsInBlock = - await safeGetPastEventsIterative( - details, strLogPrefix, ethersProvider, 10, joContract, strEventName, - nBlockFrom, nBlockTo, joFilter ); + const joAllEventsInBlock = await safeGetPastEventsIterative( + details, strLogPrefix, ethersProvider, 10, joContract, strEventName, + nBlockFrom, nBlockTo, joFilter ); const joAllTransactionEvents: any = []; let i: number; for( i = 0; i < joAllEventsInBlock.length; ++i ) { @@ -196,7 +197,8 @@ export async function getContractCallEvents( export async function safeGetTransactionCount( details: any, cntAttempts: number, - ethersProvider: any, address: string, param: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + address: string, param: any, retValOnFail: any, throwIfServerOffline: boolean ) { const strFnName = "getTransactionCount"; @@ -204,43 +206,32 @@ export async function safeGetTransactionCount( const nWaitStepMilliseconds = 10 * 1000; if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; - cntAttempts = - owaspUtils.parseIntOrHex( cntAttempts ) < 1 - ? 1 - : owaspUtils.parseIntOrHex( cntAttempts ); + cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) + ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; let idxAttempt = 1; - try { - ret = await ethersProvider[strFnName]( address, param ); - return ret; - } catch ( err ) { - ret = retValOnFail; - details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); - } - ++ idxAttempt; - while( ret === "" && idxAttempt <= cntAttempts ) { - const isOnLine = rpcCall.checkUrl( u, nWaitStepMilliseconds ); + for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); if( ! isOnLine ) { ret = retValOnFail; if( ! throwIfServerOffline ) return ret; - details.error( "Cannot call {} via {url} because server is off-line", - strFnName + "()", u ); + details.error( "Cannot call {} via {url} because server is off-line, attempt {} of {}", + strFnName + "()", u, idxAttempt, cntAttempts ); throw new Error( `Cannot ${strFnName}() via ${u} because server is off-line` ); } - details.trace( "Repeat call to {} via {url}, attempt {}", strFnName + "()", u, idxAttempt ); + details.trace( "Call to {} via {url}, attempt {} of {}", + strFnName + "()", u, idxAttempt, cntAttempts ); try { ret = await ethersProvider[strFnName]( address, param ); return ret; } catch ( err ) { ret = retValOnFail; - details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); + details.error( "Failed call attempt {} of {} to {} via {url}, error is: {err}, " + + "stack is:\n{stack}", idxAttempt, cntAttempts, strFnName + "()", u, err, err ); } - ++ idxAttempt; } if( ( idxAttempt + 1 ) > cntAttempts && ret === "" ) { details.error( "Failed call to {} via {url} after {} attempts", @@ -252,50 +243,40 @@ export async function safeGetTransactionCount( export async function safeGetTransactionReceipt( details: any, cntAttempts: number, - ethersProvider: any, txHash: string, retValOnFail?: any, throwIfServerOffline?: boolean + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + txHash: string, retValOnFail?: any, throwIfServerOffline?: boolean ) { const strFnName = "getTransactionReceipt"; const u = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; - cntAttempts = - owaspUtils.parseIntOrHex( cntAttempts ) < 1 - ? 1 - : owaspUtils.parseIntOrHex( cntAttempts ); + cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) + ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; let idxAttempt = 1; - try { - ret = await ethersProvider[strFnName]( txHash ); - return ret; - } catch ( err ) { - ret = retValOnFail; - details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); - } - ++ idxAttempt; - while( idxAttempt <= cntAttempts ) { - const isOnLine = rpcCall.checkUrl( u, nWaitStepMilliseconds ); + for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); if( ! isOnLine ) { ret = retValOnFail; if( ! throwIfServerOffline ) return ret; - details.error( "Cannot call {} via {url} because server is off-line", - strFnName + "()", u ); + details.error( "Cannot call {} via {url} because server is off-line, attempt {} of {}", + strFnName + "()", u, idxAttempt, cntAttempts ); throw new Error( `Cannot ${strFnName}() via ${u} because server is off-line` ); } - details.trace( "Repeat call to {} via {url}, attempt {}", strFnName + "()", u, idxAttempt ); + details.trace( "Call to {} via {url}, attempt {} of {}", + strFnName + "()", u, idxAttempt, cntAttempts ); try { ret = await ethersProvider[strFnName]( txHash ); return ret; } catch ( err ) { ret = retValOnFail; - details.error( "Failed call attempt {} to {} via {url}, error is: {err}, " + - "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); + details.error( "Failed call attempt {} of {} to {} via {url}, error is: {err}, " + + "stack is:\n{stack}", idxAttempt, cntAttempts, strFnName + "()", u, err, err ); } - ++ idxAttempt; } if( ( idxAttempt + 1 ) > cntAttempts ) { details.error( "Failed call to {} via {url} after {} attempts", @@ -307,7 +288,8 @@ export async function safeGetTransactionReceipt( export async function safeGetPastEvents( details: any, strLogPrefix: string, - ethersProvider: any, cntAttempts: number, joContract: any, strEventName: string, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + cntAttempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any, retValOnFail?: any, throwIfServerOffline?: boolean ) { @@ -315,10 +297,8 @@ export async function safeGetPastEvents( const nWaitStepMilliseconds = 10 * 1000; if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; - cntAttempts = - owaspUtils.parseIntOrHex( cntAttempts ) < 1 - ? 1 - : owaspUtils.parseIntOrHex( cntAttempts ); + cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) + ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; @@ -333,48 +313,26 @@ export async function safeGetPastEvents( } else nBlockTo = owaspUtils.toBN( nBlockTo ); nBlockFrom = owaspUtils.toBN( nBlockFrom ); - try { - details.trace( - "{p}First time, will query filter {} on contract {} from block {} to block {} while " + - "current latest block number on chain is {}", strLogPrefix, joFilter, - joContract.address, nBlockFrom.toHexString(), nBlockTo.toHexString(), - nLatestBlockNumber.toHexString() ); - ret = await joContract.queryFilter( - joFilter, nBlockFrom.toHexString(), nBlockTo.toHexString() ); - return ret; - } catch ( err ) { - ret = retValOnFail; - details.error( - "{p}Failed filtering attempt {} for event {} via {url}, from block {}, to block {}, " + - "error is: {err}, stack is:\n{stack}", strLogPrefix, idxAttempt, strEventName, u, - nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err ); - if( owaspUtils.extractErrorMessage( err ) - .indexOf( strErrorTextAboutNotExistingEvent ) >= 0 ) { - details.error( "{p}Did stopped filtering of {} event because no such event exist " + - "in smart contract ", strLogPrefix, strEventName ); - return ret; - } - } - ++ idxAttempt; - while( ret === "" && idxAttempt <= cntAttempts ) { - const isOnLine = rpcCall.checkUrl( u, nWaitStepMilliseconds ); + for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); if( ! isOnLine ) { ret = retValOnFail; if( ! throwIfServerOffline ) return ret; - details.error( "{p}Cannot do {} event filtering via {url} because server is off-line", - strLogPrefix, strEventName, u ); + details.error( + "{p}Cannot do {} event filtering via {url} because server is off-line, " + + "attempt {} of {}", strLogPrefix, strEventName, u, idxAttempt, cntAttempts ); throw new Error( `Cannot do ${strEventName} event filtering, ` + `from block ${nBlockFrom.toHexString()} , to block ${nBlockTo.toHexString()} ` + `via ${u} because server is off-line` ); } - details.trace( "{p}Repeat {} event filtering via {url}, attempt {}", - strLogPrefix, strEventName, u, idxAttempt ); + details.trace( "{p}Repeat {} event filtering via {url}, attempt {} of {}", + strLogPrefix, strEventName, u, idxAttempt, cntAttempts ); try { details.trace( - "{p}Attempt {}, will query filter {} on contract {} from block {} to block {}", - strLogPrefix, idxAttempt, joFilter, joContract.address, nBlockFrom.toHexString(), - nBlockTo.toHexString() ); + "{p}Attempt {} of, will query filter {} on contract {} from block {} to block {}", + strLogPrefix, idxAttempt, cntAttempts, joFilter, joContract.address, + nBlockFrom.toHexString(), nBlockTo.toHexString() ); ret = await joContract.queryFilter( joFilter, nBlockFrom.toHexString(), nBlockTo.toHexString() ); return ret; @@ -382,19 +340,18 @@ export async function safeGetPastEvents( } catch ( err ) { ret = retValOnFail; details.error( - "{p}Failed filtering attempt {} for event {} via {url}, from block {}" + - ", to block{}, error is: {err}, stack is:\n{stack}", strLogPrefix, idxAttempt, - strEventName, u, nBlockFrom.toHexString(), nBlockTo.toHexString(), - err, err ); + "{p}Failed filtering attempt {} of {} for event {} via {url}, from block {}" + + ", to block{}, error is: {err}, stack is:\n{stack}", strLogPrefix, + idxAttempt, cntAttempts, strEventName, u, + nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err ); if( owaspUtils.extractErrorMessage( err ) .indexOf( strErrorTextAboutNotExistingEvent ) >= 0 ) { details.error( "{p}Did stopped {} event filtering because no such event exist " + - "in smart contract ", strLogPrefix, strEventName ); + "in smart contract", strLogPrefix, strEventName ); return ret; } } - ++ idxAttempt; } if( ( idxAttempt + 1 ) === cntAttempts && ret === "" ) { details.error( @@ -410,7 +367,8 @@ export async function safeGetPastEvents( export async function safeGetPastEventsIterative( details: any, strLogPrefix: string, - ethersProvider: any, attempts: number, joContract: any, strEventName: string, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + attempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any ) { if( imaHelperAPIs.getBlocksCountInInIterativeStepOfEventsScan() <= 0 || diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 56505325..3be3e92a 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -61,7 +61,8 @@ export const currentTimestamp = () : number => { return Date.now().valueOf() / 1000; }; -export async function safeWaitForNextBlockToAppear( details: any, ethersProvider: any ) { +export async function safeWaitForNextBlockToAppear( + details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider ) { const nBlockNumber: any = owaspUtils.toBN( await safeGetBlockNumber( details, 10, ethersProvider ) ); details.trace( "Waiting for next block to appear..." ); @@ -77,7 +78,8 @@ export async function safeWaitForNextBlockToAppear( details: any, ethersProvider } export async function safeGetBlockNumber( - details: any, cntAttempts: number, ethersProvider: any, + details: any, cntAttempts: number, + ethersProvider: any, retValOnFail?: any, throwIfServerOffline?: boolean ) { const strFnName: string = "getBlockNumber"; @@ -85,25 +87,14 @@ export async function safeGetBlockNumber( const nWaitStepMilliseconds = 10 * 1000; if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; - cntAttempts = - owaspUtils.parseIntOrHex( cntAttempts ) < 1 - ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); + cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) + ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; - let idxAttempt = 1; let ret = retValOnFail; - try { - ret = await ethersProvider[strFnName](); - return ret; - } catch ( err ) { - ret = retValOnFail; - details.error( - "Failed call attempt {} to {} via {url}, error is: {err}, stack is:\n{stack}", - idxAttempt, strFnName + "()", u, err, err ); - } - ++ idxAttempt; - while( ret === "" && idxAttempt <= cntAttempts ) { - const isOnLine = rpcCall.checkUrl( u, nWaitStepMilliseconds ); + let idxAttempt = 1; + for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); if( ! isOnLine ) { ret = retValOnFail; if( ! throwIfServerOffline ) @@ -121,7 +112,6 @@ export async function safeGetBlockNumber( details.error( "Failed call attempt {} to via {url}, error is: {err}, " + "stack is:\n{stack}", idxAttempt, strFnName + "()", u, err, err ); } - ++ idxAttempt; } if( ( idxAttempt + 1 ) > cntAttempts && ret === "" ) { details.error( "Failed call to {} via {url} after {} attempts ", diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 2d10d5d7..7279931e 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -213,8 +213,8 @@ async function handleOracleSigned( } export async function doOracleGasPriceSetup( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, transactionCustomizerSChain: imaTx.TransactionCustomizer, joCommunityLocker: any, joAccountSC: any, diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index adc2a658..5eb612fc 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -27,10 +27,11 @@ import * as log from "./log.js"; import * as imaHelperAPIs from "./imaHelperAPIs.js"; import * as imaTx from "./imaTx.js"; import * as threadInfo from "./threadInfo.js"; +import * as owaspUtils from "./owaspUtils.js"; export async function invokeHasChain( details: any, - ethersProvider: any, // Main-Net or S-Chin + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, // Main-Net or S-Chin joLinker: any, // Main-Net or S-Chin joAccount: any, // Main-Net or S-Chin chainIdSChain: string @@ -53,7 +54,7 @@ export async function invokeHasChain( export async function waitForHasChain( details: any, - ethersProvider: any, // Main-Net or S-Chin + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, // Main-Net or S-Chin joLinker: any, // Main-Net or S-Chin joAccount: any, // Main-Net or S-Chin chainIdSChain: string, @@ -78,7 +79,7 @@ export async function waitForHasChain( // main-net.DepositBox call: function addSchain(string schainName, address tokenManagerAddress) // export async function checkIsRegisteredSChainInDepositBoxes( // step 1 - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joLinker: any, joAccountMN: any, chainIdSChain: string @@ -113,16 +114,16 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 } export async function registerSChainInDepositBoxes( // step 1 - ethersProviderMainNet: any, - joLinker: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + joLinker: owaspUtils.ethersMod.ethers.Contract, joAccountMN: any, - joTokenManagerETH: any, // only s-chain - joTokenManagerERC20: any, // only s-chain - joTokenManagerERC721: any, // only s-chain - joTokenManagerERC1155: any, // only s-chain - joTokenManagerERC721WithMetadata: any, // only s-chain - joCommunityLocker: any, // only s-chain - joTokenManagerLinker: any, + joTokenManagerETH: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joTokenManagerERC20: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joTokenManagerERC721: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joTokenManagerERC721WithMetadata: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joCommunityLocker: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joTokenManagerLinker: owaspUtils.ethersMod.ethers.Contract, chainNameSChain: string, chainNameMainNet: string, transactionCustomizerMainNet: imaTx.TransactionCustomizer, diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index 0401d638..d1d1042c 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -29,7 +29,7 @@ import * as imaTx from "./imaTx.js"; import * as imaGasUsage from "./imaGasUsageOperations.js"; export async function reimbursementShowBalance( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joCommunityPool: any, joReceiverMainNet: any, strChainNameMainNet: any, @@ -70,7 +70,7 @@ export async function reimbursementShowBalance( } export async function reimbursementEstimateAmount( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joCommunityPool: any, joReceiverMainNet: any, strChainNameMainNet: string, @@ -153,7 +153,7 @@ export async function reimbursementEstimateAmount( } export async function reimbursementWalletRecharge( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joCommunityPool: any, joAccountMN: any, strChainNameMainNet: string, @@ -215,7 +215,7 @@ export async function reimbursementWalletRecharge( } export async function reimbursementWalletWithdraw( - ethersProviderMainNet: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joCommunityPool: any, joAccountMN: any, strChainNameMainNet: string, @@ -282,7 +282,7 @@ export async function reimbursementWalletWithdraw( } export async function reimbursementSetRange( - ethersProviderSChain: any, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joCommunityLocker: any, joAccountSC: any, strChainNameSChain: string, diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index c761e92c..1ddfe808 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -67,9 +67,8 @@ async function run() { const strPathKey = process.argv[14]; if( gIsDebugLogging ) log.debug( "Path to SGX key file is {}", strPathKey ); - - const ethersProvider = owaspUtils.getEthersProviderFromURL( strURL ); - + const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = + owaspUtils.getEthersProviderFromURL( strURL ); const tx: any = { data: tcData, to: txTo, @@ -128,7 +127,7 @@ async function run() { if( gIsDebugLogging ) log.debug( "--- Raw-sent transaction result ---> {}", sr ); - const joReceipt = await ethersProvider.waitForTransaction( sr.hash ); + const joReceipt: any = await ethersProvider.waitForTransaction( sr.hash ); if( gIsDebugLogging ) log.debug( "--- Transaction receipt ---> {}", joReceipt ); joReceipt.chainId = tx.chainId; diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index a02d21dd..11a7698c 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -33,7 +33,7 @@ import * as threadInfo from "./threadInfo.js"; export async function getBalanceErc20( isMainNet: boolean, - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, joAccount: any, strCoinName: string, @@ -62,7 +62,7 @@ export async function getBalanceErc20( export async function getOwnerOfErc721( isMainNet: boolean, - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, joAccount: any, strCoinName: string, @@ -91,7 +91,7 @@ export async function getOwnerOfErc721( export async function getBalanceErc1155( isMainNet: boolean, - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, joAccount: any, strCoinName: string, @@ -120,18 +120,18 @@ export async function getBalanceErc1155( } export async function doErc721PaymentFromMainNet( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joDepositBoxERC721: any, - joMessageProxyMainNet: any, // for checking logs + joDepositBoxERC721: owaspUtils.ethersMod.ethers.Contract, + joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, tokenId: any, // which ERC721 token id to send weiHowMuch: any, // how much ETH - joTokenManagerERC721: any, // only s-chain + joTokenManagerERC721: owaspUtils.ethersMod.ethers.Contract, // only s-chain strCoinNameErc721MainNet: string, erc721PrivateTestnetJsonMainNet: any, strCoinNameErc721SChain: string, @@ -258,18 +258,18 @@ export async function doErc721PaymentFromMainNet( } export async function doErc20PaymentFromMainNet( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joDepositBoxERC20: any, - joMessageProxyMainNet: any, // for checking logs + joDepositBoxERC20: owaspUtils.ethersMod.ethers.Contract, + joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, tokenAmount: any, // how much ERC20 tokens to send weiHowMuch: any, // how much ETH - joTokenManagerERC20: any, // only s-chain + joTokenManagerERC20: owaspUtils.ethersMod.ethers.Contract, // only s-chain strCoinNameErc20MainNet: string, erc20MainNet: any, strCoinNameErc20SChain: string, @@ -395,19 +395,19 @@ export async function doErc20PaymentFromMainNet( } export async function doErc1155PaymentFromMainNet( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joDepositBoxERC1155: any, - joMessageProxyMainNet: any, // for checking logs + joDepositBoxERC1155: owaspUtils.ethersMod.ethers.Contract, + joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, tokenId: any, // which ERC1155 token id to send tokenAmount: any, // which ERC1155 token id to send weiHowMuch: any, // how much ETH - joTokenManagerERC1155: any, // only s-chain + joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain strCoinNameErc1155SMainNet: string, erc1155PrivateTestnetJsonMainNet: any, strCoinNameErc1155SChain: string, @@ -542,16 +542,17 @@ export async function doErc1155PaymentFromMainNet( } export async function doErc1155BatchPaymentFromMainNet( - ethersProviderMainNet: any, ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joDepositBoxERC1155: any, - joMessageProxyMainNet: any, // for checking logs + joDepositBoxERC1155: owaspUtils.ethersMod.ethers.Contract, + joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, arrTokenIds: any[], // which ERC1155 token id to send arrTokenAmounts: any[], // which ERC1155 token id to send weiHowMuch: any, // how much ETH - joTokenManagerERC1155: any, // only s-chain + joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain strCoinNameErc1155SMainNet: string, erc1155PrivateTestnetJsonMainNet: any, strCoinNameErc1155SChain: string, erc1155PrivateTestnetJsonSChain: any, @@ -670,15 +671,15 @@ export async function doErc1155BatchPaymentFromMainNet( } export async function doErc20PaymentFromSChain( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joTokenManagerERC20: any, // only s-chain - joMessageProxySChain: any, // for checking logs - joDepositBox: any, // only main net + joTokenManagerERC20: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs + joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net tokenAmount: any, // how much ERC20 tokens to send weiHowMuch: any, // how much ETH strCoinNameErc20MainNet: string, @@ -814,15 +815,15 @@ export async function doErc20PaymentFromSChain( } export async function doErc721PaymentFromSChain( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joTokenManagerERC721: any, // only s-chain - joMessageProxySChain: any, // for checking logs - joDepositBox: any, // only main net + joTokenManagerERC721: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs + joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net tokenId: any, // which ERC721 token id to send weiHowMuch: any, // how much ETH strCoinNameErc721MainNet: string, @@ -962,15 +963,15 @@ export async function doErc721PaymentFromSChain( } export async function doErc1155PaymentFromSChain( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joTokenManagerERC1155: any, // only s-chain - joMessageProxySChain: any, // for checking logs - joDepositBox: any, // only main net + joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs + joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net tokenId: any, // which ERC1155 token id to send tokenAmount: any, // which ERC1155 token id to send weiHowMuch: any, // how much ETH @@ -1109,15 +1110,15 @@ export async function doErc1155PaymentFromSChain( } export async function doErc1155BatchPaymentFromSChain( - ethersProviderMainNet: any, - ethersProviderSChain: any, + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, joAccountSrc: any, joAccountDst: any, - joTokenManagerERC1155: any, // only s-chain - joMessageProxySChain: any, // for checking logs - joDepositBox: any, // only main net + joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain + joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs + joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net arrTokenIds: any[], // which ERC1155 token ids to send arrTokenAmounts: any[], // which ERC1155 token amounts to send weiHowMuch: any, // how much ETH @@ -1256,11 +1257,11 @@ export async function doErc1155BatchPaymentFromSChain( export async function doErc20PaymentS2S( isForward: boolean, - ethersProviderSrc: any, + ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, joAccountSrc: any, - joTokenManagerERC20Src: any, + joTokenManagerERC20Src: owaspUtils.ethersMod.ethers.Contract, nAmountOfToken: any, // how much ERC20 tokens to send nAmountOfWei: any, // how much to send strCoinNameErc20Src: string, @@ -1396,11 +1397,11 @@ export async function doErc20PaymentS2S( export async function doErc721PaymentS2S( isForward: boolean, - ethersProviderSrc: any, + ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, joAccountSrc: any, - joTokenManagerERC721Src: any, + joTokenManagerERC721Src: owaspUtils.ethersMod.ethers.Contract, tokenId: any, // which ERC721 token id to send nAmountOfWei: any, // how much to send strCoinNameErc721Src: string, @@ -1540,11 +1541,11 @@ export async function doErc721PaymentS2S( export async function doErc1155PaymentS2S( isForward: boolean, - ethersProviderSrc: any, + ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, joAccountSrc: any, - joTokenManagerERC1155Src: any, + joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract, tokenId: any, // which ERC721 token id to send nAmountOfToken: any, // how much ERC1155 tokens to send nAmountOfWei: any, // how much to send @@ -1685,11 +1686,11 @@ export async function doErc1155PaymentS2S( export async function doErc1155BatchPaymentS2S( isForward: boolean, - ethersProviderSrc: any, + ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, joAccountSrc: any, - joTokenManagerERC1155Src: any, + joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract, arrTokenIds: any[], // which ERC1155 token id to send arrTokenAmounts: any[], // which ERC1155 token id to send nAmountOfWei: any, // how much to send @@ -1831,7 +1832,7 @@ export async function doErc1155BatchPaymentS2S( } export async function mintErc20( - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, joAccount: any, @@ -1900,7 +1901,7 @@ export async function mintErc20( } export async function mintErc721( - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, joAccount: any, @@ -1969,7 +1970,7 @@ export async function mintErc721( } export async function mintErc1155( - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: any, joAccount: any, @@ -2042,7 +2043,7 @@ export async function mintErc1155( } export async function burnErc20( - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, joAccount: any, @@ -2111,7 +2112,7 @@ export async function burnErc20( } export async function burnErc721( - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, joAccount: any, @@ -2177,7 +2178,7 @@ export async function burnErc721( } export async function burnErc1155( - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, joAccount: any, diff --git a/src/imaTx.ts b/src/imaTx.ts index 143dd836..b3c1a7e7 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -68,8 +68,9 @@ export function dryRunIgnore( isIgnored: boolean ) : boolean { export async function dryRunCall( details: any, - ethersProvider: any, - strContractName: string, joContract: any, strMethodName: string, arrArguments: any[], + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, + strMethodName: string, arrArguments: any[], joAccount: any, strActionName: string, isDryRunResultIgnore: boolean, gasPrice: any, gasValue: any, weiHowMuch: any, opts?: any @@ -251,12 +252,9 @@ function postConvertBN( jo: any, name: any ) { } async function payedCallDirect( optsPayedCall: any ) { - const ethersWallet = - new owaspUtils.ethersMod.ethers.Wallet( - owaspUtils.ensureStartsWith0x( - optsPayedCall.joAccount.privateKey ), - optsPayedCall.ethersProvider ); - + const ethersWallet = new owaspUtils.ethersMod.ethers.Wallet( + owaspUtils.ensureStartsWith0x( optsPayedCall.joAccount.privateKey ), + optsPayedCall.ethersProvider ); let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); if( chainId == "string" ) chainId = owaspUtils.parseIntOrHex( chainId ); @@ -282,8 +280,9 @@ async function payedCallDirect( optsPayedCall: any ) { } export async function payedCall( - details: any, ethersProvider: any, - strContractName: string, joContract: any, strMethodName: any, arrArguments: any[], + details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, + strMethodName: any, arrArguments: any[], joAccount: any, strActionName: string, gasPrice: any, estimatedGas: any, weiHowMuch: any, opts?: any @@ -382,7 +381,7 @@ export async function payedCall( export async function checkTransactionToSchain( unsignedTx: any, details: any, - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joAccount: any ) { const strLogPrefix = "PoW-mining: "; @@ -541,7 +540,11 @@ async function tmGetRecord( txId: any ) { return null; } -async function tmWait( details: any, txId: any, ethersProvider: any, nWaitSeconds: number = 36000 ) { +async function tmWait( + details: any, + txId: any, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + nWaitSeconds: number = 36000 ) { const strLogPrefix = log.fmtDebug( "(gathered details)" ) + " "; details.debug( "{p}TM - will wait TX {} to complete for {} second(s) maximum", strLogPrefix, txId, nWaitSeconds ); @@ -573,7 +576,7 @@ async function tmWait( details: any, txId: any, ethersProvider: any, nWaitSecond } async function tmEnsureTransaction( - details: any, ethersProvider: any, priority: any, txAdjusted: any, + details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, priority: any, txAdjusted: any, cntAttempts?: number, sleepMilliseconds?: number ) { cntAttempts = cntAttempts || 1; @@ -610,7 +613,9 @@ export class TransactionCustomizer { : null; // null means use current gasPrice or recommendedGasPrice this.gasMultiplier = gasMultiplier ? ( 0.0 + gasMultiplier ) : 1.25; } - async computeGasPrice( ethersProvider: any, maxGasPrice: any ) { + async computeGasPrice( + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + maxGasPrice: any ) { const gasPrice = owaspUtils.parseIntOrHex( owaspUtils.toBN( @@ -637,8 +642,9 @@ export class TransactionCustomizer { } async computeGas( details: any, - ethersProvider: any, - strContractName: string, joContract: any, strMethodName: string, arrArguments: any[], + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, + strMethodName: string, arrArguments: any[], joAccount: any, strActionName: string, gasPrice: any, gasValueRecommended: any, weiHowMuch: any, opts?: any diff --git a/src/loop.ts b/src/loop.ts index 0ee05b4e..050abae4 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -252,16 +252,20 @@ async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) b2 = await IMA.doTransfer( // s-chain --> main-net "S2M", optsLoop.joRuntimeOpts, + imaState.chainProperties.sc.ethersProvider, imaState.joMessageProxySChain, imaState.chainProperties.sc.joAccount, + imaState.chainProperties.mn.ethersProvider, imaState.joMessageProxyMainNet, imaState.chainProperties.mn.joAccount, + imaState.chainProperties.sc.strChainName, imaState.chainProperties.mn.strChainName, imaState.chainProperties.sc.chainId, imaState.chainProperties.mn.chainId, + imaState.joDepositBoxETH, // for logs validation on mainnet null, imaState.nTransferBlockSizeS2M, diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index baa1a195..54c200ee 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -678,8 +678,9 @@ export function fnAddressImpl_( anyThis: any ) : string { return anyThis.address_; } -export function getEthersProviderFromURL( strURL: string ) : any { - const url = new URL( strURL ); +export function getEthersProviderFromURL( strURL: URL|string ) + :ethersMod.ethers.providers.JsonRpcProvider { + const url = new URL( strURL.toString() ); let userName:string|null = null, userPwd:string|null = null; if( url.username ) { userName = url.username; @@ -697,11 +698,14 @@ export function getEthersProviderFromURL( strURL: string ) : any { if( userPwd ) joConnectionInfo.password = userPwd; } - const ethersProvider = new ethersMod.ethers.providers.JsonRpcProvider( joConnectionInfo ); + const ethersProvider: ethersMod.ethers.providers.JsonRpcProvider = + new ethersMod.ethers.providers.JsonRpcProvider( joConnectionInfo ); return ethersProvider; } -export function ethersProviderToUrl( ethersProvider: any ) : string { +export function ethersProviderToUrl( + ethersProvider: ethersMod.ethers.providers.JsonRpcProvider|null + ) : string { let strURL: string|null = null; if( ethersProvider && "connection" in ethersProvider && typeof ethersProvider.connection == "object" && From 7901d98b9153d4794f6b299338528394ee625e7f Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 11:03:11 +0000 Subject: [PATCH 14/53] IMA/TypeScript support improvements, linting added, GA improved --- .github/workflows/comprehensive.yml | 5 + .github/workflows/container-test.yml | 5 + .github/workflows/main.yml | 5 + Dockerfile | 2 + src/{.eslintrc.js => .eslintrc.cjs} | 45 ++-- src/bls.ts | 192 +++++++++-------- src/cc.ts | 214 +++++++++---------- src/cli.ts | 24 ++- src/clpTools.ts | 19 +- src/discoveryTools.ts | 49 ++--- src/eventDispatcher.ts | 10 +- src/imaCore.ts | 52 ++--- src/imaEthOperations.ts | 2 +- src/imaEventLogScan.ts | 2 +- src/imaGasUsageOperations.ts | 4 +- src/imaHelperAPIs.ts | 32 +-- src/imaOracleOperations.ts | 13 +- src/imaRegistrationOperations.ts | 2 +- src/imaSgxExternalSigner.ts | 6 +- src/imaTokenOperations.ts | 22 +- src/imaTransferErrorHandling.ts | 14 +- src/imaTx.ts | 47 ++-- src/log.ts | 307 ++++++++++++++------------- src/loop.ts | 17 +- src/loopWorker.ts | 16 +- src/main.ts | 46 ++-- src/observer.ts | 10 +- src/oracle.ts | 6 +- src/owaspUtils.ts | 167 +++++++-------- src/package.json | 8 +- src/pwa.ts | 24 ++- src/rpcCall.ts | 68 +++--- src/socket.ts | 238 +++++++++++---------- src/socketServer.ts | 14 +- src/socketSettings.ts | 2 +- src/socketUtils.ts | 72 +++---- src/state.ts | 2 +- src/threadInfo.ts | 12 +- src/tsconfig.json | 7 - src/utils.ts | 66 +++--- src/yarn.lock | 216 ++++++++++++++++++- test/agent/agent_environment.py | 1 + 42 files changed, 1174 insertions(+), 891 deletions(-) rename src/{.eslintrc.js => .eslintrc.cjs} (65%) diff --git a/.github/workflows/comprehensive.yml b/.github/workflows/comprehensive.yml index 000e7ff3..8eac844b 100644 --- a/.github/workflows/comprehensive.yml +++ b/.github/workflows/comprehensive.yml @@ -207,6 +207,11 @@ jobs: run: | yarn install + - name: INIT - build IMA + working-directory: ${{env.working-directory}} + run: | + yarn rebuild + - name: INIT - initialize comprehensive test tokens working-directory: ${{env.working-directory}} run: | diff --git a/.github/workflows/container-test.yml b/.github/workflows/container-test.yml index 241fa521..4e7645db 100644 --- a/.github/workflows/container-test.yml +++ b/.github/workflows/container-test.yml @@ -216,6 +216,11 @@ jobs: run: | yarn install + - name: INIT - build IMA + working-directory: ${{env.working-directory}} + run: | + yarn rebuild + - name: INIT - initialize comprehensive test tokens working-directory: ${{env.working-directory}} run: | diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c7e3419e..eaca4402 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -239,6 +239,11 @@ jobs: run: | yarn install + - name: INIT - build IMA + working-directory: ./src + run: | + yarn rebuild + - name: Compile contracts working-directory: ./IMA/proxy run: | diff --git a/Dockerfile b/Dockerfile index 786c5783..1ece5042 100644 --- a/Dockerfile +++ b/Dockerfile @@ -38,6 +38,7 @@ RUN which python3 RUN mkdir /ima WORKDIR /ima + COPY package.json package.json COPY runner runner @@ -66,5 +67,6 @@ RUN node-gyp --version WORKDIR /ima RUN yarn install +RUN yarn rebuild CMD ["bash", "/ima/runner/run.sh"] diff --git a/src/.eslintrc.js b/src/.eslintrc.cjs similarity index 65% rename from src/.eslintrc.js rename to src/.eslintrc.cjs index 96a46d44..16d14b2a 100644 --- a/src/.eslintrc.js +++ b/src/.eslintrc.cjs @@ -1,9 +1,10 @@ module.exports = { "env": { - "browser": false, - "es6": true + browser: false, + es2020: true, + node: true }, - "extends": "standard", + extends: "standard-with-typescript", "globals": { "Atomics": "readonly", "SharedArrayBuffer": "readonly" @@ -27,16 +28,7 @@ module.exports = { "comma-dangle": [ "error", "never" ], "comma-style": [ "error", "last" ], "comma-spacing": "off", - "space-before-function-paren": [ "error", "never" ], "space-in-parens": [ "error", "always" ], - "keyword-spacing": [ "error", { - "overrides": { - "if": { "before": false, "after": false }, - "else": { "before": true, "after": true }, - "for": { "before": false, "after": false }, - "while": { "before": false, "after": false } - } - } ], "space-before-blocks": [ "error", "always" ], "array-bracket-spacing": [ "error", "always" ], "object-curly-spacing": [ "error", "always" ], @@ -68,6 +60,33 @@ module.exports = { "object-shorthand": 0, "multiline-ternary": "off", "max-len": [ "error", { "code": 100, "tabWidth": 4 } ], - "max-lines-per-function": [ "error", { "max": 200, "skipBlankLines": false } ] + "max-lines-per-function": [ "error", { "max": 200, "skipBlankLines": false } ], + "@typescript-eslint/indent": [ "error", 4, { "ignoredNodes": [ "SwitchCase" ] } ], + "@typescript-eslint/quotes": [ "error", "double" ], + "semi": "off", + "@typescript-eslint/semi": "off", + "space-before-function-paren": "off", + "@typescript-eslint/space-before-function-paren": "off", + "keyword-spacing": "off", + "@typescript-eslint/keyword-spacing": [ "error", { + "overrides": { + "if": { "before": false, "after": false }, + "else": { "before": true, "after": true }, + "for": { "before": false, "after": false }, + "while": { "before": false, "after": false } + } + } ], + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/no-non-null-asserted-nullish-coalescing": "off", + "@typescript-eslint/prefer-nullish-coalescing": "off", + "@typescript-eslint/strict-boolean-expressions": "off", + "@typescript-eslint/no-dynamic-delete": "off", + "@typescript-eslint/no-this-alias": "off", + "@typescript-eslint/lines-between-class-members": "off", + "handle-callback-err": "off", + "n/handle-callback-err": "off", + "@typescript-eslint/no-floating-promises": "off", + "@typescript-eslint/no-misused-promises": "off", + "@typescript-eslint/prefer-optional-chain": "off" } }; diff --git a/src/bls.ts b/src/bls.ts index 5b4fcd3f..abeb382d 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -39,11 +39,11 @@ import * as utils from "./socketUtils.js"; import * as state from "./state.js"; const anyShellMod: any = shellMod as any; -const shell = anyShellMod[ "default" ]; +const shell = anyShellMod.default const Keccak = sha3Module.Keccak; -function discoverBlsThreshold( joSChainNetworkInfo: any ) : number { +function discoverBlsThreshold( joSChainNetworkInfo: any ): number { const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) @@ -57,7 +57,7 @@ function discoverBlsThreshold( joSChainNetworkInfo: any ) : number { return -1; } -function discoverBlsParticipants( joSChainNetworkInfo: any ) : number { +function discoverBlsParticipants( joSChainNetworkInfo: any ): number { const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) @@ -73,7 +73,7 @@ function discoverBlsParticipants( joSChainNetworkInfo: any ) : number { function checkBlsThresholdAndBlsParticipants( nThreshold: number, nParticipants: number, strOperation: string, details: any - ) : boolean { +): boolean { details = details || log; if( nThreshold <= 0 ) { details.fatal( "Operation {} will fail because discovered BLS threshold {}" + @@ -95,7 +95,7 @@ function checkBlsThresholdAndBlsParticipants( function discoverPublicKeyByIndex( nNodeIndex: number, joSChainNetworkInfo: any, details: any, isThrowException: boolean - ) : any { +): any { details = details || log; const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; @@ -119,7 +119,7 @@ function discoverPublicKeyByIndex( } function discoverCommonPublicKey( - details: any, joSChainNetworkInfo: any, isThrowException: boolean ) : any { + details: any, joSChainNetworkInfo: any, isThrowException: boolean ): any { const imaState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; const jarrNodes = joSChainNetworkInfo.network; @@ -143,7 +143,7 @@ function discoverCommonPublicKey( function hexPrepare( strHex: string, isInvertBefore: boolean, isInvertAfter: boolean - ) : Uint8Array { +): Uint8Array { if( isInvertBefore == undefined ) isInvertBefore = true; if( isInvertAfter == undefined ) @@ -157,12 +157,12 @@ function hexPrepare( return arrBytes; } -function stringToKeccak256( s: string ) : Uint8Array { +function stringToKeccak256( s: string ): Uint8Array { const strU256 = owaspUtils.ethersMod.ethers.utils.id( s ); return hexPrepare( strU256, true, true ); } -function arrayToKeccak256( arrBytes: Uint8Array ) : Uint8Array { +function arrayToKeccak256( arrBytes: Uint8Array ): Uint8Array { const k = new Keccak( 256 ); k.update( imaUtils.toBuffer( arrBytes ) ); const h = k.digest( "hex" ); @@ -171,7 +171,7 @@ function arrayToKeccak256( arrBytes: Uint8Array ) : Uint8Array { function keccak256Message( jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string - ) : string { +): string { let arrBytes = stringToKeccak256( strFromChainName ); arrBytes = imaUtils.bytesConcat( arrBytes, @@ -201,7 +201,7 @@ function keccak256Message( return owaspUtils.ensureStartsWith0x( imaUtils.bytesToHex( arrBytes, false ) ); } -export function keccak256U256( u256: any, isHash: boolean ) : string { +export function keccak256U256( u256: any, isHash: boolean ): string { let arrBytes = new Uint8Array(); let bytesU256 = imaUtils.hexToBytes( u256 ); @@ -222,7 +222,7 @@ export function keccak256U256( u256: any, isHash: boolean ) : string { export function keccak256ForPendingWorkAnalysis( nNodeNumber: number, strLoopWorkType: string, isStart: boolean, ts: any - ) : string { +): string { let arrBytes = new Uint8Array(); let bytesU256 = imaUtils.hexToBytes( nNodeNumber ); @@ -251,30 +251,30 @@ export function keccak256ForPendingWorkAnalysis( return strMessageHash; } -function splitSignatureShare( signatureShare: any ) : any { +function splitSignatureShare( signatureShare: any ): any { const jarr = signatureShare.split( ":" ); if( jarr.length < 2 ) throw new Error( `Failed to split signatureShare=${signatureShare.toString()}` ); return { X: jarr[0], Y: jarr[1] }; } -function getBlsGlueTmpDir() : string { +function getBlsGlueTmpDir(): string { const strTmpDir = "/tmp/ima-bls-glue"; shell.mkdir( "-p", strTmpDir ); return strTmpDir; } -function allocBlsTmpActionDir() : string { +function allocBlsTmpActionDir(): string { const strActionDir = getBlsGlueTmpDir() + "/" + imaUtils.replaceAll( imaUtils.uuid(), "-", "" ); if( ! fs.existsSync( strActionDir ) ) - fs.mkdirSync( strActionDir , { recursive: true } ); + fs.mkdirSync( strActionDir, { recursive: true } ); return strActionDir; } function performBlsGlue( details: any, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, arrSignResults: any[] - ) : any { +): any { const imaState = state.get(); const strLogPrefix = `${strDirection}/BLS/Glue: `; let joGlueResult: any = null; @@ -294,8 +294,8 @@ function performBlsGlue( strLogPrefix, "performBlsGlue", strActionDir, arrSignResults.length ); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; - let strOutput = ""; + } + const strOutput = "" try { let strInput = ""; const cnt = arrSignResults.length; @@ -363,7 +363,7 @@ function performBlsGlue( return joGlueResult; } -function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ) : any { +function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ): any { const imaState = state.get(); const strLogPrefix = "BLS/Glue: "; let joGlueResult: any = null; @@ -382,7 +382,7 @@ function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ) : strLogPrefix, strActionDir, arrSignResults.length ); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; + } let strOutput = ""; try { let strInput = ""; @@ -421,7 +421,8 @@ function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ) : " --n " + nParticipants; details.trace( "{p}Will execute HashG1 command: {}", strLogPrefix, strHasG1Command ); strOutput = - childProcessModule.execSync( strHasG1Command, { cwd: strActionDir } ).toString( "utf8" ); + childProcessModule.execSync( strHasG1Command, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}HashG1 output is:\n{raw}", strLogPrefix, strOutput || "<>" ); const joResultHashG1 = imaUtils.jsonFileLoad( path.join( strActionDir, "g1.json" ) ); details.trace( "{p}HashG1 result is: {}", strLogPrefix, joResultHashG1 ); @@ -458,7 +459,7 @@ function performBlsVerifyI( joResultFromNode: any, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, joPublicKey: any -) : boolean { +): boolean { if( !joResultFromNode ) return true; const imaState = state.get(); @@ -471,7 +472,7 @@ function performBlsVerifyI( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; + } let strOutput = ""; try { details.trace( "{p}BLS node #{} - first message nonce is {}", @@ -498,12 +499,13 @@ function performBlsVerifyI( " --t " + nThreshold + " --n " + nParticipants + " --j " + nZeroBasedNodeIndex + - " --input " + strSignResultFileName - ; + " --input " + strSignResultFileName; + details.trace( "{p}Will execute node #{} BLS verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -521,7 +523,7 @@ function performBlsVerifyI( function performBlsVerifyIU256( details: any, nZeroBasedNodeIndex: number, joResultFromNode: any, u256: any, joPublicKey: any -) : boolean { +): boolean { if( ! joResultFromNode ) return true; const imaState = state.get(); @@ -534,7 +536,7 @@ function performBlsVerifyIU256( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; + } let strOutput = ""; try { const joMsg: any = { "message": keccak256U256( u256, true ) }; @@ -551,12 +553,13 @@ function performBlsVerifyIU256( " --t " + nThreshold + " --n " + nParticipants + " --j " + nZeroBasedNodeIndex + - " --input " + strSignResultFileName - ; + " --input " + strSignResultFileName; + details.trace( "{p}Will execute node #{} BLS u256 verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS u256 node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS u256 node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -576,7 +579,7 @@ function performBlsVerify( details: any, strDirection: string, joGlueResult: any, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, joCommonPublicKey: any -) : boolean { +): boolean { if( !joGlueResult ) return true; const imaState = state.get(); @@ -588,7 +591,7 @@ function performBlsVerify( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; + } let strOutput = ""; const strLogPrefix = `${strDirection}/BLS/Summary: "`; try { @@ -622,12 +625,13 @@ function performBlsVerify( imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + - " --input " + "./glue-result.json" - ; + " --input " + "./glue-result.json"; + details.trace( "{p}Will execute BLS/summary verify command: {}", strLogPrefix, strVerifyCommand ); strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); details.success( "{p}BLS/summary verify success", strLogPrefix ); @@ -644,7 +648,7 @@ function performBlsVerify( function performBlsVerifyU256( details: any, joGlueResult: any, u256: any, joCommonPublicKey: any - ) : boolean { +): boolean { if( !joGlueResult ) return true; const imaState = state.get(); @@ -656,7 +660,7 @@ function performBlsVerifyU256( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; + } let strOutput = ""; const strLogPrefix = "BLS u256/Summary: "; try { @@ -680,12 +684,13 @@ function performBlsVerifyU256( imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + - " --input " + "./glue-result.json" - ; + " --input " + "./glue-result.json"; + details.trace( "{p}Will execute BLS u256/summary verify command: {}", strLogPrefix, strVerifyCommand ); strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS u256/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); details.success( "{p}BLS u256/summary verify success", strLogPrefix ); @@ -706,7 +711,7 @@ async function checkCorrectnessOfMessagesToSign( jarrMessages: any[], nIdxCurrentMsgBlockStart: number, joExtraSignOpts: any ) { const imaState = state.get(); - let joMessageProxy: owaspUtils.ethersMod.ethers.Contract|null = null; + let joMessageProxy: owaspUtils.ethersMod.ethers.Contract | null = null; let joAccount: any = null, joChainName: any = null; if( strDirection == "M2S" ) { joMessageProxy = imaState.joMessageProxyMainNet; @@ -719,7 +724,7 @@ async function checkCorrectnessOfMessagesToSign( } else if( strDirection == "S2S" ) { joAccount = imaState.chainProperties.sc.joAccount; joChainName = joExtraSignOpts.chainNameDst; - const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider|null = + const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = ( "ethersProviderSrc" in joExtraSignOpts && joExtraSignOpts.ethersProviderSrc ) ? joExtraSignOpts.ethersProviderSrc : null; if( ! ethersProvider ) { @@ -896,7 +901,7 @@ async function gatherSigningCheckFinish( optsSignOperation: any ) { return false; optsSignOperation.strLogPrefixB = `${optsSignOperation.strDirection} /# ` + `${optsSignOperation.nTransferLoopCounter}/BLS/Summary: `; - let strError: string|null = null, strSuccessfulResultDescription: string|null = null; + let strError: string | null = null, strSuccessfulResultDescription: string | null = null; const joGlueResult = performBlsGlue( optsSignOperation.details, optsSignOperation.strDirection, optsSignOperation.jarrMessages, optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.strFromChainName, @@ -939,7 +944,7 @@ async function gatherSigningCheckFinish( optsSignOperation: any ) { optsSignOperation.jarrMessages, joGlueResult ); optsSignOperation.fn( strError, optsSignOperation.jarrMessages, joGlueResult ) - .catch( function( err: Error|string ) { + .catch( function( err: Error | string ) { optsSignOperation.details.critical( "Problem(2) in BLS sign result handler: {err}", err ); optsSignOperation.errGathering = "Problem(2) in BLS sign " + @@ -956,7 +961,7 @@ async function gatherSigningCheckOverflow( optsSignOperation: any ) { `signature error(2), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, optsSignOperation.jarrMessages - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(3) in BLS sign result handler, not enough successful BLS signature " + @@ -987,7 +992,7 @@ async function gatherSigningStartImpl( optsSignOperation: any ) { `signature error(3), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, optsSignOperation.jarrMessages - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.critical( "Problem(4) in BLS sign result handler, not enough successful BLS signature " + @@ -1013,7 +1018,7 @@ async function gatherSigningFinishImpl( optsSignOperation: any ) { `${JSON.stringify( optsSignOperation.joGatheringTracker )} , ` + `error is: ${optsSignOperation.errGathering.toString()}`, optsSignOperation.jarrMessages - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(5) in BLS sign result handler, not enough successful BLS " + @@ -1035,7 +1040,7 @@ async function gatherSigningFinishImpl( optsSignOperation: any ) { `Failed to gather BLS signatures in ${optsSignOperation.jarrNodes.length} node(s), ` + `tracker data is: ${JSON.stringify( optsSignOperation.joGatheringTracker )}`, optsSignOperation.jarrMessages - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(6) in BLS sign result handler, not enough successful BLS signature " + @@ -1114,7 +1119,7 @@ async function doSignProcessHandleCall( owaspUtils.extractErrorMessage( joOut, "unknown wallet error(1)" ), optsSignOperation.sequenceId ); await joCall.disconnect(); - return; + return } optsSignOperation.details.debug( "{p}Node {} sign result: {}", optsSignOperation.strLogPrefix, joNode.nodeID, joOut.result ? joOut.result : null ); @@ -1137,7 +1142,7 @@ async function doSignProcessHandleCall( optsSignOperation.strLogPrefixA, nZeroBasedNodeIndex, optsSignOperation.nThreshold, optsSignOperation.nCountOfBlsPartsToCollect ); await joCall.disconnect(); - return; + return } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); const joResultFromNode: any = { @@ -1208,17 +1213,18 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { optsSignOperation.sequenceId ); const rpcCallOpts: any = null; let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) - .catch( function( err: Error|string ) { - ++optsSignOperation.joGatheringTracker.nCountReceived; - ++optsSignOperation.joGatheringTracker.nCountErrors; - optsSignOperation.details.error( - "{p}JSON RPC call(doSignProcessOneImpl) to S-Chain node {} failed, RPC call failed, " + - "error is: {err}, sequence ID is {}", optsSignOperation.strLogPrefix, - strNodeDescColorized, err, optsSignOperation.sequenceId ); - if( joCall ) - joCall.disconnect(); - joCall = null; - } ); + .catch( function( err: Error | string ) { + ++optsSignOperation.joGatheringTracker.nCountReceived; + ++optsSignOperation.joGatheringTracker.nCountErrors; + optsSignOperation.details.error( + "{p}JSON RPC call(doSignProcessOneImpl) to S-Chain node {} failed, " + + "RPC call failed, error is: {err}, sequence ID is {}", + optsSignOperation.strLogPrefix, strNodeDescColorized, + err, optsSignOperation.sequenceId ); + if( joCall ) + joCall.disconnect(); + joCall = null; + } ); if( ! joCall ) return; await doSignConfigureChainAccessParams( optsSignOperation ); @@ -1309,9 +1315,10 @@ async function doSignMessagesImpl( "successfully gathered count is reached ", optsSignOperation.strLogPrefix, log.generateTimestampString( null, true ), "skale_imaVerifyAndSign", strFromChainName, i, cntSuccess ); - break; + break } - doSignProcessOneImpl( i, optsSignOperation ); + doSignProcessOneImpl( i, optsSignOperation ) + .then( function() {} ).catch( function() {} ); } await gatherSigningStartImpl( optsSignOperation ); await gatherSigningFinishImpl( optsSignOperation ); @@ -1324,7 +1331,7 @@ async function doSignMessagesImpl( optsSignOperation.bHaveResultReportCalled = true; await optsSignOperation.fn( "Failed BLS sign due to exception: " + `${owaspUtils.extractErrorMessage( err )}`, optsSignOperation.jarrMessages - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { log.critical( "Failed BLS sign due to error-reporting callback exception: {err}", err ); if( optsSignOperation.details ) { @@ -1350,37 +1357,37 @@ export async function doSignMessagesM2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, joExtraSignOpts: any, fn: any ) { - return await doSignMessagesImpl( + await doSignMessagesImpl( nTransferLoopCounter, "M2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn ); + joExtraSignOpts, fn ) } export async function doSignMessagesS2M( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, joExtraSignOpts: any, fn: any ) { - return await doSignMessagesImpl( + await doSignMessagesImpl( nTransferLoopCounter, "S2M", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn ); + joExtraSignOpts, fn ) } export async function doSignMessagesS2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, joExtraSignOpts: any, fn: any ) { - return await doSignMessagesImpl( + await doSignMessagesImpl( nTransferLoopCounter, "S2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn ); + joExtraSignOpts, fn ) } async function prepareSignU256( optsSignU256: any ) { optsSignU256.details.debug( "{p}Will sign {} value...", optsSignU256.strLogPrefix, optsSignU256.u256 ); optsSignU256.details.trace( "{p}Will query to sign {} skaled node(s)...", - optsSignU256.strLogPrefix,optsSignU256.jarrNodes.length ); + optsSignU256.strLogPrefix, optsSignU256.jarrNodes.length ); optsSignU256.nThreshold = discoverBlsThreshold( optsSignU256.imaState.joSChainNetworkInfo ); optsSignU256.nParticipants = discoverBlsParticipants( optsSignU256.imaState.joSChainNetworkInfo ); @@ -1430,7 +1437,7 @@ async function doSignU256OneImplHandleCallResult( optsSignU256.details.error( "{p}S-Chain node {} reported wallet error: {err}", optsSignU256.strLogPrefix, strNodeDescColorized, strErrorMessage ); await joCall.disconnect(); - return; + return } optsSignU256.details.trace( "{p}Node {} sign result: ", optsSignU256.strLogPrefix, joNode.nodeID, joOut.result ? joOut.result : null ); @@ -1451,7 +1458,7 @@ async function doSignU256OneImplHandleCallResult( "number of BLS signature parts already gathered", strLogPrefixA, nZeroBasedNodeIndex, optsSignU256.nThreshold, optsSignU256.nCountOfBlsPartsToCollect ); - return; + return } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); const joResultFromNode: any = { @@ -1557,7 +1564,7 @@ async function gatherSigningCheckFinish256( optsSignU256: any ) { if( cntSuccess < optsSignU256.nCountOfBlsPartsToCollect ) return false; const strLogPrefixB = "BLS u256/Summary: "; - let strError = null, strSuccessfulResultDescription = null; + const strError = null; const joGlueResult = performBlsGlueU256( optsSignU256.details, optsSignU256.u256, optsSignU256.arrSignResults ); if( joGlueResult ) { @@ -1593,12 +1600,12 @@ async function gatherSigningCheckFinish256( optsSignU256: any ) { "glue result is {}", strError ? ( " with error " + log.fmtError( "{err}", strError ) ) : "", optsSignU256.u256, joGlueResult ); optsSignU256.fn( strError, optsSignU256.u256, joGlueResult ) - .catch( function( err: Error|string ) { - optsSignU256.details.critical( - "Problem(2) in BLS u256 sign result handler: {err}", err ); - optsSignU256.errGathering = "Problem(2) in BLS u256 sign result " + + .catch( function( err: Error | string ) { + optsSignU256.details.critical( + "Problem(2) in BLS u256 sign result handler: {err}", err ); + optsSignU256.errGathering = "Problem(2) in BLS u256 sign result " + `handler: ${owaspUtils.extractErrorMessage( err )}`; - } ); + } ); return true; } @@ -1609,7 +1616,7 @@ async function gatherSigningCheckOverflow256( optsSignU256: any ) { "signature error(2, u256), got " + `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.critical( "Problem(3) in BLS u256 sign result handler, not enough successful BLS " + @@ -1640,7 +1647,7 @@ async function doSignU256Gathering( optsSignU256: any ) { `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.error( "Problem(4) in BLS u256 sign result handler, not enough successful BLS " + @@ -1685,7 +1692,7 @@ export async function doSignU256( u256: any, details: any, fn: any ) { optsSignU256.details.warning( "{p}BLS u256 signing is unavailable", optsSignU256.strLogPrefix ); await optsSignU256.fn( "BLS u256 signing is unavailable", optsSignU256.u256 ); - return; + return } if( ! ( await prepareSignU256( optsSignU256 ) ) ) return; @@ -1696,7 +1703,7 @@ export async function doSignU256( u256: any, details: any, fn: any ) { if( optsSignU256.errGathering ) { optsSignU256.details.error( "Failed BLS u256 sign result awaiting: {err}", optsSignU256.errGathering.toString() ); - return; + return } optsSignU256.details.information( "{p}Completed signing u256 procedure", optsSignU256.strLogPrefix ); @@ -1727,7 +1734,7 @@ export async function doVerifyReadyHash( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - }; + } let strOutput = ""; try { const joPublicKey = discoverPublicKeyByIndex( @@ -1751,12 +1758,13 @@ export async function doVerifyReadyHash( " --t " + nThreshold + " --n " + nParticipants + " --j " + nZeroBasedNodeIndex + - " --input " + strSignResultFileName - ; + " --input " + strSignResultFileName; + details.trace( "{p}Will execute node #{} BLS verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ).toString( "utf8" ); + childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -1950,13 +1958,13 @@ async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) "try again later" ); } - let joSChainSrc: any = null, strUrlSrcSChain: string|null = null; + let joSChainSrc: any = null, strUrlSrcSChain: string | null = null; for( let idxSChain = 0; idxSChain < arrSChainsCached.length; ++ idxSChain ) { const joSChain = arrSChainsCached[idxSChain]; if( joSChain.name.toString() == strSChainNameSrc.toString() ) { joSChainSrc = joSChain; strUrlSrcSChain = skaleObserver.pickRandomSChainUrl( joSChain ); - break; + break } } if( joSChainSrc == null || strUrlSrcSChain == null || strUrlSrcSChain.length == 0 ) { @@ -2104,7 +2112,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { } catch ( err ) { optsHandleVerifyAndSign.details.error( "{p}{bright}JSON RPC call(handleSkaleImaVerifyAndSign) " + - "to SGX failed, RPC call failed, error is: {err}" , + "to SGX failed, RPC call failed, error is: {err}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.strDirection, err ); if( joCall ) await joCall.disconnect(); diff --git a/src/cc.ts b/src/cc.ts index 46cddc95..3e76ad78 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -25,28 +25,28 @@ let gFlagIsEnabled: boolean = false; -export function autoEnableFromCommandLineArgs() : void { +export function autoEnableFromCommandLineArgs(): void { const b: boolean = - ( process.argv.indexOf( "--colors" ) >= 0 || process.argv.indexOf( "-colors" ) >= 0 ) + ( process.argv.includes( "--colors" ) || process.argv.includes( "-colors" ) ) ? true : false; enable( b ); } -export function enable( b?: boolean ) : void { +export function enable( b?: boolean ): void { gFlagIsEnabled = !!b; } -export function isStringAlreadyColorized( s?: any ) : boolean { +export function isStringAlreadyColorized( s?: any ): boolean { if( s && typeof s == "string" && s.length > 0 && s[0] == "\x1b" ) return true; return false; } -export function isEnabled() : boolean { +export function isEnabled(): boolean { return !!gFlagIsEnabled; } -export function replaceAll( str: string, find: string, replace: string ) : string { +export function replaceAll( str: string, find: string, replace: string ): string { return str.replace( new RegExp( find, "g" ), replace ); } @@ -60,7 +60,7 @@ export function validateRadix( value?: any, radix?: any ) { return radix; } -export function validateInteger( value?: any, radix?: any ) : boolean { +export function validateInteger( value?: any, radix?: any ): boolean { try { value = "" + value; value = value.trim(); @@ -77,7 +77,7 @@ export function validateInteger( value?: any, radix?: any ) : boolean { return false; } -export function toInteger( value?: any, radix?: any ) : number { +export function toInteger( value?: any, radix?: any ): number { try { radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) @@ -88,7 +88,7 @@ export function toInteger( value?: any, radix?: any ) : number { return 0; } -export function validateFloat( value?: any ) : boolean { +export function validateFloat( value?: any ): boolean { try { const f = parseFloat( value ); if( isNaN( f ) ) @@ -99,7 +99,7 @@ export function validateFloat( value?: any ) : boolean { return false; } -function toFloat( value?: any ) : number { +function toFloat( value?: any ): number { try { const f = parseFloat( value ); return f; @@ -108,7 +108,7 @@ function toFloat( value?: any ) : number { return 0.0; } -export function toBoolean( value?: any ) : boolean { +export function toBoolean( value?: any ): boolean { let b = false; try { if( typeof value === "boolean" ) @@ -131,19 +131,19 @@ export function toBoolean( value?: any ) : boolean { return b; } -export function yn( flag?: any ) : string { +export function yn( flag?: any ): string { if( !gFlagIsEnabled ) return flag ? "true" : "false"; return toBoolean( flag ) ? yes( "yes" ) : no( "no" ); } -export function tf( flag?: any ) : string { +export function tf( flag?: any ): string { if( !gFlagIsEnabled ) return flag ? "true" : "false"; return toBoolean( flag ) ? yes( "true" ) : no( "false" ); } -export function onOff( flag?: any ) : string { +export function onOff( flag?: any ): string { if( !gFlagIsEnabled ) return flag ? "true" : "false"; return toBoolean( flag ) ? yes( "on" ) : no( "off" ); @@ -196,7 +196,7 @@ export function rainbowPart( s: string, i: number ) { return gArrRainbowParts[j] + s + gMapColorDefinitions.reset; } -export function rainbow( s?: any ) : string { +export function rainbow( s?: any ): string { if( ( !gFlagIsEnabled ) || ( !s ) || ( typeof s != "string" ) || s.length == 0 ) return s ? s.toString() : JSON.stringify( s ); let res = ""; @@ -206,7 +206,7 @@ export function rainbow( s?: any ) : string { return res; } -export function isInt2( n?: any ) : boolean { +export function isInt2( n?: any ): boolean { const intRegex = /^-?\d+$/; if( !intRegex.test( n ) ) return false; @@ -215,12 +215,12 @@ export function isInt2( n?: any ) : boolean { return parseFloat( n ) == intVal && !isNaN( intVal ); } -export function isFloat2( n?: any ) : boolean { +export function isFloat2( n?: any ): boolean { const val = parseFloat( n ); return !isNaN( val ); } -function urlObjColorized( objURL?: any ) : string { +function urlObjColorized( objURL?: any ): string { let strURL = ""; if( !objURL ) return strURL; @@ -244,24 +244,24 @@ function urlObjColorized( objURL?: any ) : string { return strURL; } -export function urlStrColorized( s?: any ) : string { +export function urlStrColorized( s?: any ): string { const objURL = safeURL( s ); if( !objURL ) return ""; return urlObjColorized( objURL ); } -export function urlColorized( x?: any ) : string { +export function urlColorized( x?: any ): string { if( typeof x === "string" || x instanceof String ) return urlStrColorized( x ); return urlObjColorized( x ); } -export function u( x?: any ) : string { +export function u( x?: any ): string { return urlColorized( x ); } -export function safeURL( arg?: any ) : URL|null { +export function safeURL( arg?: any ): URL | null { try { const sc = arg[0]; if( sc == "\"" || sc == "'" ) { @@ -271,7 +271,7 @@ export function safeURL( arg?: any ) : URL|null { const objURL = safeURL( ss ); if( objURL != null && objURL != undefined ) { const anyURL: any = objURL; - anyURL["strStrippedStringComma"] = sc; + anyURL.strStrippedStringComma = sc; } return objURL; @@ -286,14 +286,14 @@ export function safeURL( arg?: any ) : URL|null { return null; const anyURL: any = objURL; - anyURL["strStrippedStringComma"] = null; + anyURL.strStrippedStringComma = null; return objURL; } catch ( err ) { return null; } } -export function toIpv4Arr( s: string ) : any[]|null { +export function toIpv4Arr( s: string ): any[] | null { // eslint-disable-next-line max-len if( /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test( s ) ) { const arr = s.split( "." ); @@ -305,7 +305,7 @@ export function toIpv4Arr( s: string ) : any[]|null { return null; } -export function logArgToStringAsIpv4( arg?: any ) : string { +export function logArgToStringAsIpv4( arg?: any ): string { const arr = toIpv4Arr( arg ); if( !arr ) return arg.toString(); @@ -319,7 +319,7 @@ export function logArgToStringAsIpv4( arg?: any ) : string { return s; } -export function logArgToString( ...args: any[] ) : string { +export function logArgToString( ...args: any[] ): string { let i; const cnt = arguments.length; let s = ""; @@ -327,39 +327,39 @@ export function logArgToString( ...args: any[] ) : string { const arg = arguments[i]; if( arg === undefined ) { s += "" + undefval( arg ); - continue; + continue } if( arg === null ) { s += "" + nullval( arg ); - continue; + continue } if( isNaN( arg ) ) { s += "" + nanval( arg ); - continue; + continue } if( typeof arg === "boolean" ) { s += "" + tf( arg ); - continue; + continue } if( typeof arg === "object" && typeof arg.valueOf() === "boolean" ) s += "" + tf( arg.valueOf() ); if( typeof arg === "number" || typeof arg === "bigint" ) { s += "" + number( arg ); - continue; + continue } if( typeof arg === "object" && ( typeof arg.valueOf() === "number" || typeof arg.valueOf() === "bigint" ) ) { s += "" + number( arg.valueOf() ); - continue; + continue } if( typeof arg === "string" || arg instanceof String ) { const objURL = safeURL( arg ); if( objURL != null && objURL != undefined ) { let strURL = ""; const anyURL: any = objURL; - if( anyURL["strStrippedStringComma"] ) - strURL += normal( anyURL["strStrippedStringComma"] ); + if( anyURL.strStrippedStringComma ) + strURL += normal( anyURL.strStrippedStringComma ); if( objURL.protocol ) strURL += "" + yellow( objURL.protocol ) + normal( "//" ); @@ -383,55 +383,55 @@ export function logArgToString( ...args: any[] ) : string { if( objURL.search ) strURL += "" + magenta( objURL.search ); - if( anyURL["strStrippedStringComma"] ) - strURL += normal( anyURL["strStrippedStringComma"] ); + if( anyURL.strStrippedStringComma ) + strURL += normal( anyURL.strStrippedStringComma ); s += strURL; - continue; + continue } if( ( arg.length > 1 && arg[0] == "-" && arg[1] != "-" ) || ( arg.length > 2 && arg[0] == "-" && arg[1] == "-" && arg[2] != "-" ) ) { s += "" + cla( arg ); - continue; + continue } if( arg.length > 0 && ( arg[0] == "\"" || arg[0] == "'" ) ) { s += "" + strval( arg ); - continue; + continue } if( isFloat2( arg ) ) { s += "" + real( arg ); - continue; + continue } if( isInt2( arg ) ) { s += "" + number( arg ); - continue; + continue } } if( Array.isArray( arg ) || typeof arg === "object" ) { s += jsonColorizer.prettyPrintConsole( arg ); - continue; + continue } s += "" + kk( arg ); } return s; } -export const getCircularReplacerForJsonStringify = () : any => { +export const getCircularReplacerForJsonStringify = (): any => { const seen = new WeakSet(); - return ( key: any, value: any ) : any => { + return ( key: any, value: any ): any => { if( typeof value === "object" && value !== null ) { if( seen.has( value ) ) return; seen.add( value ); } return value; - }; -}; + } +} export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ cntCensoredMax: 30000, // zero to disable censoring - censor: ( censor: any ) : any => { + censor: ( censor: any ): any => { let i = 0; return ( key: any, value: any ) => { if( i !== 0 && typeof ( censor ) === "object" && @@ -442,11 +442,11 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ if( i >= jsonColorizer.cntCensoredMax ) return "[Unknown]"; - ++i; // so we know we aren't using the original object anymore + ++i // so we know we aren't using the original object anymore return value; - }; + } }, - replacerHTML: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ) : any => { + replacerHTML: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ): any => { const key = ""; const val = ""; const str = ""; @@ -471,7 +471,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ .replace( jsonLine, jsonColorizer.replacerHTML ); return s; }, - replacerConsole: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ) : any => { + replacerConsole: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ): any => { let r = pIndent || ""; if( pKey ) r = r + logArgToString( pKey.replace( /[": ]/g, "" ) ) + ": "; @@ -481,7 +481,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ return r + ( pEnd || "" ); }, - prettyPrintConsole: ( obj?: any ) : any => { + prettyPrintConsole: ( obj?: any ): any => { if( !gFlagIsEnabled ) { if( obj === null ) return "null"; @@ -526,11 +526,11 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ // see: // http://jsfiddle.net/KJQ9K/554 // https://qastack.ru/programming/4810841/pretty-print-json-using-javascript -export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ) : string { +export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ): string { strKeyNamePrefix = strKeyNamePrefix || ""; jo = jo.replace( /&/g, "&" ).replace( //g, ">" ); return jo.replace( - // eslint-disable-next-line max-len + // eslint-disable-next-line max-len /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, function( match: any ) { if( ! gFlagIsEnabled ) @@ -550,9 +550,9 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ) : str else if( /undefined/.test( match ) ) cls = "undefined"; else if( ( typeof match === "string" || match instanceof String ) && - match.length >= 2 && - ( ( match[0] == "\"" && match[match.length - 1] == "\"" ) || - ( match[0] == "'" && match[match.length - 1] == "'" ) ) + match.length >= 2 && + ( ( match[0] == "\"" && match[match.length - 1] == "\"" ) || + ( match[0] == "'" && match[match.length - 1] == "'" ) ) ) cls = "string"; switch ( cls ) { @@ -576,7 +576,7 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ) : str } ); } -export function safeStringifyJSON( jo?: any, n?: number ) : string|undefined { +export function safeStringifyJSON( jo?: any, n?: number ): string | undefined { try { const s = "" + JSON.stringify( jo, getCircularReplacerForJsonStringify(), n ); return s; @@ -585,11 +585,11 @@ export function safeStringifyJSON( jo?: any, n?: number ) : string|undefined { return undefined; } -export function jn( x?: any ) : string { +export function jn( x?: any ): string { return "" + jsonColorizer.prettyPrintConsole( x ); } -export function j1( x?: any, n?: number, strKeyNamePrefix?: string ) : string { +export function j1( x?: any, n?: number, strKeyNamePrefix?: string ): string { let isDefaultKeyNamePrefix = false; if( typeof strKeyNamePrefix !== "string" ) { strKeyNamePrefix = " "; @@ -604,7 +604,7 @@ export function j1( x?: any, n?: number, strKeyNamePrefix?: string ) : string { return s; } -export function j( x?: any ) : string { +export function j( x?: any ): string { return j1( x ); // jn } @@ -657,204 +657,204 @@ export { bBgWhite }; -export function normal( s?: any ) : string { +export function normal( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + s + reset; } -export function trace( s?: any ) : string { +export function trace( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + s + reset; } -export function debug( s?: any ) : string { +export function debug( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + s + reset; } -export function debugDark( s?: any ) : string { +export function debugDark( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgBlack + enlight + s + reset; } -export function note( s?: any ) : string { +export function note( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + s + reset; } -export function notice( s?: any ) : string { +export function notice( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function info( s?: any ) : string { +export function info( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + enlight + s + reset; } -export function warning( s?: any ) : string { +export function warning( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function warn( s?: any ) : string { +export function warn( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function error( s?: any ) : string { +export function error( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgRed + s + reset; } -export function fatal( s?: any ) : string { +export function fatal( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + bgRed + fgYellow + enlight + s + reset; } -export function success( s?: any ) : string { +export function success( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function attention( s?: any ) : string { +export function attention( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgCyan + s + reset; } -export function bright( s?: any ) : string { +export function bright( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgWhite + enlight + s + reset; } -export function sunny( s?: any ) : string { +export function sunny( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + enlight + s + reset; } -export function rx( s?: any ) : string { +export function rx( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function rxa( s?: any ) : string { +export function rxa( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + enlight + s + reset; } -export function tx( s?: any ) : string { +export function tx( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + s + reset; } -export function txa( s?: any ) : string { +export function txa( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function date( s?: any ) : string { +export function date( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function time( s?: any ) : string { +export function time( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + enlight + s + reset; } -export function frac_time( s?: any ) : string { +export function fracTime( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function yes( s?: any ) : string { +export function yes( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function no( s?: any ) : string { +export function no( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgRed + s + reset; } -export function number( s?: any ) : string { +export function number( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + enlight + s + reset; } -export function real( s?: any ) : string { +export function real( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function undefval( s?: any ) : string { +export function undefval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function nullval( s?: any ) : string { +export function nullval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function nanval( s?: any ) : string { +export function nanval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgGreen + enlight + s + reset; } -export function yellow( s?: any ) : string { +export function yellow( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; } -export function magenta( s?: any ) : string { +export function magenta( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgMagenta + s + reset; } -export function cla( s?: any ) : string { +export function cla( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgBlue + dim + s + reset; } -export function kk( s?: any ) : string { +export function kk( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + enlight + s + reset; } -export function strval( s?: any ) : string { +export function strval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); return "" + fgYellow + s + reset; @@ -867,19 +867,19 @@ export function n2s( n: any, sz: number ) { return s; } -export function timestampHR() : number { +export function timestampHR(): number { const d = new Date(); const ts = Math.floor( ( d ).getTime() ); return ts; } -export function timestampUnix() : number { +export function timestampUnix(): number { const d = new Date(); const ts = Math.floor( ( d ).getTime() / 1000 ); return ts; } -function trimLeftUnneededTimestampZeros( s?: any ) : string { +function trimLeftUnneededTimestampZeros( s?: any ): string { while( s.length >= 2 ) { if( s[0] == "0" && s[1] >= "0" && s[1] <= "9" ) s = s.substring( 1 ); @@ -889,7 +889,7 @@ function trimLeftUnneededTimestampZeros( s?: any ) : string { return s; } -export function getDurationString( tsFrom : number, tsTo : number ) : string { +export function getDurationString( tsFrom: number, tsTo: number ): string { let s = ""; let n = tsTo - tsFrom; @@ -922,7 +922,7 @@ export function getDurationString( tsFrom : number, tsTo : number ) : string { return "" + n + " " + ( ( n > 1 ) ? "days" : "day" ) + "," + s; } -export function capitalizeFirstLetter( s?: any ) : string { +export function capitalizeFirstLetter( s?: any ): string { if( ! s ) return JSON.stringify( s ); let s2 = s.toString(); @@ -932,7 +932,7 @@ export function capitalizeFirstLetter( s?: any ) : string { return s2; } -function errFnDottedName( s?: any ) : string { +function errFnDottedName( s?: any ): string { const arr = s.split( "." ); const cnt = arr.length; let i, s2 = ""; @@ -944,13 +944,13 @@ function errFnDottedName( s?: any ) : string { return s2; } -function errFnName( s?: any ) : string { +function errFnName( s?: any ): string { if( s.indexOf( "async " ) == 0 ) return bright( "async" ) + " " + errFnDottedName( s.substring( 6 ) ); return errFnDottedName( s ); } -function errLocLn( s: string, isWithBraces?: boolean ) : string { +function errLocLn( s: string, isWithBraces?: boolean ): string { let s2 = ""; s = s.replace( "file://", "" ); s = s.replace( "node:", "" ); @@ -973,11 +973,11 @@ function errLocLn( s: string, isWithBraces?: boolean ) : string { return s2; } -export function stack( err?: any ) : string { +export function stack( err?: any ): string { if( ! err ) return ""; - if( err && "stack" in err ) { - const st = err[ "stack" ]; + if( err && "stack" in err ) { + const st = err.stack if( st && typeof st == "string" ) err = st; } diff --git a/src/cli.ts b/src/cli.ts index f3fe05db..b0502d60 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -36,13 +36,14 @@ import * as imaOracleOperations from "./imaOracleOperations.js"; import * as imaTx from "./imaTx.js"; import * as state from "./state.js"; +// eslint-disable-next-line @typescript-eslint/naming-convention const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); const gStrAppName = "IMA AGENT"; const gStrVersion = imaUtils.fileLoad( path.join( __dirname, "../VERSION" ), "N/A" ).toString().trim(); -function att( ...args: any[] ) : string { return log.fmtAttention( ...args ); }; +function att( ...args: any[] ): string { return log.fmtAttention( ...args ); }; export function printAbout( isLog?: boolean ) { isLog = isLog || false; @@ -213,7 +214,9 @@ function parseHelp( imaState: any, joArg: any ) { // exits process on "--help" if( joArg.name != "help" ) return false; printAbout(); - const strAboutText = imaUtils.fileLoad( path.join( __dirname, "../about.txt" ), "N/A" ).toString(); + const strAboutText = + imaUtils.fileLoad( path.join( __dirname, "../about.txt" ), "N/A" ) + .toString(); console.log( strAboutText ); process.exit( 0 ); } @@ -631,7 +634,7 @@ function parseTransactionArgs( imaState: any, joArg: any ) { return true; } if( joArg.name == "gas-price-multiplier-mn" ) { - let gasPriceMultiplier : number = owaspUtils.toFloat( joArg.value ); + let gasPriceMultiplier: number = owaspUtils.toFloat( joArg.value ); if( gasPriceMultiplier < 0.0 ) gasPriceMultiplier = 0.0; imaState.chainProperties.mn.transactionCustomizer.gasPriceMultiplier = @@ -1279,7 +1282,7 @@ export function parse( joExternalHandlers: any ) { joArg.name == "browse-s-chain" ) { joExternalHandlers[joArg.name](); - continue; + continue } console.log( log.fmtFatal( "COMMAND LINE PARSER ERROR: unknown command line argument {}", joArg.name ) ); @@ -1288,7 +1291,7 @@ export function parse( joExternalHandlers: any ) { return 0; } -async function asyncCheckUrlAtStartup( u: URL|string, name: string ) { +async function asyncCheckUrlAtStartup( u: URL | string, name: string ) { const details = log.createMemoryStream(); const nTimeoutMilliseconds = 10 * 1000; try { @@ -1331,7 +1334,7 @@ function commonInitPrintSysInfo() { log.debug( "This process {sunny} is {}", "architecture", process.arch ); log.debug( "This process {sunny} is {}", "execPath", process.execPath ); log.debug( "This process {sunny} is {}", "platform", process.platform ); - log.debug( "This process {sunny} is {}", "release",process.release ); + log.debug( "This process {sunny} is {}", "release", process.release ); log.debug( "This process {sunny} is {}", "report", process.report ); log.debug( "This process {sunny} is {}", "config", process.config ); log.debug( "Node JS {sunny} is {}", "detailed version information", process.versions ); @@ -1526,11 +1529,12 @@ function commonInitPrintFoundContracts() { // message_proxy_mainnet_address --> message_proxy_mainnet_abi // message_proxy_chain_address --> message_proxy_chain_abi - const oct = function( joContract: owaspUtils.ethersMod.ethers.Contract ) { // optional contract address + const oct = function( + joContract?: owaspUtils.ethersMod.ethers.Contract ) { // optional contract address if( joContract && "address" in joContract && joContract.address ) return log.fmtInformation( "{}", joContract.address ); return log.fmtError( "contract is not available" ); - }; + } if( isPrintGathered ) { log.debug( "IMA contracts(Main Net):" ); @@ -2713,8 +2717,8 @@ function initContractsIMA() { new owaspUtils.ethersMod.ethers.Contract( joABI.deposit_box_erc1155_address, joABI.deposit_box_erc1155_abi, - ep ) - ; // only main net + ep ); + // only main net imaState.joDepositBoxERC721WithMetadata = new owaspUtils.ethersMod.ethers.Contract( joABI.deposit_box_erc721_with_metadata_address, diff --git a/src/clpTools.ts b/src/clpTools.ts index 07d2e97e..748985c0 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -40,7 +40,7 @@ import * as discoveryTools from "./discoveryTools.js"; import * as loop from "./loop.js"; import * as imaUtils from "./utils.js"; import * as imaBLS from "./bls.js"; -import * as imaTx from "./imaTx.js"; +import type * as imaTx from "./imaTx.js"; export async function registerAll( isPrintSummaryRegistrationCosts: boolean ) { if( !await registerStep1( false ) ) @@ -1054,8 +1054,8 @@ export function commandLineTaskPaymentS2S() { : imaState.joTokenManagerERC721 ) : ( imaState.isWithMetadata721 ? imaState.joTokenManagerERC721WithMetadataTarget - : imaState.joTokenManagerERC721Target ) - ; + : imaState.joTokenManagerERC721Target ); + const joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract = isForward ? imaState.joTokenManagerERC1155 : imaState.joTokenManagerERC1155Target; const strChainNameDst = isForward ? tc.strChainName : sc.strChainName; @@ -1090,7 +1090,8 @@ export function commandLineTaskPaymentS2S() { ? strAddrErc721ExplicitTarget : strAddrErc721Explicit; const strAddrErc1155Dst = isForward ? strAddrErc1155ExplicitTarget : strAddrErc1155Explicit; - const tx_customizer: imaTx.TransactionCustomizer = isForward ? sc.transactionCustomizer : tc.transactionCustomizer; + const txCustomizer: imaTx.TransactionCustomizer = + isForward ? sc.transactionCustomizer : tc.transactionCustomizer; if( strCoinNameErc721Src.length > 0 ) { // ERC721 payment log.information( "one S->S single ERC721 payment: {}", imaState.idToken ); @@ -1106,7 +1107,7 @@ export function commandLineTaskPaymentS2S() { strCoinNameErc721Src, joSrcErc721, strAddrErc721Dst, // only reverse payment needs it - tx_customizer + txCustomizer ); } if( strCoinNameErc20Src.length > 0 ) { @@ -1124,7 +1125,7 @@ export function commandLineTaskPaymentS2S() { strCoinNameErc20Src, joSrcErc20, strAddrErc20Dst, // only reverse payment needs it - tx_customizer + txCustomizer ); } if( @@ -1158,7 +1159,7 @@ export function commandLineTaskPaymentS2S() { strCoinNameErc1155Src, joSrcErc1155, strAddrErc1155Dst, // only reverse payment needs it - tx_customizer + txCustomizer ); } if( @@ -1192,7 +1193,7 @@ export function commandLineTaskPaymentS2S() { strCoinNameErc1155Src, joSrcErc1155, strAddrErc1155Dst, - tx_customizer + txCustomizer ); } // ETH payment @@ -1455,7 +1456,7 @@ async function handleBrowseSkaleModesRpcInfoResult( if( ! joNode ) { log.critical( "{p}Discovery node {} is completely unknown and will be skipped", strLogPrefix, i ); - continue; + continue } const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); const rpcCallOpts: any = null; diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index df7d2c2c..4ad5d5f2 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -29,7 +29,7 @@ import * as state from "./state.js"; import * as imaUtils from "./utils.js"; import * as threadInfo from "./threadInfo.js"; -export function formatBalanceInfo( bi: any, strAddress: string ) : string { +export function formatBalanceInfo( bi: any, strAddress: string ): string { let s = ""; s += log.fmtInformation( "{p}", bi.assetName ); if( "assetAddress" in bi && @@ -53,7 +53,7 @@ export function formatBalanceInfo( bi: any, strAddress: string ) : string { return s; } -function getSChainNodesCount( joSChainNetworkInfo: any ) : number { +function getSChainNodesCount( joSChainNetworkInfo: any ): number { try { if( ! joSChainNetworkInfo ) return 0; @@ -65,7 +65,7 @@ function getSChainNodesCount( joSChainNetworkInfo: any ) : number { } } -export function isSChainNodeFullyDiscovered( joNode: any ) : boolean { +export function isSChainNodeFullyDiscovered( joNode: any ): boolean { if( ! joNode ) return false; if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo == "object" && @@ -102,7 +102,7 @@ export function isSChainNodeFullyDiscovered( joNode: any ) : boolean { return false; } -export function getSChainDiscoveredNodesCount( joSChainNetworkInfo: any ) : number { +export function getSChainDiscoveredNodesCount( joSChainNetworkInfo: any ): number { try { if( ! joSChainNetworkInfo ) return 0; @@ -135,7 +135,7 @@ export async function waitUntilSChainStarted() { imaState.chainProperties.sc.strURL.length === 0 ) { log.warning( "Skipped, S-Chain URL was not provided." ); - return; + return } let bSuccess = false; let idxWaitAttempt = 0; @@ -147,7 +147,7 @@ export async function waitUntilSChainStarted() { let isError = false; const joSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, null, nCountToWait - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { log.critical( "S-Chain network discovery attempt failed: {err}", err ); isError = true; } ); @@ -163,14 +163,14 @@ export async function waitUntilSChainStarted() { if( idxWaitAttempt >= imaState.nMaxWaitSChainAttempts ) { log.warning( "Incomplete, S-Chain sanity check failed after {} attempts.", idxWaitAttempt ); - return; + return } await threadInfo.sleep( 1000 ); } log.success( "Done, S-Chain is accessible and sane." ); } -export function isSendImaAgentIndex() : boolean { +export function isSendImaAgentIndex(): boolean { return true; } @@ -178,7 +178,7 @@ let gTimerSChainDiscovery: any = null; let gFlagIsInSChainDiscovery: boolean = false; function composeStillUnknownNodesMessage( - joSChainNetworkInfo: any, cntStillUnknown: number, cntNodesOnChain: number ) : string { + joSChainNetworkInfo: any, cntStillUnknown: number, cntNodesOnChain: number ): string { let strMessage = log.fmtSuccess( ", {} of {} still unknown (", cntStillUnknown, cntNodesOnChain ); try { @@ -205,7 +205,7 @@ function composeStillUnknownNodesMessage( async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boolean, fnAfter: any ) { if( gFlagIsInSChainDiscovery ) { log.information( "Notice: long this S-Chain re-discovery is in progress now..." ); - return; + return } const imaState = state.get(); fnAfter = fnAfter || function() {}; @@ -231,7 +231,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole } // fnAfter() will be called here inside async call at beginning gFlagIsInSChainDiscovery = false; - return; + return } if( cntDiscovered < cntNodesOnChain ) { if( ! isSilentReDiscovery ) { @@ -248,7 +248,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole let isError = false; const joSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { isError = true; log.critical( "S-Chain network re-discovery failed: {err}", err ); } ); @@ -270,11 +270,13 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole imaState.joSChainNetworkInfo = joSChainNetworkInfo; } fnAfter(); - continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, null ); + continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, null ) + .then( function() {} ).catch( function() {} ); ; } catch ( err ) { } gFlagIsInSChainDiscovery = false; // fnAfter() will be called here inside async call at beginning - continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, fnAfter ); + continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, fnAfter ) + .then( function() {} ).catch( function() {} ); ; } export async function continueSChainDiscoveryInBackgroundIfNeeded( @@ -287,7 +289,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( if( ! isSilentReDiscovery ) log.information( "This S-Chain re-discovery will not be preformed" ); fnAfter(); - return; // no S-Chain re-discovery, special mode + return // no S-Chain re-discovery, special mode } const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let nCountToWait = ( cntNodesOnChain > 2 ) @@ -308,7 +310,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( log.notice( "This S-Chain re-discovery stopped" ); } fnAfter(); - return; + return } if( cntDiscovered < cntNodesOnChain ) { if( ! isSilentReDiscovery ) { @@ -325,7 +327,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( function handleDiscoverSkaleImaInfoResult( optsDiscover: any, strNodeDescColorized: string, joNode: any, joCall: any, joIn: any, joOut: any -) : void { +): void { joNode.imaInfo = joOut.result; if( isSChainNodeFullyDiscovered( joNode ) ) ++ optsDiscover.nCountReceivedImaDescriptions; @@ -374,7 +376,7 @@ async function discoverSChainWalkNodes( optsDiscover: any ) { if( isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = optsDiscover.imaState.nNodeNumber; const joOut = await joCall.call( joIn ); - await handleDiscoverSkaleImaInfoResult( + handleDiscoverSkaleImaInfoResult( optsDiscover, strNodeDescColorized, joNode, joCall, joIn, joOut ); } catch ( err ) { if( ! optsDiscover.isSilentReDiscovery ) { @@ -429,7 +431,7 @@ async function discoverSChainWait( optsDiscover: any ) { clearInterval( iv ); if( optsDiscover.fnAfter ) optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); - return; + return } ++ nWaitAttempt; if( nWaitAttempt >= cntWaitAttempts ) { @@ -518,7 +520,7 @@ async function handleDiscoverSkaleNodesRpcInfoResult( if( optsDiscover.fnAfter ) optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); rv = true; - } ).catch( function( err: Error|string ) { + } ).catch( function( err: Error | string ) { if( optsDiscover.fnAfter ) optsDiscover.fnAfter( err, null ); } ); @@ -561,7 +563,7 @@ export async function discoverSChainNetwork( const joOut = await joCall.call( joIn ); await handleDiscoverSkaleNodesRpcInfoResult( optsDiscover, scURL, joCall, joIn, joOut - ).catch( function( err: Error|string ) { + ).catch( function( err: Error | string ) { log.critical( "{p}JSON RPC call(in discoverSChainNetwork) error: {err}, stack is:\n{stack}", optsDiscover.strLogPrefix, err, err ); @@ -617,7 +619,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { if( ! isSilentReDiscovery ) log.success( "Periodic S-Chain re-discovery is not needed right from startup" ); - return; // not needed right from very beginning + return // not needed right from very beginning } const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let periodicDiscoveryInterval = imaState.joSChainDiscovery.periodicDiscoveryInterval; @@ -639,13 +641,12 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( await discoverSChainNetwork( null, isSilentReDiscovery, joPrevSChainNetworkInfo, nCountToWait ); joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; - imaState.joSChainNetworkInfo = imaState.joSChainNetworkInfo; if( checkPeriodicDiscoveryNoLongerNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { if( ! isSilentReDiscovery ) log.information( "Final periodic S-Chain re-discovery done" ); fnAfterRediscover( true ); - return; // not needed anymore, all nodes completely discovered + return // not needed anymore, all nodes completely discovered } if( ! isSilentReDiscovery ) log.information( "Partial periodic S-Chain re-discovery done" ); diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index 56155eac..0b45aada 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -25,14 +25,14 @@ export class UniversalDispatcherEvent { type: any; - constructor( type: any, jo: any ) { + constructor ( type: any, jo: any ) { this.type = type; for( const [ key, value ] of Object.entries( jo ) ) { if( key in this ) { console.warn( "UniversalDispatcherEvent will skip", key, "data field" ); - continue; + continue } - let anyThis: any = this; + const anyThis: any = this anyThis[key] = value; } } @@ -43,7 +43,7 @@ export class EventDispatcher { _listeners: any[]; isDisposing: boolean; isDisposed: boolean; - constructor() { + constructor () { this._listeners = []; this.isDisposed = false; this.isDisposing = false; @@ -80,7 +80,7 @@ export class EventDispatcher { item => item.type === type ); if( index >= 0 ) { this._listeners.splice( index, 1 ); - continue; + continue } break; } diff --git a/src/imaCore.ts b/src/imaCore.ts index 8c5d9b9b..6ea90e04 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -157,7 +157,7 @@ let gTransferLoopCounter = 0; async function doQueryOutgoingMessageCounter( optsTransfer: any ) { let nPossibleIntegerValue = 0; optsTransfer.details.debug( "{p}SRC MessageProxy address is.....{}", - optsTransfer.strLogPrefixShort,optsTransfer.joMessageProxySrc.address ); + optsTransfer.strLogPrefixShort, optsTransfer.joMessageProxySrc.address ); optsTransfer.details.debug( "{p}DST MessageProxy address is.....", optsTransfer.strLogPrefixShort, optsTransfer.joMessageProxyDst.address ); optsTransfer.strActionName = "src-chain.MessageProxy.getOutgoingMessagesCounter()"; @@ -288,7 +288,7 @@ async function analyzeGatheredRecords( optsTransfer: any, r: any ) { "{p}Found event record {} reviewed and accepted for processing, found event " + "values are {}, found block number is {}", optsTransfer.strLogPrefix, i, joValues, joValues.savedBlockNumberForOptimizations ); - break; + break } else { optsTransfer.details.debug( "{p}Found event record {} reviewed and skipped", optsTransfer.strLogPrefix, i ); @@ -381,7 +381,7 @@ async function gatherMessages( optsTransfer: any ) { if( !bSecurityCheckPassed ) { optsTransfer.details.warning( "{p}Block depth check was not passed, canceling " + "search for transfer events", optsTransfer.strLogPrefix ); - break; + break } } if( optsTransfer.nBlockAge > 0 ) { @@ -433,7 +433,7 @@ async function gatherMessages( optsTransfer: any ) { if( !bSecurityCheckPassed ) { optsTransfer.details.warning( "{p}Block age check was not passed, " + "canceling search for transfer events", optsTransfer.strLogPrefix ); - break; + break } } optsTransfer.details.success( @@ -456,7 +456,7 @@ async function gatherMessages( optsTransfer: any ) { } async function preCheckAllMessagesSign( - optsTransfer: any, err: Error|string, jarrMessages: any[], joGlueResult: any ) { + optsTransfer: any, err: Error | string, jarrMessages: any[], joGlueResult: any ) { const strDidInvokedSigningCallbackMessage = log.fmtDebug( "{p}Did invoked message signing callback, first real message index is: {}, have {} " + "message(s) to process {}", optsTransfer.strLogPrefix, @@ -481,7 +481,7 @@ async function preCheckAllMessagesSign( } async function callbackAllMessagesSign( - optsTransfer: any, err: Error|string, jarrMessages: any[], joGlueResult: any ) { + optsTransfer: any, err: Error | string, jarrMessages: any[], joGlueResult: any ) { if( ! await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) return; const nBlockSize = optsTransfer.arrMessageCounters.length; @@ -626,24 +626,24 @@ async function callbackAllMessagesSign( async function handleAllMessagesSigning( optsTransfer: any ) { try { - let errFinal = null; + let strErrFinal: string = ""; await optsTransfer.fnSignMessages( optsTransfer.nTransferLoopCounter, optsTransfer.jarrMessages, optsTransfer.nIdxCurrentMsgBlockStart, optsTransfer.chainNameSrc, optsTransfer.joExtraSignOpts, - async function( err: Error|string, jarrMessages: any[], joGlueResult: any ) { + async function( err: Error | string, jarrMessages: any[], joGlueResult: any ) { await callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ); - return; - } ).catch( function( err: Error|string ) { + return + } ).catch( function( err: Error | string ) { // callback fn as argument of optsTransfer.fnSignMessages optsTransfer.bErrorInSigningMessages = true; optsTransfer.details.error( "{p}Problem in transfer handler(in signer): {err}", optsTransfer.strLogPrefix, err ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); - errFinal = err; + strErrFinal = err.toString(); } ); - if( errFinal ) - throw errFinal; + if( strErrFinal ) + throw new Error( strErrFinal ); return true; } catch ( err ) { optsTransfer.details.error( "{p}Problem in transfer handler(general): {err}", @@ -654,7 +654,8 @@ async function handleAllMessagesSigning( optsTransfer: any ) { } } -async function checkOutgoingMessageEventInOneNode( optsTransfer: any, optsOutgoingMessageAnalysis: any ) { +async function checkOutgoingMessageEventInOneNode( + optsTransfer: any, optsOutgoingMessageAnalysis: any ) { const sc = optsTransfer.imaState.chainProperties.sc; const strUrlHttp = optsOutgoingMessageAnalysis.joNode.endpoints.ip.http; optsTransfer.details.trace( @@ -672,7 +673,7 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer: any, optsOutgoi sc.joAbiIMA.message_proxy_chain_abi, ethersProviderNode ); const strEventName = "OutgoingMessage"; - const node_r = await imaEventLogScan.safeGetPastEventsProgressive( + const nodeRV = await imaEventLogScan.safeGetPastEventsProgressive( optsTransfer.details, optsTransfer.strLogPrefixShort, ethersProviderNode, 10, joMessageProxyNode, strEventName, joMessage.savedBlockNumberForOptimizations, @@ -680,13 +681,13 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer: any, optsOutgoi joMessageProxyNode.filters[strEventName]( owaspUtils.ethersMod.ethers.utils.id( optsTransfer.chainNameDst ), owaspUtils.toBN( optsOutgoingMessageAnalysis.idxImaMessage ) ) ); - const cntEvents = node_r.length; + const cntEvents = nodeRV.length; optsTransfer.details.trace( "{p}Got {} event(s) ({}) on node {} with data: {}", optsTransfer.strLogPrefix, cntEvents, strEventName, - optsOutgoingMessageAnalysis.joNode.name, node_r ); + optsOutgoingMessageAnalysis.joNode.name, nodeRV ); for( let idxEvent = 0; idxEvent < cntEvents; ++ idxEvent ) { - const joEvent = node_r[idxEvent]; + const joEvent = nodeRV[idxEvent]; const eventValuesByName: any = { "dstChainHash": joEvent.args[0], "msgCounter": joEvent.args[1], @@ -700,7 +701,7 @@ async function checkOutgoingMessageEventInOneNode( optsTransfer: any, optsOutgoi owaspUtils.ensureStartsWith0x( eventValuesByName.dstContract ).toLowerCase() ) { bEventIsFound = true; - break; + break } } } catch ( err ) { @@ -930,10 +931,13 @@ export async function doTransfer( ethersProviderDst: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joMessageProxyDst: owaspUtils.ethersMod.ethers.Contract, joAccountDst: any, chainNameSrc: string, chainNameDst: string, chainIdSrc: string, chainIdDst: string, - joDepositBoxMainNet: owaspUtils.ethersMod.ethers.Contract|null, // for logs validation on mainnet - joTokenManagerSChain: owaspUtils.ethersMod.ethers.Contract|null, // for logs validation on s-chain + joDepositBoxMainNet: + owaspUtils.ethersMod.ethers.Contract | null, // for logs validation on mainnet + joTokenManagerSChain: + owaspUtils.ethersMod.ethers.Contract | null, // for logs validation on s-chain nTransactionsCountInBlock: number, - nTransferSteps: number, nMaxTransactionsCount: number, nBlockAwaitDepth: number, nBlockAge: number, + nTransferSteps: number, nMaxTransactionsCount: number, + nBlockAwaitDepth: number, nBlockAge: number, fnSignMessages: any, joExtraSignOpts: any, transactionCustomizerDst: imaTx.TransactionCustomizer ) { @@ -1020,7 +1024,7 @@ export async function doTransfer( nIdxCurrentMsgBlockStart, optsTransfer.jarrMessages.length, optsTransfer.jarrMessages ); await fnAfter( null, jarrMessages ); // null - no error, null - no signatures - }; + } } else { optsTransfer.details.debug( "{p}Using externally provided signing function", optsTransfer.strLogPrefix ); @@ -1047,7 +1051,7 @@ export async function doTransfer( } catch ( err ) { optsTransfer.details.critical( "{p}Error in {} during {bright}: {err}, " + "stack is:\n{stack}", optsTransfer.strLogPrefix, - optsTransfer.strGatheredDetailsName, optsTransfer.strActionName,err, err ); + optsTransfer.strGatheredDetailsName, optsTransfer.strActionName, err, err ); optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 5e164312..045ad418 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -33,7 +33,7 @@ import * as threadInfo from "./threadInfo.js"; export async function getBalanceEth( isMainNet: boolean, - ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider|null, + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null, chainId: string, joAccount?: any, contractERC20?: any diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 96f3ba1c..3c6eb168 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -345,7 +345,7 @@ export async function safeGetPastEvents( idxAttempt, cntAttempts, strEventName, u, nBlockFrom.toHexString(), nBlockTo.toHexString(), err, err ); if( owaspUtils.extractErrorMessage( err ) - .indexOf( strErrorTextAboutNotExistingEvent ) >= 0 + .includes( strErrorTextAboutNotExistingEvent ) ) { details.error( "{p}Did stopped {} event filtering because no such event exist " + "in smart contract", strLogPrefix, strEventName ); diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 9d11e042..958b1775 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -26,7 +26,7 @@ import * as log from "./log.js"; import * as owaspUtils from "./owaspUtils.js"; -export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ) : any { +export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ): any { if( ! ( strName && typeof strName == "string" && jarrReceipts ) ) return { "sumGasUsed": 0, "strReport": "N/A" }; let i, sumGasUsed = owaspUtils.toBN( "0" ), @@ -50,6 +50,6 @@ export function printGasUsageReportFromArray( details = details || log; const jo: any = composeGasUsageReportFromArray( strName, jarrReceipts ); if( jo.strReport && typeof jo.strReport == "string" && jo.strReport.length > 0 && - jo.sumGasUsed && jo.sumGasUsed.gt( owaspUtils.toBN( "0" ) ) ) + jo.sumGasUsed?.gt( owaspUtils.toBN( "0" ) ) ) log.information( jo.strReport ); } diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 3be3e92a..4a4a4eb7 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -36,30 +36,30 @@ let gMillisecondsSleepBeforeFetchOutgoingMessageEvent: number = 5000; let gMillisecondsSleepBetweenTransactionsOnSChain: number = 0; // example - 5000 let gFlagWaitForNextBlockOnSChain: boolean = false; -export function getMillisecondsSleepBeforeFetchOutgoingMessageEvent() : number { +export function getMillisecondsSleepBeforeFetchOutgoingMessageEvent(): number { return gMillisecondsSleepBeforeFetchOutgoingMessageEvent; } -export function setMillisecondsSleepBeforeFetchOutgoingMessageEvent( val?: number ) : void { +export function setMillisecondsSleepBeforeFetchOutgoingMessageEvent( val?: number ): void { gMillisecondsSleepBeforeFetchOutgoingMessageEvent = val ? val : 0; } -export function getSleepBetweenTransactionsOnSChainMilliseconds() : number { +export function getSleepBetweenTransactionsOnSChainMilliseconds(): number { return gMillisecondsSleepBetweenTransactionsOnSChain; } -export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ) : void { +export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ): void { gMillisecondsSleepBetweenTransactionsOnSChain = val ? val : 0; } -export function getWaitForNextBlockOnSChain() : boolean { +export function getWaitForNextBlockOnSChain(): boolean { return ( !!gFlagWaitForNextBlockOnSChain ); } export function setWaitForNextBlockOnSChain( val: any ) { gFlagWaitForNextBlockOnSChain = ( !!val ); } -export const currentTimestamp = () : number => { +export const currentTimestamp = (): number => { return Date.now().valueOf() / 1000; -}; +} export async function safeWaitForNextBlockToAppear( details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider ) { @@ -127,7 +127,7 @@ let gMaxBlockScanIterationsInAllRange: number = 5000; export function getBlocksCountInInIterativeStepOfEventsScan(): number { return gCountOfBlocksInIterativeStep; } -export function setBlocksCountInInIterativeStepOfEventsScan( n?: number ) : void { +export function setBlocksCountInInIterativeStepOfEventsScan( n?: number ): void { if( ! n ) gCountOfBlocksInIterativeStep = 0; else { @@ -137,10 +137,10 @@ export function setBlocksCountInInIterativeStepOfEventsScan( n?: number ) : void } } -export function getMaxIterationsInAllRangeEventsScan() : number { +export function getMaxIterationsInAllRangeEventsScan(): number { return gCountOfBlocksInIterativeStep; } -export function setMaxIterationsInAllRangeEventsScan( n?: number ) : void { +export function setMaxIterationsInAllRangeEventsScan( n?: number ): void { if( ! n ) gMaxBlockScanIterationsInAllRange = 0; else { @@ -153,29 +153,29 @@ export function setMaxIterationsInAllRangeEventsScan( n?: number ) : void { // default S<->S transfer mode for "--s2s-transfer" is "forward" let gFlagIsForwardS2S: boolean = true; -export function getS2STransferModeDescription() : string { +export function getS2STransferModeDescription(): string { return gFlagIsForwardS2S ? "forward" : "reverse"; } -export function getS2STransferModeDescriptionColorized() : string { +export function getS2STransferModeDescriptionColorized(): string { return log.posNeg( gFlagIsForwardS2S, "forward", "reverse" ); } -export function isForwardS2S() : boolean { +export function isForwardS2S(): boolean { return ( !!gFlagIsForwardS2S ); } -export function isReverseS2S() : boolean { +export function isReverseS2S(): boolean { return ( !!gFlagIsForwardS2S ); } -export function setForwardS2S( b?: boolean ) : void { +export function setForwardS2S( b?: boolean ): void { if( b == null || b == undefined ) b = true; gFlagIsForwardS2S = ( !!b ); } -export function setReverseS2S( b?: boolean ) : void { +export function setReverseS2S( b?: boolean ): void { if( b == null || b == undefined ) b = true; gFlagIsForwardS2S = b ? false : true; diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 7279931e..e440153b 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -32,10 +32,10 @@ import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; let gFlagIsEnabledOracle: boolean = false; -export function getEnabledOracle() : boolean { +export function getEnabledOracle(): boolean { return ( !!gFlagIsEnabledOracle ); } -export function setEnabledOracle( isEnabled: boolean ) : void { +export function setEnabledOracle( isEnabled: boolean ): void { gFlagIsEnabledOracle = ( !!isEnabled ); } @@ -85,7 +85,8 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { nMillisecondsSleepBefore: 1000, nMillisecondsSleepPeriod: 3000, cntAttempts: 40, - isVerbose: ( log.verboseGet() >= log.verboseName2Number( "information" ) ) ? true : false, + isVerbose: + ( log.verboseGet() >= log.verboseName2Number( "information" ) ) ? true : false, isVerboseTraceDetails: ( log.verboseGet() >= log.verboseName2Number( "debug" ) ) ? true : false }; @@ -123,7 +124,7 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { if( log.exposeDetailsGet() ) optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", true ); optsGasPriseSetup.details.close(); - return; + return } } @@ -137,7 +138,7 @@ async function handleOracleSigned( imaTransferErrorHandling.saveTransferError( "oracle", optsGasPriseSetup.details.toString() ); optsGasPriseSetup.details.close(); - return; + return } optsGasPriseSetup.strActionName = "doOracleGasPriceSetup.formatSignature"; let signature = joGlueResult ? joGlueResult.signature : null; @@ -252,7 +253,7 @@ export async function doOracleGasPriceSetup( details.trace( "{p}u256 signing callback was not provided", optsGasPriseSetup.strLogPrefix ); await fnAfter( null, u256, null ); // null - no error, null - no signatures - }; + } } else { optsGasPriseSetup.details.trace( "{p}Using externally provided u256 signing function", optsGasPriseSetup.strLogPrefix ); diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 5eb612fc..ddc4eeee 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -27,7 +27,7 @@ import * as log from "./log.js"; import * as imaHelperAPIs from "./imaHelperAPIs.js"; import * as imaTx from "./imaTx.js"; import * as threadInfo from "./threadInfo.js"; -import * as owaspUtils from "./owaspUtils.js"; +import type * as owaspUtils from "./owaspUtils.js"; export async function invokeHasChain( details: any, diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 1ddfe808..ac68fa06 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -109,10 +109,10 @@ async function run() { log.debug( "SGX wallet ECDSA sign result is: {}", joOut ); const v = parseInt( joOut.result.signature_v ); - const eth_v = v + owaspUtils.parseIntOrHex( chainId ) * 2 + 35; + const ethV = v + owaspUtils.parseIntOrHex( chainId ) * 2 + 35; const joExpanded = { "recoveryParam": v, - "v": eth_v, + "v": ethV, "r": joOut.result.signature_r, "s": joOut.result.signature_s }; @@ -144,7 +144,7 @@ async function run() { process.exit( 0 ); } catch ( err ) { if( gIsDebugLogging ) - log.debug( "--- Call error ---> {}", log.em,( err ) ); + log.debug( "--- Call error ---> {}", log.em, ( err ) ); finalizeOutput( { "error": owaspUtils.extractErrorMessage( err ) } ); process.exit( 1 ); } diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 11a7698c..172aca3f 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -927,7 +927,7 @@ export async function doErc721PaymentFromSChain( const strEventName = "OutgoingMessage"; if( joMessageProxySChain ) { details.debug( "{p}Verifying the {} event of the MessageProxy/{} contract...", - strLogPrefix, strEventName,joMessageProxySChain.address ); + strLogPrefix, strEventName, joMessageProxySChain.address ); await threadInfo.sleep( imaHelperAPIs.getMillisecondsSleepBeforeFetchOutgoingMessageEvent() ); const joEvents = await imaEventLogScan.getContractCallEvents( @@ -1221,7 +1221,7 @@ export async function doErc1155BatchPaymentFromSChain( const strEventName = "OutgoingMessage"; if( joMessageProxySChain ) { details.debug( "{p}Verifying the {} event of the MessageProxy/{} contract...", - strLogPrefix, strEventName,joMessageProxySChain.address ); + strLogPrefix, strEventName, joMessageProxySChain.address ); await threadInfo.sleep( imaHelperAPIs.getMillisecondsSleepBeforeFetchOutgoingMessageEvent() ); const joEvents = await imaEventLogScan.getContractCallEvents( @@ -1878,7 +1878,8 @@ export async function mintErc20( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + const opts: any = + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC20", contract, "mint", arrArgumentsMint, @@ -1947,7 +1948,8 @@ export async function mintErc721( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + const opts: any = + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC721", contract, "mint", arrArgumentsMint, @@ -2020,7 +2022,8 @@ export async function mintErc1155( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + const opts: any = + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC1155", contract, "mint", arrArgumentsMint, @@ -2089,7 +2092,8 @@ export async function burnErc20( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + const opts: any = + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC20", contract, "burnFrom", arrArgumentsBurn, @@ -2155,7 +2159,8 @@ export async function burnErc721( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + const opts: any = + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC721", contract, "burn", arrArgumentsBurn, @@ -2227,7 +2232,8 @@ export async function burnErc1155( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + const opts: any = + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC1155", contract, "burn", arrArgumentsBurn, diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index a7c17cbf..4f90be4a 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -36,7 +36,7 @@ let gMapTransferErrorCategories: any = { }; export const saveTransferEvents = new EventDispatcher(); -export function saveTransferError( strCategory: string, textLog: any, ts?: any ) : void { +export function saveTransferError( strCategory: string, textLog: any, ts?: any ): void { ts = ts || Math.round( ( new Date() ).getTime() / 1000 ); const c = verifyTransferErrorCategoryName( strCategory ); const joTransferEventError: any = { @@ -54,7 +54,7 @@ export function saveTransferError( strCategory: string, textLog: any, ts?: any ) { "detail": joTransferEventError } ) ); } -export function saveTransferSuccess( strCategory: string ) : void { +export function saveTransferSuccess( strCategory: string ): void { const c = verifyTransferErrorCategoryName( strCategory ); try { delete gMapTransferErrorCategories["" + c]; } catch ( err ) { } saveTransferEvents.dispatchEvent( @@ -63,12 +63,12 @@ export function saveTransferSuccess( strCategory: string ) : void { { "detail": { "category": strCategory } } ) ); } -export function saveTransferSuccessAll() : void { +export function saveTransferSuccessAll(): void { // clear all transfer error categories, out of time frame gMapTransferErrorCategories = { }; } -export function getLastTransferErrors( isIncludeTextLog: boolean ) : any[] { +export function getLastTransferErrors( isIncludeTextLog: boolean ): any[] { if( typeof isIncludeTextLog == "undefined" ) isIncludeTextLog = true; const jarr = JSON.parse( JSON.stringify( gArrLastTransferErrors ) ); @@ -82,15 +82,15 @@ export function getLastTransferErrors( isIncludeTextLog: boolean ) : any[] { return jarr; } -export function getLastErrorCategories() : string[] { +export function getLastErrorCategories(): string[] { return Object.keys( gMapTransferErrorCategories ); } let gFlagIsEnabledProgressiveEventsScan = true; -export function getEnabledProgressiveEventsScan() : boolean { +export function getEnabledProgressiveEventsScan(): boolean { return ( !!gFlagIsEnabledProgressiveEventsScan ); } -export function setEnabledProgressiveEventsScan( isEnabled: boolean ) : void { +export function setEnabledProgressiveEventsScan( isEnabled: boolean ): void { gFlagIsEnabledProgressiveEventsScan = ( !!isEnabled ); } diff --git a/src/imaTx.ts b/src/imaTx.ts index b3c1a7e7..c097e38c 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -39,16 +39,17 @@ import * as imaEventLogScan from "./imaEventLogScan.js"; import * as threadInfo from "./threadInfo.js"; +// eslint-disable-next-line @typescript-eslint/naming-convention const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); let redis: any = null; let gFlagDryRunIsEnabled: boolean = true; -export function dryRunIsEnabled() : boolean { +export function dryRunIsEnabled(): boolean { return ( !!gFlagDryRunIsEnabled ); } -export function dryRunEnable( isEnable: any ) : boolean { +export function dryRunEnable( isEnable: any ): boolean { gFlagDryRunIsEnabled = ( isEnable != null && isEnable != undefined ) ? ( !!isEnable ) : true; return ( !!gFlagDryRunIsEnabled ); @@ -56,11 +57,11 @@ export function dryRunEnable( isEnable: any ) : boolean { let gFlagDryRunIsIgnored = true; -export function dryRunIsIgnored() : boolean { +export function dryRunIsIgnored(): boolean { return ( !!gFlagDryRunIsIgnored ); } -export function dryRunIgnore( isIgnored: boolean ) : boolean { +export function dryRunIgnore( isIgnored: boolean ): boolean { gFlagDryRunIsIgnored = ( isIgnored != null && isIgnored != undefined ) ? ( !!isIgnored ) : true; return ( !!gFlagDryRunIsIgnored ); @@ -145,7 +146,7 @@ async function payedCallPrepare( optsPayedCall: any ) { optsPayedCall.unsignedTx.nonce = owaspUtils.toBN( await optsPayedCall.ethersProvider.getTransactionCount( optsPayedCall.joAccount.address() ) ); - if( optsPayedCall.opts && optsPayedCall.opts.isCheckTransactionToSchain ) { + if( optsPayedCall.opts?.isCheckTransactionToSchain ) { optsPayedCall.unsignedTx = await checkTransactionToSchain( optsPayedCall.unsignedTx, optsPayedCall.details, optsPayedCall.ethersProvider, optsPayedCall.joAccount ); @@ -343,9 +344,9 @@ export async function payedCall( const strErrorPrefix = "Transaction sign and send error(INNER FLOW): "; optsPayedCall.details.critical( "{p}bad credentials information specified, no explicit SGX and no explicit " + - "private key found", strErrorPrefix ); + "private key found", strErrorPrefix ); throw new Error( `${strErrorPrefix} bad credentials information specified, ` + - "no explicit SGX and no explicit private key found" ); + "no explicit SGX and no explicit private key found" ); } // NOTICE: "break;" is not needed here because of "throw" above } // switch( optsPayedCall.joACI.strType ) } catch ( err ) { @@ -399,9 +400,9 @@ export async function checkTransactionToSchain( if( balance.lt( requiredBalance ) ) { details.warning( "{p}Insufficient funds for {}, will run PoW-mining to get {} of gas", strLogPrefix, strFromAddress, owaspUtils.toHexStringSafe( unsignedTx.gasLimit ) ); - let powNumberBuffer = await calculatePowNumber( + const powNumberBuffer = await calculatePowNumber( strFromAddress, owaspUtils.toBN( unsignedTx.nonce ).toHexString(), - owaspUtils.toHexStringSafe( unsignedTx.gasLimit ), details, strLogPrefix ); + owaspUtils.toHexStringSafe( unsignedTx.gasLimit ), details, strLogPrefix ) details.debug( "{p}Returned PoW-mining number {}", strLogPrefix, powNumberBuffer ); let powNumber: string = powNumberBuffer.toString( "utf8" ).trim(); powNumber = imaUtils.replaceAll( powNumber, "\r", "" ); @@ -413,7 +414,7 @@ export async function checkTransactionToSchain( throw new Error( "Failed to compute gas price with PoW-mining(1), got empty text" ); powNumber = owaspUtils.toBN( owaspUtils.ensureStartsWith0x( powNumber ) ); details.trace( "{p}BN PoW-mining number is {}", strLogPrefix, powNumber ); - let powNumberBN = owaspUtils.toBN( powNumber); + const powNumberBN = owaspUtils.toBN( powNumber ); if( powNumberBN.eq( owaspUtils.toBN( "0" ) ) ) throw new Error( "Failed to compute gas price with PoW-mining(2), got zero value" ); unsignedTx.gasPrice = owaspUtils.toBN( powNumberBN.toHexString() ); @@ -480,16 +481,17 @@ export function getAccountConnectivityInfo( joAccount: any ) { joACI.isBad = false; joACI.strType = "direct"; } else { - // bad by default + // bad by default } return joACI; } const gTransactionManagerPool = "transactions"; -const tmGenerateRandomHex = - function( size: number ) { [ ...Array( size ) ] - .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ) }; +function tmGenerateRandomHex( size: number ): string { + return [ ...Array( size ) ] + .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ) +} function tmMakeId( details: any ) { const prefix = "tx-"; @@ -576,7 +578,8 @@ async function tmWait( } async function tmEnsureTransaction( - details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, priority: any, txAdjusted: any, + details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + priority: any, txAdjusted: any, cntAttempts?: number, sleepMilliseconds?: number ) { cntAttempts = cntAttempts || 1; @@ -607,7 +610,7 @@ async function tmEnsureTransaction( export class TransactionCustomizer { gasPriceMultiplier: any; gasMultiplier: any; - constructor( gasPriceMultiplier: any, gasMultiplier: any ) { + constructor ( gasPriceMultiplier: any, gasMultiplier: any ) { this.gasPriceMultiplier = gasPriceMultiplier ? ( 0.0 + gasPriceMultiplier ) : null; // null means use current gasPrice or recommendedGasPrice @@ -700,25 +703,25 @@ export class TransactionCustomizer { } }; -let gTransactionCustomizerMainNet: TransactionCustomizer|null = null; -let gTransactionCustomizerSChain: TransactionCustomizer|null = null; -let gTransactionCustomizerSChainTarget: TransactionCustomizer|null = null; +let gTransactionCustomizerMainNet: TransactionCustomizer | null = null; +let gTransactionCustomizerSChain: TransactionCustomizer | null = null; +let gTransactionCustomizerSChainTarget: TransactionCustomizer | null = null; -export function getTransactionCustomizerForMainNet() : TransactionCustomizer { +export function getTransactionCustomizerForMainNet(): TransactionCustomizer { if( gTransactionCustomizerMainNet ) return gTransactionCustomizerMainNet; gTransactionCustomizerMainNet = new TransactionCustomizer( 1.25, 1.25 ); return gTransactionCustomizerMainNet; } -export function getTransactionCustomizerForSChain() : TransactionCustomizer { +export function getTransactionCustomizerForSChain(): TransactionCustomizer { if( gTransactionCustomizerSChain ) return gTransactionCustomizerSChain; gTransactionCustomizerSChain = new TransactionCustomizer( null, 1.25 ); return gTransactionCustomizerSChain; } -export function getTransactionCustomizerForSChainTarget() : TransactionCustomizer { +export function getTransactionCustomizerForSChainTarget(): TransactionCustomizer { if( gTransactionCustomizerSChainTarget ) return gTransactionCustomizerSChainTarget; gTransactionCustomizerSChainTarget = new TransactionCustomizer( null, 1.25 ); diff --git a/src/log.ts b/src/log.ts index 26c3ba11..64b7e55c 100644 --- a/src/log.ts +++ b/src/log.ts @@ -42,40 +42,41 @@ const getDurationString = cc.getDurationString; export { safeURL, replaceAll, timestampHR, capitalizeFirstLetter, getDurationString }; -export function autoEnableColorizationFromCommandLineArgs() : void { - return cc.autoEnableFromCommandLineArgs(); +export function autoEnableColorizationFromCommandLineArgs(): void { + cc.autoEnableFromCommandLineArgs() } -export function enableColorization( bIsEnable?: boolean ) : void { +export function enableColorization( bIsEnable?: boolean ): void { cc.enable( !!bIsEnable ); } -export function isEnabledColorization() : boolean { +export function isEnabledColorization(): boolean { return ( !! ( cc.isEnabled() ) ); } -export function getPrintTimestamps() : boolean { +export function getPrintTimestamps(): boolean { return gFlagLogWithTimeStamps; } -export function setPrintTimestamps( b?: boolean ) : void { +export function setPrintTimestamps( b?: boolean ): void { gFlagLogWithTimeStamps = ( !!b ); } -export function n2s( n: any, sz: number ) : string { - let s:string = "" + n; +export function n2s( n: any, sz: number ): string { + let s: string = "" + n; while( s.length < sz ) s = "0" + s; return s; } -export function generateTimestampString( ts?: any, isColorized?: boolean ) : string { +export function generateTimestampString( ts?: any, isColorized?: boolean ): string { isColorized = ( typeof isColorized == "undefined" ) ? true : ( !!isColorized ); ts = ( ts instanceof Date ) ? ts : new Date(); - const ccDate = function( x?: any ) : string { return isColorized ? cc.date( x ) : x; }; - const ccTime = function( x?: any ) : string { return isColorized ? cc.time( x ) : x; }; - const ccFractionPartOfTime = function( x?: any ) : string { return isColorized ? cc.frac_time( x ) : x; }; - const ccBright = function( x?: any ) : string { return isColorized ? cc.bright( x ) : x; }; + const ccDate = function( x?: any ): string { return isColorized ? cc.date( x ) : x; } + const ccTime = function( x?: any ): string { return isColorized ? cc.time( x ) : x; } + const ccFractionPartOfTime = + function( x?: any ): string { return isColorized ? cc.fracTime( x ) : x; } + const ccBright = function( x?: any ): string { return isColorized ? cc.bright( x ) : x; } const s = "" + ccDate( n2s( ts.getUTCFullYear(), 4 ) ) + ccBright( "-" ) + ccDate( n2s( ts.getUTCMonth() + 1, 2 ) ) + @@ -83,16 +84,16 @@ export function generateTimestampString( ts?: any, isColorized?: boolean ) : str " " + ccTime( n2s( ts.getUTCHours(), 2 ) ) + ccBright( ":" ) + ccTime( n2s( ts.getUTCMinutes(), 2 ) ) + ccBright( ":" ) + ccTime( n2s( ts.getUTCSeconds(), 2 ) ) + - ccBright( "." ) + ccFractionPartOfTime( n2s( ts.getUTCMilliseconds(), 3 ) ) - ; + ccBright( "." ) + ccFractionPartOfTime( n2s( ts.getUTCMilliseconds(), 3 ) ); + return s; } -export function generateTimestampPrefix( ts?: any, isColorized?: boolean ) : string { +export function generateTimestampPrefix( ts?: any, isColorized?: boolean ): string { return generateTimestampString( ts, isColorized ) + cc.bright( ":" ) + " "; } -export function removeAllStreams() : void { +export function removeAllStreams(): void { let i = 0; let cnt = 0; try { cnt = gArrStreams.length; @@ -108,7 +109,7 @@ export function removeAllStreams() : void { gArrStreams = []; } -export function getStreamWithFilePath( strFilePath: string ) : any { +export function getStreamWithFilePath( strFilePath: string ): any { try { let i = 0; const cnt = gArrStreams.length; for( i = 0; i < cnt; ++i ) { @@ -124,7 +125,7 @@ export function getStreamWithFilePath( strFilePath: string ) : any { return null; } -export function createStandardOutputStream() : any { +export function createStandardOutputStream(): any { try { const objEntry: any = { "id": gIdentifierAllocatorCounter ++, @@ -135,7 +136,7 @@ export function createStandardOutputStream() : any { "haveOwnTimestamps": false, "isPausedTimeStamps": false, "strOwnIndent": "", - "write": function( ...args: any[] ) : void { + "write": function( ...args: any[] ): void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) ? generateTimestampPrefix( null, true ) : "" ); @@ -145,7 +146,7 @@ export function createStandardOutputStream() : any { this.objStream.write( s ); } catch ( err ) { } }, - "writeRaw": function( ...args: any[] ) : void { + "writeRaw": function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); try { if( this.objStream && s.length > 0 ) @@ -156,63 +157,63 @@ export function createStandardOutputStream() : any { "open": function() { try { this.objStream = process.stdout; } catch ( err ) { } }, "size": function() { return 0; }, "rotate": function( nBytesToWrite: number ) { }, - "toString": function() : string { return "" + this.strFilePath; }, + "toString": function(): string { return "" + this.strFilePath; }, "exposeDetailsTo": - function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { }, + function( otherStream: any, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters - "fatal": function( ...args: any[] ) : void { + "fatal": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function( ...args: any[] ) : void { + "critical": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) { this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, - "error": function( ...args: any[] ) : void { + "error": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function( ...args: any[] ) : void { + "warning": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function( ...args: any[] ) : void { + "attention": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function( ...args: any[] ) : void { + "information": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function( ...args: any[] ) : void { + "info": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function( ...args: any[] ) : void { + "notice": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function( ...args: any[] ) : void { + "note": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function( ...args: any[] ) : void { + "debug": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function( ...args: any[] ) : void { + "trace": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function( ...args: any[] ) : void { + "success": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } @@ -224,7 +225,7 @@ export function createStandardOutputStream() : any { return null; } -export function insertStandardOutputStream() : boolean { +export function insertStandardOutputStream(): boolean { let objEntry = getStreamWithFilePath( "stdout" ); if( objEntry !== null ) return true; @@ -235,7 +236,7 @@ export function insertStandardOutputStream() : boolean { return true; } -export function createMemoryOutputStream() : any { +export function createMemoryOutputStream(): any { try { const objEntry: any = { "id": gIdentifierAllocatorCounter ++, @@ -262,7 +263,7 @@ export function createMemoryOutputStream() : any { return true; return false; }, - "write": function( ...args: any[] ) : void { + "write": function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); for( let i = 0; i < arr.length; ++ i ) { @@ -277,7 +278,7 @@ export function createMemoryOutputStream() : any { this.arrAccumulatedLogTextLines.push( strHeader + strLine + "\n" ); } }, - "writeRaw": function( ...args: any[] ) : void { + "writeRaw": function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); for( let i = 0; i < arr.length; ++ i ) { @@ -289,14 +290,16 @@ export function createMemoryOutputStream() : any { "close": function() { this.clear(); }, "open": function() { this.clear(); }, "size": function() { return 0; }, - "rotate": function( nBytesToWrite: number ) { this.this.arrAccumulatedLogTextLines = []; }, - "toString": function() : string { + "rotate": + function( nBytesToWrite: number ) { this.this.arrAccumulatedLogTextLines = []; }, + "toString": function(): string { let s = ""; for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) s += this.arrAccumulatedLogTextLines[i]; return s; }, - "exposeDetailsTo": function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { + "exposeDetailsTo": + function( otherStream: any, strTitle: string, isSuccess: boolean ): void { if( ! ( this.arrAccumulatedLogTextLines && this.arrAccumulatedLogTextLines.length > 0 ) ) return; @@ -336,57 +339,57 @@ export function createMemoryOutputStream() : any { } }, // high-level formatters - "fatal": function( ...args: any[] ) : void { + "fatal": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function( ...args: any[] ) : void { + "critical": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); }, - "error": function( ...args: any[] ) : void { + "error": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function( ...args: any[] ) : void { + "warning": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function( ...args: any[] ) : void { + "attention": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function( ...args: any[] ) : void { + "information": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function( ...args: any[] ) : void { + "info": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function( ...args: any[] ) : void { + "notice": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function( ...args: any[] ) : void { + "note": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function( ...args: any[] ) : void { + "debug": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function( ...args: any[] ) : void { + "trace": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function( ...args: any[] ) : void { + "success": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } @@ -398,7 +401,7 @@ export function createMemoryOutputStream() : any { return null; } -export function insertMemoryOutputStream() : boolean { +export function insertMemoryOutputStream(): boolean { let objEntry = getStreamWithFilePath( "memory" ); if( objEntry !== null ) return true; @@ -410,7 +413,7 @@ export function insertMemoryOutputStream() : boolean { } export function createFileOutput( - strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : any { + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): any { try { const objEntry: any = { "id": gIdentifierAllocatorCounter ++, @@ -421,7 +424,7 @@ export function createFileOutput( "haveOwnTimestamps": false, "isPausedTimeStamps": false, "strOwnIndent": "", - "write": function( ...args: any[] ) : void { + "write": function( ...args: any[] ): void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) ? generateTimestampPrefix( null, true ) : "" ); @@ -433,7 +436,7 @@ export function createFileOutput( } } catch ( err ) { } }, - "writeRaw": function( ...args: any[] ) : void { + "writeRaw": function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); try { if( s.length > 0 ) { @@ -464,7 +467,7 @@ export function createFileOutput( const nNextSize = nFileSize + nBytesToWrite; if( nNextSize <= this.nMaxSizeBeforeRotation ) { this.open(); - return; + return } let i = 0; const cnt = 0 + this.nMaxFilesCount; for( i = 0; i < cnt; ++i ) { @@ -485,63 +488,63 @@ export function createFileOutput( } catch ( err ) { } }, - "toString": function() : string { return "" + strFilePath; }, + "toString": function(): string { return "" + strFilePath; }, "exposeDetailsTo": - function( otherStream: any, strTitle: string, isSuccess: boolean ) : void { }, + function( otherStream: any, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters - "fatal": function( ...args: any[] ) : void { + "fatal": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function( ...args: any[] ) : void { + "critical": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) { this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, - "error": function( ...args: any[] ) : void { + "error": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function( ...args: any[] ) : void { + "warning": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function( ...args: any[] ) : void { + "attention": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function( ...args: any[] ) : void { + "information": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function( ...args: any[] ) : void { + "info": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function( ...args: any[] ) : void { + "notice": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function( ...args: any[] ) : void { + "note": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function( ...args: any[] ) : void { + "debug": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function( ...args: any[] ) : void { + "trace": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function( ...args: any[] ) : void { + "success": function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } @@ -557,7 +560,7 @@ export function createFileOutput( return null; } export function insertFileOutput( - strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : any { + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): any { let objEntry = getStreamWithFilePath( "" + strFilePath ); if( objEntry !== null ) return true; @@ -568,14 +571,14 @@ export function insertFileOutput( return true; } -export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ) : string { +export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): string { strDefaultErrorText = strDefaultErrorText || "unknown error or error without a description"; if( ! jo ) return strDefaultErrorText; try { - const isError = function( err: Error|string ) { + const isError = function( err: Error | string ) { return err && err instanceof Error && err.stack && err.message; - }; + } if( ! isError( jo ) ) { if( "error" in jo ) { jo = jo.error; @@ -596,7 +599,7 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ) : return strDefaultErrorText; } -function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ) : any[]|null { +function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[] | null { if( !( strFormat && typeof strFormat == "string" ) ) return null; if( ! cntArgsMax ) @@ -629,12 +632,12 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ) : any return arrParts; } -export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string { - fnFormatter = fnFormatter || function( arg: any ) { return arg; }; +export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { + fnFormatter = fnFormatter || function( arg: any ) { return arg; } const arrParts = ( arrArgs && arrArgs.length > 0 ) ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; let s = "", isValueMode = false; - const fnDefaultOneArgumentFormatter = function( arg?: any, fnCustomFormatter?: any ) : string { + const fnDefaultOneArgumentFormatter = function( arg?: any, fnCustomFormatter?: any ): string { if( ! fnCustomFormatter ) fnCustomFormatter = fnFormatter; const t = typeof arg; @@ -648,8 +651,8 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string } else return cc.logArgToString( arg ); return arg; - }; - const fnFormatOneArgument = function( arg: any, fmt?: any ) : string { + } + const fnFormatOneArgument = function( arg: any, fmt?: any ): string { if( ! arg ) return arg; if( arg == " " || arg == "\n" ) @@ -681,7 +684,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string return fnDefaultOneArgumentFormatter( arg, cc.rainbow ); } return v( arg ); - }; + } try { let idxArgNextPrinted = 0; if( arrParts && arrParts.length > 0 ) { @@ -693,7 +696,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string if( idxArgNextPrinted < arrArgs.length ) s += fnFormatOneArgument( arrArgs[idxArgNextPrinted], joPart.text ); ++ idxArgNextPrinted; - continue; + continue } // assume joPart.type == "text" always here, at this point if( ! cc.isStringAlreadyColorized( joPart.text ) ) @@ -713,7 +716,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ) : string return s; } -export function outputStringToAllStreams( s: string ) : void { +export function outputStringToAllStreams( s: string ): void { try { if( s.length <= 0 ) return; @@ -729,160 +732,160 @@ export function outputStringToAllStreams( s: string ) : void { } } -export function write( ...args: any[] ) : void { +export function write( ...args: any[] ): void { let s: string = getPrintTimestamps() ? generateTimestampPrefix( null, true ) : ""; s += fmtArgumentsArray( args ); outputStringToAllStreams( s ); } -export function writeRaw( ...args: any[] ) : void { +export function writeRaw( ...args: any[] ): void { const s: string = fmtArgumentsArray( args ); outputStringToAllStreams( s ); } -export function getLogLinePrefixFatal() : string { +export function getLogLinePrefixFatal(): string { return cc.fatal( "FATAL ERROR:" ) + " "; } -export function getLogLinePrefixCritical() : string { +export function getLogLinePrefixCritical(): string { return cc.fatal( "CRITICAL ERROR:" ) + " "; } -export function getLogLinePrefixError() : string { +export function getLogLinePrefixError(): string { return cc.fatal( "ERROR:" ) + " "; } -export function getLogLinePrefixWarning() : string { +export function getLogLinePrefixWarning(): string { return cc.error( "WARNING:" ) + " "; } -export function getLogLinePrefixAttention() : string { +export function getLogLinePrefixAttention(): string { return ""; } -export function getLogLinePrefixInformation() : string { +export function getLogLinePrefixInformation(): string { return ""; } -export function getLogLinePrefixNotice() : string { +export function getLogLinePrefixNotice(): string { return ""; } -export function getLogLinePrefixNote() : string { +export function getLogLinePrefixNote(): string { return ""; } -export function getLogLinePrefixDebug() : string { +export function getLogLinePrefixDebug(): string { return ""; } -export function getLogLinePrefixTrace() : string { +export function getLogLinePrefixTrace(): string { return ""; } -export function getLogLinePrefixSuccess() : string { +export function getLogLinePrefixSuccess(): string { return ""; } // high-level format to returned string -export function fmtFatal( ...args: any[] ) : string { +export function fmtFatal( ...args: any[] ): string { return fmtArgumentsArray( args, cc.error ); } -export function fmtCritical( ...args: any[] ) : string { +export function fmtCritical( ...args: any[] ): string { return fmtArgumentsArray( args, cc.error ); } -export function fmtError( ...args: any[] ) : string { +export function fmtError( ...args: any[] ): string { return fmtArgumentsArray( args, cc.error ); } -export function fmtWarning( ...args: any[] ) : string { +export function fmtWarning( ...args: any[] ): string { return fmtArgumentsArray( args, cc.warning ); } -export function fmtAttention( ...args: any[] ) : string { +export function fmtAttention( ...args: any[] ): string { return fmtArgumentsArray( args, cc.attention ); } -export function fmtInformation( ...args: any[] ) : string { +export function fmtInformation( ...args: any[] ): string { return fmtArgumentsArray( args, cc.info ); } -export function fmtInfo( ...args: any[] ) : string { +export function fmtInfo( ...args: any[] ): string { return fmtArgumentsArray( args, cc.info ); } -export function fmtNotice( ...args: any[] ) : string { +export function fmtNotice( ...args: any[] ): string { return fmtArgumentsArray( args, cc.notice ); } -export function fmtNote( ...args: any[] ) : string { +export function fmtNote( ...args: any[] ): string { return fmtArgumentsArray( args, cc.note ); } -export function fmtDebug( ...args: any[] ) : string { +export function fmtDebug( ...args: any[] ): string { return fmtArgumentsArray( args, cc.debug ); } -export function fmtTrace( ...args: any[] ) : string { +export function fmtTrace( ...args: any[] ): string { return fmtArgumentsArray( args, cc.trace ); } -export function fmtSuccess( ...args: any[] ) : string { +export function fmtSuccess( ...args: any[] ): string { return fmtArgumentsArray( args, cc.success ); } // high-level formatted output -export function fatal( ...args: any[] ) : void { +export function fatal( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) write( getLogLinePrefixFatal() + fmtFatal( ...args ) + "\n" ); } -export function critical( ...args: any[] ) : void { +export function critical( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) write( getLogLinePrefixCritical() + fmtCritical( ...args ) + "\n" ); } -export function error( ...args: any[] ) : void { +export function error( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) write( getLogLinePrefixError() + fmtError( ...args ) + "\n" ); } -export function warning( ...args: any[] ) : void { +export function warning( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) write( getLogLinePrefixWarning() + fmtWarning( ...args ) + "\n" ); } -export function attention( ...args: any[] ) : void { +export function attention( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) write( getLogLinePrefixAttention() + fmtAttention( ...args ) + "\n" ); } -export function information( ...args: any[] ) : void { +export function information( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) write( getLogLinePrefixInformation() + fmtInformation( ...args ) + "\n" ); } -export function info( ...args: any[] ) : void { +export function info( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) write( getLogLinePrefixInformation() + fmtInformation( ...args ) + "\n" ); } -export function notice( ...args: any[] ) : void { +export function notice( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) write( getLogLinePrefixNotice() + fmtNotice( ...args ) + "\n" ); } -export function note( ...args: any[] ) : void { +export function note( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) write( getLogLinePrefixNote() + fmtNote( ...args ) + "\n" ); } -export function debug( ...args: any[] ) : void { +export function debug( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) write( getLogLinePrefixDebug() + fmtDebug( ...args ) + "\n" ); } -export function trace( ...args: any[] ) : void { +export function trace( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) write( getLogLinePrefixTrace() + fmtTrace( ...args ) + "\n" ); } -export function success( ...args: any[] ) : void { +export function success( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) + "\n" ); } -export function removeAll() : void { +export function removeAll(): void { removeAllStreams(); } -export function addStdout() : boolean { +export function addStdout(): boolean { return insertStandardOutputStream(); } -export function addMemory() : boolean { +export function addMemory(): boolean { return insertMemoryOutputStream(); } -export function createMemoryStream() : any { +export function createMemoryStream(): any { return createMemoryOutputStream(); } export function add( - strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ) : boolean { + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): boolean { if( ! nMaxSizeBeforeRotation ) nMaxSizeBeforeRotation = 0; if( ! nMaxFilesCount ) - nMaxFilesCount = 0; + nMaxFilesCount = 0; return insertFileOutput( strFilePath, ( nMaxSizeBeforeRotation <= 0 ) ? -1 : nMaxSizeBeforeRotation, @@ -890,20 +893,20 @@ export function add( ); } -export function close() : void { +export function close(): void { // for compatibility with created streams } -export function exposeDetailsTo( otherStream: any, strTitle: string, isSuccess: boolean ) : void { +export function exposeDetailsTo( otherStream: any, strTitle: string, isSuccess: boolean ): void { // for compatibility with created streams } -export function toString() : string { +export function toString(): string { // for compatibility with created streams return ""; } -const gMapVerbose : Map < number, string > = new Map < number, string > (); +const gMapVerbose: Map < number, string > = new Map < number, string >(); gMapVerbose.set( 0, "silent" ); gMapVerbose.set( 1, "fatal" ); gMapVerbose.set( 2, "critical" ); @@ -916,7 +919,7 @@ gMapVerbose.set( 8, "debug" ); gMapVerbose.set( 9, "trace" ); function computeVerboseAlias() { - const m: Map < string, number > = new Map < string, number > (); + const m: Map < string, number > = new Map < string, number >(); for( const [ key, val ] of gMapVerbose ) { const name = val; if( name ) @@ -936,15 +939,15 @@ function computeVerboseAlias() { m.set( "detailed", m.get( "trace" ) || 0 ); // alias return m; } -let gMapReversedVerbose: Map < string, number > = new Map < string, number > (); +let gMapReversedVerbose: Map < string, number > = new Map < string, number >(); -export function verbose() : any { return gMapVerbose; } -export function verboseReversed() : Map < string, number > { +export function verbose(): any { return gMapVerbose; } +export function verboseReversed(): Map < string, number > { if( ! gMapReversedVerbose ) gMapReversedVerbose = computeVerboseAlias(); return gMapReversedVerbose; } -export function verboseLevelAsTextForLog( vl: any ) : string { +export function verboseLevelAsTextForLog( vl: any ): string { if( typeof vl == "undefined" ) vl = verboseGet(); if( vl in gMapVerbose ) { @@ -953,9 +956,9 @@ export function verboseLevelAsTextForLog( vl: any ) : string { } return "unknown(" + JSON.stringify( vl ) + ")"; } -export function verboseName2Number( s: string ) : number { +export function verboseName2Number( s: string ): number { const mapReversedVerbose: Map < string, number > = verboseReversed(); - let n = mapReversedVerbose.get( s ); + const n = mapReversedVerbose.get( s ) if( typeof n == "undefined" ) return 9; return n; @@ -971,14 +974,14 @@ export function exposeDetailsSet( isExpose: any ) { gFlagIsExposeDetails = ( !!isExpose ); } -export function verboseGet() : number { +export function verboseGet(): number { return 0 + gVerboseLevel; } -export function verboseSet( vl?: any ) : void { +export function verboseSet( vl?: any ): void { gVerboseLevel = parseInt( vl ); } -export function verboseParse( s: string ) : number { +export function verboseParse( s: string ): number { let n: number = 5; try { const isNumbersOnly = /^\d+$/.test( s ); @@ -988,7 +991,7 @@ export function verboseParse( s: string ) : number { const ch0 = s[0].toLowerCase(); for( const [ key, val ] of gMapVerbose ) { const name = val; - const ch1:string = name[0].toLowerCase(); + const ch1: string = name[0].toLowerCase(); if( ch0 == ch1 ) { n = key; return n; @@ -999,38 +1002,38 @@ export function verboseParse( s: string ) : number { return n; } -export function verboseList() : void { +export function verboseList(): void { for( const [ key, val ] of gMapVerbose ) { const name = val; console.log( " " + cc.j( key ) + cc.sunny( "=" ) + cc.bright( name ) ); } } -export function u( x?: any ) : string { +export function u( x?: any ): string { return cc.isStringAlreadyColorized( x ) ? x : cc.u( x ); } -export function v( x?: any ) : string { +export function v( x?: any ): string { return cc.isStringAlreadyColorized( x ) ? x : cc.j( x ); } -export function em( x?: any ) : string { +export function em( x?: any ): string { return cc.isStringAlreadyColorized( x ) ? x : cc.warning( x ); } -export function stack( err?: any ) : string { +export function stack( err?: any ): string { return cc.stack( err ); } -export function onOff( x?: any ) : string { +export function onOff( x?: any ): string { return cc.isStringAlreadyColorized( x ) ? x : cc.onOff( x ); } -export function yn( x?: any ) : string { +export function yn( x?: any ): string { return cc.isStringAlreadyColorized( x ) ? x : cc.yn( x ); } -export function posNeg( condition: any, strPositive: string, strNegative: string ) : string { +export function posNeg( condition: any, strPositive: string, strNegative: string ): string { return condition ? ( cc.isStringAlreadyColorized( strPositive ) ? strPositive : cc.success( strPositive ) ) : ( cc.isStringAlreadyColorized( strNegative ) ? strNegative : cc.error( strNegative ) ); diff --git a/src/loop.ts b/src/loop.ts index 050abae4..619919a2 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -38,12 +38,13 @@ import * as skaleObserver from "./observer.js"; import * as pwa from "./pwa.js"; import * as state from "./state.js"; +// eslint-disable-next-line @typescript-eslint/naming-convention const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); // Run transfer loop export function checkTimeFraming( - d: Date|null, strDirection: string, joRuntimeOpts: any ) : boolean { + d: Date | null, strDirection: string, joRuntimeOpts: any ): boolean { try { const imaState = state.get(); if( imaState.nTimeFrameSeconds <= 0 || imaState.nNodesCount <= 1 ) @@ -252,20 +253,20 @@ async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) b2 = await IMA.doTransfer( // s-chain --> main-net "S2M", optsLoop.joRuntimeOpts, - + imaState.chainProperties.sc.ethersProvider, imaState.joMessageProxySChain, imaState.chainProperties.sc.joAccount, - + imaState.chainProperties.mn.ethersProvider, imaState.joMessageProxyMainNet, imaState.chainProperties.mn.joAccount, - + imaState.chainProperties.sc.strChainName, imaState.chainProperties.mn.strChainName, imaState.chainProperties.sc.chainId, imaState.chainProperties.mn.chainId, - + imaState.joDepositBoxETH, // for logs validation on mainnet null, imaState.nTransferBlockSizeS2M, @@ -521,7 +522,8 @@ export async function ensureHaveWorkers( opts: any ) { gArrWorkers.push( new threadInfo.Worker( path.join( __dirname, "loopWorker.js" ), { // "type": "module", - "workerData": workerData } + "workerData": workerData + } ) ); gArrWorkers[idxWorker].on( "message", function( jo: any ) { if( networkLayer.outOfWorkerAPIs.onMessage( gArrWorkers[idxWorker], jo ) ) @@ -541,7 +543,8 @@ export async function ensureHaveWorkers( opts: any ) { break; } aClient.errorLogicalInit = joMessage.error; - opts.details.critical( " Loop worker thread {} reported/returned init error: {err}", + opts.details.critical( + " Loop worker thread {} reported/returned init error: {err}", idxWorker, joMessage.error ); break; case "log": diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 559cc9c7..235ab818 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -63,9 +63,9 @@ function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { class ObserverServer extends SocketServer { initComplete?: boolean; opts: any; - intervalPeriodicSchainsCaching?: number|null; + intervalPeriodicSchainsCaching?: number | null bIsPeriodicCachingStepInProgress?: boolean; - constructor( acceptor: any ) { + constructor ( acceptor: any ) { super( acceptor ); const self: any = this; self.initComplete = false; @@ -90,7 +90,7 @@ class ObserverServer extends SocketServer { }; const isFlush = true; socket.send( jo, isFlush ); - }; + } self.initLogMethods(); self.opts = JSON.parse( JSON.stringify( joMessage.message.opts ) ); self.opts.details = { @@ -128,9 +128,9 @@ class ObserverServer extends SocketServer { socket.send( jo, isFlush ); } ); self.opts.imaState.chainProperties.mn.joAccount.address = - function() { return owaspUtils.fnAddressImpl_( this ); }; + function() { return owaspUtils.fnAddressImpl_( this ); } self.opts.imaState.chainProperties.sc.joAccount.address = - function() { return owaspUtils.fnAddressImpl_( this ); }; + function() { return owaspUtils.fnAddressImpl_( this ); } if( self.opts.imaState.chainProperties.mn.strURL && typeof self.opts.imaState.chainProperties.mn.strURL == "string" && self.opts.imaState.chainProperties.mn.strURL.length > 0 @@ -185,7 +185,7 @@ class ObserverServer extends SocketServer { self.information( "Full init compete for in-worker IMA loop {} in {}", workerData.url, threadInfo.threadDescription() ); return joAnswer; - }; + } self.mapApiHandlers.spreadUpdatedSChainNetwork = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { self.initLogMethods(); @@ -195,9 +195,9 @@ class ObserverServer extends SocketServer { threadInfo.threadDescription(), joMessage.joSChainNetworkInfo, log.posNeg( joMessage.isFinal, "final", "partial" ) ); imaState.joSChainNetworkInfo = joMessage.joSChainNetworkInfo; - }; + } // eslint-disable-next-line dot-notation - self.mapApiHandlers["skale_imaNotifyLoopWork"] = + self.mapApiHandlers.skale_imaNotifyLoopWork = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { self.initLogMethods(); pwa.handleLoopStateArrived( // NOTICE: no await here, executed async diff --git a/src/main.ts b/src/main.ts index bb049ea8..63c3801b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -132,14 +132,14 @@ function parseCommandLine() { imaCLI.initContracts(); } if( imaState.bShowConfigMode ) { - // just show configuration values and exit + // just show configuration values and exit process.exit( 0 ); } } let gServerMonitoringWS: any = null; -function initMonitoringServer() : void { +function initMonitoringServer(): void { const imaState = state.get(); if( imaState.nMonitoringPort <= 0 ) return; @@ -219,9 +219,9 @@ function initMonitoringServer() : void { "nMonitoringPort" ]; - for( const param_name of arrRuntimeParamNames ) { - if( param_name in imaState ) - joAnswer.runtime_params[param_name] = imaState[param_name]; + for( const paramName of arrRuntimeParamNames ) { + if( paramName in imaState ) + joAnswer.runtime_params[paramName] = imaState[paramName]; } } break; @@ -253,7 +253,7 @@ function initMonitoringServer() : void { let gExpressJsonRpcAppIMA: any = null; -function initJsonRpcServer() : void { +function initJsonRpcServer(): void { const imaState = state.get(); if( imaState.nJsonRpcPort <= 0 ) return; @@ -351,7 +351,7 @@ async function doTheJob() { for( idxAction = 0; idxAction < cntActions; ++idxAction ) { log.information( "{p}{p}", strLogPrefix, imaHelperAPIs.longSeparator ); const joAction = imaState.arrActions[idxAction]; - log.debug( "{p}Will execute action: {bright} ({} of {})" , + log.debug( "{p}Will execute action: {bright} ({} of {})", strLogPrefix, joAction.name, idxAction + 1, cntActions ); try { if( await joAction.fn() ) { @@ -380,9 +380,9 @@ async function doTheJob() { function handleFirstSChainDiscoveryAttemptDone( err: any, joSChainNetworkInfo: any, - isSilentReDiscovery: boolean, fnOnPeriodicDiscoveryResultAvailable: any ) : void { + isSilentReDiscovery: boolean, fnOnPeriodicDiscoveryResultAvailable: any ): void { if( err ) { - // error information is printed by discoveryTools.discoverSChainNetwork() + // error information is printed by discoveryTools.discoverSChainNetwork() process.exit( 166 ); } log.success( "S-Chain network was discovered: {}", joSChainNetworkInfo ); @@ -424,7 +424,7 @@ async function main() { ? false : imaState.joSChainDiscovery.isSilentReDiscovery; const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ) { loop.spreadUpdatedSChainNetwork( isFinal ); - }; + } if( imaState.bSignMessages ) { if( imaState.strPathBlsGlue.length == 0 ) { log.fatal( "Please specify {} command line parameter.", "--bls-glue" ); @@ -445,16 +445,16 @@ async function main() { } const nCountToWait = -1; discoveryTools.discoverSChainNetwork( - function( err: Error|string, joSChainNetworkInfo: any ) { - handleFirstSChainDiscoveryAttemptDone( - err, joSChainNetworkInfo, isSilentReDiscovery, - fnOnPeriodicDiscoveryResultAvailable ); - doTheJob(); - // Finish of IMA Agent startup, - // everything else is in async calls executed later - return 0; - }, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait - ).catch( function( err: Error|string ) { + function( err: Error | string, joSChainNetworkInfo: any ) { + handleFirstSChainDiscoveryAttemptDone( + err, joSChainNetworkInfo, isSilentReDiscovery, + fnOnPeriodicDiscoveryResultAvailable ); + doTheJob(); + // Finish of IMA Agent startup, + // everything else is in async calls executed later + return 0; + }, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait + ).catch( function( err: Error | string ) { const strError = owaspUtils.extractErrorMessage( err ); log.critical( "S-Chain network discovery failed: {err}", strError ); doTheJob(); @@ -464,9 +464,9 @@ async function main() { discoveryTools.doPeriodicSChainNetworkDiscoveryIfNeeded( isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ); doTheJob(); - // Finish of IMA Agent startup, - // everything else is in async calls executed later, - // skip exit here to avoid early termination while tasks ase still running + // Finish of IMA Agent startup, + // everything else is in async calls executed later, + // skip exit here to avoid early termination while tasks ase still running } } diff --git a/src/observer.ts b/src/observer.ts index 6b91c955..ad50c360 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -39,7 +39,7 @@ export function findSChainIndexInArrayByName( arrSChains: any[], strSChainName: let gConnectedChainsData: any = null; -export function autoUpdateLastCachedSChains() : boolean { +export function autoUpdateLastCachedSChains(): boolean { const imaState = state.get(); if( ! imaState.optsS2S.strNetworkBrowserPath ) return false; @@ -60,26 +60,26 @@ export function autoUpdateLastCachedSChains() : boolean { return true; } -export function getLastCachedSChains() : any[] { +export function getLastCachedSChains(): any[] { autoUpdateLastCachedSChains(); if( ! gConnectedChainsData ) return []; return JSON.parse( JSON.stringify( gConnectedChainsData.schains ) ); } -export function pickRandomSChainNodeIndex( joSChain: any ) : number { +export function pickRandomSChainNodeIndex( joSChain: any ): number { let min = 0, max = joSChain.nodes.length - 1; min = Math.ceil( min ); max = Math.floor( max ); const idxNode = Math.floor( Math.random() * ( max - min + 1 ) ) + min; return idxNode; } -export function pickRandomSChainNode( joSChain: any ) : any { +export function pickRandomSChainNode( joSChain: any ): any { const idxNode = pickRandomSChainNodeIndex( joSChain ); return joSChain.nodes[idxNode]; } -export function pickRandomSChainUrl( joSChain: any ) : string { +export function pickRandomSChainUrl( joSChain: any ): string { const joNode = pickRandomSChainNode( joSChain ); return "" + joNode.endpoints.ip.http; } diff --git a/src/oracle.ts b/src/oracle.ts index eb9561ef..441486a7 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -38,7 +38,7 @@ const gBigNum2: any = owaspUtils.toBN( 2 ); const gBigNum256: any = owaspUtils.toBN( 256 ); const gBigNumUpperPart: any = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); -function getUtcTimestampString( d?: Date ) : string { +function getUtcTimestampString( d?: Date ): string { d = d || new Date(); // use now time if d is not specified const nUtcUnixTimeStampWithMilliseconds = d.getTime(); const t = "" + nUtcUnixTimeStampWithMilliseconds; @@ -91,7 +91,7 @@ async function handleOracleCheckResultResult( if( isVerboseTraceDetails ) details.error( "Bad unexpected result in oracle_checkResult" ); await joCall.disconnect(); - return; + return } const joResult: any = JSON.parse( joOut.result ); if( isVerboseTraceDetails ) @@ -139,7 +139,7 @@ async function handleOracleSubmitRequestResult( details.debug( "RPC call(oracle_checkResult) is {}", joIn ); } gp = null; - joOut= await joCall.call( joIn ); + joOut = await joCall.call( joIn ); gp = await handleOracleCheckResultResult( oracleOpts, details, isVerboseTraceDetails, joCall, joIn, joOut ); if( gp ) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 54c200ee..5c8db2bc 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -34,7 +34,6 @@ import * as fs from "fs"; import * as ethereumJsUtilModule from "ethereumjs-util"; import * as ethereumJsWalletModule from "ethereumjs-wallet"; const Wallet = ethereumJsWalletModule.default; -const BN = ethereumJsUtilModule.BN; const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; @@ -43,7 +42,7 @@ const extractErrorMessage = log.extractErrorMessage; export { ethersMod, safeURL, replaceAll, extractErrorMessage, BigNumber }; -export function rxIsInt( val: any ) : boolean { +export function rxIsInt( val: any ): boolean { try { const intRegex = /^-?\d+$/; if( !intRegex.test( val ) ) @@ -56,7 +55,7 @@ export function rxIsInt( val: any ) : boolean { return false; } -export function rxIsFloat( val: any ) : boolean { +export function rxIsFloat( val: any ): boolean { try { const floatRegex = /^-?\d+(?:[.,]\d*?)?$/; if( !floatRegex.test( val ) ) @@ -70,7 +69,7 @@ export function rxIsFloat( val: any ) : boolean { return false; } -export function parseIntOrHex( s: any ) : number { +export function parseIntOrHex( s: any ): number { if( typeof s != "string" ) return parseInt( s ); s = s.trim(); @@ -79,7 +78,7 @@ export function parseIntOrHex( s: any ) : number { return parseInt( s, 10 ); } -export function validateRadix( value: any, radix?: any ) : boolean { +export function validateRadix( value: any, radix?: any ): boolean { value = "" + ( value ? value.toString() : "10" ); value = value.trim(); radix = ( radix == null || radix == undefined ) @@ -89,7 +88,7 @@ export function validateRadix( value: any, radix?: any ) : boolean { return radix; } -export function validateInteger( value: any, radix?: any ) : boolean { +export function validateInteger( value: any, radix?: any ): boolean { try { value = "" + value; value = value.trim(); @@ -106,7 +105,7 @@ export function validateInteger( value: any, radix?: any ) : boolean { return false; } -export function toInteger( value: any, radix?: any ) : number { +export function toInteger( value: any, radix?: any ): number { try { radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) @@ -117,7 +116,7 @@ export function toInteger( value: any, radix?: any ) : number { return 0; } -export function validateFloat( value: any ) : boolean { +export function validateFloat( value: any ): boolean { try { const f = parseFloat( value ); if( isNaN( f ) ) @@ -128,7 +127,7 @@ export function validateFloat( value: any ) : boolean { return false; } -export function toFloat( value: any ) : number { +export function toFloat( value: any ): number { try { const f = parseFloat( value ); return f; @@ -137,14 +136,14 @@ export function toFloat( value: any ) : number { return 0.0; } -export function validateURL( s: any ) : boolean { +export function validateURL( s: any ): boolean { const url = toURL( s ); if( url == null ) return false; return true; } -export function toURL( s: any ) : URL | null { +export function toURL( s: any ): URL | null { try { if( s == null || s == undefined ) return null; @@ -161,7 +160,7 @@ export function toURL( s: any ) : URL | null { const objURL = toURL( ss ); if( objURL != null && objURL != undefined ) { const anyURL: any = objURL; - anyURL["strStrippedStringComma"] = sc; + anyURL.strStrippedStringComma = sc; } return objURL; } @@ -173,14 +172,14 @@ export function toURL( s: any ) : URL | null { if( objURL.hostname.length === 0 ) return null; const anyURL: any = objURL; - anyURL["strStrippedStringComma"] = null; + anyURL.strStrippedStringComma = null; return objURL; } catch ( err ) { return null; } } -export function toStringURL( s?: any, defValue?: string ) : string { +export function toStringURL( s?: any, defValue?: string ): string { defValue = defValue || ""; try { const url = toURL( s ); @@ -192,7 +191,7 @@ export function toStringURL( s?: any, defValue?: string ) : string { } } -export function isUrlHTTP( strURL?: any ) : boolean { +export function isUrlHTTP( strURL?: any ): boolean { try { if( !validateURL( strURL ) ) return false; @@ -204,7 +203,7 @@ export function isUrlHTTP( strURL?: any ) : boolean { return false; } -export function isUrlWS( strURL?: any ) : boolean { +export function isUrlWS( strURL?: any ): boolean { try { if( !validateURL( strURL ) ) return false; @@ -216,7 +215,7 @@ export function isUrlWS( strURL?: any ) : boolean { return false; } -export function toBoolean( value?: any ) : boolean { +export function toBoolean( value?: any ): boolean { let b = false; try { if( typeof value === "boolean" ) @@ -237,11 +236,11 @@ export function toBoolean( value?: any ) : boolean { return b; } -export function validateInputAddresses( address?: any ) : boolean { +export function validateInputAddresses( address?: any ): boolean { return ( /^(0x){1}[0-9a-fA-F]{40}$/i.test( address ) ); } -export function validateEthAddress( value?: any ) : boolean { +export function validateEthAddress( value?: any ): boolean { try { if( validateInputAddresses( ensureStartsWith0x( value ) ) ) return true; @@ -250,7 +249,7 @@ export function validateEthAddress( value?: any ) : boolean { return false; } -export function validateEthPrivateKey( value?: any ) : boolean { +export function validateEthPrivateKey( value?: any ): boolean { try { const ethersWallet = new ethersMod.ethers.Wallet( ensureStartsWith0x( value ) ); if( ethersWallet.address ) @@ -260,7 +259,7 @@ export function validateEthPrivateKey( value?: any ) : boolean { return false; } -export function toEthAddress( value?: any, defValue?: string ) : string { +export function toEthAddress( value?: any, defValue?: string ): string { try { value = "" + ( value ? ensureStartsWith0x( value.toString() ) : "" ); defValue = defValue || ""; @@ -271,7 +270,7 @@ export function toEthAddress( value?: any, defValue?: string ) : string { return value; } -export function toEthPrivateKey( value?: any, defValue?: string ) : string { +export function toEthPrivateKey( value?: any, defValue?: string ): string { try { value = "" + ( value ? value.toString() : "" ); defValue = defValue || ""; @@ -282,7 +281,7 @@ export function toEthPrivateKey( value?: any, defValue?: string ) : string { return value; } -export function verifyArgumentWithNonEmptyValue( joArg?: any ) : any { +export function verifyArgumentWithNonEmptyValue( joArg?: any ): any { if( ( !joArg.value ) || ( typeof joArg.value === "string" && joArg.value.length === 0 ) ) { console.log( log.fmtFatal( "(OWASP) Value {} of argument {} must not be empty", joArg.value, joArg.name ) ); @@ -291,7 +290,7 @@ export function verifyArgumentWithNonEmptyValue( joArg?: any ) : any { return joArg; } -export function verifyArgumentIsURL( joArg?: any ) : any { +export function verifyArgumentIsURL( joArg?: any ): any { try { verifyArgumentWithNonEmptyValue( joArg ); const url = toURL( joArg.value ); @@ -313,7 +312,7 @@ export function verifyArgumentIsURL( joArg?: any ) : any { } } -export function verifyArgumentIsInteger( joArg?: any ) : any { +export function verifyArgumentIsInteger( joArg?: any ): any { try { verifyArgumentWithNonEmptyValue( joArg ); if( !validateInteger( joArg.value ) ) { @@ -330,7 +329,7 @@ export function verifyArgumentIsInteger( joArg?: any ) : any { } } -export function verifyArgumentIsIntegerIpPortNumber( joArg: any ) : any { +export function verifyArgumentIsIntegerIpPortNumber( joArg: any ): any { try { verifyArgumentIsInteger( joArg ); if( joArg.value < 0 ) @@ -347,7 +346,7 @@ export function verifyArgumentIsIntegerIpPortNumber( joArg: any ) : any { } } -export function verifyArgumentIsPathToExistingFile( joArg?: any ) : any { +export function verifyArgumentIsPathToExistingFile( joArg?: any ): any { try { verifyArgumentWithNonEmptyValue( joArg ); const stats = fs.lstatSync( joArg.value ); @@ -369,7 +368,7 @@ export function verifyArgumentIsPathToExistingFile( joArg?: any ) : any { } } -export function verifyArgumentIsPathToExistingFolder( joArg?: any ) : any { +export function verifyArgumentIsPathToExistingFolder( joArg?: any ): any { try { verifyArgumentWithNonEmptyValue( joArg ); const stats = fs.lstatSync( joArg.value ); @@ -391,7 +390,7 @@ export function verifyArgumentIsPathToExistingFolder( joArg?: any ) : any { } } -export function verifyArgumentIsArrayOfIntegers( joArg?: any ) : any { +export function verifyArgumentIsArrayOfIntegers( joArg?: any ): any { try { verifyArgumentWithNonEmptyValue( joArg ); if( joArg.value.length < 3 ) { @@ -428,7 +427,7 @@ export function verifyArgumentIsArrayOfIntegers( joArg?: any ) : any { } } -export function ensureStartsWith0x( s?: any ) : string { +export function ensureStartsWith0x( s?: any ): string { if( s == null || s == undefined || typeof s !== "string" ) return s; if( s.length < 2 ) @@ -438,7 +437,7 @@ export function ensureStartsWith0x( s?: any ) : string { return "0x" + s; } -export function removeStarting0x( s?: any ) : string { +export function removeStarting0x( s?: any ): string { if( s == null || s == undefined || typeof s !== "string" ) return s; if( s.length < 2 ) @@ -448,7 +447,7 @@ export function removeStarting0x( s?: any ) : string { return s; } -export function inetNtoA( n: number ) : string { +export function inetNtoA( n: number ): string { const a = ( ( n >> 24 ) & 0xFF ) >>> 0; const b = ( ( n >> 16 ) & 0xFF ) >>> 0; const c = ( ( n >> 8 ) & 0xFF ) >>> 0; @@ -456,11 +455,11 @@ export function inetNtoA( n: number ) : string { return ( a + "." + b + "." + c + "." + d ); } -export function ipFromHex( hex?: any ) : string { +export function ipFromHex( hex?: any ): string { return inetNtoA( parseInt( removeStarting0x( hex ), 16 ) ); } -export function cloneObjectByRootKeys( joIn?: any ) : any { +export function cloneObjectByRootKeys( joIn?: any ): any { const joOut: any = { }, arrKeys = Object.keys( joIn ); for( let i = 0; i < arrKeys.length; ++ i ) { const key = arrKeys[i]; @@ -472,7 +471,7 @@ export function cloneObjectByRootKeys( joIn?: any ) : any { // example: "1ether" -> "1000000000000000000" // supported suffix aliases, lowercase -const gMapMoneyNameSuffixAliases : any = { +const gMapMoneyNameSuffixAliases: any = { "ethe": "ether", "ethr": "ether", "eth": "ether", @@ -546,7 +545,7 @@ const gMapMoneyNameSuffixAliases : any = { "tether": "tether" }; -export function parseMoneyUnitName( s: string ) : string { +export function parseMoneyUnitName( s: string ): string { s = s.trim().toLowerCase(); if( s == "" ) return "wei"; @@ -557,7 +556,7 @@ export function parseMoneyUnitName( s: string ) : string { return s; } -function moneyUnitNameToEthersParseSpec( s: string ) : string|number { +function moneyUnitNameToEthersParseSpec( s: string ): string | number { switch ( s.toString().trim().toLowerCase() ) { case "shannon": return 9; case "lovelace": return 6; @@ -575,7 +574,7 @@ function moneyUnitNameToEthersParseSpec( s: string ) : string|number { return s; } -function moneyUnitNameToPostDivider( s: string ) : string|null { +function moneyUnitNameToPostDivider( s: string ): string | null { switch ( s.toString().trim().toLowerCase() ) { case "femtoether": return "1000000000000000"; case "picoether": return "1000000000000"; @@ -585,7 +584,7 @@ function moneyUnitNameToPostDivider( s: string ) : string|null { } return null; } -function moneyUnitNameToPostMultiplier( s: string ) : string|null { +function moneyUnitNameToPostMultiplier( s: string ): string | null { switch ( s.toString().trim().toLowerCase() ) { case "kether": return "1000"; case "mether": return "1000000"; @@ -595,7 +594,7 @@ function moneyUnitNameToPostMultiplier( s: string ) : string|null { return null; } -export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ) : string { +export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ): string { try { isThrowException = ( !!isThrowException ); if( s == null || s == undefined ) { @@ -612,12 +611,12 @@ export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ) : str ) { strNumber += chr; s = s.substr( 1 ); // remove first character - continue; + continue } if( chr == " " || chr == "\t" || chr == "\r" || chr == "\n" ) s = s.substr( 1 ); // remove first character s = s.trim().toLowerCase(); - break; + break } // here s is rest suffix string, number is number as string or empty string if( strNumber == "" ) @@ -633,7 +632,7 @@ export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ) : str s = s.mul( toBN( mlr ) ); s = s.toString(); return s; - } catch ( err ) { + } catch ( err: any ) { if( isThrowException ) { throw new Error( `Parse error in parseMoneySpecToWei( ${s} ), ` + `error is: ${err}` ); @@ -642,7 +641,7 @@ export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ) : str return "0"; } -export function computeChainIdFromSChainName( strName: string ) : string { +export function computeChainIdFromSChainName( strName: string ): string { let h = ethersMod.ethers.utils.id( strName ); h = removeStarting0x( h ).toLowerCase(); while( h.length < 64 ) @@ -651,12 +650,12 @@ export function computeChainIdFromSChainName( strName: string ) : string { return ensureStartsWith0x( h ); } -export function privateKeyToAccountAddress( keyPrivate: string ) : string { +export function privateKeyToAccountAddress( keyPrivate: string ): string { return ethersMod.ethers.utils.computeAddress( ensureStartsWith0x( keyPrivate ) ); } -export function privateKeyToPublicKey( keyPrivate: string ) : string { +export function privateKeyToPublicKey( keyPrivate: string ): string { const privateKeyBuffer = ethereumJsUtilModule.toBuffer( ensureStartsWith0x( keyPrivate ) ); const wallet = Wallet.fromPrivateKey( privateKeyBuffer ); @@ -664,13 +663,13 @@ export function privateKeyToPublicKey( keyPrivate: string ) : string { return removeStarting0x( publicKey ); } -export function publicKeyToAccountAddress( keyPublic : string ) : string { +export function publicKeyToAccountAddress( keyPublic: string ): string { const hash = ethersMod.ethers.utils.keccak256( ensureStartsWith0x( keyPublic ) ); const strAddress = ensureStartsWith0x( hash.substr( hash.length - 40 ) ); return strAddress; } -export function fnAddressImpl_( anyThis: any ) : string { +export function fnAddressImpl_( anyThis: any ): string { if( anyThis.address_ == undefined || anyThis.address_ == null || anyThis.address_ == "" ) { if( anyThis.privateKey ) anyThis.address_ = "" + privateKeyToAccountAddress( anyThis.privateKey ); @@ -678,10 +677,10 @@ export function fnAddressImpl_( anyThis: any ) : string { return anyThis.address_; } -export function getEthersProviderFromURL( strURL: URL|string ) - :ethersMod.ethers.providers.JsonRpcProvider { +export function getEthersProviderFromURL( + strURL: URL | string ): ethersMod.ethers.providers.JsonRpcProvider { const url = new URL( strURL.toString() ); - let userName:string|null = null, userPwd:string|null = null; + let userName: string | null = null, userPwd: string | null = null; if( url.username ) { userName = url.username; userPwd = url.password; @@ -704,9 +703,9 @@ export function getEthersProviderFromURL( strURL: URL|string ) } export function ethersProviderToUrl( - ethersProvider: ethersMod.ethers.providers.JsonRpcProvider|null - ) : string { - let strURL: string|null = null; + ethersProvider: ethersMod.ethers.providers.JsonRpcProvider | null +): string { + let strURL: string | null = null; if( ethersProvider && "connection" in ethersProvider && typeof ethersProvider.connection == "object" && "url" in ethersProvider.connection && typeof ethersProvider.connection.url == "string" @@ -715,67 +714,70 @@ export function ethersProviderToUrl( return strURL || "N/A-URL"; } -export function isHexPrefixed( s: any ) : boolean { - if( typeof s !== "string" ) +export function isHexPrefixed( s: any ): boolean { + if( typeof s !== "string" ) { throw new Error( "Parameter value of owaspUtils.isHexPrefixed() must be type 'string' but it's " + `type ${typeof s}, while checking isHexPrefixed.` ); + } return ( s.slice( 0, 2 ) === "0x" ) ? true : false; } -export function stripHexPrefix( s: any ) : string { +export function stripHexPrefix( s: any ): string { if( typeof s !== "string" ) return s; return isHexPrefixed( s ) ? s.slice( 2 ) : s; } -export function toBNbasic( x?: any, optionalRadix?: number ) : any { +export function toBNbasic( x?: any, optionalRadix?: number ): any { try { if( optionalRadix && typeof optionalRadix == "number" && optionalRadix == 16 ) x = ensureStartsWith0x( x ); const bn = ethersMod.ethers.BigNumber.from( x ); return bn; - } catch( err ) { + } catch ( err: any ) { console.log( `CRITICAL ERROR: Failure in owaspUtils.toBNbasic( ${x} ): ${err}` ); throw err; } } -export function toBN( arg: any ) : any { - if( typeof arg === 'string' || typeof arg === "number" ) { +export function toBN( arg: any ): any { + if( typeof arg === "string" || typeof arg === "number" ) { let multiplier = toBNbasic( 1 ); // eslint-disable-line - let formattedString = String( arg ).toLowerCase().trim(); - let isHexPrefixed = formattedString.substr(0, 2) === "0x" || formattedString.substr(0, 3) === "-0x"; + const formattedString = String( arg ).toLowerCase().trim() + const isHexPrefixed = + formattedString.substr( 0, 2 ) === "0x" || + formattedString.substr( 0, 3 ) === "-0x" let stringArg = stripHexPrefix(formattedString); // eslint-disable-line - if( stringArg.substr(0, 1) === "-" ) { - stringArg = stripHexPrefix(stringArg.slice(1)); + if( stringArg.substr( 0, 1 ) === "-" ) { + stringArg = stripHexPrefix( stringArg.slice( 1 ) ) multiplier = toBNbasic( -1, 10 ); } stringArg = stringArg === "" ? "0" : stringArg; - if( ( ! stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/) ) - || stringArg.match(/^[a-fA-F]+$/) - || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/)) ) - return toBNbasic( stringArg, 16).mul(multiplier); - if( ( stringArg.match(/^-?[0-9]+$/) || stringArg === "" ) && isHexPrefixed === false ) + if( ( ! stringArg.match( /^-?[0-9]+$/ ) && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) || + stringArg.match( /^[a-fA-F]+$/ ) || + ( isHexPrefixed && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) ) + return toBNbasic( stringArg, 16 ).mul( multiplier ) + if( ( stringArg.match( /^-?[0-9]+$/ ) || stringArg === "" ) && !isHexPrefixed ) return toBNbasic( stringArg, 10 ).mul( multiplier ); - } else if( typeof arg === "object" && arg.toString && (!arg.pop && !arg.push) ) { - if( arg.toString().match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy) ) + } else if( typeof arg === "object" && arg.toString && ( !arg.pop && !arg.push ) ) { + if( arg.toString().match( /^-?[0-9]+$/ ) && ( arg.mul || arg.dividedToIntegerBy ) ) return toBNbasic( arg.toString(), 10 ); - } else if( arg ) { - return toBNbasic( arg ); // try to convert as is - } + } else if( arg ) + return toBNbasic( arg ) // try to convert as is + throw new Error( "Error in owaspUtils.toBN() while converting " + - `number ${JSON.stringify(arg)}to BN.js instance, error: ` + + `number ${JSON.stringify( arg )}to BN.js instance, error: ` + "invalid number value. Value must be an integer, hex string, BN or BigNumber instance. " + "Note, decimals are not supported." ); } -export function isNumeric( s?: any ) : boolean { +export function isNumeric( s?: any ): boolean { return /^\d+$/.test( s ); } -export function toHexStringSafe( val?: any ) : string { +export function toHexStringSafe( val?: any ): string { if( ! val ) return "0x0"; if( "toHexString" in val && typeof val.toHexString == "function" ) @@ -787,7 +789,7 @@ export function toHexStringSafe( val?: any ) : string { return "" + val; } -export function setInterval2( fn: any, t: number, stepMilliSeconds?: number ) : any { +export function setInterval2( fn: any, t: number, stepMilliSeconds?: number ): any { const iv: any = { real_iv: null, stepMilliSeconds: stepMilliSeconds || 1000, @@ -804,7 +806,7 @@ export function setInterval2( fn: any, t: number, stepMilliSeconds?: number ) : return iv; } -export function clearInterval2( iv: any ) : void { +export function clearInterval2( iv: any ): void { if( ! iv ) return; if( ! ( "real_iv" in iv ) ) @@ -815,7 +817,6 @@ export function clearInterval2( iv: any ) : void { iv.real_iv = null; } -export function escapeShell( cmd: string ) : string { - return "\"" + cmd.replace( /(["'$`\\])/g,"\\$1" ) + "\""; +export function escapeShell( cmd: string ): string { + return "\"" + cmd.replace( /(["'$`\\])/g, "\\$1" ) + "\""; } - diff --git a/src/package.json b/src/package.json index e9469e5a..84776503 100644 --- a/src/package.json +++ b/src/package.json @@ -7,8 +7,8 @@ "build": "./node_modules/typescript/bin/tsc", "rebuild": "yarn clean-build && yarn build", "clean-build": "rm -rf ./src/build/* || true", - "lint-check": "eslint ./*.*js", - "lint-fix": "eslint ./*.*js --fix", + "lint-check": "eslint -c .eslintrc.cjs ./*.ts", + "lint-fix": "eslint -c .eslintrc.cjs ./*.ts --fix", "check-outdated": "yarn outdated", "upgrade-to-latest": "yarn upgrade --latest" }, @@ -39,13 +39,15 @@ }, "devDependencies": { "eslint": "^8.53.0", + "eslint-config-standard-with-typescript": "^39.1.1", "eslint-config-standard": "^17.1.0", "eslint-plugin-import": "^2.29.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^6.1.1", "eslint-plugin-standard": "^4.0.1", "eslint-plugin-n": "^16.3.0", - "typescript": "^5.3.3" + "typescript": "^5.3.3", + "@typescript-eslint/eslint-plugin": "^6.14.0" }, "resolutions": { } diff --git a/src/pwa.ts b/src/pwa.ts index f7ae8a33..d9c76bae 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -28,7 +28,7 @@ import * as rpcCall from "./rpcCall.js"; import * as imaBLS from "./bls.js"; import * as imaUtils from "./utils.js"; -function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ) : number[] { +function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): number[] { if( nNodesCount <= 1 ) return []; // PWA is N/A if( !( nNodeNumber >= 0 && nNodeNumber < nNodesCount ) ) @@ -48,7 +48,7 @@ function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ) : nu return arrWalkNodeIndices; } -export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType: string ) : boolean { +export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType: string ): boolean { if( ! strLoopWorkType ) return false; switch ( strLoopWorkType.toString().toLowerCase() ) { @@ -61,7 +61,7 @@ export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType: string ) : bo return false; } -function composeEmptyStateForPendingWorkAnalysis() : any { +function composeEmptyStateForPendingWorkAnalysis(): any { return { "oracle": { "isInProgress": false, "ts": 0 }, "m2s": { "isInProgress": false, "ts": 0 }, @@ -112,8 +112,8 @@ export async function checkOnLoopStart( } const nUtcUnixTimeStamp = Math.floor( ( new Date() ).getTime() / 1000 ); for( let i = 0; i < arrWalkNodeIndices.length; ++i ) { - const walk_node_index = arrWalkNodeIndices[i]; - const joNode: any = jarrNodes[walk_node_index]; + const walkNodeIndex = arrWalkNodeIndices[i]; + const joNode: any = jarrNodes[walkNodeIndex]; const joProps: any = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); if( joProps && typeof joProps == "object" && "isInProgress" in joProps && joProps.isInProgress && @@ -125,15 +125,15 @@ export async function checkOnLoopStart( log.warning( "PWA busy state timeout for node #{}, old timestamp is {}, current " + "system timestamp is {}, duration {} is greater than conditionally " + - "allowed {} and exceeded by {} second(s)", walk_node_index, joProps.ts, + "allowed {} and exceeded by {} second(s)", walkNodeIndex, joProps.ts, nUtcUnixTimeStamp, d, imaState.nTimeoutSecondsPWA, d - imaState.nTimeoutSecondsPWA ); }; joProps.isInProgress = false; joProps.ts = 0; - continue; + continue } - arrBusyNodeIndices.push( walk_node_index ); + arrBusyNodeIndices.push( walkNodeIndex ); } } if( arrBusyNodeIndices.length > 0 ) { @@ -240,7 +240,7 @@ async function notifyOnLoopImpl( const strNodeURL = imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ); const rpcCallOpts: any = null; let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) - .catch( async function( err: Error|string ) { + .catch( async function( err: Error | string ) { log.error( "PWA failed to perform] loop-{} notification RPC call to node #{} with " + "URL {url}, error is: {err}", se, i, strNodeURL, err ); @@ -275,10 +275,12 @@ async function notifyOnLoopImpl( return true; } -export async function notifyOnLoopStart( imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { +export async function notifyOnLoopStart( + imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { return await notifyOnLoopImpl( imaState, strLoopWorkType, true, nIndexS2S ); } -export async function notifyOnLoopEnd( imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { +export async function notifyOnLoopEnd( + imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { return await notifyOnLoopImpl( imaState, strLoopWorkType, false, nIndexS2S ); } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 9bc04939..c0b15dca 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -34,7 +34,7 @@ const gSecondsConnectionTimeout = 60; export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any ) { fnDone = fnDone || async function( nStep: number ) {}; - fnDone = fnStep || async function( nStep: number ) { return true; }; + fnDone = fnStep || async function( nStep: number ) { return true; } let nStep = 0; const promiseComplete = new Promise( function( resolve, reject ) { let isInsideAsyncHandler = false; @@ -56,7 +56,7 @@ export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any } } isInsideAsyncHandler = false; - }; + } const iv = setInterval( function() { if( isInsideAsyncHandler ) return; @@ -100,7 +100,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { wsConn.close(); doReconnectWsStep( joCall, opts ); } ); - joCall.wsConn.on( "message", async function incoming( data: any ) { + joCall.wsConn.on( "message", async function incoming( data: any ) { const joOut = JSON.parse( data ); if( joOut.id in joCall.mapPendingByCallID ) { const entry = joCall.mapPendingByCallID[joOut.id]; @@ -138,7 +138,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { const err = new Error( strWsError ); if( fn ) await fn( joCall, err ); - return; + return } } if( fn ) @@ -159,7 +159,7 @@ export async function doConnectIfNeeded( joCall: any, opts: any, fn: any ) { } if( isUrlWS( joCall.url ) && ( !joCall.wsConn ) ) { await joCall.reconnect( fn ); - return; + return } if( fn ) await fn( joCall, null ); @@ -178,7 +178,7 @@ async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { doConnect( joCall, opts, async function( joCall: any, err: any ) { if( err ) { doReconnectWsStep( joCall, opts ); - return; + return } if( fn ) await fn( joCall, null ); @@ -228,9 +228,8 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { return; } const strBody = JSON.stringify( joIn ); - let errCall: string|null = null, joOut: any = null; - if( joCall.joRpcOptions && - joCall.joRpcOptions.cert && typeof joCall.joRpcOptions.cert == "string" && + let errCall: string | null = null, joOut: any = null; + if( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" && joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" ) { const u = new URL( joCall.url ); @@ -242,13 +241,13 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { "headers": { "Content-Type": "application/json" }, - "ca": ( joCall.joRpcOptions && joCall.joRpcOptions.ca && + "ca": ( joCall.joRpcOptions?.ca && typeof joCall.joRpcOptions.ca == "string" ) ? joCall.joRpcOptions.ca : null, - "cert": ( joCall.joRpcOptions && joCall.joRpcOptions.cert && + "cert": ( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" ) ? joCall.joRpcOptions.cert : null, - "key": ( joCall.joRpcOptions && joCall.joRpcOptions.key && + "key": ( joCall.joRpcOptions?.key && typeof joCall.joRpcOptions.key == "string" ) ? joCall.joRpcOptions.key : null }; @@ -271,9 +270,9 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { joOut = JSON.parse( accumulatedBody ); errCall = null; resolve( joOut ); - } catch ( err ) { + } catch ( err: any ) { joOut = null; - errCall = "Response body parse error: " + err; + errCall = `Response body parse error: ${err}`; reject( errCall ); } } ); @@ -286,17 +285,17 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { } ); req.write( strBody ); req.end(); - } catch ( err ) { + } catch ( err: any ) { log.error( "{url} REST error {err}", joCall.url, err ); joOut = null; errCall = `HTTP(S)/RPC call(processing) error: ${err}`; reject( errCall ); } } ); - await promiseComplete.catch( function( err: Error|string ) { + await promiseComplete.catch( function( err: Error | string ) { log.error( "{url} HTTP call error {err}", joCall.url, err ); if( ! errCall ) - errCall = `HTTP(S)/RPC call(catch) error: ${err}`; + errCall = `HTTP(S)/RPC call(catch) error: ${err.toString()}`; } ); } else { try { @@ -311,27 +310,28 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { // "requestCert": true, "agent": false, "httpsAgent": false, - "ca": ( joCall.joRpcOptions && joCall.joRpcOptions.ca && + "ca": ( joCall.joRpcOptions?.ca && typeof joCall.joRpcOptions.ca == "string" ) ? joCall.joRpcOptions.ca : null, - "cert": ( joCall.joRpcOptions && joCall.joRpcOptions.cert && + "cert": ( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" ) ? joCall.joRpcOptions.cert : null, - "key": ( joCall.joRpcOptions && joCall.joRpcOptions.key && + "key": ( joCall.joRpcOptions?.key && typeof joCall.joRpcOptions.key == "string" ) ? joCall.joRpcOptions.key : null }; - const response = await urllib.request( joCall.url, requestOpts as urllib.RequestOptions ); + const response = + await urllib.request( joCall.url, requestOpts as urllib.RequestOptions ); const body = response.data.toString( "utf8" ); if( response && response.statusCode && response.statusCode !== 200 ) log.warning( "REST call status code is {}", response.statusCode ); joOut = JSON.parse( body ); errCall = null; - } catch ( err ) { + } catch ( err: any ) { log.error( "{url} request error {err}", joCall.url, err ); joOut = null; - errCall = "request error: " + err; + errCall = `request error: ${err}`; } } try { @@ -363,7 +363,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { "reconnect_if_needed": async function( fnAfter: any ) { await doConnectIfNeeded( joCall, opts, fnAfter ); }, - "call": function( joIn: any, fnAfter: any ) { + "call": async function( joIn: any, fnAfter: any ) { const self = this; const promiseComplete = new Promise( function( resolve: any, reject: any ) { self.reconnect_if_needed( async function( joCall: any, err: any ) { @@ -371,7 +371,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { if( fnAfter ) await fnAfter( joIn, null, err ); reject( err ); - return; + return } await doCall( joCall, joIn, async function( joIn: any, joOut: any, err: any ) { if( fnAfter ) @@ -380,13 +380,13 @@ export async function rpcCallCreate( strURL: string, opts: any ) { reject( err ); else resolve( joOut ); - } ).catch( function( err: Error|string ) { + } ).catch( function( err: Error | string ) { log.error( "{url} JSON RPC call(performer) error: {err}", strURL, err ); } ); } ); } ); - return promiseComplete.catch( function( err: Error|string ) { + return await promiseComplete.catch( function( err: Error | string ) { log.error( "{url} JSON RPC call(awaiter) error: {err}", strURL, err ); } ); @@ -471,9 +471,9 @@ export function getValidHostAndPort( s: any ) { const gStrTcpConnectionHeader: string = "TCP connection checker: "; -export function checkTcpPromise( strHost: string, nPort: number, nTimeoutMilliseconds: number, +export async function checkTcpPromise( strHost: string, nPort: number, nTimeoutMilliseconds: number, isLog?: boolean ) { - return new Promise( ( resolve, reject ) => { + return await new Promise( ( resolve, reject ) => { if( isLog ) { console.log( `${gStrTcpConnectionHeader}Will establish ` + @@ -542,8 +542,8 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec const promiseCompleteTcpCheck = checkTcpPromise( strHost, nPort, nTimeoutMilliseconds, isLog ) .then( function() { isOnline = true; } ) - .catch( function() { isOnline = false; } ) - ; + .catch( function() { isOnline = false; } ); + if( isLog ) { console.log( `${gStrTcpConnectionHeader}Waiting for ` + @@ -555,7 +555,7 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec `${gStrTcpConnectionHeader}TCP connection ` + `to ${strHost}:${nPort} check finished` ); } - } catch ( err ) { + } catch ( err: any ) { isOnline = false; console.log( `${gStrTcpConnectionHeader}TCP connection ` + @@ -564,7 +564,7 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec return isOnline; } -export async function checkUrl( u: URL|string, nTimeoutMilliseconds: number, isLog?: boolean ) { +export async function checkUrl( u: URL | string, nTimeoutMilliseconds: number, isLog?: boolean ) { if( ! u ) return false; const jo: any = getValidHostAndPort( u ); @@ -572,7 +572,7 @@ export async function checkUrl( u: URL|string, nTimeoutMilliseconds: number, isL console.log( `${gStrTcpConnectionHeader}Extracted from URL ${u.toString()} data ` + `fields are: ${JSON.stringify( jo )}` ); } - if( ! ( jo && jo.strHost && "nPort" in jo ) ) { + if( ! ( jo?.strHost && "nPort" in jo ) ) { console.log( `${gStrTcpConnectionHeader}Extracted from URL ${u.toString()} data ` + "fields are bad, returning \"false\" as result of TCP connection check" ); return false; diff --git a/src/socket.ts b/src/socket.ts index 920d8218..1759ed58 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -31,19 +31,19 @@ export let httpsModule: any = null; // server side only export let wsModule: any = null; // server side only export let webRtcModule: any = null; // server side only -export function setHttpsModule( mod: any ) : void { +export function setHttpsModule( mod: any ): void { httpsModule = mod ? mod : null; } -export function setWsModule( mod: any ) : void { +export function setWsModule( mod: any ): void { wsModule = mod ? mod : null; } -export function setWebRtcModule( mod: any ) : void { +export function setWebRtcModule( mod: any ): void { webRtcModule = mod ? mod : null; } export const gMapLocalServers: any = { }; // used both for local and in-worker servers -export const socketSentDataMarshall = function( data?: any ) : void { +export const socketSentDataMarshall = function( data?: any ): any { const s = data ? ( ( typeof data == "string" ) ? data @@ -51,8 +51,8 @@ export const socketSentDataMarshall = function( data?: any ) : void { ) : ""; return s; -}; -export const socketReceivedDataReverseMarshall = function( data?: any ) : object { +} +export const socketReceivedDataReverseMarshall = function( data?: any ): object { try { const jo: any = data ? ( ( typeof data == "object" ) @@ -81,7 +81,7 @@ export const updateSocketDataStatsForMessage = function( joMessage: any, joStats joStats[strMethod] ++; else joStats[strMethod] = 1; -}; +} export const generateSocketDataStatsJSON = function( jo: any ) { const joStats: any = {}; if( "arrPackedMessages" in jo && @@ -94,17 +94,17 @@ export const generateSocketDataStatsJSON = function( jo: any ) { } else updateSocketDataStatsForMessage( jo, joStats ); return joStats; -}; +} export class BasicServerAcceptor extends EventDispatcher { socketType: string; socketSubtype: string; isListening: boolean; - strEndPoint: string|null; + strEndPoint: string | null nextClientNumber: number; mapClients: any; url?: string; - constructor() { + constructor () { super(); this.socketType = "BasicAcceptor"; this.socketSubtype = "acceptor"; @@ -113,7 +113,7 @@ export class BasicServerAcceptor extends EventDispatcher { this.nextClientNumber = 1; this.mapClients = { }; } - dispose() : void { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -123,7 +123,7 @@ export class BasicServerAcceptor extends EventDispatcher { super.dispose(); } disposeNotifyClients() { - for( const [ keyWalk, entryWalk ] of Object.entries( this.mapClients ) ) { + for( const [ /*keyWalk*/, entryWalk ] of Object.entries( this.mapClients ) ) { const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { const pair: any = entry; @@ -154,7 +154,7 @@ export class BasicServerAcceptor extends EventDispatcher { flush() { if( this.isDisposing || this.isDisposed ) return; - for( const [ keyWalk, entryWalk ] of Object.entries( this.mapClients ) ) { + for( const [ /*keyWalk*/, entryWalk ] of Object.entries( this.mapClients ) ) { const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { const pair: any = entry; @@ -203,7 +203,7 @@ export class BasicSocketPipe extends EventDispatcher { clientPort: any; logicalInitComplete: any; // for external use errorLogicalInit: any; // for external use - constructor() { + constructor () { super(); this.socketType = "N/A"; this.socketSubtype = "N/A"; @@ -225,7 +225,7 @@ export class BasicSocketPipe extends EventDispatcher { super.dispose(); } disposeImpersonatedEntries() { // for external in-app usage only - for( const [ keyWalk, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { + for( const [ /*keyWalk*/, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { const entry: any = entryWalk; try { if( entry && "dispose" in entry && typeof entry.dispose == "function" ) @@ -265,7 +265,7 @@ export class BasicSocketPipe extends EventDispatcher { if( settings.logging.net.socket.send || settings.logging.net.socket.flush ) console.log( this.socketLoggingTextPrefix( "send+flush" ), data ); this.implSend( data ); - return; + return } isFlush = ( isFlush == undefined || isFlush == null ) ? true : ( !!( isFlush ) ); const jo: any = socketReceivedDataReverseMarshall( data ); @@ -380,7 +380,7 @@ export const isRunningInWorker = function() { if( self.document === undefined ) return true; return false; -}; +} // in-worker clients in connecting state export const gMapAwaitingInWorkerClients: Record < string, any > = { }; @@ -405,7 +405,7 @@ export const outOfWorkerAPIs: any = { case "inWorkerConnect": { if( !( jo.workerUUID in gMapAwaitingInWorkerClients ) ) return false; - const pipe: any = gMapAwaitingInWorkerClients[ "" + jo.workerUUID ]; + const pipe: any = gMapAwaitingInWorkerClients["" + jo.workerUUID] pipe.performSuccessfulConnection(); } return true; case "inWorkerDisconnect": { @@ -484,7 +484,7 @@ export const inWorkerAPIs: any = { export class InWorkerServerPipe extends BasicSocketPipe { fnSend: any; - constructor( acceptor: any, clientPort: string, fnSend: any ) { + constructor ( acceptor: any, clientPort: string, fnSend: any ) { super(); this.socketType = "InWorker"; this.socketSubtype = "server"; @@ -547,7 +547,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { fnSend: any; - constructor( strEndPoint: string, fnSend: any ) { + constructor ( strEndPoint: string, fnSend: any ) { super(); this.socketType = "InWorker"; this.strEndPoint = @@ -610,7 +610,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { worker: any; fnSend: any; strEndPoint: string; - constructor( strEndPoint: string, worker: any, fnSend?: any ) { + constructor ( strEndPoint: string, worker: any, fnSend?: any ) { super(); this.socketType = "InWorker"; this.socketSubtype = "client"; @@ -687,7 +687,7 @@ export class OutOfWorkerRelay extends EventDispatcher { fnCreateClient: any; onConnection_: any; // eslint-disable-next-line max-lines-per-function - constructor( + constructor ( strRelayName: string, acceptor: any, fnCreateClient: any, isAutoFlushIncoming: boolean, isAutoFlushOutgoing: boolean ) { super(); @@ -830,7 +830,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeOutgoing.send( joMessage ); if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); - }; + } let _onRelayPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" relay-client socket \"" + @@ -856,7 +856,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeOutgoing.send( joMessage ); if( self.isAutoFlushOutgoing ) pipeOutgoing.flush(); - }; + } _offAllPipeEventListeners = function() { if( _onExternalPipeClose ) { pipeIncoming.off( "close", _onExternalPipeClose ); @@ -888,7 +888,7 @@ export class OutOfWorkerRelay extends EventDispatcher { } pipeIncoming.disconnect(); pipeIncoming.dispose(); - }; + } pipeIncoming.on( "close", _onExternalPipeClose ); pipeIncoming.on( "error", _onExternalPipeError ); pipeIncoming.on( "message", _onExternalPipeMessage ); @@ -902,7 +902,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeOutgoing.on( "close", _onRelayPipeClose ); pipeOutgoing.on( "error", _onRelayPipeError ); pipeOutgoing.on( "message", _onRelayPipeMessage ); - }; + } self.acceptor.on( "connection", self.onConnection_ ); } dispose() { @@ -925,7 +925,7 @@ export class OneToOneRelay extends EventDispatcher { pipeIncoming: any; pipeOutgoing: any; // eslint-disable-next-line max-lines-per-function - constructor( + constructor ( strRelayName: string, pipeIncoming: any, pipeOutgoing: any, isAutoFlushIncoming: boolean, isAutoFlushOutgoing: boolean ) { @@ -1074,7 +1074,7 @@ export class OneToOneRelay extends EventDispatcher { pipeOutgoing.send( joMessage ); if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); - }; + } let _onOutgoingPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( @@ -1107,7 +1107,7 @@ export class OneToOneRelay extends EventDispatcher { pipeIncoming.send( joMessage ); if( self.isAutoFlushOutgoing ) pipeIncoming.flush(); - }; + } _offAllPipeEventListeners = function() { if( _onIncomingPipeClose ) { pipeIncoming.off( "close", _onIncomingPipeClose ); @@ -1139,7 +1139,7 @@ export class OneToOneRelay extends EventDispatcher { } pipeIncoming.disconnect(); pipeIncoming.dispose(); - }; + } pipeIncoming.on( "close", _onIncomingPipeClose ); pipeIncoming.on( "error", _onIncomingPipeError ); pipeIncoming.on( "message", _onIncomingPipeMessage ); @@ -1170,7 +1170,7 @@ export class DirectPipe extends BasicSocketPipe { strEndPoint: string; clientPort: number; url: string; - constructor( counterPipe: any, isBroadcastOpenEvents: boolean ) { + constructor ( counterPipe: any, isBroadcastOpenEvents: boolean ) { super(); isBroadcastOpenEvents = ( !!isBroadcastOpenEvents ); this.socketType = "Direct"; @@ -1229,7 +1229,7 @@ export class DirectPipe extends BasicSocketPipe { this.url = ""; } implSend( data: any ) { - if( ( !this.isConnected ) || ( !this.counterPipe ) || ( !this.counterPipe.isConnected ) ) { + if( ( !this.isConnected ) || ( !this.counterPipe?.isConnected ) ) { const s = "Cannot send messages to disconnected local server pipe"; this.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); @@ -1268,7 +1268,7 @@ export class LocalSocketServerPipe extends DirectPipe { export class LocalSocketServerAcceptor extends BasicServerAcceptor { nextClientPort: number; - constructor( strEndPoint: string ) { + constructor ( strEndPoint: string ) { super(); this.socketType = "Local"; this.nextClientPort = 1; @@ -1366,7 +1366,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { _onWsError: any; _onWsMessage: any; _removeWsEventListeners: any; - constructor( acceptor: any, wsConnection: any, remoteAddress: string ) { + constructor ( acceptor: any, wsConnection: any, remoteAddress: string ) { super(); this.socketType = "WS"; this.socketSubtype = "server"; @@ -1382,14 +1382,14 @@ export class WebSocketServerPipe extends BasicSocketPipe { this._onWsClose = function() { self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self } ) ); - }; + } this._onWsError = function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": self, "message": event } ) ); - }; + } this._onWsMessage = function( event: any ) { self.receive( event.data ); - }; + } this._removeWsEventListeners = function() { if( self._onWsClose ) { wsConnection.removeEventListener( "close", self._onWsClose ); @@ -1478,7 +1478,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { export class WebSocketServerAcceptor extends BasicServerAcceptor { wsServer: any; httpsModule: any; - constructor( nTcpPort: null, key?: string, cert?: string ) { + constructor ( nTcpPort: null, key?: string, cert?: string ) { super(); this.socketType = "WS"; this.wsServer = null; @@ -1522,9 +1522,9 @@ export class WebSocketClientPipe extends BasicSocketPipe { _onWsClose: any; _onWsError: any; _onWsMessage: any; - urlWS: string|null; + urlWS: string | null _removeWsEventListeners: any; - constructor( url: string|URL|null ) { + constructor ( url: string | URL | null ) { super(); this.socketType = "WS"; this.socketSubtype = "client"; @@ -1587,24 +1587,24 @@ export class WebSocketClientPipe extends BasicSocketPipe { self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); - }; + } this._onWsClose = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": self, "message": event } ) ); - }; + } this._onWsError = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { "socket": self, "message": event } ) ); - }; + } this._onWsMessage = function( event: any ) { self.receive( event.data ); - }; + } this._removeWsEventListeners = function() { if( self._onWsOpen ) { self.wsConnection.removeEventListener( "open", self._onWsOpen ); @@ -1691,13 +1691,13 @@ export class WebSocketClientPipe extends BasicSocketPipe { }; export class RTCConnection extends EventDispatcher { - strSignalingServerURL: string|null; - idRtcParticipant: string|null; + strSignalingServerURL: string | null + idRtcParticipant: string | null wasIdentified: boolean; iceComplete: any; pc: any; dc: any; - constructor( strSignalingServerURL?: string, idRtcParticipant?: string ) { + constructor ( strSignalingServerURL?: string, idRtcParticipant?: string ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); this.idRtcParticipant = "" + @@ -1796,13 +1796,13 @@ export class RTCConnection extends EventDispatcher { send( data: any ) { const s = socketSentDataMarshall( data ); if( ! this.dc ) { - this.onError( "Attempt to send message to uninitialized RTC data channel: " + s ); - return; + this.onError( `Attempt to send message to uninitialized RTC data channel: ${s}` ); + return } try { this.dc.send( s ); - } catch ( err ) { - this.onError( "Failed to send message to RTC data channel: " + err ); + } catch ( err: any ) { + this.onError( `Failed to send message to RTC data channel: ${err}` ); } } onDataChannelOpen( event: any ) { @@ -1845,9 +1845,9 @@ export class RTCConnection extends EventDispatcher { onIceComplete( event: any ) { } onIceConnectionStateChange( event: any ) { - // handler for self.pc.oniceconnectionstatechange, - // see https://developer.mozilla.org/en-US/docs/ - // Web/API/RTCPeerConnection/oniceconnectionstatechange + // handler for self.pc.oniceconnectionstatechange, + // see https://developer.mozilla.org/en-US/docs/ + // Web/API/RTCPeerConnection/oniceconnectionstatechange if( settings.logging.net.rtc.iceConnectionStateChange ) { console.log( "Participant \"" + this.idRtcParticipant + @@ -1872,10 +1872,10 @@ export class RTCConnection extends EventDispatcher { } } onIceGatheringStateChange( event: any ) { - // handler for self.pc.onicegatheringstatechange - this is recommended to handle - // in a same way as oniceconnectionstatechange, - // see https://developer.mozilla.org/en-US/docs/ - // Web/API/RTCPeerConnection/onicegatheringstatechange + // handler for self.pc.onicegatheringstatechange - this is recommended to handle + // in a same way as oniceconnectionstatechange, + // see https://developer.mozilla.org/en-US/docs/ + // Web/API/RTCPeerConnection/onicegatheringstatechange if( ! this.pc ) { console.log( "WARNING: Participant \"" + this.idRtcParticipant + @@ -1908,8 +1908,8 @@ export class RTCConnection extends EventDispatcher { } } onIceIdentifyResult( event: any ) { - // handler for self.pc.onidentityresult, - // see https://developer.mozilla.org/en-US/docs/Web/API/RTCIdentityEvent + // handler for self.pc.onidentityresult, + // see https://developer.mozilla.org/en-US/docs/Web/API/RTCIdentityEvent if( settings.logging.net.rtc.iceIceIdentifyResult ) { if( "assertion" in event ) { console.warn( @@ -1926,9 +1926,9 @@ export class RTCConnection extends EventDispatcher { } } onIceSignalingStateChange( event: any ) { - // handler for self.pc.onsignalingstatechange, see - // https://developer.mozilla.org/en-US/docs/ - // Web/API/RTCPeerConnection/onsignalingstatechange + // handler for self.pc.onsignalingstatechange, see + // https://developer.mozilla.org/en-US/docs/ + // Web/API/RTCPeerConnection/onsignalingstatechange if( settings.logging.net.rtc.iceSignalingStateChange ) { console.log( "Participant \"" + this.idRtcParticipant + @@ -1938,10 +1938,10 @@ export class RTCConnection extends EventDispatcher { } } onIceNegotiationNeeded( event: any ) { - // handler for self.pc.onnegotiationneeded, - // see https://developer.mozilla.org/en-US/docs/ - // Web/API/RTCPeerConnection/onnegotiationneeded - // TO-DO: improve this + // handler for self.pc.onnegotiationneeded, + // see https://developer.mozilla.org/en-US/docs/ + // Web/API/RTCPeerConnection/onnegotiationneeded + // TO-DO: improve this if( settings.logging.net.rtc.iceNegotiationNeeded ) { console.log( "Participant \"" + this.idRtcParticipant + @@ -1952,17 +1952,17 @@ export class RTCConnection extends EventDispatcher { }; export class RTCActor extends RTCConnection { - idSomebodyCreator: string|null; + idSomebodyCreator: string | null bWasImpersonated: boolean; isCreator: boolean; isJoiner: boolean; offerOptions: any; signalingOptions: any; signalingPipe: any; - constructor( + constructor ( strSignalingServerURL: string, idRtcParticipant: string, offerOptions: any, signalingOptions: any - ) { + ) { super( strSignalingServerURL, idRtcParticipant ); this.isDisposed = false; this.idSomebodyCreator = null; @@ -2048,7 +2048,9 @@ export class RTCActor extends RTCConnection { self.signalingPipe.on( "error", function( eventData: any ) { self.signalingPipeOnError( eventData ); } ); self.signalingPipe.on( - "message", function( eventData: any ) { self.signalingPipeOnRawMessage( eventData ); } ); + "message", function( eventData: any ) { + self.signalingPipeOnRawMessage( eventData ); + } ); self.dispatchEvent( new UniversalDispatcherEvent( "signalingDidStarted", { "detail": { "actor": this } } ) ); @@ -2120,7 +2122,7 @@ export class RTCActor extends RTCConnection { this.signalingPipeClose(); } signalingPipeOnError( eventData: any ) { - // alert( JSON.stringify( eventData ) ); + // alert( JSON.stringify( eventData ) ); this.dispatchEvent( new UniversalDispatcherEvent( "signalingPipeError", { "detail": { "actor": this, "error": eventData } } ) ); @@ -2198,7 +2200,7 @@ export class RTCActor extends RTCConnection { export class RTCServerPeer extends RTCConnection { rtcCreator: any; - idSomebodyOtherSide: string|null; + idSomebodyOtherSide: string | null idOffer: number; tsOfferCreated: any; isPublishing: boolean; @@ -2215,7 +2217,7 @@ export class RTCServerPeer extends RTCConnection { isOfferPublishedOnSignalingServer: boolean; offerOptions: any; serverPipe: any; - constructor( + constructor ( rtcCreator: any, timeToPublishMilliseconds: number, timeToSignalingNegotiationMilliseconds: number, peerConfiguration: any, peerAdditionalOptions: any, localMediaStream?: any @@ -2336,7 +2338,7 @@ export class RTCServerPeer extends RTCConnection { } publish() { if( this.isDisposed || this.isPublishing || this.isSignalingNegotiation || - ( !this.rtcCreator ) || ( !this.rtcCreator.signalingPipe ) ) + ( !this.rtcCreator?.signalingPipe ) ) return; const self = this; self.isPublishing = true; @@ -2369,15 +2371,15 @@ export class RTCServerPeer extends RTCConnection { new UniversalDispatcherEvent( "publishStart", { "detail": { "participant": self } } ) ); self.pc.oniceconnectionstatechange = - function( event: any ) { self.onIceConnectionStateChange( event ); }; + function( event: any ) { self.onIceConnectionStateChange( event ); } self.pc.onicegatheringstatechange = - function( event: any ) { self.onIceGatheringStateChange( event ); }; + function( event: any ) { self.onIceGatheringStateChange( event ); } self.pc.onidentityresult = - function( event: any ) { self.onIceIdentifyResult( event ); }; + function( event: any ) { self.onIceIdentifyResult( event ); } self.pc.onsignalingstatechange = - function( event: any ) { self.onIceSignalingStateChange( event ); }; + function( event: any ) { self.onIceSignalingStateChange( event ); } self.pc.onnegotiationneeded = - function( event: any ) { self.onIceNegotiationNeeded( event ); }; + function( event: any ) { self.onIceNegotiationNeeded( event ); } self.pc.createOffer( self.offerOptions ).then( function( offerDescription: any ) { // success @@ -2409,7 +2411,7 @@ export class RTCServerPeer extends RTCConnection { self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; self.onIceComplete( event ); - }; // onicecandidate + } // onicecandidate }, function( err: any ) { // error of setLocalDescription self.publishCancel(); @@ -2538,7 +2540,7 @@ export class RTCServerPeer extends RTCConnection { ); } } - } catch ( err ) { + } catch ( err: any ) { self.publishCancel(); self.signalingNegotiationCancel(); self.onError( "Failed to process ICE candidate: " + err ); @@ -2550,7 +2552,7 @@ export class RTCCreator extends RTCActor { idOfferNext?: number; mapServerOffers: any; mapServerPeers: any; - constructor( + constructor ( strSignalingServerURL: string, idRtcParticipant: string, offerOptions: any, signalingOptions: any ) { @@ -2572,7 +2574,7 @@ export class RTCCreator extends RTCActor { console.log( "Unregister offer", idOfferWalk, "(one of all, RTCCreator dispose)" ); rtcPeer.dispose(); } - for( const [ idSomebodyOtherSideWalk, rtcPeerWalk ] of + for( const [ /*idSomebodyOtherSideWalk*/, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.dispose(); @@ -2604,7 +2606,7 @@ export class RTCCreator extends RTCActor { idSomebodyOtherSide, "and offer ID", idOffer, ":", strError ); } this.onError( strError ); - return; + return } const rtcPeer = this.mapServerOffers[idOffer]; if( settings.logging.net.signaling.offerUnregister ) { @@ -2748,7 +2750,7 @@ export class RTCCreator extends RTCActor { send( data: any ) { // implementation in RTCCreator does send to all try { const s = socketSentDataMarshall( data ); - for( const [ idSomebodyOtherSideWalk, rtcPeerWalk ] + for( const [ /*idSomebodyOtherSideWalk*/, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; try { @@ -2763,12 +2765,12 @@ export class RTCCreator extends RTCActor { } onImpersonationComplete() { super.onImpersonationComplete(); - for( const [ idOfferWalk, rtcPeerWalk ] + for( const [ /*idOfferWalk*/, rtcPeerWalk ] of Object.entries( this.mapServerOffers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.onImpersonationCompleteForCreator(); } - for( const [ idSomebodyOtherSideWalk, rtcPeerWalk ] + for( const [ /*idSomebodyOtherSideWalk*/, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.onImpersonationCompleteForCreator(); @@ -2783,7 +2785,7 @@ export class RTCJoiner extends RTCActor { isAnswerPublishedOnSignalingServer: boolean; peerConfiguration: any; peerAdditionalOptions: any; - constructor( + constructor ( strSignalingServerURL: string, idRtcParticipant: string, offerOptions: any, signalingOptions: any, peerConfiguration: any, peerAdditionalOptions: any ) { @@ -2837,15 +2839,15 @@ export class RTCJoiner extends RTCActor { { "detail": { "participant": self, "event": event } } ) ); } ); self.pc.oniceconnectionstatechange = - function( event: any ) { self.onIceConnectionStateChange( event ); }; + function( event: any ) { self.onIceConnectionStateChange( event ); } self.pc.onicegatheringstatechange = - function( event: any ) { self.onIceGatheringStateChange( event ); }; + function( event: any ) { self.onIceGatheringStateChange( event ); } self.pc.onidentityresult = - function( event: any ) { self.onIceIdentifyResult( event ); }; + function( event: any ) { self.onIceIdentifyResult( event ); } self.pc.onsignalingstatechange = - function( event: any ) { self.onIceSignalingStateChange( event ); }; + function( event: any ) { self.onIceSignalingStateChange( event ); } self.pc.onnegotiationneeded = - function( event: any ) { self.onIceNegotiationNeeded( event ); }; + function( event: any ) { self.onIceNegotiationNeeded( event ); } self.pc.ondatachannel = function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( @@ -2866,7 +2868,7 @@ export class RTCJoiner extends RTCActor { self.dc.addEventListener( "message", function( event: any ) { self.onDataChannelMessage( event ); } ); - }; + } self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; self.onIceComplete( event ); @@ -2888,7 +2890,7 @@ export class RTCJoiner extends RTCActor { ); } } - } catch ( err ) { + } catch ( err: any ) { self.onError( "Failed to process ICE candidate: " + err ); @@ -3024,8 +3026,8 @@ export class RTCJoiner extends RTCActor { if( settings.logging.net.signaling.answer ) { console.log( " <<< " + self.describe() + "did created answer at " + - utils.formatDateTime( self.tsAnswerCreated ) + - " with description:", answerDescription ); + utils.formatDateTime( self.tsAnswerCreated ) + + " with description:", answerDescription ); } self.dispatchEvent( new UniversalDispatcherEvent( @@ -3037,7 +3039,7 @@ export class RTCJoiner extends RTCActor { if( settings.logging.net.signaling.localDescription ) { console.log( " <<< " + self.describe() + - " local description set:", answerDescription ); + " local description set:", answerDescription ); } self.dispatchEvent( new UniversalDispatcherEvent( @@ -3050,27 +3052,27 @@ export class RTCJoiner extends RTCActor { // error of setLocalDescription self.onError( "Failed to set local description " + - "(while fetching offer for \"" + - idSomebodyOtherSide + "\"): " + - err.toString() ); + "(while fetching offer for \"" + + idSomebodyOtherSide + "\"): " + + err.toString() ); } ); }, function( err: any ) { // error of createAnswer self.onError( "Failed to create answer (while fetching offer for \"" + - idSomebodyOtherSide + "\"): " + err ); + idSomebodyOtherSide + "\"): " + err ); } ); }, function( err: any ) { // error of setLocalDescription self.onError( "Failed to set remote description: (while fetching offer for \"" + - idSomebodyOtherSide + "\"): " + err ); + idSomebodyOtherSide + "\"): " + err ); } ); } else { if( settings.logging.net.signaling.error ) { console.warn( " !!! " + this.describe() + - " signaling offer publishing (step 1) error", joMessage.error ); + " signaling offer publishing (step 1) error", joMessage.error ); } this.dispatchEvent( new UniversalDispatcherEvent( @@ -3090,7 +3092,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { clientNumber?: number; rtcPeer: any; strSignalingServerURL?: string; - constructor( acceptor: any, rtcPeer: any, strSignalingServerURL: string ) { + constructor ( acceptor: any, rtcPeer: any, strSignalingServerURL: string ) { super(); const self = this; self.socketType = "WebRTC"; @@ -3171,7 +3173,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const err = "Cannot send messages to disconnected WebRTC socket server pipe"; this.onError( err ); - throw err; + throw new Error( err ); } const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); @@ -3202,7 +3204,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { timeToSignalingNegotiationMilliseconds: number; rtcCreator: any; isConnected?: false; - constructor( + constructor ( strSignalingServerURL: string, idRtcParticipant: any, offerOptions: any, signalingOptions: any, maxActiveOfferCount?: number, timeToPublishMilliseconds?: number, timeToSignalingNegotiationMilliseconds?: number, @@ -3327,7 +3329,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { const onTimeoutHandler = function() { self.disposePendingOffer( rtcPeer.idOffer ); self.updateAllPendingOffers(); - }; + } rtcPeer.on( "publishTimeout", onTimeoutHandler ); rtcPeer.on( "signalingNegotiationTimeout", onTimeoutHandler ); rtcPeer.on( "signalingNegotiationStart", function() { @@ -3346,7 +3348,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { "errorType": "rtcPeerError" } } ) ); - }; + } rtcPeer.on( "error", retranslateError ); rtcPeer.on( "rtcPeerError", retranslateError ); @@ -3364,14 +3366,14 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } } removeAllPendingOffers() { - for( const [ idOfferWalk, rtcPeerWalk ] + for( const [ /*idOfferWalk*/, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; const serverPipe = rtcPeer.serverPipe; serverPipe.dispose(); } this.rtcCreator.mapServerPeers = { }; - for( const [ idOfferWalk, rtcPeerWalk ] + for( const [ /*idOfferWalk*/, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapPendingOffers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.dispose(); @@ -3381,13 +3383,15 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { updateAllPendingOffers() { if( this.isDisposed ) return; - for( let n = Object.keys( this.mapPendingOffers ).length; n < this.maxActiveOfferCount; ++ n ) + for( let n = Object.keys( this.mapPendingOffers ).length; + n < this.maxActiveOfferCount; + ++ n ) this.addPendingOffer(); } }; export class WebRTCClientPipe extends BasicSocketPipe { - strSignalingServerURL: string|null; + strSignalingServerURL: string | null idRtcParticipant: string; offerOptions: any; signalingOptions: any; @@ -3395,7 +3399,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { peerAdditionalOptions: any; rtcPeer: any; isAutoCloseSignalingPipeOnDataChannelOpen: boolean; - constructor( + constructor ( strSignalingServerURL: string, idRtcParticipant: string, offerOptions: any, signalingOptions: any, peerConfiguration: any, peerAdditionalOptions: any ) { @@ -3543,10 +3547,10 @@ export class WebRTCClientPipe extends BasicSocketPipe { } ) ); } ); - return; + return } catch ( err ) { console.warn( "WebRTC client connect error:", err ); - continue; + continue } } } diff --git a/src/socketServer.ts b/src/socketServer.ts index 1b2d2ae9..d36ddeb6 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -36,7 +36,7 @@ export class SocketServer extends EventDispatcher { isLogSocketErrors?: boolean; isLogSocketTraffic?: boolean; isLogSocketTrafficRaw?: boolean; - constructor( acceptor: any ) { + constructor ( acceptor: any ) { super(); if( acceptor == null || acceptor == undefined || typeof acceptor != "object" ) throw new Error( "Cannot create server on bad acceptor" ); @@ -73,7 +73,7 @@ export class SocketServer extends EventDispatcher { _offAllPipeEventListeners = null; } delete self.mapAcceptedPipes[socket]; - }; + } let _onPipeError: any = function( eventData: any ) { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Socket {url} error {err}", @@ -84,7 +84,7 @@ export class SocketServer extends EventDispatcher { _offAllPipeEventListeners = null; } delete self.mapAcceptedPipes[socket]; - }; + } let _onPipeMessage: any = function( eventData: any ) { if( self.isLogSocketTrafficRaw ) { self.log( log.fmtInformation( "Socket {url} did received {sunny} {}", @@ -114,14 +114,14 @@ export class SocketServer extends EventDispatcher { } isFlush = true; } - } catch ( err ) { + } catch ( err: any ) { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Server method {} RPC exception: {err}, stack is: {stack}", joMessage.method, err, err ) ); } joAnswer = utils.prepareAnswerJSON( joMessage ); - joAnswer.error = "" + err; + joAnswer.error = "" + err.toString(); } if( joAnswer != null && joAnswer != undefined ) { @@ -153,7 +153,7 @@ export class SocketServer extends EventDispatcher { _onPipeMessage = null; } socket.disposeImpersonatedEntries(); - }; + } socket.on( "close", _onPipeClose ); socket.on( "error", _onPipeError ); socket.on( "message", _onPipeMessage ); @@ -161,7 +161,7 @@ export class SocketServer extends EventDispatcher { this.dispatchEvent( new UniversalDispatcherEvent( "initialized", { "detail": { "ref": this } } ) ); } - dispose() : void { + dispose(): void { this.isDisposing = true; super.dispose(); } diff --git a/src/socketSettings.ts b/src/socketSettings.ts index 107bf312..51d64e8b 100644 --- a/src/socketSettings.ts +++ b/src/socketSettings.ts @@ -82,7 +82,7 @@ const settings: any = { "stun:stun.voipbuster.com", "stun:stun.voipstunt.com", "stun:stun.voxgratia.org" - ] , + ], peerConfiguration: { iceServers: [ { urls: "stun:some.ip.address.here:3478", diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 3bb54045..8751c1c4 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -25,31 +25,31 @@ import { settings } from "./socketSettings.js"; -export const UUIDv4 = function() : string { +export const UUIDv4 = function(): string { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( /[xy]/g, function( c ) { const r = Math.random() * 16 | 0, v = c == "x" ? r : ( r & 0x3 | 0x8 ); return v.toString( 16 ); } ); -}; +} export const getRandomInt = function( nMax: number ): number { return Math.floor( Math.random() * Math.floor( nMax ) ); -}; +} export const randomFixedInteger = function( length: number ): number { return Math.floor( Math.pow( 10, length - 1 ) + Math.random() * ( Math.pow( 10, length ) - Math.pow( 10, length - 1 ) - 1 ) ); -}; +} -export const randomStringABC = function( length: number, arrCharacters: string ) : string { +export const randomStringABC = function( length: number, arrCharacters: string ): string { if( length <= 0 || arrCharacters.length == 0 ) return ""; let s = ""; for( let i = 0; i < length; ++i ) s += arrCharacters.charAt( Math.floor( Math.random() * arrCharacters.length ) ); return s; -}; +} export const randomString = function( length: number, @@ -77,19 +77,19 @@ export const randomString = function( if( arrCharacters.length == 0 ) return ""; return randomStringABC( length, arrCharacters ); -}; +} -export const randomHexString = function( length: number ) : string { +export const randomHexString = function( length: number ): string { // length in characters, not bytes, each byte is 2 characters const arrCharacters = "0123456789abcdef"; return randomStringABC( length, arrCharacters ); -}; +} -export const replaceAll = function( str: string, find: string, replace: string ) : string { +export const replaceAll = function( str: string, find: string, replace: string ): string { return str.replace( new RegExp( find, "g" ), replace ); -}; +} -export const simpleEscapeString = function( s?: any ) : string { +export const simpleEscapeString = function( s?: any ): string { if( s == null || s == undefined || typeof s != "string" ) return s; s = replaceAll( s, "&", "&" ); @@ -97,33 +97,33 @@ export const simpleEscapeString = function( s?: any ) : string { s = replaceAll( s, ">", ">" ); s = replaceAll( s, " ", " " ); return s; -}; +} -export const abstractUniqueID = function() : string { +export const abstractUniqueID = function(): string { const id = replaceAll( UUIDv4(), "-", "" ).toLowerCase(); return id; -}; +} -export const isEven = function( n: number ) : boolean { +export const isEven = function( n: number ): boolean { return n % 2 == 0; -}; -export const isOdd = function( n: number ) : boolean { +} +export const isOdd = function( n: number ): boolean { return Math.abs( n % 2 ) == 1; -}; +} const gCountOfCallIdDigits: number = 10; -export const randomCallID = function() : string { +export const randomCallID = function(): string { const id = randomHexString( gCountOfCallIdDigits ); return id; -}; +} -const gCountOfDirectPipeIdDigits : number = 10; -export const randomDirectPipeID = function() : string { +const gCountOfDirectPipeIdDigits: number = 10; +export const randomDirectPipeID = function(): string { const id = randomHexString( gCountOfDirectPipeIdDigits ); return id; -}; +} -export const prepareAnswerJSON = function( joMessage: any ) : any { +export const prepareAnswerJSON = function( joMessage: any ): any { const joAnswer: any = { "id": "" + ( ( joMessage != null && @@ -138,9 +138,9 @@ export const prepareAnswerJSON = function( joMessage: any ) : any { "error": null }; return joAnswer; -}; +} -export const makeValidSignalingServerURL = function( strSignalingServerURL?: string ) : string { +export const makeValidSignalingServerURL = function( strSignalingServerURL?: string ): string { const proto = settings.net.secure ? "wss" : "ws"; return "" + ( ( strSignalingServerURL != null && @@ -150,26 +150,26 @@ export const makeValidSignalingServerURL = function( strSignalingServerURL?: str ? "" + strSignalingServerURL : "" + proto + "://" + settings.net.hostname + ":" + settings.net.ports.signaling ); -}; +} -export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ) : string { +export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ): string { if( val == null || val == undefined ) return val; let s = "" + val; while( s.length < cntCharsNeeded ) s = "0" + s; return s; -}; -export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ) : string { +} +export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ): string { if( val == null || val == undefined ) return val; let s = "" + val; while( s.length < cntCharsNeeded ) s = s + "0"; return s; -}; +} -export const parseDateTime = function( ts?: any ) : Date|null { +export const parseDateTime = function( ts?: any ): Date | null { if( ts === null || ts === undefined ) return ts; if( typeof ts != "string" ) @@ -196,12 +196,12 @@ export const parseDateTime = function( ts?: any ) : Date|null { const d = new Date( u ); d.setMilliseconds( millisecond ); return d; -}; +} export const formatDateTime = function( dt: any, isDate?: boolean, isTime?: boolean, isMilliseconds?: boolean, sepDate?: string, sepTime?: string, sepBetween?: string, sepMilliseconds?: string -) : string { +): string { if( dt === null ) return "null-date-time"; if( dt === undefined ) @@ -254,4 +254,4 @@ export const formatDateTime = function( s += strTime; } return s; -}; +} diff --git a/src/state.ts b/src/state.ts index a3924609..b04a90b8 100644 --- a/src/state.ts +++ b/src/state.ts @@ -301,5 +301,5 @@ export function isPreventExitAfterLastAction() { } export function setPreventExitAfterLastAction( isPrevent: any ) { - gFlagIsPreventExitAfterLastAction = (!!isPrevent); + gFlagIsPreventExitAfterLastAction = ( !!isPrevent ) } diff --git a/src/threadInfo.ts b/src/threadInfo.ts index d3fa44e1..b14c2dc6 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -32,19 +32,19 @@ export { Worker }; const joCustomThreadProperties: any = { }; export { joCustomThreadProperties }; -export const sleep = ( milliseconds: number ) : Promise => { - return new Promise( resolve => setTimeout( resolve, milliseconds ) ); -}; +export const sleep = async( milliseconds: number ): Promise => { + await new Promise( resolve => setTimeout( resolve, milliseconds ) ) +} -export function getCurrentThreadID() : number { +export function getCurrentThreadID(): number { return worker_threads.threadId; } -export function isMainThread() : boolean { +export function isMainThread(): boolean { return ( !!( worker_threads.isMainThread ) ); } -export function threadDescription( isColorized?: boolean ) : string { +export function threadDescription( isColorized?: boolean ): string { if( typeof isColorized == "undefined" ) isColorized = true; const tid: number = getCurrentThreadID(); diff --git a/src/tsconfig.json b/src/tsconfig.json index 52358d07..1c4af757 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -15,13 +15,6 @@ // "skipLibCheck": true /* Skip type checking of declaration files. */, // "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - // "noImplicitAny": true, - // "alwaysStrict": true, - // "rootDir": ".", - // "baseUrl": ".", - - "allowArbitraryExtensions": true, - "paths": { "*": [ "./*.ts" diff --git a/src/utils.ts b/src/utils.ts index 0952730e..0ba02a05 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -36,25 +36,25 @@ export { uuid }; const ethersMod = owaspUtils.ethersMod; export { ethersMod }; -export function replaceAll( str: string, find: string, replace: string ) : string { +export function replaceAll( str: string, find: string, replace: string ): string { return str.replace( new RegExp( find, "g" ), replace ); } -export function normalizePath( strPath: string ) : string { +export function normalizePath( strPath: string ): string { strPath = strPath.replace( /^~/, os.homedir() ); strPath = path.normalize( strPath ); strPath = path.resolve( strPath ); return strPath; } -export function getRandomFileName() : string { - const timestamp = new Date().toISOString().replace( /[-:.]/g,"" ); +export function getRandomFileName(): string { + const timestamp = new Date().toISOString().replace( /[-:.]/g, "" ); const random = ( "" + Math.random() ).substring( 2, 8 ); const randomNumber = timestamp + random; return randomNumber; } -export function fileExists( strPath: string ) : boolean { +export function fileExists( strPath: string ): boolean { try { if( fs.existsSync( strPath ) ) { const stats = fs.statSync( strPath ); @@ -65,7 +65,7 @@ export function fileExists( strPath: string ) : boolean { return false; } -export function fileLoad( strPath: string, strDefault?: string ) : string { +export function fileLoad( strPath: string, strDefault?: string | null ): string { strDefault = strDefault || ""; if( !fileExists( strPath ) ) return strDefault; @@ -76,7 +76,7 @@ export function fileLoad( strPath: string, strDefault?: string ) : string { return strDefault; } -export function fileSave( strPath: string, s: string ) : boolean { +export function fileSave( strPath: string, s: string ): boolean { try { fs.writeFileSync( strPath, s ); return true; @@ -84,7 +84,7 @@ export function fileSave( strPath: string, s: string ) : boolean { return false; } -export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boolean ) : any { +export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boolean ): any { if( bLogOutput == undefined || bLogOutput == null ) bLogOutput = false; joDefault = joDefault || {}; @@ -112,7 +112,7 @@ export function jsonFileLoad( strPath: string, joDefault?: any, bLogOutput?: boo return joDefault; } -export function jsonFileSave( strPath: string, jo?: any, bLogOutput?: boolean ) : any { +export function jsonFileSave( strPath: string, jo?: any, bLogOutput?: boolean ): any { if( bLogOutput == undefined || bLogOutput == null ) bLogOutput = false; if( bLogOutput ) @@ -187,7 +187,7 @@ export async function waitForClonedTokenAppearErc20( "address" in tokenERC20SC && typeof tokenERC20SC.address == "string" ) { log.warning( "Skipping automatic ERC20 instantiation discovery, already done before" ); - return; + return } const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( @@ -203,7 +203,7 @@ export async function waitForClonedTokenAppearErc721( "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" ) { log.warning( "Skipping automatic ERC721instantiation discovery, already done before" ); - return; + return } const addressCallFrom = joAccountSC.address(); const addressOnSChain = @@ -221,7 +221,7 @@ export async function waitForClonedTokenAppearErc721WithMetadata( ) { log.warning( "Skipping automatic ERC721_with_metadata instantiation discovery, " + "already done before" ); - return; + return } const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( @@ -237,7 +237,7 @@ export async function waitForClonedTokenAppearErc1155( "address" in tokenERC1155SC && typeof tokenERC1155SC.address == "string" ) { log.warning( "Skipping automatic ERC1155 instantiation discovery, already done before" ); - return; + return } const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( @@ -246,7 +246,9 @@ export async function waitForClonedTokenAppearErc1155( tokenERC1155SC.address = "" + addressOnSChain; } -export function hexToBytes( strHex?: any, isInversiveOrder?: boolean ) : Uint8Array { // convert a hex string to a byte array +export function hexToBytes( + strHex?: any, isInversiveOrder?: boolean +): Uint8Array { // convert a hex string to a byte array isInversiveOrder = !!( ( isInversiveOrder != null && isInversiveOrder != undefined && isInversiveOrder ) ); @@ -267,7 +269,9 @@ export function hexToBytes( strHex?: any, isInversiveOrder?: boolean ) : Uint8Ar return arrBytes; } -export function bytesToHex( arrBytes: Uint8Array, isInversiveOrder?: boolean ) : string { // convert a byte array to a hex string +export function bytesToHex( + arrBytes: Uint8Array, isInversiveOrder?: boolean +): string { // convert a byte array to a hex string isInversiveOrder = !!( ( isInversiveOrder != null && isInversiveOrder != undefined && isInversiveOrder ) ); @@ -287,7 +291,7 @@ export function bytesToHex( arrBytes: Uint8Array, isInversiveOrder?: boolean ) : return hex.join( "" ); } -export function bytesAlignLeftWithZeroes( arrBytes: Uint8Array, cntMin: number ) : Uint8Array { +export function bytesAlignLeftWithZeroes( arrBytes: Uint8Array, cntMin: number ): Uint8Array { if( arrBytes.length >= cntMin ) return arrBytes; const cntNewZeros = cntMin - arrBytes.length; @@ -297,7 +301,7 @@ export function bytesAlignLeftWithZeroes( arrBytes: Uint8Array, cntMin: number ) return arrBytes; } -export function bytesAlignRightWithZeroes( arrBytes: Uint8Array, cntMin: number ) : Uint8Array { +export function bytesAlignRightWithZeroes( arrBytes: Uint8Array, cntMin: number ): Uint8Array { if( arrBytes.length >= cntMin ) return arrBytes; const cntNewZeros = cntMin - arrBytes.length; @@ -307,34 +311,35 @@ export function bytesAlignRightWithZeroes( arrBytes: Uint8Array, cntMin: number return arrBytes; } -export function concatUint8Arrays( a: Uint8Array, b: Uint8Array ) : Uint8Array { // a, b TypedArray of same type +export function concatUint8Arrays( + a: Uint8Array, b: Uint8Array ): Uint8Array { // a, b TypedArray of same type if( typeof a == "string" ) a = hexToBytes( a ); if( typeof b == "string" ) b = hexToBytes( b ); - const c = new Uint8Array( a["length"] + b["length"] ); + const c = new Uint8Array( a.length + b.length ); c.set( a, 0 ); - c.set( b, a["length"] ); + c.set( b, a.length ); return c; } -export function concatByte( ui8a: Uint8Array, byte: number ) : Uint8Array { +export function concatByte( ui8a: Uint8Array, byte: number ): Uint8Array { const b = new Uint8Array( 1 ); b[0] = byte; return concatUint8Arrays( ui8a, b ); } -export function bytesConcat( a1: Uint8Array, a2: Uint8Array ) : Uint8Array { +export function bytesConcat( a1?: Uint8Array, a2?: Uint8Array ): Uint8Array { a1 = a1 || new Uint8Array(); a2 = a2 || new Uint8Array(); return concatUint8Arrays( a1, a2 ); } -export function toBuffer( ab?: any ) { +export function toBuffer( ab?: any ): Buffer { return Buffer.from( new Uint8Array( ab ) ); } -export function discoverCoinNameInJSON( jo?: any ) : string { +export function discoverCoinNameInJSON( jo?: any ): string { if( typeof jo !== "object" ) return ""; const arrKeys = Object.keys( jo ); @@ -349,12 +354,12 @@ export function discoverCoinNameInJSON( jo?: any ) : string { j = k.indexOf( "_address" ); if( j > 0 ) { s1 = k.substring( 0, j ); - continue; + continue } j = k.indexOf( "_abi" ); if( j > 0 ) { s2 = k.substring( 0, j ); - continue; + continue } } if( s1.length === 0 || s2.length === 0 ) @@ -366,7 +371,7 @@ export function discoverCoinNameInJSON( jo?: any ) : string { export function checkKeyExistInABI( strName: string, strFile: string, joABI: any, strKey: string, isExitOnError?: boolean - ) : boolean { +): boolean { if( isExitOnError == null || isExitOnError == undefined ) isExitOnError = true; try { @@ -374,7 +379,8 @@ export function checkKeyExistInABI( return true; } catch ( err ) { if( isExitOnError ) { - log.fatal( "Loaded {} ABI JSON file {} does not contain needed key {}, stack is:\n{stack}", + log.fatal( + "Loaded {} ABI JSON file {} does not contain needed key {}, stack is:\n{stack}", strName, strFile, strKey, err ); process.exit( 126 ); } @@ -384,7 +390,7 @@ export function checkKeyExistInABI( export function checkKeysExistInABI( strName: string, strFile: string, joABI: any, arrKeys: any[], isExitOnError?: boolean - ): boolean { +): boolean { const cnt = arrKeys.length; for( let i = 0; i < cnt; ++i ) { const strKey = arrKeys[i]; @@ -394,7 +400,7 @@ export function checkKeysExistInABI( return true; } -export function composeSChainNodeUrl( joNode: any ) : string { +export function composeSChainNodeUrl( joNode: any ): string { if( "ip" in joNode && typeof joNode.ip === "string" && joNode.ip.length > 0 ) { if( "httpRpcPort" in joNode && typeof joNode.httpRpcPort === "number" && diff --git a/src/yarn.lock b/src/yarn.lock index 95500c80..7598c839 100644 --- a/src/yarn.lock +++ b/src/yarn.lock @@ -14,7 +14,7 @@ dependencies: eslint-visitor-keys "^3.3.0" -"@eslint-community/regexpp@^4.6.0", "@eslint-community/regexpp@^4.6.1": +"@eslint-community/regexpp@^4.5.1", "@eslint-community/regexpp@^4.6.0", "@eslint-community/regexpp@^4.6.1": version "4.10.0" resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.10.0.tgz#548f6de556857c8bb73bbee70c35dc82a2e74d63" integrity sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA== @@ -427,12 +427,12 @@ "@nodelib/fs.stat" "2.0.5" run-parallel "^1.1.9" -"@nodelib/fs.stat@2.0.5": +"@nodelib/fs.stat@2.0.5", "@nodelib/fs.stat@^2.0.2": version "2.0.5" resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b" integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A== -"@nodelib/fs.walk@^1.2.8": +"@nodelib/fs.walk@^1.2.3", "@nodelib/fs.walk@^1.2.8": version "1.2.8" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a" integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg== @@ -509,6 +509,11 @@ dependencies: "@types/node" "*" +"@types/json-schema@^7.0.12": + version "7.0.15" + resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" + integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== + "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" @@ -565,6 +570,11 @@ dependencies: "@types/node" "*" +"@types/semver@^7.5.0": + version "7.5.6" + resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.5.6.tgz#c65b2bfce1bec346582c07724e3f8c1017a20339" + integrity sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A== + "@types/send@*": version "0.17.4" resolved "https://registry.yarnpkg.com/@types/send/-/send-0.17.4.tgz#6619cd24e7270793702e4e6a4b958a9010cfc57a" @@ -609,6 +619,91 @@ dependencies: "@types/node" "*" +"@typescript-eslint/eslint-plugin@^6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.14.0.tgz#fc1ab5f23618ba590c87e8226ff07a760be3dd7b" + integrity sha512-1ZJBykBCXaSHG94vMMKmiHoL0MhNHKSVlcHVYZNw+BKxufhqQVTOawNpwwI1P5nIFZ/4jLVop0mcY6mJJDFNaw== + dependencies: + "@eslint-community/regexpp" "^4.5.1" + "@typescript-eslint/scope-manager" "6.14.0" + "@typescript-eslint/type-utils" "6.14.0" + "@typescript-eslint/utils" "6.14.0" + "@typescript-eslint/visitor-keys" "6.14.0" + debug "^4.3.4" + graphemer "^1.4.0" + ignore "^5.2.4" + natural-compare "^1.4.0" + semver "^7.5.4" + ts-api-utils "^1.0.1" + +"@typescript-eslint/parser@^6.4.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-6.14.0.tgz#a2d6a732e0d2b95c73f6a26ae7362877cc1b4212" + integrity sha512-QjToC14CKacd4Pa7JK4GeB/vHmWFJckec49FR4hmIRf97+KXole0T97xxu9IFiPxVQ1DBWrQ5wreLwAGwWAVQA== + dependencies: + "@typescript-eslint/scope-manager" "6.14.0" + "@typescript-eslint/types" "6.14.0" + "@typescript-eslint/typescript-estree" "6.14.0" + "@typescript-eslint/visitor-keys" "6.14.0" + debug "^4.3.4" + +"@typescript-eslint/scope-manager@6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-6.14.0.tgz#53d24363fdb5ee0d1d8cda4ed5e5321272ab3d48" + integrity sha512-VT7CFWHbZipPncAZtuALr9y3EuzY1b1t1AEkIq2bTXUPKw+pHoXflGNG5L+Gv6nKul1cz1VH8fz16IThIU0tdg== + dependencies: + "@typescript-eslint/types" "6.14.0" + "@typescript-eslint/visitor-keys" "6.14.0" + +"@typescript-eslint/type-utils@6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-6.14.0.tgz#ac9cb5ba0615c837f1a6b172feeb273d36e4f8af" + integrity sha512-x6OC9Q7HfYKqjnuNu5a7kffIYs3No30isapRBJl1iCHLitD8O0lFbRcVGiOcuyN837fqXzPZ1NS10maQzZMKqw== + dependencies: + "@typescript-eslint/typescript-estree" "6.14.0" + "@typescript-eslint/utils" "6.14.0" + debug "^4.3.4" + ts-api-utils "^1.0.1" + +"@typescript-eslint/types@6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-6.14.0.tgz#935307f7a931016b7a5eb25d494ea3e1f613e929" + integrity sha512-uty9H2K4Xs8E47z3SnXEPRNDfsis8JO27amp2GNCnzGETEW3yTqEIVg5+AI7U276oGF/tw6ZA+UesxeQ104ceA== + +"@typescript-eslint/typescript-estree@6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.14.0.tgz#90c7ddd45cd22139adf3d4577580d04c9189ac13" + integrity sha512-yPkaLwK0yH2mZKFE/bXkPAkkFgOv15GJAUzgUVonAbv0Hr4PK/N2yaA/4XQbTZQdygiDkpt5DkxPELqHguNvyw== + dependencies: + "@typescript-eslint/types" "6.14.0" + "@typescript-eslint/visitor-keys" "6.14.0" + debug "^4.3.4" + globby "^11.1.0" + is-glob "^4.0.3" + semver "^7.5.4" + ts-api-utils "^1.0.1" + +"@typescript-eslint/utils@6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-6.14.0.tgz#856a9e274367d99ffbd39c48128b93a86c4261e3" + integrity sha512-XwRTnbvRr7Ey9a1NT6jqdKX8y/atWG+8fAIu3z73HSP8h06i3r/ClMhmaF/RGWGW1tHJEwij1uEg2GbEmPYvYg== + dependencies: + "@eslint-community/eslint-utils" "^4.4.0" + "@types/json-schema" "^7.0.12" + "@types/semver" "^7.5.0" + "@typescript-eslint/scope-manager" "6.14.0" + "@typescript-eslint/types" "6.14.0" + "@typescript-eslint/typescript-estree" "6.14.0" + semver "^7.5.4" + +"@typescript-eslint/visitor-keys@6.14.0": + version "6.14.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.14.0.tgz#1d1d486581819287de824a56c22f32543561138e" + integrity sha512-fB5cw6GRhJUz03MrROVuj5Zm/Q+XWlVdIsFj+Zb1Hvqouc8t+XP2H5y53QYU/MGtd2dPg6/vJJlhoX3xc2ehfw== + dependencies: + "@typescript-eslint/types" "6.14.0" + eslint-visitor-keys "^3.4.1" + "@ungap/structured-clone@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.2.0.tgz#756641adb587851b5ccb3e095daf27ae581c8406" @@ -701,6 +796,11 @@ array-includes@^3.1.7: get-intrinsic "^1.2.1" is-string "^1.0.7" +array-union@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" + integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== + array.prototype.findlastindex@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.3.tgz#b37598438f97b579166940814e2c0493a4f50207" @@ -831,6 +931,13 @@ brace-expansion@^1.1.7: balanced-match "^1.0.0" concat-map "0.0.1" +braces@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" + integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== + dependencies: + fill-range "^7.0.1" + brorand@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" @@ -1095,6 +1202,13 @@ digest-header@^1.0.0: resolved "https://registry.yarnpkg.com/digest-header/-/digest-header-1.1.0.tgz#e16ab6cf4545bc4eea878c8c35acd1b89664d800" integrity sha512-glXVh42vz40yZb9Cq2oMOt70FIoWiv+vxNvdKdU8CwjLad25qHM3trLxhl9bVjdr6WaslIXhWpn0NO8T/67Qjg== +dir-glob@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" + integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== + dependencies: + path-type "^4.0.0" + doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" @@ -1231,7 +1345,15 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== -eslint-config-standard@^17.1.0: +eslint-config-standard-with-typescript@^39.1.1: + version "39.1.1" + resolved "https://registry.yarnpkg.com/eslint-config-standard-with-typescript/-/eslint-config-standard-with-typescript-39.1.1.tgz#d682bd1fc8f1ee996940f85c9b0a833d7cfa5fee" + integrity sha512-t6B5Ep8E4I18uuoYeYxINyqcXb2UbC0SOOTxRtBSt2JUs+EzeXbfe2oaiPs71AIdnoWhXDO2fYOHz8df3kV84A== + dependencies: + "@typescript-eslint/parser" "^6.4.0" + eslint-config-standard "17.1.0" + +eslint-config-standard@17.1.0, eslint-config-standard@^17.1.0: version "17.1.0" resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-17.1.0.tgz#40ffb8595d47a6b242e07cbfd49dc211ed128975" integrity sha512-IwHwmaBNtDK4zDHQukFDW5u/aTb8+meQWZvNFWkiGmbWjD6bqyuSSBxxXKkCftCUzc1zwCH2m/baCNDLGmuO5Q== @@ -1580,6 +1702,17 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== +fast-glob@^3.2.9: + version "3.3.2" + resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" + integrity sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow== + dependencies: + "@nodelib/fs.stat" "^2.0.2" + "@nodelib/fs.walk" "^1.2.3" + glob-parent "^5.1.2" + merge2 "^1.3.0" + micromatch "^4.0.4" + fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" @@ -1604,6 +1737,13 @@ file-entry-cache@^6.0.1: dependencies: flat-cache "^3.0.4" +fill-range@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" + integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== + dependencies: + to-regex-range "^5.0.1" + finalhandler@1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.2.tgz#b7e7d000ffd11938d0fdb053506f6ebabe9f587d" @@ -1762,6 +1902,13 @@ get-tsconfig@^4.7.0: dependencies: resolve-pkg-maps "^1.0.0" +glob-parent@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" + integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== + dependencies: + is-glob "^4.0.1" + glob-parent@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" @@ -1795,6 +1942,18 @@ globalthis@^1.0.3: dependencies: define-properties "^1.1.3" +globby@^11.1.0: + version "11.1.0" + resolved "https://registry.yarnpkg.com/globby/-/globby-11.1.0.tgz#bd4be98bb042f83d796f7e3811991fbe82a0d34b" + integrity sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g== + dependencies: + array-union "^2.1.0" + dir-glob "^3.0.1" + fast-glob "^3.2.9" + ignore "^5.2.0" + merge2 "^1.4.1" + slash "^3.0.0" + gopd@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.0.1.tgz#29ff76de69dac7489b7c0918a5788e56477c332c" @@ -2027,7 +2186,7 @@ is-extglob@^2.1.1: resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== -is-glob@^4.0.0, is-glob@^4.0.3: +is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== @@ -2046,6 +2205,11 @@ is-number-object@^1.0.4: dependencies: has-tostringtag "^1.0.0" +is-number@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" + integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== + is-path-inside@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" @@ -2262,11 +2426,24 @@ merge-descriptors@1.0.1: resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61" integrity sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w== +merge2@^1.3.0, merge2@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" + integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== + methods@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" integrity sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w== +micromatch@^4.0.4: + version "4.0.5" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.5.tgz#bc8999a7cbbf77cdc89f132f6e467051b49090c6" + integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA== + dependencies: + braces "^3.0.2" + picomatch "^2.3.1" + mime-db@1.52.0: version "1.52.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" @@ -2503,6 +2680,11 @@ path-to-regexp@0.1.7: resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" integrity sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ== +path-type@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" + integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== + pause-stream@~0.0.11: version "0.0.11" resolved "https://registry.yarnpkg.com/pause-stream/-/pause-stream-0.0.11.tgz#fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445" @@ -2521,6 +2703,11 @@ pbkdf2@^3.0.17: safe-buffer "^5.0.1" sha.js "^2.4.8" +picomatch@^2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" + integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== + prelude-ls@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" @@ -2758,7 +2945,7 @@ semver@^6.1.0, semver@^6.3.1: resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== -semver@^7.0.0, semver@^7.5.3: +semver@^7.0.0, semver@^7.5.3, semver@^7.5.4: version "7.5.4" resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== @@ -2858,6 +3045,11 @@ side-channel@^1.0.4: get-intrinsic "^1.0.2" object-inspect "^1.9.0" +slash@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" + integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== + solc@0.8.6: version "0.8.6" resolved "https://registry.yarnpkg.com/solc/-/solc-0.8.6.tgz#e4341fa6780137df97b94a0cfbd59b3f2037d0e0" @@ -2968,11 +3160,23 @@ tmp@0.0.33: dependencies: os-tmpdir "~1.0.2" +to-regex-range@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" + integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== + dependencies: + is-number "^7.0.0" + toidentifier@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== +ts-api-utils@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-1.0.3.tgz#f12c1c781d04427313dbac808f453f050e54a331" + integrity sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg== + tsconfig-paths@^3.14.2: version "3.14.2" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.14.2.tgz#6e32f1f79412decd261f92d633a9dc1cfa99f088" diff --git a/test/agent/agent_environment.py b/test/agent/agent_environment.py index 92528884..3921d6cf 100644 --- a/test/agent/agent_environment.py +++ b/test/agent/agent_environment.py @@ -36,3 +36,4 @@ def prepare(self): chdir(self.config.agent_src) execute('rm -rf node_modules') execute('yarn install') + execute('yarn rebuild') From 8c8b5f4f56fc58ce2aa5345ec34d5e6cff4397f6 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 11:12:33 +0000 Subject: [PATCH 15/53] IMA/TypeScript support improvements, linting added, GA improved --- .github/workflows/comprehensive.yml | 8 ++++---- .github/workflows/container-test.yml | 8 ++++---- runner/run.sh | 2 +- test/agent-test.mjs | 12 ++++++------ test/agent/agent.py | 2 +- test/unitTests/agentUnitTests.js | 10 +++++----- test/unitTests/testSocketServer.mjs | 2 +- test/unitTests/testSocketSignalingServer.mjs | 10 +++++----- test/unitTests/testSocketTypes.mjs | 6 +++--- test/unitTests/testSocketWorker.mjs | 2 +- 10 files changed, 31 insertions(+), 31 deletions(-) diff --git a/.github/workflows/comprehensive.yml b/.github/workflows/comprehensive.yml index 8eac844b..b12c41ae 100644 --- a/.github/workflows/comprehensive.yml +++ b/.github/workflows/comprehensive.yml @@ -281,22 +281,22 @@ jobs: - name: SELF-TEST A - use IMA to browse S-Chain via node 00-00 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.1:2164 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.1:2164 || true - name: SELF-TEST B - use IMA to browse S-Chain via node 00-01 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.2:2264 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.2:2264 || true - name: SELF-TEST C - use IMA to browse S-Chain via node 01-00 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.3:2364 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.3:2364 || true - name: SELF-TEST D - use IMA to browse S-Chain via node 01-01 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.4:2464 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.4:2464 || true - name: INIT - download SGX Wallet working-directory: ${{env.working-directory}} diff --git a/.github/workflows/container-test.yml b/.github/workflows/container-test.yml index 4e7645db..3b89a976 100644 --- a/.github/workflows/container-test.yml +++ b/.github/workflows/container-test.yml @@ -291,22 +291,22 @@ jobs: - name: SELF-TEST A - use IMA to browse S-Chain via node 00-00 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.1:2164 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.1:2164 || true - name: SELF-TEST B - use IMA to browse S-Chain via node 00-01 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.2:2264 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.2:2264 || true - name: SELF-TEST C - use IMA to browse S-Chain via node 01-00 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.3:2364 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.3:2364 || true - name: SELF-TEST D - use IMA to browse S-Chain via node 01-01 and test last is alive working-directory: ${{env.working-directory}} run: | - node ./src/main.mjs --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.4:2464 || true + node ./src/build/main.js --colors --no-gathered --browse-s-chain --url-s-chain=http://127.0.0.4:2464 || true - name: INIT - build IMA docker container working-directory: ${{env.working-directory}} diff --git a/runner/run.sh b/runner/run.sh index 6821994d..11f164ae 100644 --- a/runner/run.sh +++ b/runner/run.sh @@ -115,7 +115,7 @@ BASE_OPTIONS="--gas-price-multiplier=$GAS_PRICE_MULTIPLIER \ --no-expose-pwa \ --auto-exit=86400" -IMA_LOOP_CMD="node $DIR/../src/main.mjs --loop $BASE_OPTIONS" +IMA_LOOP_CMD="node $DIR/../src/build/main.js --loop $BASE_OPTIONS" NETWORK_BROWSER_CMD="node $DIR/../network-browser/network-browser.js" echo "$(date) - Running IMA loop and network-browser" diff --git a/test/agent-test.mjs b/test/agent-test.mjs index d111b4c6..c40e0386 100644 --- a/test/agent-test.mjs +++ b/test/agent-test.mjs @@ -29,13 +29,13 @@ import * as os from "os"; import * as path from "path"; import * as url from "url"; -import * as owaspUtils from "../src/owaspUtils.mjs"; -import * as imaTx from "../src/imaTx.mjs"; -import * as log from "../src/log.mjs"; -import * as imaUtils from "../src/utils.mjs"; -import * as imaCLI from "../src/cli.mjs"; +import * as owaspUtils from "../src/build/owaspUtils.js"; +import * as imaTx from "../src/build/imaTx.js"; +import * as log from "../src/build/log.js"; +import * as imaUtils from "../src/build/utils.js"; +import * as imaCLI from "../src/build/cli.js"; -import * as state from "../src/state.mjs"; +import * as state from "../src/build/state.js"; const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); const __filename = new URL( "", import.meta.url ).pathname; diff --git a/test/agent/agent.py b/test/agent/agent.py index 9ba8fdbb..7c115248 100644 --- a/test/agent/agent.py +++ b/test/agent/agent.py @@ -406,7 +406,7 @@ def _construct_command(self, command, flags=None): flags = {**self._get_default_flags(), command: None, **flags} return ['node', - f'{self.config.agent_src}/main.mjs'] + \ + f'{self.config.agent_src}/build/main.js'] + \ [f'--{key}' + (f'={str(value)}' if value is not None else '') for key, value in flags.items() ] def _format_command(self, command, flags=None): diff --git a/test/unitTests/agentUnitTests.js b/test/unitTests/agentUnitTests.js index 7322bc70..fb503704 100644 --- a/test/unitTests/agentUnitTests.js +++ b/test/unitTests/agentUnitTests.js @@ -25,11 +25,11 @@ const assert = require( "chai" ).assert; const expect = require( "chai" ).expect; -const IMA = require( "../../src/imaCore.mjs" ); -const imaTx = require( "../../src/imaTx.mjs" ); -const imaReg = require( "../../src/imaRegistrationOperations.mjs" ); -const imaEth = require( "../../src/imaEthOperations.mjs" ); -const imaToken = require( "../../src/imaTokenOperations.mjs" ); +const IMA = require( "../../src/build/imaCore.js" ); +const imaTx = require( "../../src/build/imaTx.js" ); +const imaReg = require( "../../src/build/imaRegistrationOperations.js" ); +const imaEth = require( "../../src/build/imaEthOperations.js" ); +const imaToken = require( "../../src/build/imaTokenOperations.js" ); const w3mod = IMA.w3mod; const transactionCustomizerMainNet = imaTx.getTransactionCustomizerForMainNet(); const transactionCustomizerSChain = imaTx.getTransactionCustomizerForSChain(); diff --git a/test/unitTests/testSocketServer.mjs b/test/unitTests/testSocketServer.mjs index 069befa5..27bd12b1 100644 --- a/test/unitTests/testSocketServer.mjs +++ b/test/unitTests/testSocketServer.mjs @@ -23,7 +23,7 @@ * @copyright SKALE Labs 2019-Present */ -import { SocketServer } from "../../src/socketServer.mjs"; +import { SocketServer } from "../../src/build/socketServer.js"; export class TestSocketServer extends SocketServer { constructor( acceptor ) { diff --git a/test/unitTests/testSocketSignalingServer.mjs b/test/unitTests/testSocketSignalingServer.mjs index c39a3945..b59a6849 100644 --- a/test/unitTests/testSocketSignalingServer.mjs +++ b/test/unitTests/testSocketSignalingServer.mjs @@ -19,7 +19,7 @@ */ /** - * @file testSocketSignalingServer.mjs.mjs + * @file testSocketSignalingServer.mjs * @copyright SKALE Labs 2019-Present */ @@ -29,10 +29,10 @@ import * as httpsModuleLoaded from "https"; import * as wsModuleLoaded from "ws"; import * as webRtcModuleLoaded from "wrtc"; -import * as networkLayer from "../../src/socket.mjs"; -import { settings } from "../../src/socketSettings.mjs"; -import { UniversalDispatcherEvent, EventDispatcher } from "../../src/eventDispatcher.mjs"; -import * as utils from "../../src/socketUtils.mjs"; +import * as networkLayer from "../../src/build/socket.js"; +import { settings } from "../../src/build/socketSettings.js"; +import { UniversalDispatcherEvent, EventDispatcher } from "../../src/build/eventDispatcher.js"; +import * as utils from "../../src/build/socketUtils.js"; const httpsModule = httpsModuleLoaded; // .default; const wsModule = wsModuleLoaded; // .default; diff --git a/test/unitTests/testSocketTypes.mjs b/test/unitTests/testSocketTypes.mjs index 9353487c..38ec2198 100644 --- a/test/unitTests/testSocketTypes.mjs +++ b/test/unitTests/testSocketTypes.mjs @@ -25,12 +25,12 @@ import * as path from "path"; import * as url from "url"; -import * as networkLayer from "../../src/socket.mjs"; +import * as networkLayer from "../../src/build/socket.js"; import { TestSocketServer } from "./testSocketServer.mjs"; import { Worker } from "worker_threads"; -import { settings } from "../../src/socketSettings.mjs"; +import { settings } from "../../src/build/socketSettings.js"; import * as ws from "ws"; -import * as threadInfo from "../../src/threadInfo.mjs"; +import * as threadInfo from "../../src/build/threadInfo.js"; const __dirname = path.dirname( url.fileURLToPath( import.meta.url ) ); diff --git a/test/unitTests/testSocketWorker.mjs b/test/unitTests/testSocketWorker.mjs index cf968742..1f43d6a3 100644 --- a/test/unitTests/testSocketWorker.mjs +++ b/test/unitTests/testSocketWorker.mjs @@ -23,7 +23,7 @@ * @copyright SKALE Labs 2019-Present */ -import * as networkLayer from "../../src/socket.mjs"; +import * as networkLayer from "../../src/build/socket.js"; import { TestSocketServer } from "./testSocketServer.mjs"; import { parentPort From c0fef1bf6f2493aac165b97be3807205ca4c81ff Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 11:37:37 +0000 Subject: [PATCH 16/53] IMA/TypeScript support improvements, linting added, GA improved --- src/.eslintrc.cjs | 16 -- src/bls.ts | 157 +++++------ src/cc.ts | 2 +- src/cli.ts | 7 +- src/clpTools.ts | 223 +++++++-------- src/discoveryTools.ts | 54 ++-- src/eventDispatcher.ts | 2 +- src/imaCore.ts | 120 ++++---- src/imaEthOperations.ts | 12 +- src/imaEventLogScan.ts | 38 +-- src/imaGasUsageOperations.ts | 8 +- src/imaOracleOperations.ts | 22 +- src/imaRegistrationOperations.ts | 4 +- src/imaReimbursementOperations.ts | 12 +- src/imaSgxExternalSigner.ts | 28 +- src/imaTokenOperations.ts | 120 ++++---- src/imaTransferErrorHandling.ts | 10 +- src/imaTx.ts | 40 +-- src/log.ts | 184 ++++++------- src/loop.ts | 312 ++++++++++----------- src/loopWorker.ts | 57 ++-- src/main.ts | 38 +-- src/observer.ts | 2 +- src/oracle.ts | 8 +- src/owaspUtils.ts | 146 +++++----- src/pwa.ts | 26 +- src/rpcCall.ts | 74 ++--- src/socket.ts | 440 +++++++++++++++--------------- src/socketServer.ts | 2 +- src/socketUtils.ts | 8 +- src/state.ts | 424 ++++++++++++++-------------- test/agent-test.mjs | 10 +- test/unitTests/agentUnitTests.js | 6 +- 33 files changed, 1309 insertions(+), 1303 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 16d14b2a..27acfcac 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -23,7 +23,6 @@ module.exports = { "quotes": [ "error", "double" ], "semi": [ "error", "always" ], "camelcase": "off", - // "no-unused-vars": "off", "eqeqeq": "off", "comma-dangle": [ "error", "never" ], "comma-style": [ "error", "last" ], @@ -36,28 +35,15 @@ module.exports = { "spaced-comment": "off", "curly": [ "error", "multi-or-nest" ], "nonblock-statement-body-position": [ "error", "below" ], - "one-var": "off", "no-unneeded-ternary": "off", "no-cond-assign": [ "error", "always" ], - "no-console": "off", - "new-cap": "off", "no-tabs": "off", "no-mixed-spaces-and-tabs": "off", - "no-prototype-builtins": "off", - "quote-props": "off", - "no-undef": "off", "no-useless-return": "off", "no-new": "off", - "no-useless-constructor": "off", - "no-lone-blocks": "off", "no-fallthrough": "off", - "no-useless-catch": "off", "padded-blocks": "off", - "no-use-before-define": "off", // [ "error", { "variables": false, "functions": false } ], "lines-between-class-members": [ "error", "never" ], - "no-var": "error", - "no-unused-vars": "error", - "object-shorthand": 0, "multiline-ternary": "off", "max-len": [ "error", { "code": 100, "tabWidth": 4 } ], "max-lines-per-function": [ "error", { "max": 200, "skipBlankLines": false } ], @@ -85,8 +71,6 @@ module.exports = { "@typescript-eslint/lines-between-class-members": "off", "handle-callback-err": "off", "n/handle-callback-err": "off", - "@typescript-eslint/no-floating-promises": "off", - "@typescript-eslint/no-misused-promises": "off", "@typescript-eslint/prefer-optional-chain": "off" } }; diff --git a/src/bls.ts b/src/bls.ts index abeb382d..201f0365 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -325,7 +325,7 @@ function performBlsGlue( details.trace( "{p}Computing G1 hash point...", strLogPrefix ); const strPath = strActionDir + "/hash.json"; details.trace( "{p}Saving {} file...", strLogPrefix, strPath ); - imaUtils.jsonFileSave( strPath, { "message": strMessageHash } ); + imaUtils.jsonFileSave( strPath, { message: strMessageHash } ); const strHasG1Command = imaState.strPathHashG1 + " --t " + nThreshold + @@ -414,7 +414,7 @@ function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ): a details.trace( "{p}Computing G1 hash point...", strLogPrefix ); const strPath = strActionDir + "/hash.json"; details.trace( "{p}Saving {} file...", strLogPrefix, strPath ); - imaUtils.jsonFileSave( strPath, { "message": strMessageHash } ); + imaUtils.jsonFileSave( strPath, { message: strMessageHash } ); const strHasG1Command = imaState.strPathHashG1 + " --t " + nThreshold + @@ -485,7 +485,7 @@ function performBlsVerifyI( keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.trace( "{p}BLS node #{} - hashed verify message is {}", strLogPrefix, nZeroBasedNodeIndex, strMessageHash ); - const joMsg: any = { "message": strMessageHash }; + const joMsg: any = { message: strMessageHash }; details.debug( "{p}BLS node #{} - composed {} composed from {} using glue {} and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, jarrMessages, joResultFromNode, joPublicKey ); @@ -539,7 +539,7 @@ function performBlsVerifyIU256( } let strOutput = ""; try { - const joMsg: any = { "message": keccak256U256( u256, true ) }; + const joMsg: any = { message: keccak256U256( u256, true ) }; details.debug( "{p}BLS u256 node #{} verify message {} composed from {} using glue {} " + "and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, u256, joResultFromNode, joPublicKey ); @@ -605,7 +605,7 @@ function performBlsVerify( keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.trace( "{p}BLS/summary verify message - hashed verify message is {}", strLogPrefix, strMessageHash ); - const joMsg: any = { "message": strMessageHash }; + const joMsg: any = { message: strMessageHash }; details.debug( "{p}BLS/summary verify message - composed JSON {} from messages array {}" + " using glue {} and common public key {}", @@ -664,7 +664,7 @@ function performBlsVerifyU256( let strOutput = ""; const strLogPrefix = "BLS u256/Summary: "; try { - const joMsg: any = { "message": keccak256U256( u256, true ) }; + const joMsg: any = { message: keccak256U256( u256, true ) }; details.debug( "{p}BLS u256/summary verify message {} composed from {} using glue {}" + " and common public key {}", @@ -712,7 +712,7 @@ async function checkCorrectnessOfMessagesToSign( ) { const imaState = state.get(); let joMessageProxy: owaspUtils.ethersMod.ethers.Contract | null = null; - let joAccount: any = null, joChainName: any = null; + let joAccount: any = null; let joChainName: any = null; if( strDirection == "M2S" ) { joMessageProxy = imaState.joMessageProxyMainNet; joAccount = imaState.chainProperties.mn.joAccount; @@ -750,7 +750,7 @@ async function checkCorrectnessOfMessagesToSign( joMessageProxy ? joMessageProxy.address : "", strCallerAccountAddress, jarrMessages.length, jarrMessages, nIdxCurrentMsgBlockStart, joChainName ); - let cntBadMessages = 0, i = 0; + let cntBadMessages = 0; let i = 0; const cnt = jarrMessages.length; if( strDirection == "S2M" || strDirection == "S2S" ) { for( i = 0; i < cnt; ++i ) { @@ -763,11 +763,11 @@ async function checkCorrectnessOfMessagesToSign( strLogPrefix, strDirection, i, cnt, idxMessage, joMessage.sender, joMessage.destinationContract, joMessage.data ); const outgoingMessageData: any = { - "dstChainHash": owaspUtils.ethersMod.ethers.utils.id( joChainName ), - "msgCounter": 0 + idxMessage, - "srcContract": joMessage.sender, - "dstContract": joMessage.destinationContract, - "data": joMessage.data + dstChainHash: owaspUtils.ethersMod.ethers.utils.id( joChainName ), + msgCounter: 0 + idxMessage, + srcContract: joMessage.sender, + dstContract: joMessage.destinationContract, + data: joMessage.data }; if( ! joMessageProxy ) throw new Error( "No message proxy available" ); @@ -901,7 +901,7 @@ async function gatherSigningCheckFinish( optsSignOperation: any ) { return false; optsSignOperation.strLogPrefixB = `${optsSignOperation.strDirection} /# ` + `${optsSignOperation.nTransferLoopCounter}/BLS/Summary: `; - let strError: string | null = null, strSuccessfulResultDescription: string | null = null; + let strError: string | null = null; let strSuccessfulResultDescription: string | null = null; const joGlueResult = performBlsGlue( optsSignOperation.details, optsSignOperation.strDirection, optsSignOperation.jarrMessages, optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.strFromChainName, @@ -1229,17 +1229,17 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { return; await doSignConfigureChainAccessParams( optsSignOperation ); const joParams: any = { - "direction": "" + optsSignOperation.strDirection, - "startMessageIdx": optsSignOperation.nIdxCurrentMsgBlockStart, - "dstChainName": optsSignOperation.targetChainName, - "srcChainName": optsSignOperation.fromChainName, - "dstChainID": optsSignOperation.targetChainID, - "srcChainID": optsSignOperation.fromChainID, - "messages": optsSignOperation.jarrMessages, - "qa": { - "skaledNumber": 0 + i, + direction: "" + optsSignOperation.strDirection, + startMessageIdx: optsSignOperation.nIdxCurrentMsgBlockStart, + dstChainName: optsSignOperation.targetChainName, + srcChainName: optsSignOperation.fromChainName, + dstChainID: optsSignOperation.targetChainID, + srcChainID: optsSignOperation.fromChainID, + messages: optsSignOperation.jarrMessages, + qa: { + skaledNumber: 0 + i, "optsSignOperation.sequenceId": "" + optsSignOperation.sequenceId, - "ts": "" + log.generateTimestampString( null, false ) + ts: "" + log.generateTimestampString( null, false ) } }; optsSignOperation.details.trace( @@ -1248,7 +1248,7 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { log.generateTimestampString( null, true ), "skale_imaVerifyAndSign", i, strNodeURL, optsSignOperation.fromChainName, optsSignOperation.targetChainName, joParams, optsSignOperation.sequenceId ); - const joIn: any = { "method": "skale_imaVerifyAndSign", "params": joParams }; + const joIn: any = { method: "skale_imaVerifyAndSign", params: joParams }; const joOut = await joCall.call( joIn ); await doSignProcessHandleCall( optsSignOperation, joParams, joCall, joIn, joOut, i ); } @@ -1260,13 +1260,13 @@ async function doSignMessagesImpl( ) { const optsSignOperation: any = { imaState: state.get(), - nTransferLoopCounter: nTransferLoopCounter, - strDirection: strDirection, - jarrMessages: jarrMessages, - nIdxCurrentMsgBlockStart: nIdxCurrentMsgBlockStart, - strFromChainName: strFromChainName, - joExtraSignOpts: joExtraSignOpts, - fn: fn, + nTransferLoopCounter, + strDirection, + jarrMessages, + nIdxCurrentMsgBlockStart, + strFromChainName, + joExtraSignOpts, + fn, bHaveResultReportCalled: false, strLogPrefix: "", strLogPrefixA: "", @@ -1318,7 +1318,10 @@ async function doSignMessagesImpl( break } doSignProcessOneImpl( i, optsSignOperation ) - .then( function() {} ).catch( function() {} ); + .then( function() {} ).catch( function( err ) { + log.error( + "Failed single BLS sign processing, reported error is: {err}", err ); + } ); } await gatherSigningStartImpl( optsSignOperation ); await gatherSigningFinishImpl( optsSignOperation ); @@ -1528,9 +1531,9 @@ async function doSignU256OneImpl( i: number, optsSignU256: any ) { optsSignU256.details.trace( "{p}Will invoke skale_imaBSU256 for to sign value {}", optsSignU256.strLogPrefix, optsSignU256.u256.toString() ); const joIn: any = { - "method": "skale_imaBSU256", - "params": { - "valueToSign": optsSignU256.u256 // must be 0x string, came from outside 0x string + method: "skale_imaBSU256", + params: { + valueToSign: optsSignU256.u256 // must be 0x string, came from outside 0x string } }; const joOut = await joCall.call( joIn ); @@ -1661,9 +1664,9 @@ async function doSignU256Gathering( optsSignU256: any ) { export async function doSignU256( u256: any, details: any, fn: any ) { const optsSignU256: any = { - u256: u256, - fn: fn, - details: details, + u256, + fn, + details, imaState: state.get(), strLogPrefix: "Sign u256: ", joGatheringTracker: { @@ -1742,7 +1745,7 @@ export async function doVerifyReadyHash( details.trace( "{p}BLS node #{} - hashed verify message is {}", strLogPrefix, nZeroBasedNodeIndex, strMessageHash ); const joMsg: any = { - "message": strMessageHash + message: strMessageHash }; details.debug( "{p}BLS node #{} - composed {} using hash {} and glue {} and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, strMessageHash, @@ -1821,7 +1824,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a const imaState = state.get(); const strLogPrefix = ""; const details: any = log.createMemoryStream(); - let joSignResult: any = null, joCall: any = null; + let joSignResult: any = null; let joCall: any = null; try { const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -1847,8 +1850,8 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 ) { rpcCallOpts = { - "cert": fs.readFileSync( joAccount.strPathSslCert, "utf8" ), - "key": fs.readFileSync( joAccount.strPathSslKey, "utf8" ) + cert: fs.readFileSync( joAccount.strPathSslCert, "utf8" ), + key: fs.readFileSync( joAccount.strPathSslKey, "utf8" ) }; } else details.warning( "Will sign via SGX without SSL options" ); @@ -1857,15 +1860,15 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); const joIn: any = { - "jsonrpc": "2.0", - "id": utils.randomCallID(), - "method": "blsSignMessageHash", - "params": { - "keyShareName": joAccount.strBlsKeyName, - "messageHash": strMessageHash, - "n": nParticipants, - "t": nThreshold, - "signerIndex": signerIndex // 1-based + jsonrpc: "2.0", + id: utils.randomCallID(), + method: "blsSignMessageHash", + params: { + keyShareName: joAccount.strBlsKeyName, + messageHash: strMessageHash, + n: nParticipants, + t: nThreshold, + signerIndex // 1-based } }; details.trace( "{p}Will invoke SGX with call data {}", strLogPrefix, joIn ); @@ -1958,7 +1961,7 @@ async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) "try again later" ); } - let joSChainSrc: any = null, strUrlSrcSChain: string | null = null; + let joSChainSrc: any = null; let strUrlSrcSChain: string | null = null; for( let idxSChain = 0; idxSChain < arrSChainsCached.length; ++ idxSChain ) { const joSChain = arrSChainsCached[idxSChain]; if( joSChain.name.toString() == strSChainNameSrc.toString() ) { @@ -2034,7 +2037,7 @@ async function handleBlsSignMessageHashResult( export async function handleSkaleImaVerifyAndSign( joCallData: any ) { const optsHandleVerifyAndSign: any = { - joCallData: joCallData, + joCallData, imaState: state.get(), strLogPrefix: "", details: log.createMemoryStream(), @@ -2082,8 +2085,8 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 ) { rpcCallOpts = { - "cert": fs.readFileSync( joAccount.strPathSslCert, "utf8" ), - "key": fs.readFileSync( joAccount.strPathSslKey, "utf8" ) + cert: fs.readFileSync( joAccount.strPathSslCert, "utf8" ), + key: fs.readFileSync( joAccount.strPathSslKey, "utf8" ) }; } else optsHandleVerifyAndSign.details.warning( "Will sign via SGX without SSL options" ); @@ -2092,15 +2095,15 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); const joIn = { - "jsonrpc": "2.0", - "id": utils.randomCallID(), - "method": "blsSignMessageHash", - "params": { - "keyShareName": joAccount.strBlsKeyName, - "messageHash": optsHandleVerifyAndSign.strMessageHash, - "n": optsHandleVerifyAndSign.nParticipants, - "t": optsHandleVerifyAndSign.nThreshold, - "signerIndex": signerIndex // 1-based + jsonrpc: "2.0", + id: utils.randomCallID(), + method: "blsSignMessageHash", + params: { + keyShareName: joAccount.strBlsKeyName, + messageHash: optsHandleVerifyAndSign.strMessageHash, + n: optsHandleVerifyAndSign.nParticipants, + t: optsHandleVerifyAndSign.nThreshold, + signerIndex // 1-based } }; optsHandleVerifyAndSign.details.trace( @@ -2200,7 +2203,7 @@ async function handleBlsSignMessageHash256Result( export async function handleSkaleImaBSU256( joCallData: any ) { const optsBSU256: any = { - joCallData: joCallData, + joCallData, imaState: state.get(), strLogPrefix: "", details: log.createMemoryStream(), @@ -2225,8 +2228,8 @@ export async function handleSkaleImaBSU256( joCallData: any ) { optsBSU256.joAccount.strPathSslCert.length > 0 ) { rpcCallOpts = { - "cert": fs.readFileSync( optsBSU256.joAccount.strPathSslCert, "utf8" ), - "key": fs.readFileSync( optsBSU256.joAccount.strPathSslKey, "utf8" ) + cert: fs.readFileSync( optsBSU256.joAccount.strPathSslCert, "utf8" ), + key: fs.readFileSync( optsBSU256.joAccount.strPathSslKey, "utf8" ) }; } else optsBSU256.details.warning( "Will sign via SGX without SSL options" ); @@ -2237,15 +2240,15 @@ export async function handleSkaleImaBSU256( joCallData: any ) { `to ${optsBSU256.joAccount.strSgxURL}` ); } const joIn = { - "jsonrpc": "2.0", - "id": utils.randomCallID(), - "method": "blsSignMessageHash", - "params": { - "keyShareName": optsBSU256.joAccount.strBlsKeyName, - "messageHash": optsBSU256.strMessageHash, - "n": optsBSU256.nParticipants, - "t": optsBSU256.nThreshold, - "signerIndex": signerIndex // 1-based + jsonrpc: "2.0", + id: utils.randomCallID(), + method: "blsSignMessageHash", + params: { + keyShareName: optsBSU256.joAccount.strBlsKeyName, + messageHash: optsBSU256.strMessageHash, + n: optsBSU256.nParticipants, + t: optsBSU256.nThreshold, + signerIndex // 1-based } }; optsBSU256.details.trace( "{p}Will invoke SGX with call data {}", diff --git a/src/cc.ts b/src/cc.ts index 3e76ad78..e8465528 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -935,7 +935,7 @@ export function capitalizeFirstLetter( s?: any ): string { function errFnDottedName( s?: any ): string { const arr = s.split( "." ); const cnt = arr.length; - let i, s2 = ""; + let i; let s2 = ""; for( i = 0; i < cnt; ++ i ) { if( i > 0 ) s2 += bright( "." ); diff --git a/src/cli.ts b/src/cli.ts index b0502d60..a16c7200 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2656,7 +2656,7 @@ export function imaInitEthersProviders() { imaState.chainProperties.mn.strURL.length > 0 ) { const u = imaState.chainProperties.mn.strURL; - asyncCheckUrlAtStartup( u, "Main-net" ); + asyncCheckUrlAtStartup( u, "Main-net" ).then( function() {} ).catch( function() {} ); imaState.chainProperties.mn.ethersProvider = owaspUtils.getEthersProviderFromURL( u ); } else { log.warning( "No Main-net URL specified in command line arguments" + @@ -2668,7 +2668,7 @@ export function imaInitEthersProviders() { imaState.chainProperties.sc.strURL.length > 0 ) { const u = imaState.chainProperties.sc.strURL; - asyncCheckUrlAtStartup( u, "S-Chain" ); + asyncCheckUrlAtStartup( u, "S-Chain" ).then( function() {} ).catch( function() {} ); imaState.chainProperties.sc.ethersProvider = owaspUtils.getEthersProviderFromURL( u ); } else { log.warning( "No S-Chain URL specified in command line arguments" + @@ -2680,7 +2680,8 @@ export function imaInitEthersProviders() { imaState.chainProperties.tc.strURL.length > 0 ) { const u = imaState.chainProperties.tc.strURL; - asyncCheckUrlAtStartup( u, "S<->S Target S-Chain" ); + asyncCheckUrlAtStartup( u, "S<->S Target S-Chain" ) + .then( function() {} ).catch( function() {} ); imaState.chainProperties.tc.ethersProvider = owaspUtils.getEthersProviderFromURL( u ); } else { log.warning( "No S<->S Target S-Chain URL specified in command line arguments" + diff --git a/src/clpTools.ts b/src/clpTools.ts index 748985c0..8e6c2de3 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -133,8 +133,8 @@ export function printSummaryRegistrationCosts( details?: any ) { export function commandLineTaskRegister() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Full registration(all steps)", - "fn": async function() { + name: "Full registration(all steps)", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // registerAll return await registerAll( true ); @@ -145,8 +145,8 @@ export function commandLineTaskRegister() { export function commandLineTaskRegister1() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Registration step 1, register S-Chain in deposit box", - "fn": async function() { + name: "Registration step 1, register S-Chain in deposit box", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // registerStep1 return await registerStep1( true ); @@ -157,8 +157,8 @@ export function commandLineTaskRegister1() { export function commandLineTaskCheckRegistration() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Full registration status check(all steps)", - "fn": async function() { + name: "Full registration status check(all steps)", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // checkRegistrationAll const b = await checkRegistrationAll(); @@ -173,8 +173,8 @@ export function commandLineTaskCheckRegistration() { export function commandLineTaskCheckRegistration1() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Registration status check step 1, register S-Chain in deposit box", - "fn": async function() { + name: "Registration status check step 1, register S-Chain in deposit box", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // checkRegistrationStep1 const b = await checkRegistrationStep1(); @@ -189,8 +189,8 @@ export function commandLineTaskCheckRegistration1() { export function commandLineTaskMintErc20() { const imaState = state.get(); imaState.arrActions.push( { - "name": "mint ERC20", - "fn": async function() { + name: "mint ERC20", + fn: async function() { let bMintIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { try { @@ -222,8 +222,8 @@ export function commandLineTaskMintErc20() { export function commandLineTaskMintErc721() { const imaState = state.get(); imaState.arrActions.push( { - "name": "mint ERC721", - "fn": async function() { + name: "mint ERC721", + fn: async function() { let bMintIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc721.length > 0 ) { try { @@ -263,8 +263,8 @@ export function commandLineTaskMintErc721() { export function commandLineTaskMintErc1155() { const imaState = state.get(); imaState.arrActions.push( { - "name": "mint ERC1155", - "fn": async function() { + name: "mint ERC1155", + fn: async function() { let bMintIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc1155.length > 0 ) { try { @@ -307,8 +307,8 @@ export function commandLineTaskMintErc1155() { export function commandLineTaskBurnErc20() { const imaState = state.get(); imaState.arrActions.push( { - "name": "burn ERC20", - "fn": async function() { + name: "burn ERC20", + fn: async function() { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { try { @@ -342,8 +342,8 @@ export function commandLineTaskBurnErc20() { export function commandLineTaskBurnErc721() { const imaState = state.get(); imaState.arrActions.push( { - "name": "burn ERC721", - "fn": async function() { + name: "burn ERC721", + fn: async function() { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc721.length > 0 ) { try { @@ -382,8 +382,8 @@ export function commandLineTaskBurnErc721() { export function commandLineTaskBurnErc1155() { const imaState = state.get(); imaState.arrActions.push( { - "name": "burn ERC1155", - "fn": async function() { + name: "burn ERC1155", + fn: async function() { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc1155.length > 0 ) { try { @@ -430,14 +430,14 @@ export async function commandLineTaskShowBalanceEth( let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider ) { arrBalancesMN.push( { - "assetName": "RealETH", - "balance": await imaEth.getBalanceEth( true, // isMainNet + assetName: "RealETH", + balance: await imaEth.getBalanceEth( true, // isMainNet imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.chainId, imaState.chainProperties.mn.joAccount ) } ); arrBalancesMN.push( { - "assetName": "CanReceiveETH", - "balance": await imaEth.viewEthPaymentFromSchainOnMainNet( + assetName: "CanReceiveETH", + balance: await imaEth.viewEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.joAccount, imaState.joDepositBoxETH ) } ); @@ -449,30 +449,30 @@ export async function commandLineTaskShowBalanceEth( } if( imaState.chainProperties.sc.ethersProvider ) { arrBalancesSC.push( { - "assetName": "S-Chain Real ETH as ERC20", - "assetAddress": assetAddress, - "balance": await imaEth.getBalanceEth( false, // isMainNet + assetName: "S-Chain Real ETH as ERC20", + assetAddress, + balance: await imaEth.getBalanceEth( false, // isMainNet imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, imaState.chainProperties.sc.joAccount, imaState.joEthErc20 ) } ); arrBalancesSC.push( { - "assetName": "S-Chain ETH Fuel", - "balance": await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain + assetName: "S-Chain ETH Fuel", + balance: await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, imaState.chainProperties.sc.joAccount ) } ); } if( imaState.chainProperties.tc.ethersProvider ) { arrBalancesSC.push( { - "assetName": "Target S-Chain Real ETH as ERC20", - "assetAddress": assetAddress, - "balance": await imaEth.getBalanceEth( false, // isMainNet + assetName: "Target S-Chain Real ETH as ERC20", + assetAddress, + balance: await imaEth.getBalanceEth( false, // isMainNet imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.sc.chainId, imaState.chainProperties.tc.joAccount, imaState.joEthErc20 ) } ); arrBalancesTC.push( { - "assetName": "Target S-Chain ETH Fuel", - "balance": await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain + assetName: "Target S-Chain ETH Fuel", + balance: await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId, imaState.chainProperties.tc.joAccount ) } ); @@ -492,9 +492,9 @@ export async function commandLineTaskShowBalanceErc20( imaState.chainProperties.mn.strCoinNameErc20 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesMN.push( { - "assetName": "ERC20", - "assetAddress": assetAddress, - "balance": await imaToken.getBalanceErc20( true, // isMainNet + assetName: "ERC20", + assetAddress, + balance: await imaToken.getBalanceErc20( true, // isMainNet imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.chainId, imaState.chainProperties.mn.joAccount, imaState.chainProperties.mn.strCoinNameErc20, @@ -509,9 +509,9 @@ export async function commandLineTaskShowBalanceErc20( imaState.chainProperties.sc.strCoinNameErc20 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesSC.push( { - "assetName": "ERC20", - "assetAddress": assetAddress, - "balance": await imaToken.getBalanceErc20( false, // isMainNet + assetName: "ERC20", + assetAddress, + balance: await imaToken.getBalanceErc20( false, // isMainNet imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strCoinNameErc20, @@ -526,9 +526,9 @@ export async function commandLineTaskShowBalanceErc20( imaState.chainProperties.tc.strCoinNameErc20 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesTC.push( { - "assetName": "ERC20", - "assetAddress": assetAddress, - "balance": await imaToken.getBalanceErc20( true, // isMainNet + assetName: "ERC20", + assetAddress, + balance: await imaToken.getBalanceErc20( true, // isMainNet imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.mn.chainId, imaState.chainProperties.tc.joAccount, imaState.chainProperties.tc.strCoinNameErc20, @@ -552,10 +552,10 @@ export async function commandLineTaskShowBalanceErc721( imaState.chainProperties.mn.strCoinNameErc721 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesMN.push( { - "assetName": "ERC721", - "assetAddress": assetAddress, - "idToken": idToken, - "owner": await imaToken.getOwnerOfErc721( true, // isMainNet + assetName: "ERC721", + assetAddress, + idToken, + owner: await imaToken.getOwnerOfErc721( true, // isMainNet imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.chainId, imaState.chainProperties.mn.joAccount, @@ -574,10 +574,10 @@ export async function commandLineTaskShowBalanceErc721( imaState.chainProperties.sc.strCoinNameErc721 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesSC.push( { - "assetName": "ERC721", - "assetAddress": assetAddress, - "idToken": idToken, - "owner": await imaToken.getOwnerOfErc721( false, // isMainNet + assetName: "ERC721", + assetAddress, + idToken, + owner: await imaToken.getOwnerOfErc721( false, // isMainNet imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, imaState.chainProperties.sc.joAccount, @@ -596,10 +596,10 @@ export async function commandLineTaskShowBalanceErc721( imaState.chainProperties.tc.strCoinNameErc721 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesTC.push( { - "assetName": "ERC721", - "assetAddress": assetAddress, - "idToken": idToken, - "owner": await imaToken.getOwnerOfErc721( false, // isMainNet + assetName: "ERC721", + assetAddress, + idToken, + owner: await imaToken.getOwnerOfErc721( false, // isMainNet imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId, imaState.chainProperties.tc.joAccount, @@ -625,10 +625,10 @@ export async function commandLineTaskShowBalanceErc1155( imaState.chainProperties.mn.strCoinNameErc1155 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesMN.push( { - "assetName": "ERC1155", - "assetAddress": assetAddress, - "idToken": idToken, - "balance": await imaToken.getBalanceErc1155( true, // isMainNet + assetName: "ERC1155", + assetAddress, + idToken, + balance: await imaToken.getBalanceErc1155( true, // isMainNet imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.chainId, imaState.chainProperties.mn.joAccount, @@ -647,10 +647,10 @@ export async function commandLineTaskShowBalanceErc1155( imaState.chainProperties.sc.strCoinNameErc1155 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesSC.push( { - "assetName": "ERC1155", - "assetAddress": assetAddress, - "idToken": idToken, - "balance": await imaToken.getBalanceErc1155( false, // isMainNet + assetName: "ERC1155", + assetAddress, + idToken, + balance: await imaToken.getBalanceErc1155( false, // isMainNet imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, imaState.chainProperties.sc.joAccount, @@ -669,10 +669,10 @@ export async function commandLineTaskShowBalanceErc1155( imaState.chainProperties.tc.strCoinNameErc1155 + "_address"]; } catch ( err ) { assetAddress = null; } arrBalancesTC.push( { - "assetName": "ERC1155", - "assetAddress": assetAddress, - "idToken": idToken, - "balance": await imaToken.getBalanceErc1155( false, // isMainNet + assetName: "ERC1155", + assetAddress, + idToken, + balance: await imaToken.getBalanceErc1155( false, // isMainNet imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId, imaState.chainProperties.tc.joAccount, @@ -686,9 +686,10 @@ export async function commandLineTaskShowBalanceErc1155( export function commandLineTaskShowBalance() { const imaState = state.get(); imaState.arrActions.push( { - "name": "show balance", - "fn": async function() { - const arrBalancesMN: any = [], arrBalancesSC: any = [], arrBalancesTC: any = []; + name: "show balance", + fn: async function() { + const arrBalancesMN: any = []; + const arrBalancesSC: any = []; const arrBalancesTC: any = []; await commandLineTaskShowBalanceEth( arrBalancesMN, arrBalancesSC, arrBalancesTC ); await commandLineTaskShowBalanceErc20( @@ -743,8 +744,8 @@ export function commandLineTaskShowBalance() { export function commandLineTaskPaymentM2S() { const imaState = state.get(); imaState.arrActions.push( { - "name": "one M->S single payment", - "fn": async function() { + name: "one M->S single payment", + fn: async function() { if( imaState.chainProperties.mn.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one M->S single ERC721 payment: {}", imaState.idToken ); @@ -893,8 +894,8 @@ export function commandLineTaskPaymentM2S() { export function commandLineTaskPaymentS2M() { const imaState = state.get(); imaState.arrActions.push( { - "name": "one S->M single payment", - "fn": async function() { + name: "one S->M single payment", + fn: async function() { if( imaState.chainProperties.sc.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one S->M single ERC721 payment: {}", imaState.idToken ); @@ -1038,10 +1039,10 @@ export function commandLineTaskPaymentS2M() { export function commandLineTaskPaymentS2S() { const imaState = state.get(); imaState.arrActions.push( { - "name": "one S->S single payment", - "fn": async function() { + name: "one S->S single payment", + fn: async function() { const isForward = imaHelperAPIs.isForwardS2S(); - const sc = imaState.chainProperties.sc, tc = imaState.chainProperties.tc; + const sc = imaState.chainProperties.sc; const tc = imaState.chainProperties.tc; const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = isForward ? sc.ethersProvider : tc.ethersProvider; const chainIdSrc = isForward ? sc.chainId : tc.chainId; @@ -1207,8 +1208,8 @@ export function commandLineTaskPaymentS2S() { export function commandLineTaskReceiveS2M() { const imaState = state.get(); imaState.arrActions.push( { - "name": "receive one S->M single ETH payment", - "fn": async function() { + name: "receive one S->M single ETH payment", + fn: async function() { log.information( "receive one S->M single ETH payment:" ); return await imaEth.receiveEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, @@ -1224,8 +1225,8 @@ export function commandLineTaskReceiveS2M() { export function commandLineTaskViewS2M() { const imaState = state.get(); imaState.arrActions.push( { - "name": "view one S->M single ETH payment", - "fn": async function() { + name: "view one S->M single ETH payment", + fn: async function() { log.information( "view one S->M single ETH payment:" ); const xWei = await imaEth.viewEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, @@ -1245,8 +1246,8 @@ export function commandLineTaskViewS2M() { export function commandLineTaskTransferM2S() { const imaState = state.get(); imaState.arrActions.push( { - "name": "single M->S transfer loop", - "fn": async function() { + name: "single M->S transfer loop", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // main-net --> s-chain transfer const joRuntimeOpts: any = { @@ -1285,8 +1286,8 @@ export function commandLineTaskTransferM2S() { export function commandLineTaskTransferS2M() { const imaState = state.get(); imaState.arrActions.push( { - "name": "single S->M transfer loop", - "fn": async function() { + name: "single S->M transfer loop", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer const joRuntimeOpts: any = { @@ -1325,8 +1326,8 @@ export function commandLineTaskTransferS2M() { export function commandLineTaskTransferS2S() { const imaState = state.get(); imaState.arrActions.push( { - "name": "single S->S transfer loop", - "fn": async function() { + name: "single S->S transfer loop", + fn: async function() { if( ! imaState.optsS2S.isEnabled ) return; if( ! imaState.bNoWaitSChainStarted ) @@ -1361,8 +1362,8 @@ export function commandLineTaskTransferS2S() { export function commandLineTaskTransfer() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Single M<->S transfer loop iteration", - "fn": async function() { + name: "Single M<->S transfer loop iteration", + fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); const joRuntimeOpts: any = { @@ -1371,7 +1372,7 @@ export function commandLineTaskTransfer() { cntChainsKnownForS2S: 0 }; const optsLoop: any = { - joRuntimeOpts: joRuntimeOpts, + joRuntimeOpts, isDelayFirstRun: false, enableStepOracle: true, enableStepM2S: true, @@ -1386,8 +1387,8 @@ export function commandLineTaskTransfer() { export function commandLineTaskLoop() { const imaState = state.get(); imaState.arrActions.push( { - "name": "M<->S and S->S transfer loop, startup in parallel mode", - "fn": async function() { + name: "M<->S and S->S transfer loop, startup in parallel mode", + fn: async function() { state.setPreventExitAfterLastAction( true ); if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // M<->S transfer loop @@ -1400,8 +1401,8 @@ export function commandLineTaskLoop() { if( isPrintSummaryRegistrationCosts ) printSummaryRegistrationCosts(); const opts: any = { - imaState: imaState, - "details": log + imaState, + details: log }; return await loop.runParallelLoops( opts @@ -1413,8 +1414,8 @@ export function commandLineTaskLoop() { export function commandLineTaskLoopSimple() { const imaState = state.get(); imaState.arrActions.push( { - "name": "M<->S and S->S transfer loop, startup simple mode", - "fn": async function() { + name: "M<->S and S->S transfer loop, startup simple mode", + fn: async function() { state.setPreventExitAfterLastAction( true ); if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // M<->S transfer loop @@ -1432,7 +1433,7 @@ export function commandLineTaskLoopSimple() { cntChainsKnownForS2S: 0 }; const optsLoop: any = { - joRuntimeOpts: joRuntimeOpts, + joRuntimeOpts, isDelayFirstRun: false, enableStepOracle: true, enableStepM2S: true, @@ -1465,7 +1466,7 @@ async function handleBrowseSkaleModesRpcInfoResult( joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); - const jIn: any = { "method": "skale_imaInfo", "params": { } }; + const jIn: any = { method: "skale_imaInfo", params: { } }; if( discoveryTools.isSendImaAgentIndex() ) jIn.params.fromImaAgentIndex = imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -1493,8 +1494,8 @@ export function commandLineTaskBrowseSChain() { const imaState = state.get(); imaState.bIsNeededCommonInit = false; imaState.arrActions.push( { - "name": "Browse S-Chain network", - "fn": async function() { + name: "Browse S-Chain network", + fn: async function() { const strLogPrefix = "S-Chain Browse: "; if( imaState.chainProperties.sc.strURL.length === 0 ) { log.fatal( "Missing S-Chain URL, please specify {}", "--url-s-chain" ); @@ -1509,7 +1510,7 @@ export function commandLineTaskBrowseSChain() { throw new Error( "Failed to create JSON RPC call object " + `to ${imaState.chainProperties.sc.strURL}` ); } - const joIn: any = { "method": "skale_nodesRpcInfo", "params": { } }; + const joIn: any = { method: "skale_nodesRpcInfo", params: { } }; if( discoveryTools.isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -1528,8 +1529,8 @@ export function commandLineTaskBrowseSChain() { export function commandLineTaskReimbursementShowBalance() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Gas Reimbursement - Show Balance", - "fn": async function() { + name: "Gas Reimbursement - Show Balance", + fn: async function() { await imaReimbursement.reimbursementShowBalance( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, @@ -1548,8 +1549,8 @@ export function commandLineTaskReimbursementShowBalance() { export function commandLineTaskReimbursementEstimateAmount() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Gas Reimbursement - Estimate Amount", - "fn": async function() { + name: "Gas Reimbursement - Estimate Amount", + fn: async function() { await imaReimbursement.reimbursementEstimateAmount( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, @@ -1568,8 +1569,8 @@ export function commandLineTaskReimbursementEstimateAmount() { export function commandLineTaskReimbursementRecharge() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Gas Reimbursement - Recharge User Wallet", - "fn": async function() { + name: "Gas Reimbursement - Recharge User Wallet", + fn: async function() { await imaReimbursement.reimbursementWalletRecharge( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, @@ -1588,8 +1589,8 @@ export function commandLineTaskReimbursementRecharge() { export function commandLineTaskReimbursementWithdraw() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Gas Reimbursement - Withdraw User Wallet", - "fn": async function() { + name: "Gas Reimbursement - Withdraw User Wallet", + fn: async function() { await imaReimbursement.reimbursementWalletWithdraw( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, @@ -1608,8 +1609,8 @@ export function commandLineTaskReimbursementWithdraw() { export function commandLineTaskReimbursementSetRange() { const imaState = state.get(); imaState.arrActions.push( { - "name": "Gas Reimbursement - Set Minimal time interval from S2M and S2S transfers", - "fn": async function() { + name: "Gas Reimbursement - Set Minimal time interval from S2M and S2S transfers", + fn: async function() { await imaReimbursement.reimbursementSetRange( imaState.chainProperties.sc.ethersProvider, imaState.joCommunityLocker, diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 4ad5d5f2..027de917 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -271,12 +271,18 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole } fnAfter(); continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, null ) - .then( function() {} ).catch( function() {} ); ; + .then( function() {} ).catch( function( err ) { + log.error( + "Failed to continue S-chain discovery, reported error is: {err}", err ); + } ); ; } catch ( err ) { } gFlagIsInSChainDiscovery = false; // fnAfter() will be called here inside async call at beginning continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, fnAfter ) - .then( function() {} ).catch( function() {} ); ; + .then( function() {} ).catch( function( err ) { + log.error( + "Failed to continue S-chain discovery, reported error is: {err}", err ); + } ); } export async function continueSChainDiscoveryInBackgroundIfNeeded( @@ -320,7 +326,8 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( } } gTimerSChainDiscovery = setInterval( function() { - handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery, fnAfter ); + handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery, fnAfter ) + .then( function() {} ).catch( function() {} ); }, imaState.joSChainDiscovery.periodicDiscoveryInterval ); } @@ -372,7 +379,7 @@ async function discoverSChainWalkNodes( optsDiscover: any ) { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); - const joIn: any = { "method": "skale_imaInfo", "params": { } }; + const joIn: any = { method: "skale_imaInfo", params: { } }; if( isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = optsDiscover.imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -521,6 +528,8 @@ async function handleDiscoverSkaleNodesRpcInfoResult( optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); rv = true; } ).catch( function( err: Error | string ) { + log.error( + "Failed to wait until S-chain discovery complete, reported error is: {err}", err ); if( optsDiscover.fnAfter ) optsDiscover.fnAfter( err, null ); } ); @@ -531,10 +540,10 @@ export async function discoverSChainNetwork( fnAfter: any, isSilentReDiscovery: boolean, joPrevSChainNetworkInfo: any, nCountToWait: number ) { const optsDiscover: any = { - fnAfter: fnAfter, + fnAfter, isSilentReDiscovery: ( !!isSilentReDiscovery ), joPrevSChainNetworkInfo: joPrevSChainNetworkInfo || null, - nCountToWait: nCountToWait, + nCountToWait, imaState: state.get(), strLogPrefix: "S-Chain network discovery: ", joSChainNetworkInfo: null, @@ -557,7 +566,7 @@ export async function discoverSChainNetwork( joCall = await rpcCall.create( scURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${scURL}` ); - const joIn: any = { "method": "skale_nodesRpcInfo", "params": { } }; + const joIn: any = { method: "skale_nodesRpcInfo", params: { } }; if( isSendImaAgentIndex() ) joIn.params.fromImaAgentIndex = optsDiscover.imaState.nNodeNumber; const joOut = await joCall.call( joIn ); @@ -630,7 +639,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( periodicDiscoveryInterval ); } fnAfterRediscover = fnAfterRediscover || function() { }; - gIntervalPeriodicDiscovery = setInterval( async function() { + gIntervalPeriodicDiscovery = setInterval( function() { let nCountToWait = ( cntNodesOnChain > 2 ) ? Math.ceil( cntNodesOnChain * 2 / 3 ) : cntNodesOnChain; @@ -638,20 +647,21 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( nCountToWait = cntNodesOnChain; if( !isSilentReDiscovery ) log.information( "This S-Chain discovery will be done for periodic discovery update" ); - await discoverSChainNetwork( - null, isSilentReDiscovery, joPrevSChainNetworkInfo, nCountToWait ); - joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; - if( checkPeriodicDiscoveryNoLongerNeeded( - joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { - if( ! isSilentReDiscovery ) - log.information( "Final periodic S-Chain re-discovery done" ); - fnAfterRediscover( true ); - return // not needed anymore, all nodes completely discovered - } - if( ! isSilentReDiscovery ) - log.information( "Partial periodic S-Chain re-discovery done" ); - - fnAfterRediscover( false ); + discoverSChainNetwork( + null, isSilentReDiscovery, joPrevSChainNetworkInfo, nCountToWait ) + .then( function() { + joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; + if( checkPeriodicDiscoveryNoLongerNeeded( + joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { + if( ! isSilentReDiscovery ) + log.information( "Final periodic S-Chain re-discovery done" ); + fnAfterRediscover( true ); + return // not needed anymore, all nodes completely discovered + } + if( ! isSilentReDiscovery ) + log.information( "Partial periodic S-Chain re-discovery done" ); + fnAfterRediscover( false ); + } ).catch( function() {} ); }, periodicDiscoveryInterval ); if( ! isSilentReDiscovery ) { log.information( "Periodic S-Chain re-discovery was started with interval {}" + diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index 0b45aada..773544d4 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -54,7 +54,7 @@ export class EventDispatcher { this.isDisposing = true; this.isDisposed = true; this.dispatchEvent( - new UniversalDispatcherEvent( "dispose", { "detail": { "ref": this } } ) + new UniversalDispatcherEvent( "dispose", { detail: { ref: this } } ) ); this.removeAllEventListeners(); } diff --git a/src/imaCore.ts b/src/imaCore.ts index 6ea90e04..4bd38c93 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -61,13 +61,13 @@ async function findOutReferenceLogRecord( for( let idxLogRecord = 0; idxLogRecord < cntLogRecord; ++ idxLogRecord ) { const joEvent = arrLogRecords[idxLogRecord]; const ev: any = { - "currentMessage": joEvent.args[0], - "previousOutgoingMessageBlockId": joEvent.args[1] + currentMessage: joEvent.args[0], + previousOutgoingMessageBlockId: joEvent.args[1] }; const joReferenceLogRecord: any = { - "currentMessage": ev.currentMessage, - "previousOutgoingMessageBlockId": ev.previousOutgoingMessageBlockId, - "currentBlockId": bnBlockId + currentMessage: ev.currentMessage, + previousOutgoingMessageBlockId: ev.previousOutgoingMessageBlockId, + currentBlockId: bnBlockId }; const bnCurrentMessage = owaspUtils.toBN( joReferenceLogRecord.currentMessage.toString() ); @@ -275,11 +275,11 @@ async function analyzeGatheredRecords( optsTransfer: any, r: any ) { optsTransfer.details.debug( "{p}Will review found event record {} with data {}", optsTransfer.strLogPrefix, i, joEvent ); const ev: any = { - "dstChainHash": joEvent.args[0], - "msgCounter": joEvent.args[1], - "srcContract": joEvent.args[2], - "dstContract": joEvent.args[3], - "data": joEvent.args[4] + dstChainHash: joEvent.args[0], + msgCounter: joEvent.args[1], + srcContract: joEvent.args[2], + dstContract: joEvent.args[3], + data: joEvent.args[4] }; if( ev.dstChainHash == strChainHashWeAreLookingFor ) { joValues = ev; @@ -321,7 +321,7 @@ async function gatherMessages( optsTransfer: any ) { const idxProcessing = optsTransfer.cntProcessed + idxInBlock; if( idxProcessing > optsTransfer.nMaxTransactionsCount ) break; - let nBlockFrom = 0, nBlockTo = "latest"; + let nBlockFrom = 0; let nBlockTo = "latest"; if( optsTransfer.arrLogRecordReferences.length > 0 ) { const joReferenceLogRecord = optsTransfer.arrLogRecordReferences.shift(); if( joReferenceLogRecord && "currentBlockId" in joReferenceLogRecord && @@ -444,12 +444,12 @@ async function gatherMessages( optsTransfer: any ) { optsTransfer.strLogPrefix, optsTransfer.nIdxCurrentMsg ); optsTransfer.arrMessageCounters.push( optsTransfer.nIdxCurrentMsg ); const joMessage: any = { - "sender": joValues.srcContract, - "destinationContract": joValues.dstContract, - "to": joValues.to, - "amount": joValues.amount, - "data": joValues.data, - "savedBlockNumberForOptimizations": joValues.savedBlockNumberForOptimizations + sender: joValues.srcContract, + destinationContract: joValues.dstContract, + to: joValues.to, + amount: joValues.amount, + data: joValues.data, + savedBlockNumberForOptimizations: joValues.savedBlockNumberForOptimizations }; optsTransfer.jarrMessages.push( joMessage ); } @@ -563,10 +563,10 @@ async function callbackAllMessagesSign( weiHowMuchPostIncomingMessages, opts ); if( joReceipt && typeof joReceipt == "object" ) { optsTransfer.jarrReceipts.push( { - "description": "doTransfer/postIncomingMessages()", + description: "doTransfer/postIncomingMessages()", "optsTransfer.detailsString": "" + optsTransfer.strGatheredDetailsName, - "receipt": joReceipt + receipt: joReceipt } ); imaGasUsage.printGasUsageReportFromArray( "(intermediate result) TRANSFER " + optsTransfer.chainNameSrc + " -> " + optsTransfer.chainNameDst, @@ -632,7 +632,7 @@ async function handleAllMessagesSigning( optsTransfer: any ) { optsTransfer.chainNameSrc, optsTransfer.joExtraSignOpts, async function( err: Error | string, jarrMessages: any[], joGlueResult: any ) { await callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ); - return + } ).catch( function( err: Error | string ) { // callback fn as argument of optsTransfer.fnSignMessages optsTransfer.bErrorInSigningMessages = true; @@ -689,11 +689,11 @@ async function checkOutgoingMessageEventInOneNode( for( let idxEvent = 0; idxEvent < cntEvents; ++ idxEvent ) { const joEvent = nodeRV[idxEvent]; const eventValuesByName: any = { - "dstChainHash": joEvent.args[0], - "msgCounter": joEvent.args[1], - "srcContract": joEvent.args[2], - "dstContract": joEvent.args[3], - "data": joEvent.args[4] + dstChainHash: joEvent.args[0], + msgCounter: joEvent.args[1], + srcContract: joEvent.args[2], + dstContract: joEvent.args[3], + data: joEvent.args[4] }; if( owaspUtils.ensureStartsWith0x( joMessage.sender ).toLowerCase() == owaspUtils.ensureStartsWith0x( eventValuesByName.srcContract ).toLowerCase() && @@ -753,12 +753,12 @@ async function checkOutgoingMessageEvent( optsTransfer: any, joSChain: any ) { "message envelope data: {}", optsTransfer.strLogPrefix, optsTransfer.strDirection, idxMessage + 1, cntMessages, idxImaMessage, joMessage ); const optsOutgoingMessageAnalysis: any = { - idxMessage: idxMessage, - idxImaMessage: idxImaMessage, - joMessage: joMessage, + idxMessage, + idxImaMessage, + joMessage, joNode: null, idxNode: 0, - cntNodes: cntNodes, + cntNodes, cntPassedNodes: 0, cntFailedNodes: 0 }; @@ -942,28 +942,28 @@ export async function doTransfer( transactionCustomizerDst: imaTx.TransactionCustomizer ) { const optsTransfer: any = { - strDirection: strDirection, - joRuntimeOpts: joRuntimeOpts, - ethersProviderSrc: ethersProviderSrc, - joMessageProxySrc: joMessageProxySrc, - joAccountSrc: joAccountSrc, - ethersProviderDst: ethersProviderDst, - joMessageProxyDst: joMessageProxyDst, - joAccountDst: joAccountDst, - chainNameSrc: chainNameSrc, - chainNameDst: chainNameDst, - chainIdSrc: chainIdSrc, - chainIdDst: chainIdDst, - joDepositBoxMainNet: joDepositBoxMainNet, // for logs validation on mainnet - joTokenManagerSChain: joTokenManagerSChain, // for logs validation on s-chain - nTransactionsCountInBlock: nTransactionsCountInBlock, - nTransferSteps: nTransferSteps, - nMaxTransactionsCount: nMaxTransactionsCount, - nBlockAwaitDepth: nBlockAwaitDepth, - nBlockAge: nBlockAge, - fnSignMessages: fnSignMessages, - joExtraSignOpts: joExtraSignOpts, - transactionCustomizerDst: transactionCustomizerDst, + strDirection, + joRuntimeOpts, + ethersProviderSrc, + joMessageProxySrc, + joAccountSrc, + ethersProviderDst, + joMessageProxyDst, + joAccountDst, + chainNameSrc, + chainNameDst, + chainIdSrc, + chainIdDst, + joDepositBoxMainNet, // for logs validation on mainnet + joTokenManagerSChain, // for logs validation on s-chain + nTransactionsCountInBlock, + nTransferSteps, + nMaxTransactionsCount, + nBlockAwaitDepth, + nBlockAge, + fnSignMessages, + joExtraSignOpts, + transactionCustomizerDst, imaState: state.get(), nTransferLoopCounter: 0 + gTransferLoopCounter, strTransferErrorCategoryName: "loop-" + strDirection, @@ -1107,7 +1107,7 @@ export async function doAllS2S( // s-chain --> s-chain fnSignMessages: any, transactionCustomizerDst: imaTx.TransactionCustomizer ) { - let cntOK = 0, cntFail = 0, nIndexS2S = 0; + let cntOK = 0; let cntFail = 0; let nIndexS2S = 0; const sc = imaState.chainProperties.sc; const strDirection = "S2S"; const arrSChainsCached = skaleObserver.getLastCachedSChains(); @@ -1145,14 +1145,14 @@ export async function doAllS2S( // s-chain --> s-chain sc.joAbiIMA.message_proxy_chain_abi, ethersProviderSrc ); const joExtraSignOpts: any = { - chainNameSrc: chainNameSrc, - chainIdSrc: chainIdSrc, - chainNameDst: chainNameDst, - chainIdDst: chainIdDst, - joAccountSrc: joAccountSrc, - joAccountDst: joAccountDst, - ethersProviderSrc: ethersProviderSrc, - ethersProviderDst: ethersProviderDst + chainNameSrc, + chainIdSrc, + chainNameDst, + chainIdDst, + joAccountSrc, + joAccountDst, + ethersProviderSrc, + ethersProviderDst }; joRuntimeOpts.idxChainKnownForS2S = idxSChain; joRuntimeOpts.cntChainsKnownForS2S = cntSChains; diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 045ad418..d9880c60 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -113,8 +113,8 @@ export async function doEthPaymentFromMainNet( gasPrice, estimatedGas, weiHowMuch ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "doEthPaymentFromMainNet", - "receipt": joReceipt + description: "doEthPaymentFromMainNet", + receipt: joReceipt } ); } @@ -210,8 +210,8 @@ export async function doEthPaymentFromSChain( gasPrice, estimatedGas, 0, opts ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "doEthPaymentFromSChain", - "receipt": joReceipt + description: "doEthPaymentFromSChain", + receipt: joReceipt } ); } @@ -294,8 +294,8 @@ export async function receiveEthPaymentFromSchainOnMainNet( gasPrice, estimatedGas, weiHowMuch ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "receiveEthPaymentFromSchainOnMainNet", - "receipt": joReceipt + description: "receiveEthPaymentFromSchainOnMainNet", + receipt: joReceipt } ); } } catch ( err ) { diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 3c6eb168..9fadf1f2 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -39,30 +39,30 @@ export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumbe const blocksInOneYear = blocksInOneDay * 366; const blocksInThreeYears = blocksInOneYear * 3; const arrProgressiveEventsScanPlanA = [ { - "nBlockFrom": + nBlockFrom: nLatestBlockNumber - blocksInOneDay, - "nBlockTo": "latest", - "type": "1 day" + nBlockTo: "latest", + type: "1 day" }, { - "nBlockFrom": + nBlockFrom: nLatestBlockNumber - blocksInOneWeek, - "nBlockTo": "latest", - "type": "1 week" + nBlockTo: "latest", + type: "1 week" }, { - "nBlockFrom": + nBlockFrom: nLatestBlockNumber - blocksInOneMonth, - "nBlockTo": "latest", - "type": "1 month" + nBlockTo: "latest", + type: "1 month" }, { - "nBlockFrom": + nBlockFrom: nLatestBlockNumber - blocksInOneYear, - "nBlockTo": "latest", - "type": "1 year" + nBlockTo: "latest", + type: "1 year" }, { - "nBlockFrom": + nBlockFrom: nLatestBlockNumber - blocksInThreeYears, - "nBlockTo": "latest", - "type": "3 years" + nBlockTo: "latest", + type: "3 years" } ]; const arrProgressiveEventsScanPlan: any[] = []; for( let idxPlan = 0; idxPlan < arrProgressiveEventsScanPlanA.length; ++idxPlan ) { @@ -75,11 +75,11 @@ export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumbe arrProgressiveEventsScanPlan[arrProgressiveEventsScanPlan.length - 1]; if( ! ( joLastPlan.nBlockFrom == 0 && joLastPlan.nBlockTo == "latest" ) ) { arrProgressiveEventsScanPlan.push( - { "nBlockFrom": 0, "nBlockTo": "latest", "type": "entire block range" } ); + { nBlockFrom: 0, nBlockTo: "latest", type: "entire block range" } ); } } else { arrProgressiveEventsScanPlan.push( - { "nBlockFrom": 0, "nBlockTo": "latest", "type": "entire block range" } ); + { nBlockFrom: 0, nBlockTo: "latest", type: "entire block range" } ); } return arrProgressiveEventsScanPlan; } @@ -132,7 +132,7 @@ export async function safeGetPastEventsProgressive( createProgressiveEventsScanPlan( details, nLatestBlockNumberPlus1 ); details.trace( "Composed progressive event log records scan plan is: {}", arrProgressiveEventsScanPlan ); - let joLastPlan: any = { "nBlockFrom": 0, "nBlockTo": "latest", "type": "entire block range" }; + let joLastPlan: any = { nBlockFrom: 0, nBlockTo: "latest", type: "entire block range" }; for( let idxPlan = 0; idxPlan < arrProgressiveEventsScanPlan.length; ++idxPlan ) { const joPlan = arrProgressiveEventsScanPlan[idxPlan]; if( joPlan.nBlockFrom < 0 ) @@ -173,7 +173,7 @@ export async function getContractCallEvents( joFilter = joFilter || {}; nBlockNumber = owaspUtils.toBN( nBlockNumber ); const n10 = owaspUtils.toBN( 10 ); - let nBlockFrom = nBlockNumber.sub( n10 ), nBlockTo = nBlockNumber.add( n10 ); + let nBlockFrom = nBlockNumber.sub( n10 ); let nBlockTo = nBlockNumber.add( n10 ); const nBlockZero = owaspUtils.toBN( 0 ); const nLatestBlockNumber = owaspUtils.toBN( await imaHelperAPIs.safeGetBlockNumber( details, 10, ethersProvider ) ); diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 958b1775..2fe640bd 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -28,9 +28,9 @@ import * as owaspUtils from "./owaspUtils.js"; export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ): any { if( ! ( strName && typeof strName == "string" && jarrReceipts ) ) - return { "sumGasUsed": 0, "strReport": "N/A" }; - let i, sumGasUsed = owaspUtils.toBN( "0" ), - s = "\n" + log.fmtInformation( "Gas usage report for " ) + + return { sumGasUsed: 0, strReport: "N/A" }; + let i; let sumGasUsed = owaspUtils.toBN( "0" ); + let s = "\n" + log.fmtInformation( "Gas usage report for " ) + log.fmtInformation( "{p}\n", strName ); for( i = 0; i < jarrReceipts.length; ++ i ) { try { @@ -42,7 +42,7 @@ export function composeGasUsageReportFromArray( strName: string, jarrReceipts: a } s += " " + log.fmtAttention( "SUM" ) + log.fmtDebug( "....." ) + log.fmtInformation( "{}", sumGasUsed.toString() ); - return { "sumGasUsed": sumGasUsed, "strReport": s }; + return { sumGasUsed, strReport: s }; } export function printGasUsageReportFromArray( diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index e440153b..394419c7 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -124,7 +124,7 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { if( log.exposeDetailsGet() ) optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", true ); optsGasPriseSetup.details.close(); - return + } } @@ -203,8 +203,8 @@ async function handleOracleSigned( gasPrice, estimatedGasSetGasPrice, weiHowMuch, opts ); if( joReceipt && typeof joReceipt == "object" ) { optsGasPriseSetup.jarrReceipts.push( { - "description": "doOracleGasPriceSetup/setGasPrice", - "receipt": joReceipt + description: "doOracleGasPriceSetup/setGasPrice", + receipt: joReceipt } ); imaGasUsage.printGasUsageReportFromArray( "(intermediate result) ORACLE GAS PRICE SETUP ", @@ -226,14 +226,14 @@ export async function doOracleGasPriceSetup( if( ! getEnabledOracle() ) return true; const optsGasPriseSetup: any = { - ethersProviderMainNet: ethersProviderMainNet, - ethersProviderSChain: ethersProviderSChain, - transactionCustomizerSChain: transactionCustomizerSChain, - joCommunityLocker: joCommunityLocker, - joAccountSC: joAccountSC, - chainIdMainNet: chainIdMainNet, - chainIdSChain: chainIdSChain, - fnSignMsgOracle: fnSignMsgOracle, + ethersProviderMainNet, + ethersProviderSChain, + transactionCustomizerSChain, + joCommunityLocker, + joAccountSC, + chainIdMainNet, + chainIdSChain, + fnSignMsgOracle, details: log.createMemoryStream(), jarrReceipts: [], strLogPrefix: "Oracle gas price setup: ", diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index ddc4eeee..71ef7a99 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -175,8 +175,8 @@ export async function registerSChainInDepositBoxes( // step 1 gasPrice, estimatedGas, weiHowMuch ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "registerSChainInDepositBoxes", - "receipt": joReceipt + description: "registerSChainInDepositBoxes", + receipt: joReceipt } ); } const isSChainStatusOKay = await waitForHasChain( diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index d1d1042c..2edfde3d 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -195,8 +195,8 @@ export async function reimbursementWalletRecharge( joAccountMN, strActionName, gasPrice, estimatedGas, nReimbursementRecharge, null ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "reimbursementWalletRecharge", - "receipt": joReceipt + description: "reimbursementWalletRecharge", + receipt: joReceipt } ); } } catch ( err ) { @@ -262,8 +262,8 @@ export async function reimbursementWalletWithdraw( gasPrice, estimatedGas, weiHowMuch ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "reimbursementWalletWithdraw", - "receipt": joReceipt + description: "reimbursementWalletWithdraw", + receipt: joReceipt } ); } } catch ( err ) { @@ -327,8 +327,8 @@ export async function reimbursementSetRange( joAccountSC, strActionName, gasPrice, estimatedGas, weiHowMuch, opts ); if( joReceipt && typeof joReceipt == "object" ) { jarrReceipts.push( { - "description": "reimbursementSetRange", - "receipt": joReceipt + description: "reimbursementSetRange", + receipt: joReceipt } ); } } catch ( err ) { diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index ac68fa06..c8ab0649 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -88,19 +88,19 @@ async function run() { log.debug( "--- TX hash ---> {}", txHash ); const rpcCallOpts: any = { - "cert": fs.readFileSync( strPathCert, "utf8" ), - "key": fs.readFileSync( strPathKey, "utf8" ) + cert: fs.readFileSync( strPathCert, "utf8" ), + key: fs.readFileSync( strPathKey, "utf8" ) }; const joCall: any = await rpcCall.create( strSgxWalletURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strSgxWalletURL}` ); const joIn: any = { - "method": "ecdsaSignMessageHash", - "params": { - "keyName": "" + strSgxKeyName, - "messageHash": txHash, - "base": 16 + method: "ecdsaSignMessageHash", + params: { + keyName: "" + strSgxKeyName, + messageHash: txHash, + base: 16 } }; const joOut: any = await joCall.call( joIn ); @@ -111,10 +111,10 @@ async function run() { const v = parseInt( joOut.result.signature_v ); const ethV = v + owaspUtils.parseIntOrHex( chainId ) * 2 + 35; const joExpanded = { - "recoveryParam": v, - "v": ethV, - "r": joOut.result.signature_r, - "s": joOut.result.signature_s + recoveryParam: v, + v: ethV, + r: joOut.result.signature_r, + s: joOut.result.signature_s }; if( gIsDebugLogging ) log.debug( "--- Expanded signature ---> {}", joExpanded ); @@ -145,14 +145,14 @@ async function run() { } catch ( err ) { if( gIsDebugLogging ) log.debug( "--- Call error ---> {}", log.em, ( err ) ); - finalizeOutput( { "error": owaspUtils.extractErrorMessage( err ) } ); + finalizeOutput( { error: owaspUtils.extractErrorMessage( err ) } ); process.exit( 1 ); } } catch ( err ) { if( gIsDebugLogging ) log.error( "RPC call to SGX failed: {err}", err ); - finalizeOutput( { "error": owaspUtils.extractErrorMessage( err ) } ); + finalizeOutput( { error: owaspUtils.extractErrorMessage( err ) } ); process.exit( 1 ); } } -run(); +run().then( function() {} ).catch( function() {} ); diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 172aca3f..4f37c9ac 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -183,8 +183,8 @@ export async function doErc721PaymentFromMainNet( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc721PaymentFromMainNet/approve", - "receipt": joReceiptApprove + description: "doErc721PaymentFromMainNet/approve", + receipt: joReceiptApprove } ); } @@ -215,8 +215,8 @@ export async function doErc721PaymentFromMainNet( weiHowMuchDepositERC721, null ); if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { jarrReceipts.push( { - "description": "doErc721PaymentFromMainNet/deposit", - "receipt": joReceiptDeposit + description: "doErc721PaymentFromMainNet/deposit", + receipt: joReceiptDeposit } ); } @@ -321,8 +321,8 @@ export async function doErc20PaymentFromMainNet( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc20PaymentFromMainNet/approve", - "receipt": joReceiptApprove + description: "doErc20PaymentFromMainNet/approve", + receipt: joReceiptApprove } ); } @@ -352,8 +352,8 @@ export async function doErc20PaymentFromMainNet( weiHowMuchDepositERC20, null ); if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { jarrReceipts.push( { - "description": "doErc20PaymentFromMainNet/deposit", - "receipt": joReceiptDeposit + description: "doErc20PaymentFromMainNet/deposit", + receipt: joReceiptDeposit } ); } @@ -464,8 +464,8 @@ export async function doErc1155PaymentFromMainNet( null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc1155PaymentFromMainNet/approve", - "receipt": joReceiptApprove + description: "doErc1155PaymentFromMainNet/approve", + receipt: joReceiptApprove } ); } strActionName = "ERC1155 payment from Main Net, depositERC1155"; @@ -500,8 +500,8 @@ export async function doErc1155PaymentFromMainNet( gasPrice, estimatedGasDeposit, weiHowMuchDepositERC1155, null ); if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { jarrReceipts.push( { - "description": "doErc1155PaymentFromMainNet/deposit", - "receipt": joReceiptDeposit + description: "doErc1155PaymentFromMainNet/deposit", + receipt: joReceiptDeposit } ); } // Must-have event(s) analysis as indicator(s) of success @@ -597,8 +597,8 @@ export async function doErc1155BatchPaymentFromMainNet( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc1155BatchPaymentFromMainNet/approve", - "receipt": joReceiptApprove + description: "doErc1155BatchPaymentFromMainNet/approve", + receipt: joReceiptApprove } ); } strActionName = "ERC1155 batch-payment from Main Net, depositERC1155Batch"; @@ -629,8 +629,8 @@ export async function doErc1155BatchPaymentFromMainNet( gasPrice, estimatedGasDeposit, weiHowMuchDepositERC1155Batch, null ); if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { jarrReceipts.push( { - "description": "doErc1155BatchPaymentFromMainNet/deposit", - "receipt": joReceiptDeposit + description: "doErc1155BatchPaymentFromMainNet/deposit", + receipt: joReceiptDeposit } ); } // Must-have event(s) analysis as indicator(s) of success @@ -732,8 +732,8 @@ export async function doErc20PaymentFromSChain( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc20PaymentFromSChain/approve", - "receipt": joReceiptApprove + description: "doErc20PaymentFromSChain/approve", + receipt: joReceiptApprove } ); } const nSleep = imaHelperAPIs.getSleepBetweenTransactionsOnSChainMilliseconds(); @@ -773,8 +773,8 @@ export async function doErc20PaymentFromSChain( estimatedGasExitToMainERC20, weiHowMuchExitToMainERC20, opts ); if( joReceiptExitToMainERC20 && typeof joReceiptExitToMainERC20 == "object" ) { jarrReceipts.push( { - "description": "doErc20PaymentFromSChain/exit-to-main", - "receipt": joReceiptExitToMainERC20 + description: "doErc20PaymentFromSChain/exit-to-main", + receipt: joReceiptExitToMainERC20 } ); } // Must-have event(s) analysis as indicator(s) of success @@ -878,8 +878,8 @@ export async function doErc721PaymentFromSChain( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc721PaymentFromSChain/transfer-from", - "receipt": joReceiptApprove + description: "doErc721PaymentFromSChain/transfer-from", + receipt: joReceiptApprove } ); } const nSleep = imaHelperAPIs.getSleepBetweenTransactionsOnSChainMilliseconds(); @@ -919,8 +919,8 @@ export async function doErc721PaymentFromSChain( estimatedGasExitToMainERC721, weiHowMuchExitToMainERC721, opts ); if( joReceiptExitToMainERC721 && typeof joReceiptExitToMainERC721 == "object" ) { jarrReceipts.push( { - "description": "doErc721PaymentFromSChain/exit-to-main", - "receipt": joReceiptExitToMainERC721 + description: "doErc721PaymentFromSChain/exit-to-main", + receipt: joReceiptExitToMainERC721 } ); } // Must-have event(s) analysis as indicator(s) of success @@ -1026,8 +1026,8 @@ export async function doErc1155PaymentFromSChain( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc1155PaymentFromSChain/transfer-from", - "receipt": joReceiptApprove + description: "doErc1155PaymentFromSChain/transfer-from", + receipt: joReceiptApprove } ); } const nSleep = imaHelperAPIs.getSleepBetweenTransactionsOnSChainMilliseconds(); @@ -1067,8 +1067,8 @@ export async function doErc1155PaymentFromSChain( estimatedGasExitToMainERC1155, weiHowMuchExitToMainERC1155, opts ); if( joReceiptExitToMainERC1155 && typeof joReceiptExitToMainERC1155 == "object" ) { jarrReceipts.push( { - "description": "doErc1155PaymentFromSChain/exit-to-main", - "receipt": joReceiptExitToMainERC1155 + description: "doErc1155PaymentFromSChain/exit-to-main", + receipt: joReceiptExitToMainERC1155 } ); } // Must-have event(s) analysis as indicator(s) of success @@ -1169,8 +1169,8 @@ export async function doErc1155BatchPaymentFromSChain( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": "doErc1155BatchPaymentFromSChain/transfer-from", - "receipt": joReceiptApprove + description: "doErc1155BatchPaymentFromSChain/transfer-from", + receipt: joReceiptApprove } ); } const nSleep = imaHelperAPIs.getSleepBetweenTransactionsOnSChainMilliseconds(); @@ -1213,8 +1213,8 @@ export async function doErc1155BatchPaymentFromSChain( typeof joReceiptExitToMainERC1155Batch == "object" ) { jarrReceipts.push( { - "description": "doErc1155BatchPaymentFromSChain/exit-to-main", - "receipt": joReceiptExitToMainERC1155Batch + description: "doErc1155BatchPaymentFromSChain/exit-to-main", + receipt: joReceiptExitToMainERC1155Batch } ); } // Must-have event(s) analysis as indicator(s) of success @@ -1342,8 +1342,8 @@ export async function doErc20PaymentS2S( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": `doErc20PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, - "receipt": joReceiptApprove + description: `doErc20PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, + receipt: joReceiptApprove } ); } strActionName = `ERC20 payment S2S, transferERC20 ${( isForward ? "forward" : "reverse" )}`; @@ -1373,8 +1373,8 @@ export async function doErc20PaymentS2S( estimatedGasTransfer, weiHowMuchTransferERC20, null ); if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { jarrReceipts.push( { - "description": "doErc20PaymentS2S/transfer", - "receipt": joReceiptTransfer + description: "doErc20PaymentS2S/transfer", + receipt: joReceiptTransfer } ); } } catch ( err ) { @@ -1482,9 +1482,9 @@ export async function doErc721PaymentS2S( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": + description: `doErc721PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, - "receipt": joReceiptApprove + receipt: joReceiptApprove } ); } const isIgnoreTransferERC721 = true; @@ -1516,8 +1516,8 @@ export async function doErc721PaymentS2S( gasPrice, estimatedGasTransfer, weiHowMuchTransferERC721, null ); if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { jarrReceipts.push( { - "description": "doErc721PaymentS2S/transfer", - "receipt": joReceiptTransfer + description: "doErc721PaymentS2S/transfer", + receipt: joReceiptTransfer } ); } } catch ( err ) { @@ -1628,9 +1628,9 @@ export async function doErc1155PaymentS2S( estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": + description: `doErc1155PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, - "receipt": joReceiptApprove + receipt: joReceiptApprove } ); } strActionName = @@ -1661,8 +1661,8 @@ export async function doErc1155PaymentS2S( weiHowMuchTransferERC1155, null ); if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { jarrReceipts.push( { - "description": "doErc1155PaymentS2S/transfer", - "receipt": joReceiptTransfer + description: "doErc1155PaymentS2S/transfer", + receipt: joReceiptTransfer } ); } } catch ( err ) { @@ -1774,9 +1774,9 @@ export async function doErc1155BatchPaymentS2S( joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( joReceiptApprove && typeof joReceiptApprove == "object" ) { jarrReceipts.push( { - "description": + description: `doErc1155BatchPaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, - "receipt": joReceiptApprove + receipt: joReceiptApprove } ); } strActionName = @@ -1808,8 +1808,8 @@ export async function doErc1155BatchPaymentS2S( gasPrice, estimatedGasTransfer, weiHowMuchTransferERC1155, null ); if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { jarrReceipts.push( { - "description": "doErc1155PaymentS2S/transfer", - "receipt": joReceiptTransfer + description: "doErc1155PaymentS2S/transfer", + receipt: joReceiptTransfer } ); } } catch ( err ) { @@ -1885,8 +1885,8 @@ export async function mintErc20( "ERC20", contract, "mint", arrArgumentsMint, joAccount, strActionName, gasPrice, estimatedGasMint, weiHowMuchMint, opts ); imaGasUsage.printGasUsageReportFromArray( "MINT ERC20 ", [ { - "description": "mintErc20()/mint", - "receipt": joReceipt + description: "mintErc20()/mint", + receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) details.exposeDetailsTo( log, "mintErc20", true ); @@ -1955,8 +1955,8 @@ export async function mintErc721( "ERC721", contract, "mint", arrArgumentsMint, joAccount, strActionName, gasPrice, estimatedGasMint, weiHowMuchMint, opts ); imaGasUsage.printGasUsageReportFromArray( "MINT ERC721 ", [ { - "description": "mintErc721()/mint", - "receipt": joReceipt + description: "mintErc721()/mint", + receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) details.exposeDetailsTo( log, "mintErc721", true ); @@ -2029,8 +2029,8 @@ export async function mintErc1155( "ERC1155", contract, "mint", arrArgumentsMint, joAccount, strActionName, gasPrice, estimatedGasMint, weiHowMuchMint, opts ); imaGasUsage.printGasUsageReportFromArray( "MINT ERC1155 ", [ { - "description": "mintErc1155()/mint", - "receipt": joReceipt + description: "mintErc1155()/mint", + receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) details.exposeDetailsTo( log, "mintErc1155", true ); @@ -2099,8 +2099,8 @@ export async function burnErc20( "ERC20", contract, "burnFrom", arrArgumentsBurn, joAccount, strActionName, gasPrice, estimatedGasBurn, weiHowMuchBurn, opts ); imaGasUsage.printGasUsageReportFromArray( "BURN ERC20 ", [ { - "description": "burnErc20()/burn", - "receipt": joReceipt + description: "burnErc20()/burn", + receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) details.exposeDetailsTo( log, "burnErc20", true ); @@ -2166,8 +2166,8 @@ export async function burnErc721( "ERC721", contract, "burn", arrArgumentsBurn, joAccount, strActionName, gasPrice, estimatedGasBurn, weiHowMuchBurn, opts ); imaGasUsage.printGasUsageReportFromArray( "BURN ERC721 ", [ { - "description": "burnErc721()/burn", - "receipt": joReceipt + description: "burnErc721()/burn", + receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) details.exposeDetailsTo( log, "burnErc721", true ); @@ -2240,8 +2240,8 @@ export async function burnErc1155( joAccount, strActionName, gasPrice, estimatedGasBurn, weiHowMuchBurn, opts ); imaGasUsage.printGasUsageReportFromArray( "BURN ERC1155 ", [ { - "description": "burnErc1155()/burn", - "receipt": joReceipt + description: "burnErc1155()/burn", + receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) details.exposeDetailsTo( log, "burnErc1155", true ); diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 4f90be4a..5bec39f2 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -40,9 +40,9 @@ export function saveTransferError( strCategory: string, textLog: any, ts?: any ) ts = ts || Math.round( ( new Date() ).getTime() / 1000 ); const c = verifyTransferErrorCategoryName( strCategory ); const joTransferEventError: any = { - "ts": ts, - "category": "" + c, - "textLog": "" + textLog.toString() + ts, + category: "" + c, + textLog: "" + textLog.toString() }; gArrLastTransferErrors.push( joTransferEventError ); while( gArrLastTransferErrors.length > gMaxLastTransferErrors ) @@ -51,7 +51,7 @@ export function saveTransferError( strCategory: string, textLog: any, ts?: any ) saveTransferEvents.dispatchEvent( new UniversalDispatcherEvent( "error", - { "detail": joTransferEventError } ) ); + { detail: joTransferEventError } ) ); } export function saveTransferSuccess( strCategory: string ): void { @@ -60,7 +60,7 @@ export function saveTransferSuccess( strCategory: string ): void { saveTransferEvents.dispatchEvent( new UniversalDispatcherEvent( "success", - { "detail": { "category": strCategory } } ) ); + { detail: { category: strCategory } } ) ); } export function saveTransferSuccessAll(): void { diff --git a/src/imaTx.ts b/src/imaTx.ts index c097e38c..c7f2b244 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -289,18 +289,18 @@ export async function payedCall( opts?: any ) { const optsPayedCall: any = { - details: details, - ethersProvider: ethersProvider, - strContractName: strContractName, - joContract: joContract, - strMethodName: strMethodName, - arrArguments: arrArguments, - joAccount: joAccount, - strActionName: strActionName, - gasPrice: gasPrice, - estimatedGas: estimatedGas, - weiHowMuch: weiHowMuch, - opts: opts, + details, + ethersProvider, + strContractName, + joContract, + strMethodName, + arrArguments, + joAccount, + strActionName, + gasPrice, + estimatedGas, + weiHowMuch, + opts, strContractCallDescription: "", strLogPrefix: "", joACI: null, @@ -366,9 +366,9 @@ export async function payedCall( const ethSpent = owaspUtils.ethersMod.ethers.utils.formatEther( optsPayedCall.joReceipt.cumulativeGasUsed.mul( optsPayedCall.unsignedTx.gasPrice ) ); optsPayedCall.joReceipt.summary = { - bnGasSpent: bnGasSpent, - gasSpent: gasSpent, - ethSpent: ethSpent + bnGasSpent, + gasSpent, + ethSpent }; optsPayedCall.details.trace( "{p}gas spent: {}", optsPayedCall.strLogPrefix, gasSpent ); optsPayedCall.details.trace( "{p}ETH spent: {}", optsPayedCall.strLogPrefix, ethSpent ); @@ -454,9 +454,9 @@ export async function calculatePowNumber( export function getAccountConnectivityInfo( joAccount: any ) { const joACI: any = { - "isBad": true, - "strType": "bad", - "isAutoSend": false + isBad: true, + strType: "bad", + isAutoSend: false }; if( "strTransactionManagerURL" in joAccount && typeof joAccount.strTransactionManagerURL == "string" && @@ -504,8 +504,8 @@ function tmMakeId( details: any ) { function tmMakeRecord( tx: any = {}, score: any ) { const status = "PROPOSED"; return JSON.stringify( { - "score": score, - "status": status, + score, + status, ...tx } ); } diff --git a/src/log.ts b/src/log.ts index 64b7e55c..db5ff272 100644 --- a/src/log.ts +++ b/src/log.ts @@ -128,15 +128,15 @@ export function getStreamWithFilePath( strFilePath: string ): any { export function createStandardOutputStream(): any { try { const objEntry: any = { - "id": gIdentifierAllocatorCounter ++, - "strPath": "stdout", - "nMaxSizeBeforeRotation": -1, - "nMaxFilesCount": -1, - "objStream": null, - "haveOwnTimestamps": false, - "isPausedTimeStamps": false, - "strOwnIndent": "", - "write": function( ...args: any[] ): void { + id: gIdentifierAllocatorCounter ++, + strPath: "stdout", + nMaxSizeBeforeRotation: -1, + nMaxFilesCount: -1, + objStream: null, + haveOwnTimestamps: false, + isPausedTimeStamps: false, + strOwnIndent: "", + write: function( ...args: any[] ): void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) ? generateTimestampPrefix( null, true ) : "" ); @@ -146,74 +146,74 @@ export function createStandardOutputStream(): any { this.objStream.write( s ); } catch ( err ) { } }, - "writeRaw": function( ...args: any[] ): void { + writeRaw: function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); try { if( this.objStream && s.length > 0 ) this.objStream.write( s ); } catch ( err ) { } }, - "close": function() { this.objStream = null; }, - "open": function() { try { this.objStream = process.stdout; } catch ( err ) { } }, - "size": function() { return 0; }, - "rotate": function( nBytesToWrite: number ) { }, - "toString": function(): string { return "" + this.strFilePath; }, - "exposeDetailsTo": + close: function() { this.objStream = null; }, + open: function() { try { this.objStream = process.stdout; } catch ( err ) { } }, + size: function() { return 0; }, + rotate: function( nBytesToWrite: number ) { }, + toString: function(): string { return "" + this.strFilePath; }, + exposeDetailsTo: function( otherStream: any, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters - "fatal": function( ...args: any[] ): void { + fatal: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function( ...args: any[] ): void { + critical: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) { this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, - "error": function( ...args: any[] ): void { + error: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function( ...args: any[] ): void { + warning: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function( ...args: any[] ): void { + attention: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function( ...args: any[] ): void { + information: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function( ...args: any[] ): void { + info: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function( ...args: any[] ): void { + notice: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function( ...args: any[] ): void { + note: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function( ...args: any[] ): void { + debug: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function( ...args: any[] ): void { + trace: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function( ...args: any[] ): void { + success: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } @@ -239,20 +239,20 @@ export function insertStandardOutputStream(): boolean { export function createMemoryOutputStream(): any { try { const objEntry: any = { - "id": gIdentifierAllocatorCounter ++, - "strPath": "memory", - "nMaxSizeBeforeRotation": -1, - "nMaxFilesCount": -1, - "arrAccumulatedLogTextLines": [], - "haveOwnTimestamps": true, - "isPausedTimeStamps": false, - "strOwnIndent": " ", - "isBeginningOfAccumulatedLog": function() { + id: gIdentifierAllocatorCounter ++, + strPath: "memory", + nMaxSizeBeforeRotation: -1, + nMaxFilesCount: -1, + arrAccumulatedLogTextLines: [], + haveOwnTimestamps: true, + isPausedTimeStamps: false, + strOwnIndent: " ", + isBeginningOfAccumulatedLog: function() { if( this.arrAccumulatedLogTextLines.length == 0 ) return true; return false; }, - "isLastLineEndsWithCarriageReturn": function() { + isLastLineEndsWithCarriageReturn: function() { if( this.arrAccumulatedLogTextLines.length == 0 ) return false; const s = this.arrAccumulatedLogTextLines[ @@ -263,7 +263,7 @@ export function createMemoryOutputStream(): any { return true; return false; }, - "write": function( ...args: any[] ): void { + write: function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); for( let i = 0; i < arr.length; ++ i ) { @@ -278,7 +278,7 @@ export function createMemoryOutputStream(): any { this.arrAccumulatedLogTextLines.push( strHeader + strLine + "\n" ); } }, - "writeRaw": function( ...args: any[] ): void { + writeRaw: function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); for( let i = 0; i < arr.length; ++ i ) { @@ -286,19 +286,19 @@ export function createMemoryOutputStream(): any { this.arrAccumulatedLogTextLines.push( strLine + "\n" ); } }, - "clear": function() { this.arrAccumulatedLogTextLines = []; }, - "close": function() { this.clear(); }, - "open": function() { this.clear(); }, - "size": function() { return 0; }, - "rotate": + clear: function() { this.arrAccumulatedLogTextLines = []; }, + close: function() { this.clear(); }, + open: function() { this.clear(); }, + size: function() { return 0; }, + rotate: function( nBytesToWrite: number ) { this.this.arrAccumulatedLogTextLines = []; }, - "toString": function(): string { + toString: function(): string { let s = ""; for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) s += this.arrAccumulatedLogTextLines[i]; return s; }, - "exposeDetailsTo": + exposeDetailsTo: function( otherStream: any, strTitle: string, isSuccess: boolean ): void { if( ! ( this.arrAccumulatedLogTextLines && this.arrAccumulatedLogTextLines.length > 0 ) ) @@ -339,57 +339,57 @@ export function createMemoryOutputStream(): any { } }, // high-level formatters - "fatal": function( ...args: any[] ): void { + fatal: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function( ...args: any[] ): void { + critical: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); }, - "error": function( ...args: any[] ): void { + error: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function( ...args: any[] ): void { + warning: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function( ...args: any[] ): void { + attention: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function( ...args: any[] ): void { + information: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function( ...args: any[] ): void { + info: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function( ...args: any[] ): void { + notice: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function( ...args: any[] ): void { + note: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function( ...args: any[] ): void { + debug: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function( ...args: any[] ): void { + trace: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function( ...args: any[] ): void { + success: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } @@ -416,15 +416,15 @@ export function createFileOutput( strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): any { try { const objEntry: any = { - "id": gIdentifierAllocatorCounter ++, - "strPath": "" + strFilePath, - "nMaxSizeBeforeRotation": 0 + ( nMaxSizeBeforeRotation || 0 ), - "nMaxFilesCount": 0 + ( nMaxFilesCount || 0 ), - "objStream": null, - "haveOwnTimestamps": false, - "isPausedTimeStamps": false, - "strOwnIndent": "", - "write": function( ...args: any[] ): void { + id: gIdentifierAllocatorCounter ++, + strPath: "" + strFilePath, + nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation || 0 ), + nMaxFilesCount: 0 + ( nMaxFilesCount || 0 ), + objStream: null, + haveOwnTimestamps: false, + isPausedTimeStamps: false, + strOwnIndent: "", + write: function( ...args: any[] ): void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) ? generateTimestampPrefix( null, true ) : "" ); @@ -436,7 +436,7 @@ export function createFileOutput( } } catch ( err ) { } }, - "writeRaw": function( ...args: any[] ): void { + writeRaw: function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); try { if( s.length > 0 ) { @@ -445,20 +445,20 @@ export function createFileOutput( } } catch ( err ) { } }, - "close": function() { + close: function() { if( !this.objStream ) return; fs.closeSync( this.objStream ); this.objStream = null; }, - "open": function() { + open: function() { this.objStream = fs.openSync( this.strPath, "a", fs.constants.O_NONBLOCK | fs.constants.O_RDWR ); }, - "size": function() { + size: function() { try { return fs.lstatSync( this.strPath ).size; } catch ( err ) { return 0; } }, - "rotate": function( nBytesToWrite: number ) { + rotate: function( nBytesToWrite: number ) { try { if( this.nMaxSizeBeforeRotation <= 0 || this.nMaxFilesCount <= 1 ) return; @@ -488,63 +488,63 @@ export function createFileOutput( } catch ( err ) { } }, - "toString": function(): string { return "" + strFilePath; }, - "exposeDetailsTo": + toString: function(): string { return "" + strFilePath; }, + exposeDetailsTo: function( otherStream: any, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters - "fatal": function( ...args: any[] ): void { + fatal: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) this.write( getLogLinePrefixFatal() + fmtFatal( ...args ) ); }, - "critical": function( ...args: any[] ): void { + critical: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "critical" ) ) { this.write( getLogLinePrefixCritical() + fmtCritical( ...args ) ); } }, - "error": function( ...args: any[] ): void { + error: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "error" ) ) this.write( getLogLinePrefixError() + fmtError( ...args ) ); }, - "warning": function( ...args: any[] ): void { + warning: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "warning" ) ) this.write( getLogLinePrefixWarning() + fmtWarning( ...args ) ); }, - "attention": function( ...args: any[] ): void { + attention: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "attention" ) ) { this.write( getLogLinePrefixAttention() + fmtAttention( ...args ) ); } }, - "information": function( ...args: any[] ): void { + information: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "info": function( ...args: any[] ): void { + info: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) { this.write( getLogLinePrefixInformation() + fmtInformation( ...args ) ); } }, - "notice": function( ...args: any[] ): void { + notice: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNotice() + fmtNotice( ...args ) ); }, - "note": function( ...args: any[] ): void { + note: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "notice" ) ) this.write( getLogLinePrefixNote() + fmtNote( ...args ) ); }, - "debug": function( ...args: any[] ): void { + debug: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "debug" ) ) this.write( getLogLinePrefixDebug() + fmtDebug( ...args ) ); }, - "trace": function( ...args: any[] ): void { + trace: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "trace" ) ) this.write( getLogLinePrefixTrace() + fmtTrace( ...args ) ); }, - "success": function( ...args: any[] ): void { + success: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "information" ) ) this.write( getLogLinePrefixSuccess() + fmtSuccess( ...args ) ); } @@ -605,7 +605,7 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ if( ! cntArgsMax ) cntArgsMax = 0; const arrParts: any[] = []; - let s = strFormat, cntFoundArgs = 0; + let s = strFormat; let cntFoundArgs = 0; for( ; true; ) { if( cntFoundArgs >= cntArgsMax ) break; // nothing to do split for @@ -619,8 +619,8 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ const strArgDesc = s.substring( nStart + 1, nEnd ).trim().toLowerCase(); s = s.substring( nEnd + 1 ); if( strPart.length > 0 ) - arrParts.push( { "type": "text", "text": strPart } ); - arrParts.push( { "type": "arg", "text": strArgDesc } ); + arrParts.push( { type: "text", text: strPart } ); + arrParts.push( { type: "arg", text: strArgDesc } ); ++ cntFoundArgs; if( s.length == 0 ) break; @@ -628,7 +628,7 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ if( cntFoundArgs == 0 ) return null; if( s.length > 0 ) - arrParts.push( { "type": "text", "text": s } ); + arrParts.push( { type: "text", text: s } ); return arrParts; } @@ -636,7 +636,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { fnFormatter = fnFormatter || function( arg: any ) { return arg; } const arrParts = ( arrArgs && arrArgs.length > 0 ) ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; - let s = "", isValueMode = false; + let s = ""; let isValueMode = false; const fnDefaultOneArgumentFormatter = function( arg?: any, fnCustomFormatter?: any ): string { if( ! fnCustomFormatter ) fnCustomFormatter = fnFormatter; diff --git a/src/loop.ts b/src/loop.ts index 619919a2..9a1cb911 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -349,7 +349,7 @@ export async function singleTransferLoop( optsLoop: any ) { const strLogPrefix = `Single Loop in ${threadInfo.threadDescription( false )} `; try { log.debug( "{p}{p}", strLogPrefix, imaHelperAPIs.longSeparator ); - let b0 = false, b1 = false, b2 = false, b3 = false; + let b0 = false; let b1 = false; let b2 = false; let b3 = false; // Oracle loop part: if( optsLoop.enableStepOracle ) { if( imaState.loopState.oracle.isInProgress ) { @@ -408,16 +408,16 @@ export async function singleTransferLoop( optsLoop: any ) { export async function singleTransferLoopWithRepeat( optsLoop: any ) { const imaState = state.get(); await singleTransferLoop( optsLoop ); - setTimeout( async function() { - await singleTransferLoopWithRepeat( optsLoop ); + setTimeout( function() { + singleTransferLoopWithRepeat( optsLoop ).then( function() {} ).catch( function() {} ); }, imaState.nLoopPeriodSeconds * 1000 ); }; export async function runTransferLoop( optsLoop: any ) { const imaState = state.get(); const isDelayFirstRun = owaspUtils.toBoolean( optsLoop.isDelayFirstRun ); if( isDelayFirstRun ) { - setTimeout( async function() { - await singleTransferLoopWithRepeat( optsLoop ); + setTimeout( function() { + singleTransferLoopWithRepeat( optsLoop ).then( function() {} ).catch( function() {} ); }, imaState.nLoopPeriodSeconds * 1000 ); } else await singleTransferLoopWithRepeat( optsLoop ); @@ -431,65 +431,65 @@ const gArrClients: any[] = []; function constructChainProperties( opts: any ) { return { - "mn": { - "joAccount": { - "privateKey": opts.imaState.chainProperties.mn.joAccount.privateKey, - "address_": opts.imaState.chainProperties.mn.joAccount.address_, - "strTransactionManagerURL": + mn: { + joAccount: { + privateKey: opts.imaState.chainProperties.mn.joAccount.privateKey, + address_: opts.imaState.chainProperties.mn.joAccount.address_, + strTransactionManagerURL: opts.imaState.chainProperties.mn.joAccount.strTransactionManagerURL, - "nTmPriority": opts.imaState.chainProperties.mn.joAccount.nTmPriority, - "strSgxURL": opts.imaState.chainProperties.mn.joAccount.strSgxURL, - "strSgxKeyName": opts.imaState.chainProperties.mn.joAccount.strSgxKeyName, - "strPathSslKey": opts.imaState.chainProperties.mn.joAccount.strPathSslKey, - "strPathSslCert": opts.imaState.chainProperties.mn.joAccount.strPathSslCert, - "strBlsKeyName": opts.imaState.chainProperties.mn.joAccount.strBlsKeyName + nTmPriority: opts.imaState.chainProperties.mn.joAccount.nTmPriority, + strSgxURL: opts.imaState.chainProperties.mn.joAccount.strSgxURL, + strSgxKeyName: opts.imaState.chainProperties.mn.joAccount.strSgxKeyName, + strPathSslKey: opts.imaState.chainProperties.mn.joAccount.strPathSslKey, + strPathSslCert: opts.imaState.chainProperties.mn.joAccount.strPathSslCert, + strBlsKeyName: opts.imaState.chainProperties.mn.joAccount.strBlsKeyName }, - "ethersProvider": null, - "strURL": opts.imaState.chainProperties.mn.strURL, - "strChainName": opts.imaState.chainProperties.mn.strChainName, - "chainId": opts.imaState.chainProperties.mn.chainId, - "joAbiIMA": opts.imaState.chainProperties.mn.joAbiIMA, - "bHaveAbiIMA": opts.imaState.chainProperties.mn.bHaveAbiIMA + ethersProvider: null, + strURL: opts.imaState.chainProperties.mn.strURL, + strChainName: opts.imaState.chainProperties.mn.strChainName, + chainId: opts.imaState.chainProperties.mn.chainId, + joAbiIMA: opts.imaState.chainProperties.mn.joAbiIMA, + bHaveAbiIMA: opts.imaState.chainProperties.mn.bHaveAbiIMA }, - "sc": { - "joAccount": { - "privateKey": opts.imaState.chainProperties.sc.joAccount.privateKey, - "address_": opts.imaState.chainProperties.sc.joAccount.address_, - "strTransactionManagerURL": + sc: { + joAccount: { + privateKey: opts.imaState.chainProperties.sc.joAccount.privateKey, + address_: opts.imaState.chainProperties.sc.joAccount.address_, + strTransactionManagerURL: opts.imaState.chainProperties.sc.joAccount.strTransactionManagerURL, - "nTmPriority": opts.imaState.chainProperties.sc.joAccount.nTmPriority, - "strSgxURL": opts.imaState.chainProperties.sc.joAccount.strSgxURL, - "strSgxKeyName": opts.imaState.chainProperties.sc.joAccount.strSgxKeyName, - "strPathSslKey": opts.imaState.chainProperties.sc.joAccount.strPathSslKey, - "strPathSslCert": opts.imaState.chainProperties.mn.joAccount.strPathSslCert, - "strBlsKeyName": opts.imaState.chainProperties.mn.joAccount.strBlsKeyName + nTmPriority: opts.imaState.chainProperties.sc.joAccount.nTmPriority, + strSgxURL: opts.imaState.chainProperties.sc.joAccount.strSgxURL, + strSgxKeyName: opts.imaState.chainProperties.sc.joAccount.strSgxKeyName, + strPathSslKey: opts.imaState.chainProperties.sc.joAccount.strPathSslKey, + strPathSslCert: opts.imaState.chainProperties.mn.joAccount.strPathSslCert, + strBlsKeyName: opts.imaState.chainProperties.mn.joAccount.strBlsKeyName }, - "ethersProvider": null, - "strURL": opts.imaState.chainProperties.sc.strURL, - "strChainName": opts.imaState.chainProperties.sc.strChainName, - "chainId": opts.imaState.chainProperties.sc.chainId, - "joAbiIMA": opts.imaState.chainProperties.sc.joAbiIMA, - "bHaveAbiIMA": opts.imaState.chainProperties.sc.bHaveAbiIMA + ethersProvider: null, + strURL: opts.imaState.chainProperties.sc.strURL, + strChainName: opts.imaState.chainProperties.sc.strChainName, + chainId: opts.imaState.chainProperties.sc.chainId, + joAbiIMA: opts.imaState.chainProperties.sc.joAbiIMA, + bHaveAbiIMA: opts.imaState.chainProperties.sc.bHaveAbiIMA }, - "tc": { - "joAccount": { - "privateKey": opts.imaState.chainProperties.tc.joAccount.privateKey, - "address_": opts.imaState.chainProperties.tc.joAccount.address_, - "strTransactionManagerURL": + tc: { + joAccount: { + privateKey: opts.imaState.chainProperties.tc.joAccount.privateKey, + address_: opts.imaState.chainProperties.tc.joAccount.address_, + strTransactionManagerURL: opts.imaState.chainProperties.tc.joAccount.strTransactionManagerURL, - "nTmPriority": opts.imaState.chainProperties.tc.joAccount.nTmPriority, - "strSgxURL": opts.imaState.chainProperties.tc.joAccount.strSgxURL, - "strSgxKeyName": opts.imaState.chainProperties.tc.joAccount.strSgxKeyName, - "strPathSslKey": opts.imaState.chainProperties.tc.joAccount.strPathSslKey, - "strPathSslCert": opts.imaState.chainProperties.tc.joAccount.strPathSslCert, - "strBlsKeyName": opts.imaState.chainProperties.tc.joAccount.strBlsKeyName + nTmPriority: opts.imaState.chainProperties.tc.joAccount.nTmPriority, + strSgxURL: opts.imaState.chainProperties.tc.joAccount.strSgxURL, + strSgxKeyName: opts.imaState.chainProperties.tc.joAccount.strSgxKeyName, + strPathSslKey: opts.imaState.chainProperties.tc.joAccount.strPathSslKey, + strPathSslCert: opts.imaState.chainProperties.tc.joAccount.strPathSslCert, + strBlsKeyName: opts.imaState.chainProperties.tc.joAccount.strBlsKeyName }, - "ethersProvider": null, - "strURL": opts.imaState.chainProperties.tc.strURL, - "strChainName": opts.imaState.chainProperties.tc.strChainName, - "chainId": opts.imaState.chainProperties.tc.chainId, - "joAbiIMA": opts.imaState.chainProperties.tc.joAbiIMA, - "bHaveAbiIMA": opts.imaState.chainProperties.tc.bHaveAbiIMA + ethersProvider: null, + strURL: opts.imaState.chainProperties.tc.strURL, + strChainName: opts.imaState.chainProperties.tc.strChainName, + chainId: opts.imaState.chainProperties.tc.chainId, + joAbiIMA: opts.imaState.chainProperties.tc.joAbiIMA, + bHaveAbiIMA: opts.imaState.chainProperties.tc.bHaveAbiIMA } }; } @@ -516,13 +516,13 @@ export async function ensureHaveWorkers( opts: any ) { cntWorkers, " worker(s) in ", threadInfo.threadDescription(), "..." ); for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) { const workerData: any = { - "url": "ima_loop_server" + idxWorker, - "colorization": { isEnabled: log.isEnabledColorization() } + url: "ima_loop_server" + idxWorker, + colorization: { isEnabled: log.isEnabledColorization() } }; gArrWorkers.push( new threadInfo.Worker( path.join( __dirname, "loopWorker.js" ), { // "type": "module", - "workerData": workerData + workerData } ) ); gArrWorkers[idxWorker].on( "message", function( jo: any ) { @@ -560,107 +560,107 @@ export async function ensureHaveWorkers( opts: any ) { } // switch ( joMessage.method ) } ); const jo: any = { - "method": "init", - "message": { - "opts": { - "imaState": { - "optsLoop": getDefaultOptsLoop( idxWorker ), - "verbose_": log.verboseGet(), - "expose_details_": log.exposeDetailsGet(), - "loopState": state.gDefaultValueForLoopState, - "isPrintGathered": opts.imaState.isPrintGathered, - "isPrintSecurityValues": opts.imaState.isPrintSecurityValues, - "isPrintPWA": opts.imaState.isPrintPWA, - "isDynamicLogInDoTransfer": opts.imaState.isDynamicLogInDoTransfer, - "isDynamicLogInBlsSigner": opts.imaState.isDynamicLogInBlsSigner, - "bIsNeededCommonInit": false, - "bSignMessages": opts.imaState.bSignMessages, - "joSChainNetworkInfo": opts.imaState.joSChainNetworkInfo, - "strPathBlsGlue": opts.imaState.strPathBlsGlue, - "strPathHashG1": opts.imaState.strPathHashG1, - "strPathBlsVerify": opts.imaState.strPathBlsVerify, - "isEnabledMultiCall": opts.imaState.isEnabledMultiCall, - "bNoWaitSChainStarted": opts.imaState.bNoWaitSChainStarted, - "nMaxWaitSChainAttempts": opts.imaState.nMaxWaitSChainAttempts, - "nTransferBlockSizeM2S": opts.imaState.nTransferBlockSizeM2S, - "nTransferBlockSizeS2M": opts.imaState.nTransferBlockSizeS2M, - "nTransferBlockSizeS2S": opts.imaState.nTransferBlockSizeS2S, - "nTransferStepsM2S": opts.imaState.nTransferStepsM2S, - "nTransferStepsS2M": opts.imaState.nTransferStepsS2M, - "nTransferStepsS2S": opts.imaState.nTransferStepsS2S, - "nMaxTransactionsM2S": opts.imaState.nMaxTransactionsM2S, - "nMaxTransactionsS2M": opts.imaState.nMaxTransactionsS2M, - "nMaxTransactionsS2S": opts.imaState.nMaxTransactionsS2S, - - "nBlockAwaitDepthM2S": opts.imaState.nBlockAwaitDepthM2S, - "nBlockAwaitDepthS2M": opts.imaState.nBlockAwaitDepthS2M, - "nBlockAwaitDepthS2S": opts.imaState.nBlockAwaitDepthS2S, - "nBlockAgeM2S": opts.imaState.nBlockAgeM2S, - "nBlockAgeS2M": opts.imaState.nBlockAgeS2M, - "nBlockAgeS2S": opts.imaState.nBlockAgeS2S, - - "nLoopPeriodSeconds": opts.imaState.nLoopPeriodSeconds, - "nNodeNumber": opts.imaState.nNodeNumber, - "nNodesCount": opts.imaState.nNodesCount, - "nTimeFrameSeconds": opts.imaState.nTimeFrameSeconds, - "nNextFrameGap": opts.imaState.nNextFrameGap, - - "joCommunityPool": null, - "joDepositBoxETH": null, - "joDepositBoxERC20": null, - "joDepositBoxERC721": null, - "joDepositBoxERC1155": null, - "joDepositBoxERC721WithMetadata": null, - "joLinker": null, - "isWithMetadata721": false, - - "joTokenManagerETH": null, - "joTokenManagerERC20": null, - "joTokenManagerERC20Target": null, - "joTokenManagerERC721": null, - "joTokenManagerERC721Target": null, - "joTokenManagerERC1155": null, - "joTokenManagerERC1155Target": null, - "joTokenManagerERC721WithMetadata": null, - "joTokenManagerERC721WithMetadataTarget": null, - "joCommunityLocker": null, - "joCommunityLockerTarget": null, - "joMessageProxyMainNet": null, - "joMessageProxySChain": null, - "joMessageProxySChainTarget": null, - "joTokenManagerLinker": null, - "joTokenManagerLinkerTarget": null, - "joEthErc20": null, - "joEthErc20Target": null, - - "chainProperties": constructChainProperties( opts ), - "joAbiSkaleManager": opts.imaState.joAbiSkaleManager, - "bHaveSkaleManagerABI": opts.imaState.bHaveSkaleManagerABI, - "strChainNameOriginChain": opts.imaState.strChainNameOriginChain, - "isPWA": opts.imaState.isPWA, - "nTimeoutSecondsPWA": opts.imaState.nTimeoutSecondsPWA, - "strReimbursementChain": opts.imaState.strReimbursementChain, - "isShowReimbursementBalance": opts.imaState.isShowReimbursementBalance, - "nReimbursementRecharge": opts.imaState.nReimbursementRecharge, - "nReimbursementWithdraw": opts.imaState.nReimbursementWithdraw, - "nReimbursementRange": opts.imaState.nReimbursementRange, - "joSChainDiscovery": { - "isSilentReDiscovery": + method: "init", + message: { + opts: { + imaState: { + optsLoop: getDefaultOptsLoop( idxWorker ), + verbose_: log.verboseGet(), + expose_details_: log.exposeDetailsGet(), + loopState: state.gDefaultValueForLoopState, + isPrintGathered: opts.imaState.isPrintGathered, + isPrintSecurityValues: opts.imaState.isPrintSecurityValues, + isPrintPWA: opts.imaState.isPrintPWA, + isDynamicLogInDoTransfer: opts.imaState.isDynamicLogInDoTransfer, + isDynamicLogInBlsSigner: opts.imaState.isDynamicLogInBlsSigner, + bIsNeededCommonInit: false, + bSignMessages: opts.imaState.bSignMessages, + joSChainNetworkInfo: opts.imaState.joSChainNetworkInfo, + strPathBlsGlue: opts.imaState.strPathBlsGlue, + strPathHashG1: opts.imaState.strPathHashG1, + strPathBlsVerify: opts.imaState.strPathBlsVerify, + isEnabledMultiCall: opts.imaState.isEnabledMultiCall, + bNoWaitSChainStarted: opts.imaState.bNoWaitSChainStarted, + nMaxWaitSChainAttempts: opts.imaState.nMaxWaitSChainAttempts, + nTransferBlockSizeM2S: opts.imaState.nTransferBlockSizeM2S, + nTransferBlockSizeS2M: opts.imaState.nTransferBlockSizeS2M, + nTransferBlockSizeS2S: opts.imaState.nTransferBlockSizeS2S, + nTransferStepsM2S: opts.imaState.nTransferStepsM2S, + nTransferStepsS2M: opts.imaState.nTransferStepsS2M, + nTransferStepsS2S: opts.imaState.nTransferStepsS2S, + nMaxTransactionsM2S: opts.imaState.nMaxTransactionsM2S, + nMaxTransactionsS2M: opts.imaState.nMaxTransactionsS2M, + nMaxTransactionsS2S: opts.imaState.nMaxTransactionsS2S, + + nBlockAwaitDepthM2S: opts.imaState.nBlockAwaitDepthM2S, + nBlockAwaitDepthS2M: opts.imaState.nBlockAwaitDepthS2M, + nBlockAwaitDepthS2S: opts.imaState.nBlockAwaitDepthS2S, + nBlockAgeM2S: opts.imaState.nBlockAgeM2S, + nBlockAgeS2M: opts.imaState.nBlockAgeS2M, + nBlockAgeS2S: opts.imaState.nBlockAgeS2S, + + nLoopPeriodSeconds: opts.imaState.nLoopPeriodSeconds, + nNodeNumber: opts.imaState.nNodeNumber, + nNodesCount: opts.imaState.nNodesCount, + nTimeFrameSeconds: opts.imaState.nTimeFrameSeconds, + nNextFrameGap: opts.imaState.nNextFrameGap, + + joCommunityPool: null, + joDepositBoxETH: null, + joDepositBoxERC20: null, + joDepositBoxERC721: null, + joDepositBoxERC1155: null, + joDepositBoxERC721WithMetadata: null, + joLinker: null, + isWithMetadata721: false, + + joTokenManagerETH: null, + joTokenManagerERC20: null, + joTokenManagerERC20Target: null, + joTokenManagerERC721: null, + joTokenManagerERC721Target: null, + joTokenManagerERC1155: null, + joTokenManagerERC1155Target: null, + joTokenManagerERC721WithMetadata: null, + joTokenManagerERC721WithMetadataTarget: null, + joCommunityLocker: null, + joCommunityLockerTarget: null, + joMessageProxyMainNet: null, + joMessageProxySChain: null, + joMessageProxySChainTarget: null, + joTokenManagerLinker: null, + joTokenManagerLinkerTarget: null, + joEthErc20: null, + joEthErc20Target: null, + + chainProperties: constructChainProperties( opts ), + joAbiSkaleManager: opts.imaState.joAbiSkaleManager, + bHaveSkaleManagerABI: opts.imaState.bHaveSkaleManagerABI, + strChainNameOriginChain: opts.imaState.strChainNameOriginChain, + isPWA: opts.imaState.isPWA, + nTimeoutSecondsPWA: opts.imaState.nTimeoutSecondsPWA, + strReimbursementChain: opts.imaState.strReimbursementChain, + isShowReimbursementBalance: opts.imaState.isShowReimbursementBalance, + nReimbursementRecharge: opts.imaState.nReimbursementRecharge, + nReimbursementWithdraw: opts.imaState.nReimbursementWithdraw, + nReimbursementRange: opts.imaState.nReimbursementRange, + joSChainDiscovery: { + isSilentReDiscovery: opts.imaState.joSChainDiscovery.isSilentReDiscovery, - "repeatIntervalMilliseconds": + repeatIntervalMilliseconds: opts.imaState.joSChainDiscovery.repeatIntervalMilliseconds, - "periodicDiscoveryInterval": + periodicDiscoveryInterval: opts.imaState.joSChainDiscovery.periodicDiscoveryInterval }, - "optsS2S": { // S-Chain to S-Chain transfer options - "isEnabled": true, - "strNetworkBrowserPath": opts.imaState.optsS2S.strNetworkBrowserPath + optsS2S: { // S-Chain to S-Chain transfer options + isEnabled: true, + strNetworkBrowserPath: opts.imaState.optsS2S.strNetworkBrowserPath }, - "nJsonRpcPort": opts.imaState.nJsonRpcPort, - "isCrossImaBlsMode": opts.imaState.isCrossImaBlsMode + nJsonRpcPort: opts.imaState.nJsonRpcPort, + isCrossImaBlsMode: opts.imaState.isCrossImaBlsMode } }, - "colorization": { "isEnabled": log.isEnabledColorization() } + colorization: { isEnabled: log.isEnabledColorization() } } }; while( ! aClient.logicalInitComplete ) { @@ -695,9 +695,9 @@ export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) export async function spreadUpdatedSChainNetwork( isFinal: boolean ) { const imaState = state.get(); const joMessage: any = { - "method": "spreadUpdatedSChainNetwork", - "isFinal": ( !!isFinal ), - "joSChainNetworkInfo": imaState.joSChainNetworkInfo + method: "spreadUpdatedSChainNetwork", + isFinal: ( !!isFinal ), + joSChainNetworkInfo: imaState.joSChainNetworkInfo }; const cntWorkers = gArrWorkers.length; for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 235ab818..ff80c781 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -48,13 +48,13 @@ if( parentPort ) { function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = networkLayer.socketReceivedDataReverseMarshall( data ); const joSend: any = { - "workerMessageType": + workerMessageType: ( type && typeof type == "string" && type.length > 0 ) ? type : "inWorkerMessage", - "workerEndPoint": endpoint, - "workerUUID": workerUUID, - "data": jo + workerEndPoint: endpoint, + workerUUID, + data: jo }; if( parentPort ) parentPort.postMessage( networkLayer.socketSentDataMarshall( joSend ) ); @@ -76,17 +76,17 @@ class ObserverServer extends SocketServer { self.mapApiHandlers.init = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { joAnswer.message = { - "method": "" + joMessage.method, - "error": null + method: "" + joMessage.method, + error: null }; if( self.initComplete ) return joAnswer; self.log = function() { const args = Array.prototype.slice.call( arguments ); const jo: any = { - "method": "log", - "error": null, - "message": args.join( " " ) + method: "log", + error: null, + message: args.join( " " ) }; const isFlush = true; socket.send( jo, isFlush ); @@ -94,35 +94,35 @@ class ObserverServer extends SocketServer { self.initLogMethods(); self.opts = JSON.parse( JSON.stringify( joMessage.message.opts ) ); self.opts.details = { - "write": self.log, - "fatal": self.fatal, - "critical": self.critical, - "error": self.error, - "warning": self.warning, - "attention": self.attention, - "information": self.information, - "info": self.info, - "notice": self.notice, - "note": self.note, - "debug": self.debug, - "trace": self.trace, - "success": self.success + write: self.log, + fatal: self.fatal, + critical: self.critical, + error: self.error, + warning: self.warning, + attention: self.attention, + information: self.information, + info: self.info, + notice: self.notice, + note: self.note, + debug: self.debug, + trace: self.trace, + success: self.success }; log.enableColorization( joMessage.message.colorization.isEnabled ); log.verboseSet( self.opts.imaState.verbose_ ); log.exposeDetailsSet( self.opts.imaState.expose_details_ ); imaTransferErrorHandling.saveTransferEvents.on( "error", function( eventData: any ) { const jo: any = { - "method": "saveTransferError", - "message": eventData.detail + method: "saveTransferError", + message: eventData.detail }; const isFlush = true; socket.send( jo, isFlush ); } ); imaTransferErrorHandling.saveTransferEvents.on( "success", function( eventData: any ) { const jo: any = { - "method": "saveTransferSuccess", - "message": eventData.detail + method: "saveTransferSuccess", + message: eventData.detail }; const isFlush = true; socket.send( jo, isFlush ); @@ -181,7 +181,8 @@ class ObserverServer extends SocketServer { " S2S", log.fmtDebug( " transfers........." ), log.yn( self.opts.imaState.optsLoop.enableStepS2S ) ); /* await */ - loop.runTransferLoop( self.opts.imaState.optsLoop ); + loop.runTransferLoop( self.opts.imaState.optsLoop ) + .then( function() {} ).catch( function() {} ); self.information( "Full init compete for in-worker IMA loop {} in {}", workerData.url, threadInfo.threadDescription() ); return joAnswer; @@ -208,7 +209,7 @@ class ObserverServer extends SocketServer { ( !!( joMessage.params.isStart ) ), owaspUtils.toInteger( joMessage.params.ts ), joMessage.params.signature - ); + ).then( function() {} ).catch( function() {} ); }; console.log( "Initialized in-worker IMA loop {} server in {}", workerData.url, threadInfo.threadDescription() ); diff --git a/src/main.ts b/src/main.ts index 63c3801b..cec33baf 100644 --- a/src/main.ts +++ b/src/main.ts @@ -59,8 +59,8 @@ function parseCommandLine() { log.autoEnableColorizationFromCommandLineArgs(); const strPrintedArguments = process.argv.join( " " ); imaCLI.parse( { - "register": clpTools.commandLineTaskRegister, - "register1": clpTools.commandLineTaskRegister1, + register: clpTools.commandLineTaskRegister, + register1: clpTools.commandLineTaskRegister1, "check-registration": clpTools.commandLineTaskCheckRegistration, "check-registration1": clpTools.commandLineTaskCheckRegistration1, "mint-erc20": clpTools.commandLineTaskMintErc20, @@ -78,8 +78,8 @@ function parseCommandLine() { "m2s-transfer": clpTools.commandLineTaskTransferM2S, "s2m-transfer": clpTools.commandLineTaskTransferS2M, "s2s-transfer": clpTools.commandLineTaskTransferS2S, - "transfer": clpTools.commandLineTaskTransfer, - "loop": clpTools.commandLineTaskLoop, + transfer: clpTools.commandLineTaskTransfer, + loop: clpTools.commandLineTaskLoop, "simple-loop": clpTools.commandLineTaskLoopSimple, "browse-s-chain": clpTools.commandLineTaskBrowseSChain } ); @@ -162,9 +162,9 @@ function initMonitoringServer(): void { log.debug( "{p}New connection from {}", strLogPrefix, ip ); wsPeer.on( "message", function( message: any ) { const joAnswer: any = { - "method": null, - "id": null, - "error": null + method: null, + id: null, + error: null }; try { const joMessage: any = JSON.parse( message ); @@ -276,9 +276,9 @@ function initJsonRpcServer(): void { } }; let joAnswer: any = { - "method": null, - "id": null, - "error": null + method: null, + id: null, + error: null }; try { const joMessage: any = JSON.parse( message ); @@ -391,8 +391,9 @@ function handleFirstSChainDiscoveryAttemptDone( discoveryTools.continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, function() { discoveryTools.doPeriodicSChainNetworkDiscoveryIfNeeded( - isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ); - } ); + isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ) + .then( function() {} ).catch( function() {} ); + } ).then( function() {} ).catch( function() {} ); imaState.joSChainNetworkInfo = joSChainNetworkInfo; } @@ -423,7 +424,7 @@ async function main() { const isSilentReDiscovery = imaState.isPrintSecurityValues ? false : imaState.joSChainDiscovery.isSilentReDiscovery; const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ) { - loop.spreadUpdatedSChainNetwork( isFinal ); + loop.spreadUpdatedSChainNetwork( isFinal ).then( function() {} ).catch( function() {} ); } if( imaState.bSignMessages ) { if( imaState.strPathBlsGlue.length == 0 ) { @@ -449,7 +450,7 @@ async function main() { handleFirstSChainDiscoveryAttemptDone( err, joSChainNetworkInfo, isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ); - doTheJob(); + doTheJob().then( function() {} ).catch( function() {} ); // Finish of IMA Agent startup, // everything else is in async calls executed later return 0; @@ -457,13 +458,14 @@ async function main() { ).catch( function( err: Error | string ) { const strError = owaspUtils.extractErrorMessage( err ); log.critical( "S-Chain network discovery failed: {err}", strError ); - doTheJob(); + doTheJob().then( function() {} ).catch( function() {} ); } ); } } else { discoveryTools.doPeriodicSChainNetworkDiscoveryIfNeeded( - isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ); - doTheJob(); + isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ) + .then( function() {} ).catch( function() {} ); + doTheJob().then( function() {} ).catch( function() {} ); // Finish of IMA Agent startup, // everything else is in async calls executed later, // skip exit here to avoid early termination while tasks ase still running @@ -471,4 +473,4 @@ async function main() { } -main(); +main().then( function() {} ).catch( function() {} ); diff --git a/src/observer.ts b/src/observer.ts index ad50c360..62b25999 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -68,7 +68,7 @@ export function getLastCachedSChains(): any[] { } export function pickRandomSChainNodeIndex( joSChain: any ): number { - let min = 0, max = joSChain.nodes.length - 1; + let min = 0; let max = joSChain.nodes.length - 1; min = Math.ceil( min ); max = Math.floor( max ); const idxNode = Math.floor( Math.random() * ( max - min + 1 ) ) + min; diff --git a/src/oracle.ts b/src/oracle.ts index 441486a7..75c83efc 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -51,7 +51,7 @@ export function findPowNumber( strRequestPart: string, details: any, isVerbose?: details.debug( "source part of request to find PoW number is {}", strRequestPart ); const t = getUtcTimestampString(); - let i = 0, n = 0, s = ""; + let i = 0; let n = 0; let s = ""; if( isVerbose ) details.debug( "source t={}, this is UTC timestamp", t ); for( ; i < gConstMaxPowResultLimit; ++ i ) { @@ -132,7 +132,7 @@ async function handleOracleSubmitRequestResult( if( nMillisecondsToSleep > 0 ) await threadInfo.sleep( nMillisecondsToSleep ); try { - const joIn: any = { "method": "oracle_checkResult", "params": [ joOut.result ] }; + const joIn: any = { method: "oracle_checkResult", params: [ joOut.result ] }; if( isVerboseTraceDetails ) { details.debug( "RPC call oracle_checkResult attempt {} " + "of {}...", idxAttempt, cntAttempts ); @@ -160,7 +160,7 @@ async function handleOracleSubmitRequestResult( export async function oracleGetGasPrice( oracleOpts: any, details: any ) { details = details || log; const url: string = oracleOpts.url; - let gp: any = null, joCall: any = null; + let gp: any = null; let joCall: any = null; try { const isVerbose = "isVerbose" in oracleOpts ? oracleOpts.isVerbose : false; let isVerboseTraceDetails = "isVerboseTraceDetails" in oracleOpts @@ -176,7 +176,7 @@ export async function oracleGetGasPrice( oracleOpts: any, details: any ) { "\"post\":\"{\\\"jsonrpc\\\":\\\"2.0\\\"," + "\\\"method\\\":\\\"eth_gasPrice\\\",\\\"params\\\":[],\\\"id\\\":1}\"", details, isVerbose ); - const joIn: any = { "method": "oracle_submitRequest", "params": [ s ] }; + const joIn: any = { method: "oracle_submitRequest", params: [ s ] }; if( isVerboseTraceDetails ) details.debug( "RPC call {} is {}", "oracle_submitRequest", joIn ); const joOut: any = await joCall.call( joIn ); diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 5c8db2bc..a9c5011b 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -460,7 +460,7 @@ export function ipFromHex( hex?: any ): string { } export function cloneObjectByRootKeys( joIn?: any ): any { - const joOut: any = { }, arrKeys = Object.keys( joIn ); + const joOut: any = { }; const arrKeys = Object.keys( joIn ); for( let i = 0; i < arrKeys.length; ++ i ) { const key = arrKeys[i]; const value = joIn[key]; @@ -472,77 +472,77 @@ export function cloneObjectByRootKeys( joIn?: any ): any { // example: "1ether" -> "1000000000000000000" // supported suffix aliases, lowercase const gMapMoneyNameSuffixAliases: any = { - "ethe": "ether", - "ethr": "ether", - "eth": "ether", - "eter": "ether", - "ete": "ether", - "et": "ether", - "eh": "ether", - "er": "ether", - "finne": "finney", - "finn": "finney", - "fin": "finney", - "fn": "finney", - "fi": "finney", - "szab": "szabo", - "szb": "szabo", - "sza": "szabo", - "sz": "szabo", - "shanno": "shannon", - "shannn": "shannon", - "shann": "shannon", - "shan": "shannon", - "sha": "shannon", - "shn": "shannon", - "sh": "shannon", - "lovelac": "lovelace", - "lovela": "lovelace", - "lovel": "lovelace", - "love": "lovelace", - "lovl": "lovelace", - "lvl": "lovelace", - "lvla": "lovelace", - "lvlc": "lovelace", - "lvc": "lovelace", - "lv": "lovelace", - "lo": "lovelace", - "lc": "lovelace", - "ll": "lovelace", - "babbag": "babbage", - "babba": "babbage", - "babbg": "babbage", - "babb": "babbage", - "bab": "babbage", - "bag": "babbage", - "bbb": "babbage", - "bb": "babbage", - "bg": "babbage", - "ba": "babbage", - "be": "babbage", - "we": "wei", - "wi": "wei", + ethe: "ether", + ethr: "ether", + eth: "ether", + eter: "ether", + ete: "ether", + et: "ether", + eh: "ether", + er: "ether", + finne: "finney", + finn: "finney", + fin: "finney", + fn: "finney", + fi: "finney", + szab: "szabo", + szb: "szabo", + sza: "szabo", + sz: "szabo", + shanno: "shannon", + shannn: "shannon", + shann: "shannon", + shan: "shannon", + sha: "shannon", + shn: "shannon", + sh: "shannon", + lovelac: "lovelace", + lovela: "lovelace", + lovel: "lovelace", + love: "lovelace", + lovl: "lovelace", + lvl: "lovelace", + lvla: "lovelace", + lvlc: "lovelace", + lvc: "lovelace", + lv: "lovelace", + lo: "lovelace", + lc: "lovelace", + ll: "lovelace", + babbag: "babbage", + babba: "babbage", + babbg: "babbage", + babb: "babbage", + bab: "babbage", + bag: "babbage", + bbb: "babbage", + bb: "babbage", + bg: "babbage", + ba: "babbage", + be: "babbage", + we: "wei", + wi: "wei", // next are advanced kind of - "noether": "noether", - "noeth": "noether", - "kwei": "kwei", - "femtoether": "femtoether", - "femto": "femtoether", - "mwei": "mwei", - "picoether": "picoether", - "pico": "picoether", - "gwei": "gwei", - "nanoether": "nanoether", - "nano": "nanoether", - "microether": "microether", - "micro": "microether", - "milliether": "milliether", - "milli": "milliether", - "kether": "kether", - "mether": "mether", - "gether": "gether", - "tether": "tether" + noether: "noether", + noeth: "noether", + kwei: "kwei", + femtoether: "femtoether", + femto: "femtoether", + mwei: "mwei", + picoether: "picoether", + pico: "picoether", + gwei: "gwei", + nanoether: "nanoether", + nano: "nanoether", + microether: "microether", + micro: "microether", + milliether: "milliether", + milli: "milliether", + kether: "kether", + mether: "mether", + gether: "gether", + tether: "tether" }; export function parseMoneyUnitName( s: string ): string { @@ -622,8 +622,8 @@ export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ): stri if( strNumber == "" ) throw new Error( "no number or float value found" ); s = parseMoneyUnitName( s ); - const ddr = moneyUnitNameToPostDivider( s ), - mlr = moneyUnitNameToPostMultiplier( s ); + const ddr = moneyUnitNameToPostDivider( s ); + const mlr = moneyUnitNameToPostMultiplier( s ); s = moneyUnitNameToEthersParseSpec( s ); s = ethersMod.ethers.utils.parseUnits( strNumber, s ); if( ddr != null ) @@ -680,7 +680,7 @@ export function fnAddressImpl_( anyThis: any ): string { export function getEthersProviderFromURL( strURL: URL | string ): ethersMod.ethers.providers.JsonRpcProvider { const url = new URL( strURL.toString() ); - let userName: string | null = null, userPwd: string | null = null; + let userName: string | null = null; let userPwd: string | null = null; if( url.username ) { userName = url.username; userPwd = url.password; diff --git a/src/pwa.ts b/src/pwa.ts index d9c76bae..762967b5 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -63,10 +63,10 @@ export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType: string ): boo function composeEmptyStateForPendingWorkAnalysis(): any { return { - "oracle": { "isInProgress": false, "ts": 0 }, - "m2s": { "isInProgress": false, "ts": 0 }, - "s2m": { "isInProgress": false, "ts": 0 }, - "s2s": { "mapS2S": { } } + oracle: { isInProgress: false, ts: 0 }, + m2s: { isInProgress: false, ts: 0 }, + s2m: { isInProgress: false, ts: 0 }, + s2s: { mapS2S: { } } }; } @@ -81,7 +81,7 @@ function getNodeProgressAndTimestamp( joNode: any, strLoopWorkType: string, nInd if( strLoopWorkType != "s2s" ) return joNode.pwaState[strLoopWorkType]; if( ! ( nIndexS2S in joNode.pwaState[strLoopWorkType].mapS2S ) ) - joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S] = { "isInProgress": false, "ts": 0 }; + joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S] = { isInProgress: false, ts: 0 }; return joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S]; } @@ -251,14 +251,14 @@ async function notifyOnLoopImpl( if( ! joCall ) return false; const joIn: any = { - "method": "skale_imaNotifyLoopWork", - "params": { - "nNodeNumber": 0 + imaState.nNodeNumber, - "strLoopWorkType": "" + strLoopWorkType, - "nIndexS2S": 0 + nIndexS2S, - "isStart": ( !!isStart ), - "ts": nUtcUnixTimeStamp, - "signature": signature + method: "skale_imaNotifyLoopWork", + params: { + nNodeNumber: 0 + imaState.nNodeNumber, + strLoopWorkType: "" + strLoopWorkType, + nIndexS2S: 0 + nIndexS2S, + isStart: ( !!isStart ), + ts: nUtcUnixTimeStamp, + signature } }; await joCall.call( joIn ); // no return value needed here diff --git a/src/rpcCall.ts b/src/rpcCall.ts index c0b15dca..2ceef243 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -90,7 +90,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { const wsConn = joCall.wsConn; joCall.wsConn = null; wsConn.close(); - doReconnectWsStep( joCall, opts ); + doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); } ); joCall.wsConn.on( "fail", async function( err: any ) { strWsError = err.toString() || "internal web socket failure"; @@ -98,7 +98,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { const wsConn = joCall.wsConn; joCall.wsConn = null; wsConn.close(); - doReconnectWsStep( joCall, opts ); + doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); } ); joCall.wsConn.on( "message", async function incoming( data: any ) { const joOut = JSON.parse( data ); @@ -129,7 +129,8 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { const wsConn = joCall.wsConn; joCall.wsConn = null; wsConn.close(); - doReconnectWsStep( joCall, opts ); + doReconnectWsStep( joCall, opts ) + .then( function() {} ).catch( function() {} ); return false; // stop waiting } return true; // continue waiting @@ -177,12 +178,13 @@ async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { return; doConnect( joCall, opts, async function( joCall: any, err: any ) { if( err ) { - doReconnectWsStep( joCall, opts ); + doReconnectWsStep( joCall, opts ) + .then( function() {} ).catch( function() {} ); return } if( fn ) await fn( joCall, null ); - } ); + } ).then( function() {} ).catch( function() {} ); } async function doDisconnect( joCall: any, fn: any ) { @@ -208,8 +210,8 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { joIn = enrichTopLevelFieldsInJSON( joIn ); if( joCall.wsConn ) { const entry: any = { - joIn: joIn, - fn: fn, + joIn, + fn, out: null }; joCall.mapPendingByCallID[joIn.id] = entry; @@ -228,26 +230,26 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { return; } const strBody = JSON.stringify( joIn ); - let errCall: string | null = null, joOut: any = null; + let errCall: string | null = null; let joOut: any = null; if( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" && joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" ) { const u = new URL( joCall.url ); const options: any = { - "hostname": u.hostname, - "port": u.port, - "path": "/", - "method": "POST", - "headers": { + hostname: u.hostname, + port: u.port, + path: "/", + method: "POST", + headers: { "Content-Type": "application/json" }, - "ca": ( joCall.joRpcOptions?.ca && + ca: ( joCall.joRpcOptions?.ca && typeof joCall.joRpcOptions.ca == "string" ) ? joCall.joRpcOptions.ca : null, - "cert": ( joCall.joRpcOptions?.cert && + cert: ( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" ) ? joCall.joRpcOptions.cert : null, - "key": ( joCall.joRpcOptions?.key && + key: ( joCall.joRpcOptions?.key && typeof joCall.joRpcOptions.key == "string" ) ? joCall.joRpcOptions.key : null }; @@ -300,23 +302,23 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { } else { try { const requestOpts = { - "method": "POST", - "timeout": gSecondsConnectionTimeout * 1000, // in milliseconds - "headers": { + method: "POST", + timeout: gSecondsConnectionTimeout * 1000, // in milliseconds + headers: { "Content-Type": "application/json" }, - "content": strBody, - "rejectUnauthorized": false, + content: strBody, + rejectUnauthorized: false, // "requestCert": true, - "agent": false, - "httpsAgent": false, - "ca": ( joCall.joRpcOptions?.ca && + agent: false, + httpsAgent: false, + ca: ( joCall.joRpcOptions?.ca && typeof joCall.joRpcOptions.ca == "string" ) ? joCall.joRpcOptions.ca : null, - "cert": ( joCall.joRpcOptions?.cert && + cert: ( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" ) ? joCall.joRpcOptions.cert : null, - "key": ( joCall.joRpcOptions?.key && + key: ( joCall.joRpcOptions?.key && typeof joCall.joRpcOptions.key == "string" ) ? joCall.joRpcOptions.key : null }; @@ -350,20 +352,20 @@ export async function rpcCallCreate( strURL: string, opts: any ) { `bad parameters: ${JSON.stringify( arguments )}` ); } const joCall: any = { - "url": "" + strURL, - "joRpcOptions": opts ? opts : null, - "mapPendingByCallID": { }, - "wsConn": null, - "isAutoReconnect": + url: "" + strURL, + joRpcOptions: opts ? opts : null, + mapPendingByCallID: { }, + wsConn: null, + isAutoReconnect: ( opts && "isAutoReconnect" in opts && opts.isAutoReconnect ) ? true : false, - "isDisconnectMode": false, - "reconnect": async function( fnAfter: any ) { + isDisconnectMode: false, + reconnect: async function( fnAfter: any ) { await doConnect( joCall, fnAfter ); }, - "reconnect_if_needed": async function( fnAfter: any ) { + reconnect_if_needed: async function( fnAfter: any ) { await doConnectIfNeeded( joCall, opts, fnAfter ); }, - "call": async function( joIn: any, fnAfter: any ) { + call: async function( joIn: any, fnAfter: any ) { const self = this; const promiseComplete = new Promise( function( resolve: any, reject: any ) { self.reconnect_if_needed( async function( joCall: any, err: any ) { @@ -391,7 +393,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { "{url} JSON RPC call(awaiter) error: {err}", strURL, err ); } ); }, - "disconnect": async function( fnAfter?: any ) { + disconnect: async function( fnAfter?: any ) { await doDisconnect( joCall, fnAfter ); } }; diff --git a/src/socket.ts b/src/socket.ts index 1759ed58..491c25ee 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -63,9 +63,9 @@ export const socketReceivedDataReverseMarshall = function( data?: any ): object return jo; } catch ( err ) { return { - "error": true, - "message": "data un-marshal error", - "data": data + error: true, + message: "data un-marshal error", + data }; } }; @@ -178,13 +178,13 @@ export class BasicServerAcceptor extends EventDispatcher { const iv = setTimeout( function() { clearTimeout( iv ); serverPipe.dispatchEvent( - new UniversalDispatcherEvent( "open", { "socket": serverPipe } ) ); + new UniversalDispatcherEvent( "open", { socket: serverPipe } ) ); self.dispatchEvent( new UniversalDispatcherEvent( "connection", - { "socket": serverPipe, "remoteAddress": "" + self.url } ) ); + { socket: serverPipe, remoteAddress: "" + self.url } ) ); clientPipe.dispatchEvent( - new UniversalDispatcherEvent( "open", { "socket": clientPipe } ) ); + new UniversalDispatcherEvent( "open", { socket: clientPipe } ) ); }, 0 ); return clientPipe; } @@ -307,7 +307,7 @@ export class BasicSocketPipe extends EventDispatcher { implReceive( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( - new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); + new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); } receive( data: any ) { if( settings.logging.net.socket.receiveBlock ) @@ -388,7 +388,7 @@ export const gMapAwaitingInWorkerClients: Record < string, any > = { }; export const gMapConnectedInWorkerClients: Record < string, any > = { }; export const outOfWorkerAPIs: any = { - "onMessage": function( worker: any, data: any ) { + onMessage: function( worker: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); if( ! ( "workerMessageType" in jo ) || typeof jo.workerMessageType != "string" || @@ -424,22 +424,22 @@ export const outOfWorkerAPIs: any = { return false; // TO-DO: send error answer and return true } // switch( jo.workerMessageType ) }, - "onSendMessage": function( worker: any, type: any, endpoint: any, workerUUID: any, data: any ) { + onSendMessage: function( worker: any, type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); const joSend: any = { - "workerMessageType": + workerMessageType: ( type && typeof type == "string" && type.length > 0 ) ? type : "inWorkerMessage", - "workerEndPoint": endpoint, - "workerUUID": workerUUID, - "data": jo + workerEndPoint: endpoint, + workerUUID, + data: jo }; //worker.postMessage( socketReceivedDataReverseMarshall( joSend ) ); worker.postMessage( socketSentDataMarshall( joSend ) ); } }; export const inWorkerAPIs: any = { - "onMessage": function( data: any ) { + onMessage: function( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); if( ! ( "workerMessageType" in jo ) || typeof jo.workerMessageType != "string" || @@ -467,15 +467,15 @@ export const inWorkerAPIs: any = { return false; // TO-DO: send error answer and return true } // switch( jo.workerMessageType ) }, - "onSendMessage": function( type: any, endpoint: any, workerUUID: any, data: any ) { + onSendMessage: function( type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); const joSend: any = { - "workerMessageType": + workerMessageType: ( type && typeof type == "string" && type.length > 0 ) ? type : "inWorkerMessage", - "workerEndPoint": endpoint, - "workerUUID": workerUUID, - "data": jo + workerEndPoint: endpoint, + workerUUID, + data: jo }; //postMessage( socketReceivedDataReverseMarshall( joSend ) ); postMessage( socketSentDataMarshall( joSend ) ); @@ -498,10 +498,10 @@ export class InWorkerServerPipe extends BasicSocketPipe { const self = this; const iv = setTimeout( function() { clearTimeout( iv ); - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( - "connection", { "socket": self, "remoteAddress": "" + self.url } ) ); + "connection", { socket: self, remoteAddress: "" + self.url } ) ); }, 0 ); } dispose() { @@ -511,7 +511,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { handleServerDisposed() { this.performDisconnect(); this.isConnected = false; - this.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": this } ) ); + this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); this.acceptor = null; this.fnSend = null; this.url = ""; @@ -524,7 +524,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.isConnected = false; if( this.acceptor ) this.acceptor.unregisterClientByKey( this.clientPort ); - this.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": this } ) ); + this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); this.acceptor = null; this.fnSend = null; this.url = ""; @@ -533,7 +533,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend != "function" ) { const s = "Cannot send messages to disconnected in-worker server pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } const jo: any = socketReceivedDataReverseMarshall( data ); @@ -558,7 +558,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { "Cannot start in-worker socket server on already listening \"" + this.strEndPoint + "\" endpoint"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } gMapLocalServers[this.strEndPoint] = this; @@ -567,7 +567,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { const self = this; const iv = setTimeout( function() { clearTimeout( iv ); - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } dispose() { @@ -644,7 +644,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.isConnected = false; delete gMapConnectedInWorkerClients["" + this.clientPort]; this.fnSend( this.worker, "inWorkerDisconnect", this.strEndPoint, this.clientPort, {} ); - this.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": this } ) ); + this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); this.worker = null; this.clientPort = ""; this.strEndPoint = ""; @@ -654,7 +654,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { delete gMapAwaitingInWorkerClients[this.clientPort]; gMapConnectedInWorkerClients["" + this.clientPort] = this; this.isConnected = true; - this.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": this } ) ); + this.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: this } ) ); } implSend( data: any ) { if( ( !this.isConnected ) || @@ -666,7 +666,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { "socket": this, "message": "" + s } ) + { socket: this, message: "" + s } ) ); throw new Error( s ); } @@ -727,9 +727,9 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "connection", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress } ) ); // 1) configure incoming pipe let _offAllPipeEventListeners: any = null; @@ -741,10 +741,10 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "close", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": true + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: true } ) ); if( _offAllPipeEventListeners ) { _offAllPipeEventListeners(); @@ -759,10 +759,10 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "close", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": false + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: false } ) ); if( _offAllPipeEventListeners ) { _offAllPipeEventListeners(); @@ -777,10 +777,10 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "error", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": true + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: true } ) ); if( _offAllPipeEventListeners ) { _offAllPipeEventListeners(); @@ -795,10 +795,10 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "error", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": false + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: false } ) ); if( _offAllPipeEventListeners ) { _offAllPipeEventListeners(); @@ -821,11 +821,11 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "message", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": true, - "message": joMessage + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: true, + message: joMessage } ) ); pipeOutgoing.send( joMessage ); if( self.isAutoFlushIncoming ) @@ -847,11 +847,11 @@ export class OutOfWorkerRelay extends EventDispatcher { } self.dispatchEvent( new UniversalDispatcherEvent( "message", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": false, - "message": joMessage + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: false, + message: joMessage } ) ); pipeOutgoing.send( joMessage ); if( self.isAutoFlushOutgoing ) @@ -964,10 +964,10 @@ export class OneToOneRelay extends EventDispatcher { self.dispatchEvent( new UniversalDispatcherEvent( "close", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": true + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: true } ) ); if( _offAllPipeEventListeners ) { @@ -985,10 +985,10 @@ export class OneToOneRelay extends EventDispatcher { self.dispatchEvent( new UniversalDispatcherEvent( "close", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": false + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: false } ) ); if( _offAllPipeEventListeners ) { @@ -1008,10 +1008,10 @@ export class OneToOneRelay extends EventDispatcher { new UniversalDispatcherEvent( "error", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": true + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: true } ) ); if( _offAllPipeEventListeners ) { @@ -1031,10 +1031,10 @@ export class OneToOneRelay extends EventDispatcher { new UniversalDispatcherEvent( "error", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": false + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: false } ) ); if( _offAllPipeEventListeners ) { @@ -1064,11 +1064,11 @@ export class OneToOneRelay extends EventDispatcher { new UniversalDispatcherEvent( "message", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": true, - "message": joMessage + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: true, + message: joMessage } ) ); pipeOutgoing.send( joMessage ); @@ -1097,11 +1097,11 @@ export class OneToOneRelay extends EventDispatcher { new UniversalDispatcherEvent( "message", { - "relay": self, - "socket": pipeIncoming, - "remoteAddress": "" + pipeIncoming.strSavedRemoteAddress, - "isExternalSocket": false, - "message": joMessage + relay: self, + socket: pipeIncoming, + remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + isExternalSocket: false, + message: joMessage } ) ); pipeIncoming.send( joMessage ); @@ -1193,10 +1193,10 @@ export class DirectPipe extends BasicSocketPipe { const iv = setTimeout( function() { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( - "open", { "socket": self } ) ); + "open", { socket: self } ) ); self.counterPipe.dispatchEvent( new UniversalDispatcherEvent( - "open", { "socket": self.counterPipe } ) ); + "open", { socket: self.counterPipe } ) ); }, 0 ); } } @@ -1208,7 +1208,7 @@ export class DirectPipe extends BasicSocketPipe { handleServerDisposed() { // this method is for using in local client/server pipe pairs this.performDisconnect(); this.isConnected = false; - this.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": this } ) ); + this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); this.acceptor = null; this.counterPipe = null; this.clientPort = 0; @@ -1221,7 +1221,7 @@ export class DirectPipe extends BasicSocketPipe { this.isConnected = false; if( this.acceptor ) this.acceptor.unregisterClientByKey( this.clientPort ); - this.dispatchEvent( new UniversalDispatcherEvent( "close", { "socket": this } ) ); + this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); this.counterPipe.performDisconnect(); this.acceptor = null; this.counterPipe = null; @@ -1232,7 +1232,7 @@ export class DirectPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.counterPipe?.isConnected ) ) { const s = "Cannot send messages to disconnected local server pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -1258,7 +1258,7 @@ export class LocalSocketServerPipe extends DirectPipe { const self = this; const iv = setTimeout( function() { clearTimeout( iv ); - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } dispose() { @@ -1280,7 +1280,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { "Cannot start local socket server on already listening \"" + this.strEndPoint + "\" endpoint"; this.dispatchEvent( new UniversalDispatcherEvent( - "error", { "socket": this, "message": "" + s } ) ); + "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } gMapLocalServers[this.strEndPoint] = this; @@ -1289,7 +1289,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { const iv = setTimeout( function() { clearTimeout( iv ); self.dispatchEvent( - new UniversalDispatcherEvent( "open", { "socket": self } ) ); + new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } dispose() { @@ -1327,7 +1327,7 @@ export class LocalSocketClientPipe extends DirectPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { "socket": this, "message": "" + s } ) ); + { socket: this, message: "" + s } ) ); throw new Error( s ); } this.acceptor = gMapLocalServers[this.strEndPoint]; @@ -1339,17 +1339,17 @@ export class LocalSocketClientPipe extends DirectPipe { serverPipe.counterPipe = this; this.counterPipe = serverPipe; this.acceptor.mapClients[0 + this.clientPort] = { - serverPipe: serverPipe, + serverPipe, clientPipe: this }; const self = this; const iv = setTimeout( function() { clearTimeout( iv ); - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( "connection", - { "socket": serverPipe, "remoteAddress": "" + self.url } ) + { socket: serverPipe, remoteAddress: "" + self.url } ) ); }, 0 ); } @@ -1381,11 +1381,11 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.url = "ws_server_pipe(" + this.clientNumber + ")://" + remoteAddress; this._onWsClose = function() { self.dispatchEvent( - new UniversalDispatcherEvent( "close", { "socket": self } ) ); + new UniversalDispatcherEvent( "close", { socket: self } ) ); } this._onWsError = function( event: any ) { self.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": self, "message": event } ) ); + new UniversalDispatcherEvent( "error", { socket: self, message: event } ) ); } this._onWsMessage = function( event: any ) { self.receive( event.data ); @@ -1410,11 +1410,11 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.acceptor.mapClients["" + this.clientPort] = this; const iv = setTimeout( function() { clearTimeout( iv ); - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( "connection", - { "socket": self, "remoteAddress": "" + remoteAddress } ) + { socket: self, remoteAddress: "" + remoteAddress } ) ); }, 0 ); } @@ -1458,7 +1458,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket server pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -1471,7 +1471,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { implReceive( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( - new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); + new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); } }; @@ -1504,7 +1504,7 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { this.isListening = true; const iv = setTimeout( function() { clearTimeout( iv ); - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } dispose() { @@ -1551,7 +1551,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket client pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -1586,21 +1586,21 @@ export class WebSocketClientPipe extends BasicSocketPipe { self.isConnected = true; self.dispatchEvent( new UniversalDispatcherEvent( - "open", { "socket": self } ) ); + "open", { socket: self } ) ); } this._onWsClose = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( - "close", { "socket": self, "message": event } ) ); + "close", { socket: self, message: event } ) ); } this._onWsError = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( - "error", { "socket": self, "message": event } ) ); + "error", { socket: self, message: event } ) ); } this._onWsMessage = function( event: any ) { self.receive( event.data ); @@ -1650,7 +1650,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { if( url.length == 0 ) { const s = "Cannot connect web socket server \"" + url + "\", bad url"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": this, "message": "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); throw new Error( s ); } this.wsConnectAttempt( url, settings.net.ws.client.reconnectAfterMilliseconds, null ); @@ -1661,7 +1661,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this._removeWsEventListeners = null; } if( this.wsConnection ) { - let bPass = false, anyError = null; + let bPass = false; let anyError = null; try { this.wsConnection.close(); bPass = true; @@ -1686,7 +1686,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { implReceive( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( - new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); + new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); } }; @@ -1763,7 +1763,7 @@ export class RTCConnection extends EventDispatcher { this.dc = null; this.dispatchEvent( new UniversalDispatcherEvent( - "dataChannelClose", { "detail": { "actor": this } } ) ); + "dataChannelClose", { detail: { actor: this } } ) ); } } closePeer() { @@ -1780,14 +1780,14 @@ export class RTCConnection extends EventDispatcher { } this.dispatchEvent( new UniversalDispatcherEvent( - "peerClose", { "detail": { "actor": this } } ) ); + "peerClose", { detail: { actor: this } } ) ); this.pc = null; } } onError( err: any ) { this.dispatchEvent( new UniversalDispatcherEvent( - "rtcParticipantError", { "detail": { "actor": this, "error": err } } ) ); + "rtcParticipantError", { detail: { actor: this, error: err } } ) ); if( settings.logging.net.rtc.error ) console.warn( " !!! " + this.describe() + " error:", err ); this.closeDataChannel(); @@ -1808,17 +1808,17 @@ export class RTCConnection extends EventDispatcher { onDataChannelOpen( event: any ) { this.dispatchEvent( new UniversalDispatcherEvent( - "dataChannelOpen", { "detail": { "actor": this } } ) ); + "dataChannelOpen", { detail: { actor: this } } ) ); } onDataChannelClose( even: any ) { this.dispatchEvent( new UniversalDispatcherEvent( - "dataChannelClose", { "detail": { "actor": this } } ) ); + "dataChannelClose", { detail: { actor: this } } ) ); } onDataChannelError( event: any ) { this.dispatchEvent( new UniversalDispatcherEvent( - "dataChannelError", { "detail": { "actor": this } } ) ); + "dataChannelError", { detail: { actor: this } } ) ); this.onError( "Data channel error " + event.toString() ); } onDataChannelMessage( event: any ) { @@ -1838,7 +1838,7 @@ export class RTCConnection extends EventDispatcher { } else { this.dispatchEvent( new UniversalDispatcherEvent( - "dataChannelMessage", { "detail": { "actor": this, "data": data } } ) ); + "dataChannelMessage", { detail: { actor: this, data } } ) ); } } } @@ -2039,7 +2039,7 @@ export class RTCActor extends RTCConnection { self.signalingPipeClose(); self.dispatchEvent( new UniversalDispatcherEvent( - "signalingWillStart", { "detail": { "actor": this } } ) ); + "signalingWillStart", { detail: { actor: this } } ) ); self.signalingPipe = new WebSocketClientPipe( self.strSignalingServerURL ); self.signalingPipe.on( "open", function( eventData: any ) { self.signalingPipeOnOpen( eventData ); } ); @@ -2053,7 +2053,7 @@ export class RTCActor extends RTCConnection { } ); self.dispatchEvent( new UniversalDispatcherEvent( - "signalingDidStarted", { "detail": { "actor": this } } ) ); + "signalingDidStarted", { detail: { actor: this } } ) ); } catch ( err ) { if( settings.logging.net.signaling.error ) console.warn( this.describe() + " error starting signaling pipe:", err ); @@ -2076,26 +2076,26 @@ export class RTCActor extends RTCConnection { this.signalingPipe = null; this.dispatchEvent( new UniversalDispatcherEvent( - "signalingClosed", { "detail": { "actor": this } } ) ); + "signalingClosed", { detail: { actor: this } } ) ); } } signalingPipeOnOpen( eventData: any ) { try { this.dispatchEvent( new UniversalDispatcherEvent( - "signalingOpened", { "detail": { "actor": this } } ) ); + "signalingOpened", { detail: { actor: this } } ) ); if( settings.logging.net.signaling.connect ) { console.log( "+++ " + this.describe() + " did connected to " + this.strSignalingServerURL ); } const joImpersonateMessage = { - "id": utils.randomCallID(), - "method": "signalingImpersonate", - "idCategory": "" + this.signalingOptions.idCategory, - "idSpace": "" + this.signalingOptions.idSpace, - "idRtcParticipant": "" + this.idRtcParticipant, - "role": this.isCreator ? "creator" : "joiner" + id: utils.randomCallID(), + method: "signalingImpersonate", + idCategory: "" + this.signalingOptions.idCategory, + idSpace: "" + this.signalingOptions.idSpace, + idRtcParticipant: "" + this.idRtcParticipant, + role: this.isCreator ? "creator" : "joiner" }; if( settings.logging.net.signaling.message ) console.log( " <<< " + this.describe() + " message out", joImpersonateMessage ); @@ -2112,7 +2112,7 @@ export class RTCActor extends RTCConnection { signalingPipeOnClose( eventData: any ) { this.dispatchEvent( new UniversalDispatcherEvent( - "signalingPipeClose", { "detail": { "actor": this } } ) ); + "signalingPipeClose", { detail: { actor: this } } ) ); if( settings.logging.net.signaling.disconnect ) { console.warn( " !!! " + this.describe() + " signaling pipe closed for " + @@ -2125,7 +2125,7 @@ export class RTCActor extends RTCConnection { // alert( JSON.stringify( eventData ) ); this.dispatchEvent( new UniversalDispatcherEvent( - "signalingPipeError", { "detail": { "actor": this, "error": eventData } } ) ); + "signalingPipeError", { detail: { actor: this, error: eventData } } ) ); if( settings.logging.net.signaling.error ) { console.warn( " !!! " + this.describe() + " signaling pipe error for " + @@ -2155,7 +2155,7 @@ export class RTCActor extends RTCConnection { } signalingPipeOnMessage( joMessage: any ) { switch ( joMessage.method ) { - case "signalingImpersonate": { + case "signalingImpersonate": if( joMessage.error == null ) { // OKay, impersonated this.bWasImpersonated = true; @@ -2166,7 +2166,7 @@ export class RTCActor extends RTCConnection { } this.dispatchEvent( new UniversalDispatcherEvent( - "signalingPassedImpersonation", { "detail": { "actor": this } } ) ); + "signalingPassedImpersonation", { detail: { actor: this } } ) ); this.onImpersonationComplete(); } else { if( settings.logging.net.signaling.error ) { @@ -2178,11 +2178,11 @@ export class RTCActor extends RTCConnection { this.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedImpersonation", - { "detail": { "actor": this, "error": joMessage.error } } ) + { detail: { actor: this, error: joMessage.error } } ) ); this.onError( joMessage.error ); } - } break; + break; default: if( settings.logging.net.signaling.error ) { console.warn( @@ -2357,19 +2357,19 @@ export class RTCServerPeer extends RTCConnection { self.dispatchEvent( new UniversalDispatcherEvent( "publishTimeout", - { "detail": { "participant": self } } ) + { detail: { participant: self } } ) ); if( self.rtcCreator ) { self.rtcCreator.dispatchEvent( new UniversalDispatcherEvent( "publishTimeout", - { "detail": { "participant": self } } ) + { detail: { participant: self } } ) ); } }, self.timeToPublishMilliseconds ); } self.dispatchEvent( new UniversalDispatcherEvent( - "publishStart", { "detail": { "participant": self } } ) ); + "publishStart", { detail: { participant: self } } ) ); self.pc.oniceconnectionstatechange = function( event: any ) { self.onIceConnectionStateChange( event ); } self.pc.onicegatheringstatechange = @@ -2393,7 +2393,7 @@ export class RTCServerPeer extends RTCConnection { } self.dispatchEvent( new UniversalDispatcherEvent( - "offerCreated", { "detail": { "participant": self } } ) ); + "offerCreated", { detail: { participant: self } } ) ); self.pc.setLocalDescription( offerDescription ).then( function() { // success @@ -2406,7 +2406,7 @@ export class RTCServerPeer extends RTCConnection { self.dispatchEvent( new UniversalDispatcherEvent( "localDescriptionSet", - { "detail": { "participant": self } } ) + { detail: { participant: self } } ) ); self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; @@ -2434,9 +2434,9 @@ export class RTCServerPeer extends RTCConnection { new UniversalDispatcherEvent( "identified", { - "detail": { - "participant": this, - "idSomebodyOtherSide": "" + idSomebodyOtherSide + detail: { + participant: this, + idSomebodyOtherSide: "" + idSomebodyOtherSide } } ) ); @@ -2466,6 +2466,7 @@ export class RTCServerPeer extends RTCConnection { } publishOfferOnSignalingServer() { const self = this; + // eslint-disable-next-line no-useless-catch try { if( settings.logging.net.signaling.candidate ) console.log( " <<< " + self.describe() + " got candidate", event ); @@ -2474,11 +2475,11 @@ export class RTCServerPeer extends RTCConnection { if( ! self.rtcCreator.signalingPipe ) throw new Error( "no connection to signaling server" ); const joPublishOfferMessage = { - "id": utils.randomCallID(), - "method": "signalingPublishOffer", - "offer": self.pc.localDescription, - "idSomebodyCreator": "" + self.rtcCreator.idRtcParticipant, - "idOffer": 0 + ( self.idOffer || 0 ) + id: utils.randomCallID(), + method: "signalingPublishOffer", + offer: self.pc.localDescription, + idSomebodyCreator: "" + self.rtcCreator.idRtcParticipant, + idOffer: 0 + ( self.idOffer || 0 ) }; if( settings.logging.net.signaling.message ) { console.log( @@ -2490,7 +2491,7 @@ export class RTCServerPeer extends RTCConnection { self.publishCancel(); self.dispatchEvent( new UniversalDispatcherEvent( - "signalingNegotiationStart", { "detail": { "participant": self } } ) ); + "signalingNegotiationStart", { detail: { participant: self } } ) ); if( self.timeToSignalingNegotiationMilliseconds > 0 ) { self.isSignalingNegotiation = true; self.timerSignalingNegotiation = setTimeout( function() { @@ -2506,13 +2507,13 @@ export class RTCServerPeer extends RTCConnection { self.dispatchEvent( new UniversalDispatcherEvent( "signalingNegotiationTimeout", - { "detail": { "participant": self } } ) + { detail: { participant: self } } ) ); if( self.rtcCreator ) { self.rtcCreator.dispatchEvent( new UniversalDispatcherEvent( "signalingNegotiationTimeout", - { "detail": { "participant": self } } ) + { detail: { participant: self } } ) ); } }, self.timeToSignalingNegotiationMilliseconds ); @@ -2624,20 +2625,20 @@ export class RTCCreator extends RTCActor { this.dispatchEvent( new UniversalDispatcherEvent( "rtcPeerError", - { "detail": { "actor": this, "peer": rtcPeer, "error": err } } ) + { detail: { actor: this, peer: rtcPeer, error: err } } ) ); } signalingPipeOnMessage( joMessage: any ) { const self = this; switch ( joMessage.method ) { - case "signalingPublishOffer": { + case "signalingPublishOffer": if( joMessage.error == null ) { // OKay, creator offer published if( settings.logging.net.signaling.offer ) console.log( "Success, " + this.describe() + " offer published (step 1)" ); this.dispatchEvent( new UniversalDispatcherEvent( - "signalingPassedOfferPublish", { "detail": { "actor": this } } ) ); + "signalingPassedOfferPublish", { detail: { actor: this } } ) ); } else { if( settings.logging.net.signaling.error ) { console.warn( @@ -2647,12 +2648,12 @@ export class RTCCreator extends RTCActor { this.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedOfferPublish", - { "detail": { "actor": this, "error": joMessage.error } } ) + { detail: { actor: this, error: joMessage.error } } ) ); this.onError( joMessage.error ); } - } break; - case "signalingPublishAnswer": { // server peer got result + break; + case "signalingPublishAnswer": // server peer got result if( joMessage.error == null ) { const idSomebodyOtherSide = "" + joMessage.idSomebody_joiner; const idOffer = 0 + joMessage.idOffer; @@ -2680,9 +2681,9 @@ export class RTCCreator extends RTCActor { new UniversalDispatcherEvent( "signalingPassedPublishAnswer", { - "detail": { - "actor": this, - "idSomebodyOtherSide": "" + idSomebodyOtherSide, + detail: { + actor: this, + idSomebodyOtherSide: "" + idSomebodyOtherSide, idOffer: 0 + idOffer } } ) @@ -2719,7 +2720,7 @@ export class RTCCreator extends RTCActor { self.dispatchEvent( new UniversalDispatcherEvent( "remoteDescriptionSet", - { "detail": { "participant": self } } ) + { detail: { participant: self } } ) ); self.onOtherSideIdentified( idSomebodyOtherSide, idOffer ); // server peer got result @@ -2737,11 +2738,11 @@ export class RTCCreator extends RTCActor { this.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedPublishAnswer", - { "detail": { "actor": this, "error": joMessage.error } } ) + { detail: { actor: this, error: joMessage.error } } ) ); this.onError( joMessage.error ); } - } break; + break; default: super.signalingPipeOnMessage( joMessage ); break; @@ -2836,7 +2837,7 @@ export class RTCJoiner extends RTCActor { self.dispatchEvent( new UniversalDispatcherEvent( "trackAvailable", - { "detail": { "participant": self, "event": event } } ) ); + { detail: { participant: self, event } } ) ); } ); self.pc.oniceconnectionstatechange = function( event: any ) { self.onIceConnectionStateChange( event ); } @@ -2852,7 +2853,7 @@ export class RTCJoiner extends RTCActor { self.dispatchEvent( new UniversalDispatcherEvent( "dataChannelAvailable", - { "detail": { "participant": self, "event": event } } ) + { detail: { participant: self, event } } ) ); const dataChannel = event.channel || event; self.dc = dataChannel; @@ -2899,6 +2900,7 @@ export class RTCJoiner extends RTCActor { } publishSignalingAnswer( event: any ) { const self = this; + // eslint-disable-next-line no-useless-catch try { if( event.candidate == null || settings.net.rtc.fastPublishMode.joiner @@ -2912,12 +2914,12 @@ export class RTCJoiner extends RTCActor { if( ! self.signalingPipe ) throw new Error( "no connection to signaling server" ); const joPublishAnswerMessage = { - "id": utils.randomCallID(), - "method": "signalingPublishAnswer", - "answer": self.pc.localDescription, - "idRtcParticipant": "" + self.idRtcParticipant, - "idSomebodyCreator": "" + self.idSomebodyCreator, - "idOffer": 0 + self.idOffer + id: utils.randomCallID(), + method: "signalingPublishAnswer", + answer: self.pc.localDescription, + idRtcParticipant: "" + self.idRtcParticipant, + idSomebodyCreator: "" + self.idSomebodyCreator, + idOffer: 0 + self.idOffer }; if( settings.logging.net.signaling.message ) { console.log( @@ -2939,8 +2941,8 @@ export class RTCJoiner extends RTCActor { onImpersonationComplete() { super.onImpersonationComplete(); const joFetchOfferMessage = { - "id": utils.randomCallID(), - "method": "signalingFetchOffer" + id: utils.randomCallID(), + method: "signalingFetchOffer" }; if( settings.logging.net.signaling.message ) { console.log( @@ -2967,16 +2969,16 @@ export class RTCJoiner extends RTCActor { new UniversalDispatcherEvent( "identified", { - "detail": { - "participant": this, - "idSomebodyOtherSide": "" + idSomebodyOtherSide + detail: { + participant: this, + idSomebodyOtherSide: "" + idSomebodyOtherSide } } ) ); } signalingPipeOnMessage( joMessage: any ) { const self = this; switch ( joMessage.method ) { - case "signalingFetchOffer": { + case "signalingFetchOffer": if( joMessage.error == null ) { // OKay, fetched offer from creator this.delayedInitPeer(); @@ -2992,9 +2994,9 @@ export class RTCJoiner extends RTCActor { new UniversalDispatcherEvent( "signalingPassedFetchOffer", { - "detail": { - "actor": this, - "idSomebodyOtherSide": "" + idSomebodyOtherSide, + detail: { + actor: this, + idSomebodyOtherSide: "" + idSomebodyOtherSide, idOffer: 0 + idOffer } } ) ); @@ -3018,7 +3020,7 @@ export class RTCJoiner extends RTCActor { self.dispatchEvent( new UniversalDispatcherEvent( "remoteDescriptionSet", - { "detail": { "participant": self } } ) ); + { detail: { participant: self } } ) ); self.pc.createAnswer( self.offerOptions ).then( function( answerDescription: any ) { // success @@ -3032,7 +3034,7 @@ export class RTCJoiner extends RTCActor { self.dispatchEvent( new UniversalDispatcherEvent( "answerCreated", - { "detail": { "participant": self } } ) ); + { detail: { participant: self } } ) ); self.pc.setLocalDescription( answerDescription ).then( function() { // success @@ -3044,7 +3046,7 @@ export class RTCJoiner extends RTCActor { self.dispatchEvent( new UniversalDispatcherEvent( "localDescriptionSet", - { "detail": { "participant": self } } ) ); + { detail: { participant: self } } ) ); self.onOtherSideIdentified( idSomebodyOtherSide, idOffer ); // client peer got result @@ -3077,10 +3079,10 @@ export class RTCJoiner extends RTCActor { this.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedFetchOffer", - { "detail": { "actor": this, "error": joMessage.error } } ) ); + { detail: { actor: this, error: joMessage.error } } ) ); this.onError( joMessage.error ); } - } break; + break; default: super.signalingPipeOnMessage( joMessage ); break; @@ -3109,11 +3111,11 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { self.isConnected = true; self.acceptor.mapClients["" + self.clientPort] = self; - self.dispatchEvent( new UniversalDispatcherEvent( "open", { "socket": self } ) ); + self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( "connection", - { "socket": self, strSignalingServerURL: "" + strSignalingServerURL } ) ); + { socket: self, strSignalingServerURL: "" + strSignalingServerURL } ) ); } ); self.rtcPeer.on( "dataChannelMessage", function( jo: any ) { self.receive( jo.detail.data ); @@ -3121,22 +3123,22 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.rtcPeer.on( "rtcParticipantError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": self, "message": jo } ) ); + new UniversalDispatcherEvent( "error", { socket: self, message: jo } ) ); } ); self.rtcPeer.on( "dataChannelError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( - new UniversalDispatcherEvent( "error", { "socket": self, "message": jo } ) ); + new UniversalDispatcherEvent( "error", { socket: self, message: jo } ) ); } ); self.rtcPeer.on( "dataChannelClose", function( jo: any ) { self.isConnected = false; self.dispatchEvent( - new UniversalDispatcherEvent( "close", { "socket": self, "message": jo } ) ); + new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); } ); self.rtcPeer.on( "peerClose", function( jo: any ) { self.isConnected = false; self.dispatchEvent( - new UniversalDispatcherEvent( "close", { "socket": self, "message": jo } ) ); + new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); } ); } dispose() { @@ -3187,7 +3189,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { implReceive( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( - new UniversalDispatcherEvent( "message", { "socket": this, "message": jo } ) ); + new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); } }; @@ -3250,23 +3252,23 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { self.dispatchEvent( new UniversalDispatcherEvent( "signalingPassedImpersonation", - { "detail": { "acceptor": self } } ) ); + { detail: { acceptor: self } } ) ); } ); this.rtcCreator.on( "signalingFailedImpersonation", function( eventData: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedImpersonation", - { "detail": { "acceptor": self } } ) ); + { detail: { acceptor: self } } ) ); } ); this.rtcCreator.on( "error", function( eventData: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "error", { - "detail": { - "acceptor": self, - "eventData": eventData, - "errorType": "rtcCreatorError" + detail: { + acceptor: self, + eventData, + errorType: "rtcCreatorError" } } ) ); } ); @@ -3274,14 +3276,14 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { self.dispatchEvent( new UniversalDispatcherEvent( "close", - { "detail": { "acceptor": self, "eventData": eventData } } ) ); + { detail: { acceptor: self, eventData } } ) ); } ); self.rtcCreator.on( "signalingPipeError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", - { "socket": self, "message": jo, "errorType": "signalingPipeError" } ) ); + { socket: self, message: jo, errorType: "signalingPipeError" } ) ); } ); } dispose() { @@ -3317,14 +3319,14 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { new WebRTCServerPipe( self, rtcPeer, self.strSignalingServerURL ); self.detachPendingOffer( rtcPeer.idOffer ); self.dispatchEvent( - new UniversalDispatcherEvent( "identified", { "detail": { "peer": rtcPeer } } ) ); + new UniversalDispatcherEvent( "identified", { detail: { peer: rtcPeer } } ) ); self.updateAllPendingOffers(); } ); rtcPeer.on( "localDescriptionSet", function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "peerLocalDescriptionSet", - { "detail": { "acceptor": self, "peerEvent": event } } ) ); + { detail: { acceptor: self, peerEvent: event } } ) ); } ); const onTimeoutHandler = function() { self.disposePendingOffer( rtcPeer.idOffer ); @@ -3341,11 +3343,11 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { new UniversalDispatcherEvent( "error", { - "detail": { - "acceptor": self, - "rtcPeer": rtcPeer, - "eventData": eventData, - "errorType": "rtcPeerError" + detail: { + acceptor: self, + rtcPeer, + eventData, + errorType: "rtcPeerError" } } ) ); } @@ -3440,7 +3442,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { "socket": this, "message": "" + s, "errorType": "dataSendError" } ) ); + { socket: this, message: "" + s, errorType: "dataSendError" } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -3465,7 +3467,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { "socket": this, "message": "" + s, "errorType": "badSignalingServerURL" } ) ); + { socket: this, message: "" + s, errorType: "badSignalingServerURL" } ) ); throw new Error( s ); } const self = this; @@ -3492,7 +3494,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { self.isConnected = true; self.dispatchEvent( - new UniversalDispatcherEvent( "open", { "socket": self } ) + new UniversalDispatcherEvent( "open", { socket: self } ) ); if( self.isAutoCloseSignalingPipeOnDataChannelOpen ) { if( settings.logging.net.signaling.disconnect ) { @@ -3513,9 +3515,9 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.dispatchEvent( new UniversalDispatcherEvent( "error", { - "socket": self, - "message": jo, - "errorType": "rtcParticipantError" + socket: self, + message: jo, + errorType: "rtcParticipantError" } ) ); } ); @@ -3524,9 +3526,9 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.dispatchEvent( new UniversalDispatcherEvent( "error", { - "socket": self, - "message": jo, - "errorType": "dataChannelError" + socket: self, + message: jo, + errorType: "dataChannelError" } ) ); } ); @@ -3534,16 +3536,16 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", - { "socket": self, "message": jo } ) ); + { socket: self, message: jo } ) ); } ); self.rtcPeer.on( "signalingPipeError", function( jo: any ) { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { - "socket": self, - "message": jo, - "errorType": "signalingPipeError" + socket: self, + message: jo, + errorType: "signalingPipeError" } ) ); } ); @@ -3568,6 +3570,6 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "message", - { "socket": this, "message": jo } ) ); + { socket: this, message: jo } ) ); } }; diff --git a/src/socketServer.ts b/src/socketServer.ts index d36ddeb6..787c4ffa 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -159,7 +159,7 @@ export class SocketServer extends EventDispatcher { socket.on( "message", _onPipeMessage ); } ); this.dispatchEvent( - new UniversalDispatcherEvent( "initialized", { "detail": { "ref": this } } ) ); + new UniversalDispatcherEvent( "initialized", { detail: { ref: this } } ) ); } dispose(): void { this.isDisposing = true; diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 8751c1c4..83adda09 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -27,7 +27,7 @@ import { settings } from "./socketSettings.js"; export const UUIDv4 = function(): string { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( /[xy]/g, function( c ) { - const r = Math.random() * 16 | 0, v = c == "x" ? r : ( r & 0x3 | 0x8 ); + const r = Math.random() * 16 | 0; const v = c == "x" ? r : ( r & 0x3 | 0x8 ); return v.toString( 16 ); } ); } @@ -125,17 +125,17 @@ export const randomDirectPipeID = function(): string { export const prepareAnswerJSON = function( joMessage: any ): any { const joAnswer: any = { - "id": "" + + id: "" + ( ( joMessage != null && joMessage != undefined && typeof joMessage.id == "string" ) ? joMessage.id : randomCallID() ), - "method": "" + + method: "" + ( ( joMessage != null && joMessage != undefined && typeof joMessage.method == "string" ) ? joMessage.method : "" ), - "error": null + error: null }; return joAnswer; } diff --git a/src/state.ts b/src/state.ts index b04a90b8..a7176420 100644 --- a/src/state.ts +++ b/src/state.ts @@ -2,141 +2,141 @@ import * as owaspUtils from "./owaspUtils.js"; import * as imaTx from "./imaTx.js"; export const gDefaultValueForLoopState: any = { - "oracle": { - "isInProgress": false, - "wasInProgress": false + oracle: { + isInProgress: false, + wasInProgress: false }, - "m2s": { - "isInProgress": false, - "wasInProgress": false + m2s: { + isInProgress: false, + wasInProgress: false }, - "s2m": { - "isInProgress": false, - "wasInProgress": false + s2m: { + isInProgress: false, + wasInProgress: false }, - "s2s": { - "isInProgress": false, - "wasInProgress": false + s2s: { + isInProgress: false, + wasInProgress: false } }; function constructChainProperties() { return { - "mn": { - "joAccount": { - "privateKey": + mn: { + joAccount: { + privateKey: owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_ETHEREUM ), - "address": + address: function() { return owaspUtils.fnAddressImpl_( this ); }, - "strTransactionManagerURL": + strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_ETHEREUM ), - "nTmPriority": + nTmPriority: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_PRIORITY_ETHEREUM ) || 5, - "strSgxURL": owaspUtils.toStringURL( process.env.SGX_URL_ETHEREUM ), - "strSgxKeyName": owaspUtils.toStringURL( process.env.SGX_KEY_ETHEREUM ), - "strPathSslKey": + strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_ETHEREUM ), + strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_ETHEREUM ), + strPathSslKey: ( process.env.SGX_SSL_KEY_FILE_ETHEREUM || "" ).toString().trim(), - "strPathSslCert": + strPathSslCert: ( process.env.SGX_SSL_CERT_FILE_ETHEREUM || "" ).toString().trim(), - "strBlsKeyName": owaspUtils.toStringURL( process.env.BLS_KEY_ETHEREUM ) + strBlsKeyName: owaspUtils.toStringURL( process.env.BLS_KEY_ETHEREUM ) }, - "transactionCustomizer": imaTx.getTransactionCustomizerForMainNet(), - "ethersProvider": null, - "strURL": owaspUtils.toStringURL( process.env.URL_W3_ETHEREUM ), - "strChainName": + transactionCustomizer: imaTx.getTransactionCustomizerForMainNet(), + ethersProvider: null, + strURL: owaspUtils.toStringURL( process.env.URL_W3_ETHEREUM ), + strChainName: ( process.env.CHAIN_NAME_ETHEREUM || "Mainnet" ).toString().trim(), - "chainId": owaspUtils.toInteger( process.env.CID_ETHEREUM ) || -4, - "strPathAbiJson": null, - "joAbiIMA": { }, - "bHaveAbiIMA": false, - "joErc20": null, - "joErc721": null, - "joErc1155": null, - "strCoinNameErc20": "", // in-JSON coin name - "strCoinNameErc721": "", // in-JSON coin name - "strCoinNameErc1155": "", // in-JSON coin name - "strPathJsonErc20": "", - "strPathJsonErc721": "", - "strPathJsonErc1155": "" + chainId: owaspUtils.toInteger( process.env.CID_ETHEREUM ) || -4, + strPathAbiJson: null, + joAbiIMA: { }, + bHaveAbiIMA: false, + joErc20: null, + joErc721: null, + joErc1155: null, + strCoinNameErc20: "", // in-JSON coin name + strCoinNameErc721: "", // in-JSON coin name + strCoinNameErc1155: "", // in-JSON coin name + strPathJsonErc20: "", + strPathJsonErc721: "", + strPathJsonErc1155: "" }, - "sc": { - "joAccount": { - "privateKey": + sc: { + joAccount: { + privateKey: owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN ), - "address": + address: function() { return owaspUtils.fnAddressImpl_( this ); }, - "strTransactionManagerURL": + strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN ), - "nTmPriority": + nTmPriority: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_PRIORITY_S_CHAIN ) || 5, - "strSgxURL": owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN ), - "strSgxKeyName": owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN ), - "strPathSslKey": + strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN ), + strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN ), + strPathSslKey: ( process.env.SGX_SSL_KEY_FILE_S_CHAIN || "" ).toString().trim(), - "strPathSslCert": + strPathSslCert: ( process.env.SGX_SSL_CERT_FILE_S_CHAIN || "" ).toString().trim(), - "strBlsKeyName": owaspUtils.toStringURL( process.env.BLS_KEY_S_CHAIN ) + strBlsKeyName: owaspUtils.toStringURL( process.env.BLS_KEY_S_CHAIN ) }, - "transactionCustomizer": imaTx.getTransactionCustomizerForSChain(), - "ethersProvider": null, - "strURL": owaspUtils.toStringURL( process.env.URL_W3_S_CHAIN ), - "strChainName": + transactionCustomizer: imaTx.getTransactionCustomizerForSChain(), + ethersProvider: null, + strURL: owaspUtils.toStringURL( process.env.URL_W3_S_CHAIN ), + strChainName: ( process.env.CHAIN_NAME_SCHAIN || "id-S-chain" ).toString().trim(), - "chainId": owaspUtils.toInteger( process.env.CID_SCHAIN ) || -4, - "strPathAbiJson": null, - "joAbiIMA": { }, - "bHaveAbiIMA": false, - "joErc20": null, - "joErc721": null, - "joErc1155": null, - "strCoinNameErc20": "", // in-JSON coin name - "strCoinNameErc721": "", // in-JSON coin name - "strCoinNameErc1155": "", // in-JSON coin name - "strPathJsonErc20": "", - "strPathJsonErc721": "", - "strPathJsonErc1155": "" + chainId: owaspUtils.toInteger( process.env.CID_SCHAIN ) || -4, + strPathAbiJson: null, + joAbiIMA: { }, + bHaveAbiIMA: false, + joErc20: null, + joErc721: null, + joErc1155: null, + strCoinNameErc20: "", // in-JSON coin name + strCoinNameErc721: "", // in-JSON coin name + strCoinNameErc1155: "", // in-JSON coin name + strPathJsonErc20: "", + strPathJsonErc721: "", + strPathJsonErc1155: "" }, - "tc": { - "joAccount": { - "privateKey": + tc: { + joAccount: { + privateKey: owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN_TARGET ), - "address": + address: function() { return owaspUtils.fnAddressImpl_( this ); }, - "strTransactionManagerURL": + strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN_TARGET ), - "nTmPriority": + nTmPriority: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_PRIORITY_S_CHAIN_TARGET ) || 5, - "strSgxURL": owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN_TARGET ), - "strSgxKeyName": owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN_TARGET ), - "strPathSslKey": + strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN_TARGET ), + strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN_TARGET ), + strPathSslKey: ( process.env.SGX_SSL_KEY_FILE_S_CHAIN_TARGET || "" ).toString().trim(), - "strPathSslCert": + strPathSslCert: ( process.env.SGX_SSL_CERT_FILE_S_CHAIN_TARGET || "" ).toString().trim(), - "strBlsKeyName": owaspUtils.toStringURL( process.env.BLS_KEY_T_CHAIN ) + strBlsKeyName: owaspUtils.toStringURL( process.env.BLS_KEY_T_CHAIN ) }, - "transactionCustomizer": imaTx.getTransactionCustomizerForSChainTarget(), - "ethersProvider": null, - "strURL": owaspUtils.toStringURL( process.env.URL_W3_S_CHAIN_TARGET ), - "strChainName": + transactionCustomizer: imaTx.getTransactionCustomizerForSChainTarget(), + ethersProvider: null, + strURL: owaspUtils.toStringURL( process.env.URL_W3_S_CHAIN_TARGET ), + strChainName: ( process.env.CHAIN_NAME_SCHAIN_TARGET || "id-T-chain" ).toString().trim(), - "chainId": owaspUtils.toInteger( process.env.CID_SCHAIN_TARGET ) || -4, - "strPathAbiJson": null, - "joAbiIMA": { }, - "bHaveAbiIMA": false, - "joErc20": null, - "joErc721": null, - "joErc1155": null, - "strCoinNameErc20": "", // in-JSON coin name - "strCoinNameErc721": "", // in-JSON coin name - "strCoinNameErc1155": "", // in-JSON coin name - "strPathJsonErc20": "", - "strPathJsonErc721": "", - "strPathJsonErc1155": "" + chainId: owaspUtils.toInteger( process.env.CID_SCHAIN_TARGET ) || -4, + strPathAbiJson: null, + joAbiIMA: { }, + bHaveAbiIMA: false, + joErc20: null, + joErc721: null, + joErc1155: null, + strCoinNameErc20: "", // in-JSON coin name + strCoinNameErc721: "", // in-JSON coin name + strCoinNameErc1155: "", // in-JSON coin name + strPathJsonErc20: "", + strPathJsonErc721: "", + strPathJsonErc1155: "" } }; } @@ -147,144 +147,144 @@ export function get() { if( imaState ) return imaState; imaState = { - "loopState": gDefaultValueForLoopState, - - "strLogFilePath": "", - "nLogMaxSizeBeforeRotation": -1, - "nLogMaxFilesCount": -1, - "isPrintGathered": true, - "isPrintSecurityValues": false, - "isPrintPWA": false, - "isDynamicLogInDoTransfer": true, - "isDynamicLogInBlsSigner": false, - - "bIsNeededCommonInit": true, + loopState: gDefaultValueForLoopState, + + strLogFilePath: "", + nLogMaxSizeBeforeRotation: -1, + nLogMaxFilesCount: -1, + isPrintGathered: true, + isPrintSecurityValues: false, + isPrintPWA: false, + isDynamicLogInDoTransfer: true, + isDynamicLogInBlsSigner: false, + + bIsNeededCommonInit: true, // use BLS message signing, turned on with --sign-messages - "bSignMessages": false, + bSignMessages: false, // scanned S-Chain network description - "joSChainNetworkInfo": null, + joSChainNetworkInfo: null, // path to bls_glue app, must have if --sign-messages specified - "strPathBlsGlue": "", + strPathBlsGlue: "", // path to hash_g1 app, must have if --sign-messages specified - "strPathHashG1": "", + strPathHashG1: "", // path to verify_bls app, optional, // if specified then we will verify gathered BLS signature - "strPathBlsVerify": "", + strPathBlsVerify: "", // true - just show configuration values and exit - "bShowConfigMode": false, - - "isEnabledMultiCall": true, - - "bNoWaitSChainStarted": false, - "nMaxWaitSChainAttempts": 0 + Number.MAX_SAFE_INTEGER, // 20 - - "nAmountOfWei": 0, - "nAmountOfToken": 0, - "arrAmountsOfTokens": null, - "idToken": 0, - - "nTransferBlockSizeM2S": 4, - "nTransferBlockSizeS2M": 4, - "nTransferBlockSizeS2S": 4, - "nTransferStepsM2S": 8, - "nTransferStepsS2M": 8, - "nTransferStepsS2S": 8, - "nMaxTransactionsM2S": 0, - "nMaxTransactionsS2M": 0, - "nMaxTransactionsS2S": 0, - - "nBlockAwaitDepthM2S": 0, - "nBlockAwaitDepthS2M": 0, - "nBlockAwaitDepthS2S": 0, - "nBlockAgeM2S": 0, - "nBlockAgeS2M": 0, - "nBlockAgeS2S": 0, - - "nLoopPeriodSeconds": 10, - - "nNodeNumber": 0, // S-Chain node number(zero based) - "nNodesCount": 1, - "nTimeFrameSeconds": 0, // 0-disable, 60-recommended - "nNextFrameGap": 10, - - "nAutoExitAfterSeconds": 0, // 0-disable - - "joCommunityPool": null, // only main net - "joDepositBoxETH": null, // only main net - "joDepositBoxERC20": null, // only main net - "joDepositBoxERC721": null, // only main net - "joDepositBoxERC1155": null, // only main net - "joDepositBoxERC721WithMetadata": null, // only main net - "joLinker": null, // only main net - - "isWithMetadata721": false, - - "joTokenManagerETH": null, // only s-chain - "joTokenManagerERC20": null, // only s-chain - "joTokenManagerERC20Target": null, // only s-chain - "joTokenManagerERC721": null, // only s-chain target - "joTokenManagerERC721Target": null, // only s-chain target - "joTokenManagerERC1155": null, // only s-chain - "joTokenManagerERC1155Target": null, // only s-chain target - "joTokenManagerERC721WithMetadata": null, // only s-chain target - "joTokenManagerERC721WithMetadataTarget": null, // only s-chain target - "joCommunityLocker": null, // only s-chain - "joCommunityLockerTarget": null, // only s-chain target - "joMessageProxyMainNet": null, - "joMessageProxySChain": null, - "joMessageProxySChainTarget": null, // only s-chain target - "joTokenManagerLinker": null, - "joTokenManagerLinkerTarget": null, // only s-chain target - "joEthErc20": null, // only s-chain - "joEthErc20Target": null, // only s-chain target - - "chainProperties": constructChainProperties(), - - "strPathAbiJsonSkaleManager": "", - "joAbiSkaleManager": { }, - "bHaveSkaleManagerABI": false, - - "strChainNameOriginChain": + bShowConfigMode: false, + + isEnabledMultiCall: true, + + bNoWaitSChainStarted: false, + nMaxWaitSChainAttempts: 0 + Number.MAX_SAFE_INTEGER, // 20 + + nAmountOfWei: 0, + nAmountOfToken: 0, + arrAmountsOfTokens: null, + idToken: 0, + + nTransferBlockSizeM2S: 4, + nTransferBlockSizeS2M: 4, + nTransferBlockSizeS2S: 4, + nTransferStepsM2S: 8, + nTransferStepsS2M: 8, + nTransferStepsS2S: 8, + nMaxTransactionsM2S: 0, + nMaxTransactionsS2M: 0, + nMaxTransactionsS2S: 0, + + nBlockAwaitDepthM2S: 0, + nBlockAwaitDepthS2M: 0, + nBlockAwaitDepthS2S: 0, + nBlockAgeM2S: 0, + nBlockAgeS2M: 0, + nBlockAgeS2S: 0, + + nLoopPeriodSeconds: 10, + + nNodeNumber: 0, // S-Chain node number(zero based) + nNodesCount: 1, + nTimeFrameSeconds: 0, // 0-disable, 60-recommended + nNextFrameGap: 10, + + nAutoExitAfterSeconds: 0, // 0-disable + + joCommunityPool: null, // only main net + joDepositBoxETH: null, // only main net + joDepositBoxERC20: null, // only main net + joDepositBoxERC721: null, // only main net + joDepositBoxERC1155: null, // only main net + joDepositBoxERC721WithMetadata: null, // only main net + joLinker: null, // only main net + + isWithMetadata721: false, + + joTokenManagerETH: null, // only s-chain + joTokenManagerERC20: null, // only s-chain + joTokenManagerERC20Target: null, // only s-chain + joTokenManagerERC721: null, // only s-chain target + joTokenManagerERC721Target: null, // only s-chain target + joTokenManagerERC1155: null, // only s-chain + joTokenManagerERC1155Target: null, // only s-chain target + joTokenManagerERC721WithMetadata: null, // only s-chain target + joTokenManagerERC721WithMetadataTarget: null, // only s-chain target + joCommunityLocker: null, // only s-chain + joCommunityLockerTarget: null, // only s-chain target + joMessageProxyMainNet: null, + joMessageProxySChain: null, + joMessageProxySChainTarget: null, // only s-chain target + joTokenManagerLinker: null, + joTokenManagerLinkerTarget: null, // only s-chain target + joEthErc20: null, // only s-chain + joEthErc20Target: null, // only s-chain target + + chainProperties: constructChainProperties(), + + strPathAbiJsonSkaleManager: "", + joAbiSkaleManager: { }, + bHaveSkaleManagerABI: false, + + strChainNameOriginChain: ( process.env.CHAIN_NAME_SCHAIN_ORIGIN || "Mainnet" ).toString().trim(), - "strAddrErc20Explicit": "", - "strAddrErc20ExplicitTarget": "", // S<->S target - "strAddrErc721Explicit": "", - "strAddrErc721ExplicitTarget": "", // S<->S target - "strAddrErc1155Explicit": "", - "strAddrErc1155ExplicitTarget": "", // S<->S target + strAddrErc20Explicit: "", + strAddrErc20ExplicitTarget: "", // S<->S target + strAddrErc721Explicit: "", + strAddrErc721ExplicitTarget: "", // S<->S target + strAddrErc1155Explicit: "", + strAddrErc1155ExplicitTarget: "", // S<->S target - "isPWA": true, - "nTimeoutSecondsPWA": 60, + isPWA: true, + nTimeoutSecondsPWA: 60, - "nMonitoringPort": 0, // 0 - default, means monitoring server is disabled - "bLogMonitoringServer": false, + nMonitoringPort: 0, // 0 - default, means monitoring server is disabled + bLogMonitoringServer: false, - "strReimbursementChain": "", - "isShowReimbursementBalance": false, - "nReimbursementRecharge": 0, - "nReimbursementWithdraw": 0, - "nReimbursementRange": -1, // < 0 - do not change anything + strReimbursementChain: "", + isShowReimbursementBalance: false, + nReimbursementRecharge: 0, + nReimbursementWithdraw: 0, + nReimbursementRange: -1, // < 0 - do not change anything - "joSChainDiscovery": { - "isSilentReDiscovery": false, + joSChainDiscovery: { + isSilentReDiscovery: false, // zero to disable (for debugging only) - "repeatIntervalMilliseconds": 5 * 1000, - "periodicDiscoveryInterval": 5 * 60 * 1000 + repeatIntervalMilliseconds: 5 * 1000, + periodicDiscoveryInterval: 5 * 60 * 1000 }, // S-Chain to S-Chain transfer options - "optsS2S": { + optsS2S: { // is S-Chain to S-Chain transfers enabled - "isEnabled": true, - "strNetworkBrowserPath": null + isEnabled: true, + strNetworkBrowserPath: null }, - "nJsonRpcPort": 0, // 0 to disable - "isCrossImaBlsMode": false, + nJsonRpcPort: 0, // 0 to disable + isCrossImaBlsMode: false, - "arrActions": [] // array of actions to run + arrActions: [] // array of actions to run }; return imaState; } diff --git a/test/agent-test.mjs b/test/agent-test.mjs index c40e0386..68fc2877 100644 --- a/test/agent-test.mjs +++ b/test/agent-test.mjs @@ -138,7 +138,7 @@ const imaState = { "mn": { "joAccount": { "privateKey": owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_ETHEREUM ), - "address": owaspUtils.fnAddressImpl_, + "address": function () { return owaspUtils.fnAddressImpl_( this ); }, "strTransactionManagerURL": owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_ETHEREUM ), "nTmPriority": @@ -174,7 +174,7 @@ const imaState = { "sc": { "joAccount": { "privateKey": owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN ), - "address": owaspUtils.fnAddressImpl_, + "address": function () { return owaspUtils.fnAddressImpl_( this ); }, "strTransactionManagerURL": owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN ), "nTmPriority": @@ -211,7 +211,7 @@ const imaState = { "joAccount": { "privateKey": owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN_TARGET ), - "address": owaspUtils.fnAddressImpl_, + "address": function () { return owaspUtils.fnAddressImpl_( this ); }, "strTransactionManagerURL": owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN_TARGET ), "nTmPriority": @@ -720,7 +720,7 @@ describe( "OWASP-5", function() { "privateKey": owaspUtils.toEthPrivateKey( "23ABDBD3C61B5330AF61EBE8BEF582F4E5CC08E554053A718BDCE7813B9DC1FC" ), - "address": owaspUtils.fnAddressImpl_ + "address": function () { return owaspUtils.fnAddressImpl_( this ); } }; it( "Extract address from private key", function() { @@ -950,7 +950,7 @@ describe( "CLI", function() { "privateKey": owaspUtils.toEthPrivateKey( "23ABDBD3C61B5330AF61EBE8BEF582F4E5CC08E554053A718BDCE7813B9DC1FC" ), - "address": owaspUtils.fnAddressImpl_ + "address": function () { return owaspUtils.fnAddressImpl_( this ); } }; assert.equal( imaCLI.ensureHaveCredentials( diff --git a/test/unitTests/agentUnitTests.js b/test/unitTests/agentUnitTests.js index fb503704..cf306dbb 100644 --- a/test/unitTests/agentUnitTests.js +++ b/test/unitTests/agentUnitTests.js @@ -110,17 +110,17 @@ function toWei( stringA, stringB ) { // mockup for `joAccountDst` const joAccountDst = { - "address": IMA.owaspUtils.fnAddressImpl_, + "address": function () { return IMA.owaspUtils.fnAddressImpl_( this ); }, privateKey: "6270720ecca0185a979b6791bea433e9dbf23345e5b5b1b0258b1fbaf32b4390" }; // mockup for `joAccountSrc` const joAccountSrc = { - "address": IMA.owaspUtils.fnAddressImpl_, + "address": function () { return IMA.owaspUtils.fnAddressImpl_( this ); }, privateKey: "6270720ecca0185a979b6791bea433e9dbf23345e5b5b1b0258b1fbaf32b4390" }; // mockup for `joMainNetAccount` const joMainNetAccount = { - "address": IMA.owaspUtils.fnAddressImpl_, + "address": function () { return IMA.owaspUtils.fnAddressImpl_( this ); }, privateKey: "6270720ecca0185a979b6791bea433e9dbf23345e5b5b1b0258b1fbaf32b4390" }; // mockup for `joDepositBox` From 2e4dfe00e92cf7812c367302b34e6824710ad497 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 12:25:47 +0000 Subject: [PATCH 17/53] IMA/TypeScript support improvements, unit-test fixes --- src/bls.ts | 30 ++++++------ src/cc.ts | 28 +++++------ src/cli.ts | 4 +- src/clpTools.ts | 2 +- src/discoveryTools.ts | 20 ++++---- src/eventDispatcher.ts | 4 +- src/imaCore.ts | 10 ++-- src/imaHelperAPIs.ts | 2 +- src/imaOracleOperations.ts | 4 +- src/imaTx.ts | 6 +-- src/log.ts | 20 ++++---- src/loop.ts | 10 ++-- src/loopWorker.ts | 12 ++--- src/main.ts | 20 ++++---- src/oracle.ts | 2 +- src/owaspUtils.ts | 36 +++++++++----- src/pwa.ts | 2 +- src/rpcCall.ts | 12 ++--- src/socket.ts | 82 ++++++++++++++++---------------- src/socketServer.ts | 6 +-- src/socketUtils.ts | 38 +++++++-------- src/threadInfo.ts | 2 +- src/utils.ts | 12 ++--- test/unitTests/agentUnitTests.js | 12 ++--- 24 files changed, 193 insertions(+), 183 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index 201f0365..b0d222bb 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -294,7 +294,7 @@ function performBlsGlue( strLogPrefix, "performBlsGlue", strActionDir, arrSignResults.length ); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; const strOutput = "" try { let strInput = ""; @@ -382,7 +382,7 @@ function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ): a strLogPrefix, strActionDir, arrSignResults.length ); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; let strOutput = ""; try { let strInput = ""; @@ -472,7 +472,7 @@ function performBlsVerifyI( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; let strOutput = ""; try { details.trace( "{p}BLS node #{} - first message nonce is {}", @@ -536,7 +536,7 @@ function performBlsVerifyIU256( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; let strOutput = ""; try { const joMsg: any = { message: keccak256U256( u256, true ) }; @@ -591,7 +591,7 @@ function performBlsVerify( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; let strOutput = ""; const strLogPrefix = `${strDirection}/BLS/Summary: "`; try { @@ -660,7 +660,7 @@ function performBlsVerifyU256( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; let strOutput = ""; const strLogPrefix = "BLS u256/Summary: "; try { @@ -1119,7 +1119,7 @@ async function doSignProcessHandleCall( owaspUtils.extractErrorMessage( joOut, "unknown wallet error(1)" ), optsSignOperation.sequenceId ); await joCall.disconnect(); - return + return; } optsSignOperation.details.debug( "{p}Node {} sign result: {}", optsSignOperation.strLogPrefix, joNode.nodeID, joOut.result ? joOut.result : null ); @@ -1142,7 +1142,7 @@ async function doSignProcessHandleCall( optsSignOperation.strLogPrefixA, nZeroBasedNodeIndex, optsSignOperation.nThreshold, optsSignOperation.nCountOfBlsPartsToCollect ); await joCall.disconnect(); - return + return; } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); const joResultFromNode: any = { @@ -1315,7 +1315,7 @@ async function doSignMessagesImpl( "successfully gathered count is reached ", optsSignOperation.strLogPrefix, log.generateTimestampString( null, true ), "skale_imaVerifyAndSign", strFromChainName, i, cntSuccess ); - break + break; } doSignProcessOneImpl( i, optsSignOperation ) .then( function() {} ).catch( function( err ) { @@ -1440,7 +1440,7 @@ async function doSignU256OneImplHandleCallResult( optsSignU256.details.error( "{p}S-Chain node {} reported wallet error: {err}", optsSignU256.strLogPrefix, strNodeDescColorized, strErrorMessage ); await joCall.disconnect(); - return + return; } optsSignU256.details.trace( "{p}Node {} sign result: ", optsSignU256.strLogPrefix, joNode.nodeID, joOut.result ? joOut.result : null ); @@ -1461,7 +1461,7 @@ async function doSignU256OneImplHandleCallResult( "number of BLS signature parts already gathered", strLogPrefixA, nZeroBasedNodeIndex, optsSignU256.nThreshold, optsSignU256.nCountOfBlsPartsToCollect ); - return + return; } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); const joResultFromNode: any = { @@ -1695,7 +1695,7 @@ export async function doSignU256( u256: any, details: any, fn: any ) { optsSignU256.details.warning( "{p}BLS u256 signing is unavailable", optsSignU256.strLogPrefix ); await optsSignU256.fn( "BLS u256 signing is unavailable", optsSignU256.u256 ); - return + return; } if( ! ( await prepareSignU256( optsSignU256 ) ) ) return; @@ -1706,7 +1706,7 @@ export async function doSignU256( u256: any, details: any, fn: any ) { if( optsSignU256.errGathering ) { optsSignU256.details.error( "Failed BLS u256 sign result awaiting: {err}", optsSignU256.errGathering.toString() ); - return + return; } optsSignU256.details.information( "{p}Completed signing u256 procedure", optsSignU256.strLogPrefix ); @@ -1737,7 +1737,7 @@ export async function doVerifyReadyHash( const strActionDir = allocBlsTmpActionDir(); const fnShellRestore = function() { shell.rm( "-rf", strActionDir ); - } + }; let strOutput = ""; try { const joPublicKey = discoverPublicKeyByIndex( @@ -1967,7 +1967,7 @@ async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) if( joSChain.name.toString() == strSChainNameSrc.toString() ) { joSChainSrc = joSChain; strUrlSrcSChain = skaleObserver.pickRandomSChainUrl( joSChain ); - break + break; } } if( joSChainSrc == null || strUrlSrcSChain == null || strUrlSrcSChain.length == 0 ) { diff --git a/src/cc.ts b/src/cc.ts index e8465528..63ed1e1f 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -327,31 +327,31 @@ export function logArgToString( ...args: any[] ): string { const arg = arguments[i]; if( arg === undefined ) { s += "" + undefval( arg ); - continue + continue; } if( arg === null ) { s += "" + nullval( arg ); - continue + continue; } if( isNaN( arg ) ) { s += "" + nanval( arg ); - continue + continue; } if( typeof arg === "boolean" ) { s += "" + tf( arg ); - continue + continue; } if( typeof arg === "object" && typeof arg.valueOf() === "boolean" ) s += "" + tf( arg.valueOf() ); if( typeof arg === "number" || typeof arg === "bigint" ) { s += "" + number( arg ); - continue + continue; } if( typeof arg === "object" && ( typeof arg.valueOf() === "number" || typeof arg.valueOf() === "bigint" ) ) { s += "" + number( arg.valueOf() ); - continue + continue; } if( typeof arg === "string" || arg instanceof String ) { const objURL = safeURL( arg ); @@ -387,30 +387,30 @@ export function logArgToString( ...args: any[] ): string { strURL += normal( anyURL.strStrippedStringComma ); s += strURL; - continue + continue; } if( ( arg.length > 1 && arg[0] == "-" && arg[1] != "-" ) || ( arg.length > 2 && arg[0] == "-" && arg[1] == "-" && arg[2] != "-" ) ) { s += "" + cla( arg ); - continue + continue; } if( arg.length > 0 && ( arg[0] == "\"" || arg[0] == "'" ) ) { s += "" + strval( arg ); - continue + continue; } if( isFloat2( arg ) ) { s += "" + real( arg ); - continue + continue; } if( isInt2( arg ) ) { s += "" + number( arg ); - continue + continue; } } if( Array.isArray( arg ) || typeof arg === "object" ) { s += jsonColorizer.prettyPrintConsole( arg ); - continue + continue; } s += "" + kk( arg ); } @@ -426,7 +426,7 @@ export const getCircularReplacerForJsonStringify = (): any => { seen.add( value ); } return value; - } + }; } export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ @@ -444,7 +444,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ ++i // so we know we aren't using the original object anymore return value; - } + }; }, replacerHTML: ( match?: any, pIndent?: any, pKey?: any, pVal?: any, pEnd?: any ): any => { const key = ""; diff --git a/src/cli.ts b/src/cli.ts index a16c7200..ba4d924f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1282,7 +1282,7 @@ export function parse( joExternalHandlers: any ) { joArg.name == "browse-s-chain" ) { joExternalHandlers[joArg.name](); - continue + continue; } console.log( log.fmtFatal( "COMMAND LINE PARSER ERROR: unknown command line argument {}", joArg.name ) ); @@ -1534,7 +1534,7 @@ function commonInitPrintFoundContracts() { if( joContract && "address" in joContract && joContract.address ) return log.fmtInformation( "{}", joContract.address ); return log.fmtError( "contract is not available" ); - } + }; if( isPrintGathered ) { log.debug( "IMA contracts(Main Net):" ); diff --git a/src/clpTools.ts b/src/clpTools.ts index 8e6c2de3..f7cc8903 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -1457,7 +1457,7 @@ async function handleBrowseSkaleModesRpcInfoResult( if( ! joNode ) { log.critical( "{p}Discovery node {} is completely unknown and will be skipped", strLogPrefix, i ); - continue + continue; } const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); const rpcCallOpts: any = null; diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 027de917..80de8532 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -135,7 +135,7 @@ export async function waitUntilSChainStarted() { imaState.chainProperties.sc.strURL.length === 0 ) { log.warning( "Skipped, S-Chain URL was not provided." ); - return + return; } let bSuccess = false; let idxWaitAttempt = 0; @@ -163,7 +163,7 @@ export async function waitUntilSChainStarted() { if( idxWaitAttempt >= imaState.nMaxWaitSChainAttempts ) { log.warning( "Incomplete, S-Chain sanity check failed after {} attempts.", idxWaitAttempt ); - return + return; } await threadInfo.sleep( 1000 ); } @@ -205,7 +205,7 @@ function composeStillUnknownNodesMessage( async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boolean, fnAfter: any ) { if( gFlagIsInSChainDiscovery ) { log.information( "Notice: long this S-Chain re-discovery is in progress now..." ); - return + return; } const imaState = state.get(); fnAfter = fnAfter || function() {}; @@ -231,7 +231,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole } // fnAfter() will be called here inside async call at beginning gFlagIsInSChainDiscovery = false; - return + return; } if( cntDiscovered < cntNodesOnChain ) { if( ! isSilentReDiscovery ) { @@ -274,7 +274,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole .then( function() {} ).catch( function( err ) { log.error( "Failed to continue S-chain discovery, reported error is: {err}", err ); - } ); ; + } ) } catch ( err ) { } gFlagIsInSChainDiscovery = false; // fnAfter() will be called here inside async call at beginning @@ -295,7 +295,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( if( ! isSilentReDiscovery ) log.information( "This S-Chain re-discovery will not be preformed" ); fnAfter(); - return // no S-Chain re-discovery, special mode + return; // no S-Chain re-discovery, special mode } const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let nCountToWait = ( cntNodesOnChain > 2 ) @@ -316,7 +316,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( log.notice( "This S-Chain re-discovery stopped" ); } fnAfter(); - return + return; } if( cntDiscovered < cntNodesOnChain ) { if( ! isSilentReDiscovery ) { @@ -438,7 +438,7 @@ async function discoverSChainWait( optsDiscover: any ) { clearInterval( iv ); if( optsDiscover.fnAfter ) optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); - return + return; } ++ nWaitAttempt; if( nWaitAttempt >= cntWaitAttempts ) { @@ -628,7 +628,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { if( ! isSilentReDiscovery ) log.success( "Periodic S-Chain re-discovery is not needed right from startup" ); - return // not needed right from very beginning + return; // not needed right from very beginning } const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let periodicDiscoveryInterval = imaState.joSChainDiscovery.periodicDiscoveryInterval; @@ -656,7 +656,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( if( ! isSilentReDiscovery ) log.information( "Final periodic S-Chain re-discovery done" ); fnAfterRediscover( true ); - return // not needed anymore, all nodes completely discovered + return; // not needed anymore, all nodes completely discovered } if( ! isSilentReDiscovery ) log.information( "Partial periodic S-Chain re-discovery done" ); diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index 773544d4..1d616798 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -30,7 +30,7 @@ export class UniversalDispatcherEvent { for( const [ key, value ] of Object.entries( jo ) ) { if( key in this ) { console.warn( "UniversalDispatcherEvent will skip", key, "data field" ); - continue + continue; } const anyThis: any = this anyThis[key] = value; @@ -80,7 +80,7 @@ export class EventDispatcher { item => item.type === type ); if( index >= 0 ) { this._listeners.splice( index, 1 ); - continue + continue; } break; } diff --git a/src/imaCore.ts b/src/imaCore.ts index 4bd38c93..970579bc 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -288,7 +288,7 @@ async function analyzeGatheredRecords( optsTransfer: any, r: any ) { "{p}Found event record {} reviewed and accepted for processing, found event " + "values are {}, found block number is {}", optsTransfer.strLogPrefix, i, joValues, joValues.savedBlockNumberForOptimizations ); - break + break; } else { optsTransfer.details.debug( "{p}Found event record {} reviewed and skipped", optsTransfer.strLogPrefix, i ); @@ -381,7 +381,7 @@ async function gatherMessages( optsTransfer: any ) { if( !bSecurityCheckPassed ) { optsTransfer.details.warning( "{p}Block depth check was not passed, canceling " + "search for transfer events", optsTransfer.strLogPrefix ); - break + break; } } if( optsTransfer.nBlockAge > 0 ) { @@ -433,7 +433,7 @@ async function gatherMessages( optsTransfer: any ) { if( !bSecurityCheckPassed ) { optsTransfer.details.warning( "{p}Block age check was not passed, " + "canceling search for transfer events", optsTransfer.strLogPrefix ); - break + break; } } optsTransfer.details.success( @@ -701,7 +701,7 @@ async function checkOutgoingMessageEventInOneNode( owaspUtils.ensureStartsWith0x( eventValuesByName.dstContract ).toLowerCase() ) { bEventIsFound = true; - break + break; } } } catch ( err ) { @@ -1024,7 +1024,7 @@ export async function doTransfer( nIdxCurrentMsgBlockStart, optsTransfer.jarrMessages.length, optsTransfer.jarrMessages ); await fnAfter( null, jarrMessages ); // null - no error, null - no signatures - } + }; } else { optsTransfer.details.debug( "{p}Using externally provided signing function", optsTransfer.strLogPrefix ); diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 4a4a4eb7..c5c311ce 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -59,7 +59,7 @@ export function setWaitForNextBlockOnSChain( val: any ) { export const currentTimestamp = (): number => { return Date.now().valueOf() / 1000; -} +}; export async function safeWaitForNextBlockToAppear( details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider ) { diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 394419c7..6a9cf216 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -138,7 +138,7 @@ async function handleOracleSigned( imaTransferErrorHandling.saveTransferError( "oracle", optsGasPriseSetup.details.toString() ); optsGasPriseSetup.details.close(); - return + return; } optsGasPriseSetup.strActionName = "doOracleGasPriceSetup.formatSignature"; let signature = joGlueResult ? joGlueResult.signature : null; @@ -253,7 +253,7 @@ export async function doOracleGasPriceSetup( details.trace( "{p}u256 signing callback was not provided", optsGasPriseSetup.strLogPrefix ); await fnAfter( null, u256, null ); // null - no error, null - no signatures - } + }; } else { optsGasPriseSetup.details.trace( "{p}Using externally provided u256 signing function", optsGasPriseSetup.strLogPrefix ); diff --git a/src/imaTx.ts b/src/imaTx.ts index c7f2b244..67834a2f 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -333,13 +333,13 @@ export async function payedCall( switch ( optsPayedCall.joACI.strType ) { case "tm": await payedCallTM( optsPayedCall ); - break; + break case "sgx": await payedCallSGX( optsPayedCall ); - break; + break case "direct": await payedCallDirect( optsPayedCall ); - break; + break default: { const strErrorPrefix = "Transaction sign and send error(INNER FLOW): "; optsPayedCall.details.critical( diff --git a/src/log.ts b/src/log.ts index db5ff272..cc778824 100644 --- a/src/log.ts +++ b/src/log.ts @@ -72,11 +72,11 @@ export function generateTimestampString( ts?: any, isColorized?: boolean ): stri ( typeof isColorized == "undefined" ) ? true : ( !!isColorized ); ts = ( ts instanceof Date ) ? ts : new Date(); - const ccDate = function( x?: any ): string { return isColorized ? cc.date( x ) : x; } - const ccTime = function( x?: any ): string { return isColorized ? cc.time( x ) : x; } + const ccDate = function( x?: any ): string { return isColorized ? cc.date( x ) : x; }; + const ccTime = function( x?: any ): string { return isColorized ? cc.time( x ) : x; }; const ccFractionPartOfTime = - function( x?: any ): string { return isColorized ? cc.fracTime( x ) : x; } - const ccBright = function( x?: any ): string { return isColorized ? cc.bright( x ) : x; } + function( x?: any ): string { return isColorized ? cc.fracTime( x ) : x; }; + const ccBright = function( x?: any ): string { return isColorized ? cc.bright( x ) : x; }; const s = "" + ccDate( n2s( ts.getUTCFullYear(), 4 ) ) + ccBright( "-" ) + ccDate( n2s( ts.getUTCMonth() + 1, 2 ) ) + @@ -467,7 +467,7 @@ export function createFileOutput( const nNextSize = nFileSize + nBytesToWrite; if( nNextSize <= this.nMaxSizeBeforeRotation ) { this.open(); - return + return; } let i = 0; const cnt = 0 + this.nMaxFilesCount; for( i = 0; i < cnt; ++i ) { @@ -578,7 +578,7 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): s try { const isError = function( err: Error | string ) { return err && err instanceof Error && err.stack && err.message; - } + }; if( ! isError( jo ) ) { if( "error" in jo ) { jo = jo.error; @@ -633,7 +633,7 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ } export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { - fnFormatter = fnFormatter || function( arg: any ) { return arg; } + fnFormatter = fnFormatter || function( arg: any ) { return arg; }; const arrParts = ( arrArgs && arrArgs.length > 0 ) ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; let s = ""; let isValueMode = false; @@ -651,7 +651,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { } else return cc.logArgToString( arg ); return arg; - } + }; const fnFormatOneArgument = function( arg: any, fmt?: any ): string { if( ! arg ) return arg; @@ -684,7 +684,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { return fnDefaultOneArgumentFormatter( arg, cc.rainbow ); } return v( arg ); - } + }; try { let idxArgNextPrinted = 0; if( arrParts && arrParts.length > 0 ) { @@ -696,7 +696,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { if( idxArgNextPrinted < arrArgs.length ) s += fnFormatOneArgument( arrArgs[idxArgNextPrinted], joPart.text ); ++ idxArgNextPrinted; - continue + continue; } // assume joPart.type == "text" always here, at this point if( ! cc.isStringAlreadyColorized( joPart.text ) ) diff --git a/src/loop.ts b/src/loop.ts index 9a1cb911..653e729f 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -540,23 +540,23 @@ export async function ensureHaveWorkers( opts: any ) { case "init": if( ! joMessage.error ) { aClient.logicalInitComplete = true; - break; + break } aClient.errorLogicalInit = joMessage.error; opts.details.critical( " Loop worker thread {} reported/returned init error: {err}", idxWorker, joMessage.error ); - break; + break case "log": log.information( "LOOP WORKER {} {}", workerData.url, joMessage.message ); - break; + break case "saveTransferError": imaTransferErrorHandling.saveTransferError( joMessage.message.category, joMessage.message.textLog, joMessage.message.ts ); - break; + break case "saveTransferSuccess": imaTransferErrorHandling.saveTransferSuccess( joMessage.message.category ); - break; + break } // switch ( joMessage.method ) } ); const jo: any = { diff --git a/src/loopWorker.ts b/src/loopWorker.ts index ff80c781..772f0ef7 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -90,7 +90,7 @@ class ObserverServer extends SocketServer { }; const isFlush = true; socket.send( jo, isFlush ); - } + }; self.initLogMethods(); self.opts = JSON.parse( JSON.stringify( joMessage.message.opts ) ); self.opts.details = { @@ -128,9 +128,9 @@ class ObserverServer extends SocketServer { socket.send( jo, isFlush ); } ); self.opts.imaState.chainProperties.mn.joAccount.address = - function() { return owaspUtils.fnAddressImpl_( this ); } + function() { return owaspUtils.fnAddressImpl_( this ); }; self.opts.imaState.chainProperties.sc.joAccount.address = - function() { return owaspUtils.fnAddressImpl_( this ); } + function() { return owaspUtils.fnAddressImpl_( this ); }; if( self.opts.imaState.chainProperties.mn.strURL && typeof self.opts.imaState.chainProperties.mn.strURL == "string" && self.opts.imaState.chainProperties.mn.strURL.length > 0 @@ -186,7 +186,7 @@ class ObserverServer extends SocketServer { self.information( "Full init compete for in-worker IMA loop {} in {}", workerData.url, threadInfo.threadDescription() ); return joAnswer; - } + }; self.mapApiHandlers.spreadUpdatedSChainNetwork = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { self.initLogMethods(); @@ -196,7 +196,7 @@ class ObserverServer extends SocketServer { threadInfo.threadDescription(), joMessage.joSChainNetworkInfo, log.posNeg( joMessage.isFinal, "final", "partial" ) ); imaState.joSChainNetworkInfo = joMessage.joSChainNetworkInfo; - } + }; // eslint-disable-next-line dot-notation self.mapApiHandlers.skale_imaNotifyLoopWork = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { @@ -210,7 +210,7 @@ class ObserverServer extends SocketServer { owaspUtils.toInteger( joMessage.params.ts ), joMessage.params.signature ).then( function() {} ).catch( function() {} ); - }; + } console.log( "Initialized in-worker IMA loop {} server in {}", workerData.url, threadInfo.threadDescription() ); } diff --git a/src/main.ts b/src/main.ts index cec33baf..eef38d8c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -183,7 +183,7 @@ function initMonitoringServer(): void { break; case "get_schain_network_info": joAnswer.schain_network_info = imaState.joSChainNetworkInfo; - break; + break case "get_runtime_params": { joAnswer.runtime_params = {}; @@ -231,7 +231,7 @@ function initMonitoringServer(): void { ? true : false ); joAnswer.last_error_categories = imaTransferErrorHandling.getLastErrorCategories(); - break; + break default: throw new Error( `Unknown method name ${joMessage.method} was specified` ); } // switch( joMessage.method ) @@ -296,17 +296,17 @@ function initJsonRpcServer(): void { case "echo": joAnswer.result = "echo"; fnSendAnswer( joAnswer ); - break; + break case "ping": joAnswer.result = "pong"; fnSendAnswer( joAnswer ); - break; + break case "skale_imaVerifyAndSign": joAnswer = await imaBLS.handleSkaleImaVerifyAndSign( joMessage ); - break; + break case "skale_imaBSU256": joAnswer = await imaBLS.handleSkaleImaBSU256( joMessage ); - break; + break case "skale_imaNotifyLoopWork": if( await pwa.handleLoopStateArrived( imaState, @@ -319,13 +319,13 @@ function initJsonRpcServer(): void { ) ) await loop.spreadArrivedStateOfPendingWorkAnalysis( joMessage ); - break; + break case "skale_getCachedSNB": joAnswer.arrSChainsCached = skaleObserver.getLastCachedSChains(); - break; + break default: joAnswer.error = `Unknown method name ${joMessage.method} was specified`; - break; + break } // switch( joMessage.method ) if( ( !joAnswer ) || typeof joAnswer != "object" ) { joAnswer = {}; @@ -425,7 +425,7 @@ async function main() { ? false : imaState.joSChainDiscovery.isSilentReDiscovery; const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ) { loop.spreadUpdatedSChainNetwork( isFinal ).then( function() {} ).catch( function() {} ); - } + }; if( imaState.bSignMessages ) { if( imaState.strPathBlsGlue.length == 0 ) { log.fatal( "Please specify {} command line parameter.", "--bls-glue" ); diff --git a/src/oracle.ts b/src/oracle.ts index 75c83efc..c5bcfc8b 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -91,7 +91,7 @@ async function handleOracleCheckResultResult( if( isVerboseTraceDetails ) details.error( "Bad unexpected result in oracle_checkResult" ); await joCall.disconnect(); - return + return; } const joResult: any = JSON.parse( joOut.result ); if( isVerboseTraceDetails ) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index a9c5011b..36491d8c 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -31,9 +31,6 @@ import * as log from "./log.js"; import * as ethersMod from "ethers"; import * as fs from "fs"; -import * as ethereumJsUtilModule from "ethereumjs-util"; -import * as ethereumJsWalletModule from "ethereumjs-wallet"; -const Wallet = ethereumJsWalletModule.default; const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; @@ -611,12 +608,12 @@ export function parseMoneySpecToWei( s?: any, isThrowException?: boolean ): stri ) { strNumber += chr; s = s.substr( 1 ); // remove first character - continue + continue; } if( chr == " " || chr == "\t" || chr == "\r" || chr == "\n" ) s = s.substr( 1 ); // remove first character s = s.trim().toLowerCase(); - break + break; } // here s is rest suffix string, number is number as string or empty string if( strNumber == "" ) @@ -656,17 +653,30 @@ export function privateKeyToAccountAddress( keyPrivate: string ): string { } export function privateKeyToPublicKey( keyPrivate: string ): string { - const privateKeyBuffer = - ethereumJsUtilModule.toBuffer( ensureStartsWith0x( keyPrivate ) ); - const wallet = Wallet.fromPrivateKey( privateKeyBuffer ); - const publicKey = wallet.getPublicKeyString(); - return removeStarting0x( publicKey ); + try { + if( ! keyPrivate ) + return ""; + if( keyPrivate.trim().length == 0 ) + return ""; + const ethersWallet = new ethersMod.ethers.Wallet( ensureStartsWith0x( keyPrivate ) ); + return ethersWallet.publicKey; + } catch ( err ) { + return ""; + } } export function publicKeyToAccountAddress( keyPublic: string ): string { - const hash = ethersMod.ethers.utils.keccak256( ensureStartsWith0x( keyPublic ) ); - const strAddress = ensureStartsWith0x( hash.substr( hash.length - 40 ) ); - return strAddress; + try { + if( ! keyPublic ) + return ""; + if( keyPublic.trim().length == 0 ) + return ""; + const hash = ethersMod.ethers.utils.keccak256( ensureStartsWith0x( keyPublic ) ); + const strAddress = ensureStartsWith0x( hash.substr( hash.length - 40 ) ); + return strAddress; + } catch ( err ) { + return ""; + } } export function fnAddressImpl_( anyThis: any ): string { diff --git a/src/pwa.ts b/src/pwa.ts index 762967b5..e3e72ad6 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -131,7 +131,7 @@ export async function checkOnLoopStart( }; joProps.isInProgress = false; joProps.ts = 0; - continue + continue; } arrBusyNodeIndices.push( walkNodeIndex ); } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 2ceef243..6eadffa3 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -34,7 +34,7 @@ const gSecondsConnectionTimeout = 60; export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any ) { fnDone = fnDone || async function( nStep: number ) {}; - fnDone = fnStep || async function( nStep: number ) { return true; } + fnDone = fnStep || async function( nStep: number ) { return true; }; let nStep = 0; const promiseComplete = new Promise( function( resolve, reject ) { let isInsideAsyncHandler = false; @@ -56,7 +56,7 @@ export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any } } isInsideAsyncHandler = false; - } + }; const iv = setInterval( function() { if( isInsideAsyncHandler ) return; @@ -139,7 +139,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { const err = new Error( strWsError ); if( fn ) await fn( joCall, err ); - return + return; } } if( fn ) @@ -160,7 +160,7 @@ export async function doConnectIfNeeded( joCall: any, opts: any, fn: any ) { } if( isUrlWS( joCall.url ) && ( !joCall.wsConn ) ) { await joCall.reconnect( fn ); - return + return; } if( fn ) await fn( joCall, null ); @@ -180,7 +180,7 @@ async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { if( err ) { doReconnectWsStep( joCall, opts ) .then( function() {} ).catch( function() {} ); - return + return; } if( fn ) await fn( joCall, null ); @@ -373,7 +373,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { if( fnAfter ) await fnAfter( joIn, null, err ); reject( err ); - return + return; } await doCall( joCall, joIn, async function( joIn: any, joOut: any, err: any ) { if( fnAfter ) diff --git a/src/socket.ts b/src/socket.ts index 491c25ee..26e5b03f 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -51,7 +51,7 @@ export const socketSentDataMarshall = function( data?: any ): any { ) : ""; return s; -} +}; export const socketReceivedDataReverseMarshall = function( data?: any ): object { try { const jo: any = data @@ -81,7 +81,7 @@ export const updateSocketDataStatsForMessage = function( joMessage: any, joStats joStats[strMethod] ++; else joStats[strMethod] = 1; -} +}; export const generateSocketDataStatsJSON = function( jo: any ) { const joStats: any = {}; if( "arrPackedMessages" in jo && @@ -94,7 +94,7 @@ export const generateSocketDataStatsJSON = function( jo: any ) { } else updateSocketDataStatsForMessage( jo, joStats ); return joStats; -} +}; export class BasicServerAcceptor extends EventDispatcher { socketType: string; @@ -265,7 +265,7 @@ export class BasicSocketPipe extends EventDispatcher { if( settings.logging.net.socket.send || settings.logging.net.socket.flush ) console.log( this.socketLoggingTextPrefix( "send+flush" ), data ); this.implSend( data ); - return + return; } isFlush = ( isFlush == undefined || isFlush == null ) ? true : ( !!( isFlush ) ); const jo: any = socketReceivedDataReverseMarshall( data ); @@ -380,7 +380,7 @@ export const isRunningInWorker = function() { if( self.document === undefined ) return true; return false; -} +}; // in-worker clients in connecting state export const gMapAwaitingInWorkerClients: Record < string, any > = { }; @@ -830,7 +830,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeOutgoing.send( joMessage ); if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); - } + }; let _onRelayPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" relay-client socket \"" + @@ -856,7 +856,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeOutgoing.send( joMessage ); if( self.isAutoFlushOutgoing ) pipeOutgoing.flush(); - } + }; _offAllPipeEventListeners = function() { if( _onExternalPipeClose ) { pipeIncoming.off( "close", _onExternalPipeClose ); @@ -888,7 +888,7 @@ export class OutOfWorkerRelay extends EventDispatcher { } pipeIncoming.disconnect(); pipeIncoming.dispose(); - } + }; pipeIncoming.on( "close", _onExternalPipeClose ); pipeIncoming.on( "error", _onExternalPipeError ); pipeIncoming.on( "message", _onExternalPipeMessage ); @@ -902,7 +902,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeOutgoing.on( "close", _onRelayPipeClose ); pipeOutgoing.on( "error", _onRelayPipeError ); pipeOutgoing.on( "message", _onRelayPipeMessage ); - } + }; self.acceptor.on( "connection", self.onConnection_ ); } dispose() { @@ -1074,7 +1074,7 @@ export class OneToOneRelay extends EventDispatcher { pipeOutgoing.send( joMessage ); if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); - } + }; let _onOutgoingPipeMessage: any = function( eventData: any ) { if( settings.logging.net.relay.rawMessage ) { console.log( @@ -1107,7 +1107,7 @@ export class OneToOneRelay extends EventDispatcher { pipeIncoming.send( joMessage ); if( self.isAutoFlushOutgoing ) pipeIncoming.flush(); - } + }; _offAllPipeEventListeners = function() { if( _onIncomingPipeClose ) { pipeIncoming.off( "close", _onIncomingPipeClose ); @@ -1139,7 +1139,7 @@ export class OneToOneRelay extends EventDispatcher { } pipeIncoming.disconnect(); pipeIncoming.dispose(); - } + }; pipeIncoming.on( "close", _onIncomingPipeClose ); pipeIncoming.on( "error", _onIncomingPipeError ); pipeIncoming.on( "message", _onIncomingPipeMessage ); @@ -1382,14 +1382,14 @@ export class WebSocketServerPipe extends BasicSocketPipe { this._onWsClose = function() { self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self } ) ); - } + }; this._onWsError = function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: self, message: event } ) ); - } + }; this._onWsMessage = function( event: any ) { self.receive( event.data ); - } + }; this._removeWsEventListeners = function() { if( self._onWsClose ) { wsConnection.removeEventListener( "close", self._onWsClose ); @@ -1587,24 +1587,24 @@ export class WebSocketClientPipe extends BasicSocketPipe { self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); - } + }; this._onWsClose = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self, message: event } ) ); - } + }; this._onWsError = function( event: any ) { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: self, message: event } ) ); - } + }; this._onWsMessage = function( event: any ) { self.receive( event.data ); - } + }; this._removeWsEventListeners = function() { if( self._onWsOpen ) { self.wsConnection.removeEventListener( "open", self._onWsOpen ); @@ -1797,7 +1797,7 @@ export class RTCConnection extends EventDispatcher { const s = socketSentDataMarshall( data ); if( ! this.dc ) { this.onError( `Attempt to send message to uninitialized RTC data channel: ${s}` ); - return + return; } try { this.dc.send( s ); @@ -1881,7 +1881,7 @@ export class RTCConnection extends EventDispatcher { "WARNING: Participant \"" + this.idRtcParticipant + "\" ICE gathering state changed event with no pc\", event is:", event ); - return; + return } if( settings.logging.net.rtc.iceGatheringStateChange ) { console.log( @@ -2371,15 +2371,15 @@ export class RTCServerPeer extends RTCConnection { new UniversalDispatcherEvent( "publishStart", { detail: { participant: self } } ) ); self.pc.oniceconnectionstatechange = - function( event: any ) { self.onIceConnectionStateChange( event ); } + function( event: any ) { self.onIceConnectionStateChange( event ); }; self.pc.onicegatheringstatechange = - function( event: any ) { self.onIceGatheringStateChange( event ); } + function( event: any ) { self.onIceGatheringStateChange( event ); }; self.pc.onidentityresult = - function( event: any ) { self.onIceIdentifyResult( event ); } + function( event: any ) { self.onIceIdentifyResult( event ); }; self.pc.onsignalingstatechange = - function( event: any ) { self.onIceSignalingStateChange( event ); } + function( event: any ) { self.onIceSignalingStateChange( event ); }; self.pc.onnegotiationneeded = - function( event: any ) { self.onIceNegotiationNeeded( event ); } + function( event: any ) { self.onIceNegotiationNeeded( event ); }; self.pc.createOffer( self.offerOptions ).then( function( offerDescription: any ) { // success @@ -2411,7 +2411,7 @@ export class RTCServerPeer extends RTCConnection { self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; self.onIceComplete( event ); - } // onicecandidate + }; // onicecandidate }, function( err: any ) { // error of setLocalDescription self.publishCancel(); @@ -2607,7 +2607,7 @@ export class RTCCreator extends RTCActor { idSomebodyOtherSide, "and offer ID", idOffer, ":", strError ); } this.onError( strError ); - return + return; } const rtcPeer = this.mapServerOffers[idOffer]; if( settings.logging.net.signaling.offerUnregister ) { @@ -2668,7 +2668,7 @@ export class RTCCreator extends RTCActor { ); } this.onError( strError ); - return; + return } const rtcPeer = this.mapServerOffers[idOffer]; // OKay, finally got answer from candida @@ -2745,7 +2745,7 @@ export class RTCCreator extends RTCActor { break; default: super.signalingPipeOnMessage( joMessage ); - break; + break } // switch( joMessage.method ) } send( data: any ) { // implementation in RTCCreator does send to all @@ -2840,15 +2840,15 @@ export class RTCJoiner extends RTCActor { { detail: { participant: self, event } } ) ); } ); self.pc.oniceconnectionstatechange = - function( event: any ) { self.onIceConnectionStateChange( event ); } + function( event: any ) { self.onIceConnectionStateChange( event ); }; self.pc.onicegatheringstatechange = - function( event: any ) { self.onIceGatheringStateChange( event ); } + function( event: any ) { self.onIceGatheringStateChange( event ); }; self.pc.onidentityresult = - function( event: any ) { self.onIceIdentifyResult( event ); } + function( event: any ) { self.onIceIdentifyResult( event ); }; self.pc.onsignalingstatechange = - function( event: any ) { self.onIceSignalingStateChange( event ); } + function( event: any ) { self.onIceSignalingStateChange( event ); }; self.pc.onnegotiationneeded = - function( event: any ) { self.onIceNegotiationNeeded( event ); } + function( event: any ) { self.onIceNegotiationNeeded( event ); }; self.pc.ondatachannel = function( event: any ) { self.dispatchEvent( new UniversalDispatcherEvent( @@ -2869,7 +2869,7 @@ export class RTCJoiner extends RTCActor { self.dc.addEventListener( "message", function( event: any ) { self.onDataChannelMessage( event ); } ); - } + }; self.pc.onicecandidate = function( event: any ) { self.iceComplete = true; self.onIceComplete( event ); @@ -3085,7 +3085,7 @@ export class RTCJoiner extends RTCActor { break; default: super.signalingPipeOnMessage( joMessage ); - break; + break } // switch( joMessage.method ) } }; @@ -3331,7 +3331,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { const onTimeoutHandler = function() { self.disposePendingOffer( rtcPeer.idOffer ); self.updateAllPendingOffers(); - } + }; rtcPeer.on( "publishTimeout", onTimeoutHandler ); rtcPeer.on( "signalingNegotiationTimeout", onTimeoutHandler ); rtcPeer.on( "signalingNegotiationStart", function() { @@ -3350,7 +3350,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { errorType: "rtcPeerError" } } ) ); - } + }; rtcPeer.on( "error", retranslateError ); rtcPeer.on( "rtcPeerError", retranslateError ); @@ -3549,10 +3549,10 @@ export class WebRTCClientPipe extends BasicSocketPipe { } ) ); } ); - return + return; } catch ( err ) { console.warn( "WebRTC client connect error:", err ); - continue + continue; } } } diff --git a/src/socketServer.ts b/src/socketServer.ts index 787c4ffa..42fc773c 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -73,7 +73,7 @@ export class SocketServer extends EventDispatcher { _offAllPipeEventListeners = null; } delete self.mapAcceptedPipes[socket]; - } + }; let _onPipeError: any = function( eventData: any ) { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Socket {url} error {err}", @@ -84,7 +84,7 @@ export class SocketServer extends EventDispatcher { _offAllPipeEventListeners = null; } delete self.mapAcceptedPipes[socket]; - } + }; let _onPipeMessage: any = function( eventData: any ) { if( self.isLogSocketTrafficRaw ) { self.log( log.fmtInformation( "Socket {url} did received {sunny} {}", @@ -153,7 +153,7 @@ export class SocketServer extends EventDispatcher { _onPipeMessage = null; } socket.disposeImpersonatedEntries(); - } + }; socket.on( "close", _onPipeClose ); socket.on( "error", _onPipeError ); socket.on( "message", _onPipeMessage ); diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 83adda09..18bbeb1a 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -30,17 +30,17 @@ export const UUIDv4 = function(): string { const r = Math.random() * 16 | 0; const v = c == "x" ? r : ( r & 0x3 | 0x8 ); return v.toString( 16 ); } ); -} +}; export const getRandomInt = function( nMax: number ): number { return Math.floor( Math.random() * Math.floor( nMax ) ); -} +}; export const randomFixedInteger = function( length: number ): number { return Math.floor( Math.pow( 10, length - 1 ) + Math.random() * ( Math.pow( 10, length ) - Math.pow( 10, length - 1 ) - 1 ) ); -} +}; export const randomStringABC = function( length: number, arrCharacters: string ): string { if( length <= 0 || arrCharacters.length == 0 ) @@ -49,7 +49,7 @@ export const randomStringABC = function( length: number, arrCharacters: string ) for( let i = 0; i < length; ++i ) s += arrCharacters.charAt( Math.floor( Math.random() * arrCharacters.length ) ); return s; -} +}; export const randomString = function( length: number, @@ -77,17 +77,17 @@ export const randomString = function( if( arrCharacters.length == 0 ) return ""; return randomStringABC( length, arrCharacters ); -} +}; export const randomHexString = function( length: number ): string { // length in characters, not bytes, each byte is 2 characters const arrCharacters = "0123456789abcdef"; return randomStringABC( length, arrCharacters ); -} +}; export const replaceAll = function( str: string, find: string, replace: string ): string { return str.replace( new RegExp( find, "g" ), replace ); -} +}; export const simpleEscapeString = function( s?: any ): string { if( s == null || s == undefined || typeof s != "string" ) @@ -97,31 +97,31 @@ export const simpleEscapeString = function( s?: any ): string { s = replaceAll( s, ">", ">" ); s = replaceAll( s, " ", " " ); return s; -} +}; export const abstractUniqueID = function(): string { const id = replaceAll( UUIDv4(), "-", "" ).toLowerCase(); return id; -} +}; export const isEven = function( n: number ): boolean { return n % 2 == 0; -} +}; export const isOdd = function( n: number ): boolean { return Math.abs( n % 2 ) == 1; -} +}; const gCountOfCallIdDigits: number = 10; export const randomCallID = function(): string { const id = randomHexString( gCountOfCallIdDigits ); return id; -} +}; const gCountOfDirectPipeIdDigits: number = 10; export const randomDirectPipeID = function(): string { const id = randomHexString( gCountOfDirectPipeIdDigits ); return id; -} +}; export const prepareAnswerJSON = function( joMessage: any ): any { const joAnswer: any = { @@ -138,7 +138,7 @@ export const prepareAnswerJSON = function( joMessage: any ): any { error: null }; return joAnswer; -} +}; export const makeValidSignalingServerURL = function( strSignalingServerURL?: string ): string { const proto = settings.net.secure ? "wss" : "ws"; @@ -150,7 +150,7 @@ export const makeValidSignalingServerURL = function( strSignalingServerURL?: str ? "" + strSignalingServerURL : "" + proto + "://" + settings.net.hostname + ":" + settings.net.ports.signaling ); -} +}; export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ): string { if( val == null || val == undefined ) @@ -159,7 +159,7 @@ export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ): str while( s.length < cntCharsNeeded ) s = "0" + s; return s; -} +}; export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ): string { if( val == null || val == undefined ) return val; @@ -167,7 +167,7 @@ export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ): st while( s.length < cntCharsNeeded ) s = s + "0"; return s; -} +}; export const parseDateTime = function( ts?: any ): Date | null { if( ts === null || ts === undefined ) @@ -196,7 +196,7 @@ export const parseDateTime = function( ts?: any ): Date | null { const d = new Date( u ); d.setMilliseconds( millisecond ); return d; -} +}; export const formatDateTime = function( dt: any, isDate?: boolean, isTime?: boolean, isMilliseconds?: boolean, @@ -254,4 +254,4 @@ export const formatDateTime = function( s += strTime; } return s; -} +}; diff --git a/src/threadInfo.ts b/src/threadInfo.ts index b14c2dc6..e69d7310 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -34,7 +34,7 @@ export { joCustomThreadProperties }; export const sleep = async( milliseconds: number ): Promise => { await new Promise( resolve => setTimeout( resolve, milliseconds ) ) -} +}; export function getCurrentThreadID(): number { return worker_threads.threadId; diff --git a/src/utils.ts b/src/utils.ts index 0ba02a05..76d10b8d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -187,7 +187,7 @@ export async function waitForClonedTokenAppearErc20( "address" in tokenERC20SC && typeof tokenERC20SC.address == "string" ) { log.warning( "Skipping automatic ERC20 instantiation discovery, already done before" ); - return + return; } const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( @@ -203,7 +203,7 @@ export async function waitForClonedTokenAppearErc721( "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" ) { log.warning( "Skipping automatic ERC721instantiation discovery, already done before" ); - return + return; } const addressCallFrom = joAccountSC.address(); const addressOnSChain = @@ -221,7 +221,7 @@ export async function waitForClonedTokenAppearErc721WithMetadata( ) { log.warning( "Skipping automatic ERC721_with_metadata instantiation discovery, " + "already done before" ); - return + return; } const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( @@ -237,7 +237,7 @@ export async function waitForClonedTokenAppearErc1155( "address" in tokenERC1155SC && typeof tokenERC1155SC.address == "string" ) { log.warning( "Skipping automatic ERC1155 instantiation discovery, already done before" ); - return + return; } const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( @@ -354,12 +354,12 @@ export function discoverCoinNameInJSON( jo?: any ): string { j = k.indexOf( "_address" ); if( j > 0 ) { s1 = k.substring( 0, j ); - continue + continue; } j = k.indexOf( "_abi" ); if( j > 0 ) { s2 = k.substring( 0, j ); - continue + continue; } } if( s1.length === 0 || s2.length === 0 ) diff --git a/test/unitTests/agentUnitTests.js b/test/unitTests/agentUnitTests.js index cf306dbb..0245790d 100644 --- a/test/unitTests/agentUnitTests.js +++ b/test/unitTests/agentUnitTests.js @@ -30,7 +30,6 @@ const imaTx = require( "../../src/build/imaTx.js" ); const imaReg = require( "../../src/build/imaRegistrationOperations.js" ); const imaEth = require( "../../src/build/imaEthOperations.js" ); const imaToken = require( "../../src/build/imaTokenOperations.js" ); -const w3mod = IMA.w3mod; const transactionCustomizerMainNet = imaTx.getTransactionCustomizerForMainNet(); const transactionCustomizerSChain = imaTx.getTransactionCustomizerForSChain(); @@ -266,15 +265,16 @@ describe( "tests for `IMA Core` 1", function() { it( "should invoke `privateKeyToPublicKey`", async function() { const keyPrivate = "23abdbd3c61b5330af61ebe8bef582f4e5cc08e554053a718bdce7813b9dc1fc"; let keyPrivateUnd; // undefined - let w3mod_undefined; // undefined - // if w3mod `undefined` or `null` // eslint-disable-next-line no-unused-expressions - expect( IMA.owaspUtils.privateKeyToPublicKey( w3mod_undefined, keyPrivate ) ).to.be.empty; + expect( IMA.owaspUtils.privateKeyToPublicKey( keyPrivate ) ).to.be.equal( + "0x045dd431d36ce6b88f27d351051b31a26848c4a886f0dd0bc87a7d5a9d821417c9" + + "e807e8589f680ab0f2ab29831231ad7b3d6659990ee830582fede785fc3c33c4" + ); // if keyPrivate `undefined` or `null` // eslint-disable-next-line no-unused-expressions - expect( IMA.owaspUtils.privateKeyToPublicKey( w3mod, keyPrivateUnd ) ).to.be.empty; + expect( IMA.owaspUtils.privateKeyToPublicKey( keyPrivateUnd ) ).to.be.empty; // when all parameters is OK - expect( IMA.owaspUtils.privateKeyToPublicKey( w3mod, keyPrivate ) ).to.have.lengthOf( 128 ); + expect( IMA.owaspUtils.privateKeyToPublicKey( keyPrivate ) ).to.have.lengthOf( 128 ); } ); } ); From 2636e2877ed7f652ed480dc3f93dd6cd0b9faf6c Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 12:57:42 +0000 Subject: [PATCH 18/53] IMA/TypeScript support improvements, unit-test fixes --- src/cli.ts | 7 ++++--- src/owaspUtils.ts | 6 ++++-- test/agent-test.mjs | 4 ++-- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index ba4d924f..772b3943 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1201,11 +1201,12 @@ function parseOtherArgs( imaState: any, joArg: any ) { return false; } -export function parse( joExternalHandlers: any ) { +export function parse( joExternalHandlers: any, argv?: any[] ) { const imaState = state.get(); - const cntArgs = process.argv.length; + argv = argv || process.argv; + const cntArgs = argv.length; for( let idxArg = 2; idxArg < cntArgs; ++idxArg ) { - const joArg = parseCommandLineArgument( process.argv[idxArg] ); + const joArg = parseCommandLineArgument( argv[idxArg] ); parseHelp( imaState, joArg ); // exits process on "--help" parseVersion( imaState, joArg ); // exits process on "--version" if( parseBasicArgs( imaState, joArg ) ) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 36491d8c..99e8d10e 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -31,6 +31,7 @@ import * as log from "./log.js"; import * as ethersMod from "ethers"; import * as fs from "fs"; +import { hexToBytes } from "utils"; const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; @@ -658,8 +659,9 @@ export function privateKeyToPublicKey( keyPrivate: string ): string { return ""; if( keyPrivate.trim().length == 0 ) return ""; - const ethersWallet = new ethersMod.ethers.Wallet( ensureStartsWith0x( keyPrivate ) ); - return ethersWallet.publicKey; + const ethersWallet = new ethersMod.ethers.Wallet( + hexToBytes( ensureStartsWith0x( keyPrivate ), false ) ); + return removeStarting0x( ethersWallet.publicKey ); } catch ( err ) { return ""; } diff --git a/test/agent-test.mjs b/test/agent-test.mjs index 68fc2877..2925fdcf 100644 --- a/test/agent-test.mjs +++ b/test/agent-test.mjs @@ -1151,11 +1151,11 @@ describe( "Agent Utils Module-2", function() { assert.equal( strDst, "01230000" ); } ); - it( "Typed array concatenation", function() { + it( "Uint8 arrays concatenation", function() { const strSrcLeft = "0xbaad", strSrcRight = "0xf00d"; const arrBytesLeft = imaUtils.hexToBytes( strSrcLeft, false ); const arrBytesRight = imaUtils.hexToBytes( strSrcRight, false ); - const arrBytes = imaUtils.concatTypedArrays( arrBytesLeft, arrBytesRight ); + const arrBytes = imaUtils.concatUint8Arrays( arrBytesLeft, arrBytesRight ); const strDst = imaUtils.bytesToHex( arrBytes, false ); assert.equal( strDst, "baadf00d" ); } ); From 9a97714298b84d0561703e30bd495a23d8c65876 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 13:42:04 +0000 Subject: [PATCH 19/53] IMA/TypeScript support improvements, unit-test fixes --- src/owaspUtils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 99e8d10e..d149536d 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -31,7 +31,7 @@ import * as log from "./log.js"; import * as ethersMod from "ethers"; import * as fs from "fs"; -import { hexToBytes } from "utils"; +import * as imaUtils from "./utils.js"; const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; @@ -660,7 +660,7 @@ export function privateKeyToPublicKey( keyPrivate: string ): string { if( keyPrivate.trim().length == 0 ) return ""; const ethersWallet = new ethersMod.ethers.Wallet( - hexToBytes( ensureStartsWith0x( keyPrivate ), false ) ); + imaUtils.hexToBytes( ensureStartsWith0x( keyPrivate ), false ) ); return removeStarting0x( ethersWallet.publicKey ); } catch ( err ) { return ""; From 764865fbd4b2ac8bdb2f21de84db0492dc65fdaf Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Thu, 14 Dec 2023 14:24:12 +0000 Subject: [PATCH 20/53] IMA/TypeScript support improvements, unit-test fixes --- src/owaspUtils.ts | 29 ------------------------- test/agent-test.mjs | 36 -------------------------------- test/unitTests/agentUnitTests.js | 31 --------------------------- 3 files changed, 96 deletions(-) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index d149536d..9fbe1183 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -31,7 +31,6 @@ import * as log from "./log.js"; import * as ethersMod from "ethers"; import * as fs from "fs"; -import * as imaUtils from "./utils.js"; const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; @@ -653,34 +652,6 @@ export function privateKeyToAccountAddress( keyPrivate: string ): string { ensureStartsWith0x( keyPrivate ) ); } -export function privateKeyToPublicKey( keyPrivate: string ): string { - try { - if( ! keyPrivate ) - return ""; - if( keyPrivate.trim().length == 0 ) - return ""; - const ethersWallet = new ethersMod.ethers.Wallet( - imaUtils.hexToBytes( ensureStartsWith0x( keyPrivate ), false ) ); - return removeStarting0x( ethersWallet.publicKey ); - } catch ( err ) { - return ""; - } -} - -export function publicKeyToAccountAddress( keyPublic: string ): string { - try { - if( ! keyPublic ) - return ""; - if( keyPublic.trim().length == 0 ) - return ""; - const hash = ethersMod.ethers.utils.keccak256( ensureStartsWith0x( keyPublic ) ); - const strAddress = ensureStartsWith0x( hash.substr( hash.length - 40 ) ); - return strAddress; - } catch ( err ) { - return ""; - } -} - export function fnAddressImpl_( anyThis: any ): string { if( anyThis.address_ == undefined || anyThis.address_ == null || anyThis.address_ == "" ) { if( anyThis.privateKey ) diff --git a/test/agent-test.mjs b/test/agent-test.mjs index 2925fdcf..6e1673e3 100644 --- a/test/agent-test.mjs +++ b/test/agent-test.mjs @@ -715,42 +715,6 @@ describe( "OWASP-5", function() { } ); - describe( "Key/address utilities", function() { - const joTestAccount = { - "privateKey": - owaspUtils.toEthPrivateKey( - "23ABDBD3C61B5330AF61EBE8BEF582F4E5CC08E554053A718BDCE7813B9DC1FC" ), - "address": function () { return owaspUtils.fnAddressImpl_( this ); } - }; - - it( "Extract address from private key", function() { - const address = joTestAccount.address(); - const address2 = - owaspUtils.privateKeyToAccountAddress( joTestAccount.privateKey ); - assert.equal( - address.toLowerCase(), - "0x7aa5E36AA15E93D10F4F26357C30F052DacDde5F".toLowerCase() ); - assert.equal( - address2.toLowerCase(), - "0x7aa5E36AA15E93D10F4F26357C30F052DacDde5F".toLowerCase() ); - } ); - - it( "Extract public key from private key", function() { - const publicKey = owaspUtils.privateKeyToPublicKey( joTestAccount.privateKey ); - assert.equal( - publicKey.toLowerCase(), - ( "5dd431d36ce6b88f27d351051b31a26848c4a886f0dd0bc87a7d5a9d82" + - "1417c9e807e8589f680ab0f2ab29831231ad" + - "7b3d6659990ee830582fede785fc3c33c4" ).toLowerCase() ); - } ); - - it( "Extract address from public key", function() { - const address = joTestAccount.address(); - const publicKey = owaspUtils.privateKeyToPublicKey( joTestAccount.privateKey ); - const address2 = owaspUtils.publicKeyToAccountAddress( publicKey ); - assert.equal( address.toLowerCase(), address2.toLowerCase() ); - } ); - } ); } ); describe( "OWASP-6", function() { diff --git a/test/unitTests/agentUnitTests.js b/test/unitTests/agentUnitTests.js index 0245790d..60e24165 100644 --- a/test/unitTests/agentUnitTests.js +++ b/test/unitTests/agentUnitTests.js @@ -262,41 +262,10 @@ describe( "tests for `IMA Core` 1", function() { expect( IMA.owaspUtils.removeStarting0x( "1" ) ).to.be.equal( "1" ); } ); - it( "should invoke `privateKeyToPublicKey`", async function() { - const keyPrivate = "23abdbd3c61b5330af61ebe8bef582f4e5cc08e554053a718bdce7813b9dc1fc"; - let keyPrivateUnd; // undefined - // eslint-disable-next-line no-unused-expressions - expect( IMA.owaspUtils.privateKeyToPublicKey( keyPrivate ) ).to.be.equal( - "0x045dd431d36ce6b88f27d351051b31a26848c4a886f0dd0bc87a7d5a9d821417c9" + - "e807e8589f680ab0f2ab29831231ad7b3d6659990ee830582fede785fc3c33c4" - ); - // if keyPrivate `undefined` or `null` - // eslint-disable-next-line no-unused-expressions - expect( IMA.owaspUtils.privateKeyToPublicKey( keyPrivateUnd ) ).to.be.empty; - // when all parameters is OK - expect( IMA.owaspUtils.privateKeyToPublicKey( keyPrivate ) ).to.have.lengthOf( 128 ); - } ); - } ); describe( "tests for `IMA Core` 2", function() { - it( "should invoke `publicKeyToAccountAddress`", async function() { - const keyPublic = "5dd431d36ce6b88f27d351051b31a26848c4a886f0dd0bc87a7d5a9d821417c9" + - "e807e8589f680ab0f2ab29831231ad7b3d6659990ee830582fede785fc3c33c4"; - let keyPublicUnd; // undefined - // if keyPrivate `undefined` or `null` - // eslint-disable-next-line no-unused-expressions - expect( IMA.owaspUtils.publicKeyToAccountAddress( keyPublicUnd ) ).to.be.empty; - // when all parameters is OK - expect( IMA.owaspUtils.publicKeyToAccountAddress( keyPublic ) ).to.include( "0x" ); - } ); - - it( "should invoke `privateKeyToAccountAddress`", async function() { - const keyPrivate = "23abdbd3c61b5330af61ebe8bef582f4e5cc08e554053a718bdce7813b9dc1fc"; - expect( IMA.owaspUtils.privateKeyToAccountAddress( keyPrivate ) ).to.include( "0x" ); - } ); - it( "should return `false` invoke `checkIsRegisteredSChainInDepositBoxes`", async function() { let joLinker; // for `false` output // eslint-disable-next-line no-unused-expressions From 132799a626fbcf0cd2111f3105a6bde72bfcf391 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 15 Dec 2023 11:33:33 +0000 Subject: [PATCH 21/53] IMA/TypeScript support improvements --- src/imaOracleOperations.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 6a9cf216..c589e315 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -79,7 +79,7 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { optsGasPriseSetup.strActionName = "prepareOracleGasPriceSetup.getGasPrice()"; optsGasPriseSetup.gasPriceOnMainNet = null; if( getEnabledOracle() ) { - const oracleOpts: any = { + const oracleOpts = { url: owaspUtils.ethersProviderToUrl( optsGasPriseSetup.ethersProviderSChain ), callOpts: { }, nMillisecondsSleepBefore: 1000, From 9d72bbb52a1269541f0070a4994235de71db11df Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Mon, 18 Dec 2023 19:39:34 +0000 Subject: [PATCH 22/53] Massively added types to various compound and simple data pbjects --- src/bls.ts | 217 +++++++++---- src/cli.ts | 488 +++++++++++++++--------------- src/clpTools.ts | 472 ++++++++++++++++++++--------- src/discoveryTools.ts | 22 +- src/imaCore.ts | 105 +++++-- src/imaEthOperations.ts | 17 +- src/imaHelperAPIs.ts | 4 +- src/imaOracleOperations.ts | 7 +- src/imaRegistrationOperations.ts | 53 ++-- src/imaReimbursementOperations.ts | 27 +- src/imaSgxExternalSigner.ts | 4 +- src/imaTokenOperations.ts | 77 ++--- src/imaTx.ts | 52 +++- src/loop.ts | 145 ++++++--- src/loopWorker.ts | 6 +- src/main.ts | 20 +- src/observer.ts | 2 +- src/oracle.ts | 7 +- src/owaspUtils.ts | 2 +- src/pwa.ts | 32 +- src/rpcCall.ts | 62 ++-- src/state.ts | 257 ++++++++++++++-- src/utils.ts | 9 +- 23 files changed, 1407 insertions(+), 680 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index b0d222bb..3013f7fd 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -37,6 +37,79 @@ import * as discoveryTools from "./discoveryTools.js"; import * as threadInfo from "./threadInfo.js"; import * as utils from "./socketUtils.js"; import * as state from "./state.js"; +import type * as loop from "./loop.js"; + +export interface TGatheringTracker { + nCountReceivedPrevious: number + nCountReceived: number + nCountErrors: number + nCountSkipped: number + nWaitIntervalStepMilliseconds: number + nWaitIntervalMaxSteps: number +} + +export interface TSignOperationOptions { + imaState: state.TIMAState + nTransferLoopCounter: number + strDirection: string + jarrMessages: any[] + nIdxCurrentMsgBlockStart: number + strFromChainName: string + joExtraSignOpts: loop.TExtraSignOpts + fn: any + bHaveResultReportCalled: boolean + strLogPrefix: string + strLogPrefixA: string + strLogPrefixB: string + joGatheringTracker: TGatheringTracker + arrSignResults: any[] + details: any + strGatheredDetailsName: string + sequenceId: string + jarrNodes: any[] + nThreshold: number + nParticipants: number + nCountOfBlsPartsToCollect: number + errGathering: Error | string | null + targetChainName: string + fromChainName: string + targetChainID: string | number + fromChainID: string | number +} + +export interface TBSU256Options { + joCallData: any + imaState: state.TIMAState + strLogPrefix: string + details: any + joRetVal: any | null + isSuccess: boolean + nThreshold: number + nParticipants: number + u256: any | null + strMessageHash: string + joAccount: state.TAccount | null +} + +export interface THandleVerifyAndSignOptions { + joCallData: any + imaState: state.TIMAState + strLogPrefix: string + details: any + joRetVal: any + isSuccess: boolean + nIdxCurrentMsgBlockStart: number + strFromChainName: string + strToChainName: string + strFromChainID: string + strToChainID: string + strDirection: string + jarrMessages: any[] + strMessageHash: string + joExtraSignOpts: loop.TExtraSignOpts | null + nThreshold: number + nParticipants: number +} const anyShellMod: any = shellMod as any; const shell = anyShellMod.default @@ -44,7 +117,7 @@ const shell = anyShellMod.default const Keccak = sha3Module.Keccak; function discoverBlsThreshold( joSChainNetworkInfo: any ): number { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) return -1; @@ -58,7 +131,7 @@ function discoverBlsThreshold( joSChainNetworkInfo: any ): number { } function discoverBlsParticipants( joSChainNetworkInfo: any ): number { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) return -1; @@ -97,7 +170,7 @@ function discoverPublicKeyByIndex( nNodeIndex: number, joSChainNetworkInfo: any, details: any, isThrowException: boolean ): any { details = details || log; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; const jarrNodes = joSChainNetworkInfo.network; const cntNodes = jarrNodes.length; @@ -120,7 +193,7 @@ function discoverPublicKeyByIndex( function discoverCommonPublicKey( details: any, joSChainNetworkInfo: any, isThrowException: boolean ): any { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; const jarrNodes = joSChainNetworkInfo.network; for( let i = 0; i < jarrNodes.length; ++i ) { @@ -275,7 +348,7 @@ function performBlsGlue( details: any, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, arrSignResults: any[] ): any { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strLogPrefix = `${strDirection}/BLS/Glue: `; let joGlueResult: any = null; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); @@ -364,7 +437,7 @@ function performBlsGlue( } function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ): any { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strLogPrefix = "BLS/Glue: "; let joGlueResult: any = null; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); @@ -462,7 +535,7 @@ function performBlsVerifyI( ): boolean { if( !joResultFromNode ) return true; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strLogPrefix = `${strDirection}/BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -526,7 +599,7 @@ function performBlsVerifyIU256( ): boolean { if( ! joResultFromNode ) return true; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strLogPrefix = `BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -582,7 +655,7 @@ function performBlsVerify( ): boolean { if( !joGlueResult ) return true; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); if( ! checkBlsThresholdAndBlsParticipants( @@ -651,7 +724,7 @@ function performBlsVerifyU256( ): boolean { if( !joGlueResult ) return true; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); if( ! checkBlsThresholdAndBlsParticipants( @@ -708,11 +781,13 @@ function performBlsVerifyU256( async function checkCorrectnessOfMessagesToSign( details: any, strLogPrefix: string, strDirection: string, - jarrMessages: any[], nIdxCurrentMsgBlockStart: number, joExtraSignOpts: any + jarrMessages: any[], nIdxCurrentMsgBlockStart: number, + joExtraSignOpts: loop.TExtraSignOpts | null ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); let joMessageProxy: owaspUtils.ethersMod.ethers.Contract | null = null; - let joAccount: any = null; let joChainName: any = null; + let joAccount: state.TAccount | null = null; + let joChainName: string | null = null; if( strDirection == "M2S" ) { joMessageProxy = imaState.joMessageProxyMainNet; joAccount = imaState.chainProperties.mn.joAccount; @@ -723,9 +798,12 @@ async function checkCorrectnessOfMessagesToSign( joChainName = imaState.chainProperties.mn.strChainName; } else if( strDirection == "S2S" ) { joAccount = imaState.chainProperties.sc.joAccount; + if( ( !joExtraSignOpts ) || ( !( joExtraSignOpts.chainNameDst ) ) ) + throw new Error( "Missing destination chain name for BLS signing" ); joChainName = joExtraSignOpts.chainNameDst; const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = - ( "ethersProviderSrc" in joExtraSignOpts && joExtraSignOpts.ethersProviderSrc ) + ( joExtraSignOpts && "ethersProviderSrc" in joExtraSignOpts && + joExtraSignOpts.ethersProviderSrc ) ? joExtraSignOpts.ethersProviderSrc : null; if( ! ethersProvider ) { throw new Error( "CRITICAL ERROR: No provider specified in extra signing options " + @@ -800,7 +878,7 @@ async function checkCorrectnessOfMessagesToSign( } -async function prepareSignMessagesImpl( optsSignOperation: any ) { +async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions ) { optsSignOperation.fn = optsSignOperation.fn || function() {}; optsSignOperation.sequenceId = owaspUtils.removeStarting0x( @@ -883,7 +961,7 @@ async function prepareSignMessagesImpl( optsSignOperation: any ) { return true; } -async function gatherSigningCheckFinish( optsSignOperation: any ) { +async function gatherSigningCheckFinish( optsSignOperation: TSignOperationOptions ) { const cntSuccess = optsSignOperation.arrSignResults.length; if( optsSignOperation.joGatheringTracker.nCountReceivedPrevious != optsSignOperation.joGatheringTracker.nCountReceived ) { @@ -954,7 +1032,7 @@ async function gatherSigningCheckFinish( optsSignOperation: any ) { return true; } -async function gatherSigningCheckOverflow( optsSignOperation: any ) { +async function gatherSigningCheckOverflow( optsSignOperation: TSignOperationOptions ) { if( optsSignOperation.joGatheringTracker.nCountReceived < optsSignOperation.jarrNodes.length ) return false; optsSignOperation.fn( @@ -974,7 +1052,7 @@ async function gatherSigningCheckOverflow( optsSignOperation: any ) { return true; } -async function gatherSigningStartImpl( optsSignOperation: any ) { +async function gatherSigningStartImpl( optsSignOperation: TSignOperationOptions ) { optsSignOperation.details.debug( "{p}Waiting for BLS glue result...", optsSignOperation.strLogPrefix ); optsSignOperation.errGathering = null; @@ -1004,7 +1082,7 @@ async function gatherSigningStartImpl( optsSignOperation: any ) { optsSignOperation.bHaveResultReportCalled = true; } -async function gatherSigningFinishImpl( optsSignOperation: any ) { +async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions ) { optsSignOperation.details.trace( "{p}Will await for message BLS verification and sending...", optsSignOperation.strLogPrefix ); if( optsSignOperation.errGathering ) { @@ -1053,7 +1131,7 @@ async function gatherSigningFinishImpl( optsSignOperation: any ) { } } -async function doSignConfigureChainAccessParams( optsSignOperation: any ) { +async function doSignConfigureChainAccessParams( optsSignOperation: TSignOperationOptions ) { optsSignOperation.targetChainName = ""; optsSignOperation.fromChainName = ""; optsSignOperation.targetChainID = -4; @@ -1093,8 +1171,9 @@ async function doSignConfigureChainAccessParams( optsSignOperation: any ) { } async function doSignProcessHandleCall( - optsSignOperation: any, joParams: any, joCall: any, joIn: any, joOut: any, i: number ) { - const imaState = state.get(); + optsSignOperation: TSignOperationOptions, joParams: any, joCall: rpcCall.TRPCCall, + joIn: any, joOut: any, i: number ) { + const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignOperation.jarrNodes[i]; const strNodeURL = optsSignOperation.imaState.isCrossImaBlsMode @@ -1201,8 +1280,8 @@ async function doSignProcessHandleCall( await joCall.disconnect(); } -async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { - const imaState = state.get(); +async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperationOptions ) { + const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignOperation.jarrNodes[i]; const strNodeURL = optsSignOperation.imaState.isCrossImaBlsMode @@ -1211,9 +1290,9 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { const strNodeDescColorized = log.fmtDebug( "{url} ({}/{}, ID {}), sequence ID is {}", strNodeURL, i, optsSignOperation.jarrNodes.length, joNode.nodeID, optsSignOperation.sequenceId ); - const rpcCallOpts: any = null; - let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) - .catch( function( err: Error | string ) { + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; + const joCall = + await rpcCall.create( strNodeURL, rpcCallOpts ).catch( function( err: Error | string ) { ++optsSignOperation.joGatheringTracker.nCountReceived; ++optsSignOperation.joGatheringTracker.nCountErrors; optsSignOperation.details.error( @@ -1223,7 +1302,6 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { err, optsSignOperation.sequenceId ); if( joCall ) joCall.disconnect(); - joCall = null; } ); if( ! joCall ) return; @@ -1256,9 +1334,9 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: any ) { async function doSignMessagesImpl( nTransferLoopCounter: number, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: any, fn: any + joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { - const optsSignOperation: any = { + const optsSignOperation: TSignOperationOptions = { imaState: state.get(), nTransferLoopCounter, strDirection, @@ -1271,7 +1349,14 @@ async function doSignMessagesImpl( strLogPrefix: "", strLogPrefixA: "", strLogPrefixB: "", - joGatheringTracker: {}, + joGatheringTracker: { + nCountReceivedPrevious: 0, + nCountReceived: 0, + nCountErrors: 0, + nCountSkipped: 0, + nWaitIntervalStepMilliseconds: 500, + nWaitIntervalMaxSteps: 10 * 60 * 3 // 10 is 1 second + }, arrSignResults: [], details: log, strGatheredDetailsName: "", @@ -1359,7 +1444,7 @@ async function doSignMessagesImpl( export async function doSignMessagesM2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: any, fn: any ) { + joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { await doSignMessagesImpl( nTransferLoopCounter, "M2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1369,7 +1454,7 @@ export async function doSignMessagesM2S( export async function doSignMessagesS2M( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: any, fn: any ) { + joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { await doSignMessagesImpl( nTransferLoopCounter, "S2M", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1379,7 +1464,7 @@ export async function doSignMessagesS2M( export async function doSignMessagesS2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: any, fn: any ) { + joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { await doSignMessagesImpl( nTransferLoopCounter, "S2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1417,8 +1502,8 @@ async function prepareSignU256( optsSignU256: any ) { } async function doSignU256OneImplHandleCallResult( - i: number, optsSignU256: any, joCall: any, joIn: any, joOut: any ) { - const imaState = state.get(); + i: number, optsSignU256: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignU256.jarrNodes[i]; const strNodeURL = optsSignU256.imaState.isCrossImaBlsMode @@ -1514,7 +1599,7 @@ async function doSignU256OneImplHandleCallResult( } async function doSignU256OneImpl( i: number, optsSignU256: any ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignU256.jarrNodes[i]; const strNodeURL = optsSignU256.imaState.isCrossImaBlsMode @@ -1522,8 +1607,8 @@ async function doSignU256OneImpl( i: number, optsSignU256: any ) { : imaUtils.composeSChainNodeUrl( joNode ); const strNodeDescColorized = log.fmtDebug( "{url} ({}/{}, ID {})", strNodeURL, i, optsSignU256.jarrNodes.length, joNode.nodeID ); - const rpcCallOpts: any = null; - let joCall: any = null; + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; + let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) @@ -1716,7 +1801,7 @@ export async function doVerifyReadyHash( strMessageHash: string, nZeroBasedNodeIndex: number, signature: any, isExposeOutput: boolean ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strDirection = "RAW"; const strLogPrefix = `${strDirection}/BLS/#${nZeroBasedNodeIndex}: `; const details = log.createMemoryStream(); @@ -1789,7 +1874,8 @@ export async function doVerifyReadyHash( async function doSignReadyHashHandleCallResult( strLogPrefix: string, details: any, - strMessageHash: string, isExposeOutput: any, joCall: any, joIn: any, joOut: any + strMessageHash: string, isExposeOutput: boolean, joCall: rpcCall.TRPCCall, + joIn: any, joOut: any ) { details.trace( "{p}Call to ", "SGX done, answer is: {}", strLogPrefix, joOut ); let joSignResult = joOut; @@ -1821,10 +1907,11 @@ async function doSignReadyHashHandleCallResult( } export async function doSignReadyHash( strMessageHash: string, isExposeOutput: any ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strLogPrefix = ""; const details: any = log.createMemoryStream(); - let joSignResult: any = null; let joCall: any = null; + let joSignResult: any = null; + let joCall: rpcCall.TRPCCall | null = null; try { const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -1836,15 +1923,15 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a if( ! checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "sign ready hash", details ) ) return false; - let joAccount = imaState.chainProperties.sc.joAccount; - if( ! joAccount.strURL ) { + let joAccount: state.TAccount = imaState.chainProperties.sc.joAccount; + if( ! joAccount.strSgxURL ) { joAccount = imaState.chainProperties.mn.joAccount; if( ! joAccount.strSgxURL ) throw new Error( "SGX URL is unknown, cannot sign U256" ); if( ! joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign U256" ); } - let rpcCallOpts: any = null; + let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey == "string" && joAccount.strPathSslKey.length > 0 && "strPathSslCert" in joAccount && typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 @@ -1893,7 +1980,8 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a return joSignResult; } -async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) { +async function prepareHandlingOfSkaleImaVerifyAndSign( + optsHandleVerifyAndSign: THandleVerifyAndSignOptions ) { optsHandleVerifyAndSign.details.debug( "{p}Will verify and sign {}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.joCallData ); optsHandleVerifyAndSign.nIdxCurrentMsgBlockStart = @@ -1947,7 +2035,8 @@ async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: return true; } -async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) { +async function prepareS2sOfSkaleImaVerifyAndSign( + optsHandleVerifyAndSign: THandleVerifyAndSignOptions ) { const strSChainNameSrc = optsHandleVerifyAndSign.joCallData.params.srcChainName; const strSChainNameDst = optsHandleVerifyAndSign.joCallData.params.dstChainName; optsHandleVerifyAndSign.details.trace( @@ -1990,8 +2079,8 @@ async function prepareS2sOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign: any ) } async function handleBlsSignMessageHashResult( - optsHandleVerifyAndSign: any, joCallData: any, joAccount: any, - joCall: any, joIn: any, joOut: any + optsHandleVerifyAndSign: THandleVerifyAndSignOptions, joCallData: any, + joAccount: state.TAccount, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { optsHandleVerifyAndSign.details.trace( "{p}{bright} Call to SGX done, " + "answer is: {}", optsHandleVerifyAndSign.strLogPrefix, @@ -2036,7 +2125,7 @@ async function handleBlsSignMessageHashResult( } export async function handleSkaleImaVerifyAndSign( joCallData: any ) { - const optsHandleVerifyAndSign: any = { + const optsHandleVerifyAndSign: THandleVerifyAndSignOptions = { joCallData, imaState: state.get(), strLogPrefix: "", @@ -2055,7 +2144,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { nThreshold: 1, nParticipants: 1 }; - let joCall: any = null; + let joCall: rpcCall.TRPCCall | null = null; try { if( ! ( await prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) ) ) return null; @@ -2072,14 +2161,14 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { optsHandleVerifyAndSign.details.debug( "{p}Will BLS-sign verified messages.", optsHandleVerifyAndSign.strLogPrefix ); let joAccount = optsHandleVerifyAndSign.imaState.chainProperties.sc.joAccount; - if( ! joAccount.strURL ) { + if( ! joAccount.strSgxURL ) { joAccount = optsHandleVerifyAndSign.imaState.chainProperties.mn.joAccount; if( ! joAccount.strSgxURL ) throw new Error( "SGX URL is unknown, cannot sign(handle) IMA message(s)" ); if( ! joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign IMA message(s)" ); } - let rpcCallOpts: any = null; + let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey == "string" && joAccount.strPathSslKey.length > 0 && "strPathSslCert" in joAccount && typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 @@ -2128,7 +2217,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { return optsHandleVerifyAndSign.joRetVal; } -async function handleSkaleImaBSU256Prepare( optsBSU256: any ) { +async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { optsBSU256.details.debug( "{p}Will U256-BLS-sign {}", optsBSU256.strLogPrefix, optsBSU256.joCallData ); optsBSU256.nThreshold = discoverBlsThreshold( optsBSU256.imaState.joSChainNetworkInfo ); @@ -2150,9 +2239,11 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: any ) { optsBSU256.details.trace( "{p}hash of U256 value to sign is {}", optsBSU256.strLogPrefix, optsBSU256.strMessageHash ); optsBSU256.details.trace( "{p}Will BLS-sign U256.", optsBSU256.strLogPrefix ); - optsBSU256.joAccount = optsBSU256.imaState.chainProperties.sc.optsBSU256.joAccount; - if( ! optsBSU256.joAccount.strURL ) { - optsBSU256.joAccount = optsBSU256.imaState.chainProperties.mn.optsBSU256.joAccount; + if( ! optsBSU256.joAccount ) + throw new Error( "No account to perform blsSignMessageHash for U256" ) + optsBSU256.joAccount = optsBSU256.imaState.chainProperties.sc.joAccount; + if( ! optsBSU256.joAccount.strSgxURL ) { + optsBSU256.joAccount = optsBSU256.imaState.chainProperties.mn.joAccount; if( ! optsBSU256.joAccount.strSgxURL ) throw new Error( "SGX URL is unknown, cannot sign U256" ); if( ! optsBSU256.joAccount.strBlsKeyName ) @@ -2162,7 +2253,7 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: any ) { } async function handleBlsSignMessageHash256Result( - optsBSU256: any, joCallData: any, joCall: any, joIn: any, joOut: any + optsBSU256: TBSU256Options, joCallData: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { optsBSU256.details.trace( "{p}Call to SGX done, answer is: {}", optsBSU256.strLogPrefix, joOut ); @@ -2202,7 +2293,7 @@ async function handleBlsSignMessageHash256Result( } export async function handleSkaleImaBSU256( joCallData: any ) { - const optsBSU256: any = { + const optsBSU256: TBSU256Options = { joCallData, imaState: state.get(), strLogPrefix: "", @@ -2215,11 +2306,13 @@ export async function handleSkaleImaBSU256( joCallData: any ) { strMessageHash: "", joAccount: null }; - let joCall: any = null; + let joCall: rpcCall.TRPCCall | null = null; try { if( ! ( await handleSkaleImaBSU256Prepare( optsBSU256 ) ) ) return null; - let rpcCallOpts: any = null; + if( ! optsBSU256.joAccount ) + throw new Error( "No account to perform blsSignMessageHash for U256" ) + let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; if( "strPathSslKey" in optsBSU256.joAccount && typeof optsBSU256.joAccount.strPathSslKey == "string" && optsBSU256.joAccount.strPathSslKey.length > 0 && diff --git a/src/cli.ts b/src/cli.ts index 772b3943..70d6f9f3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -109,7 +109,8 @@ export function ensureHaveValue( } export function ensureHaveCredentials( - strFriendlyChainName: string, joAccount: any, isExitIfEmpty: boolean, isPrintValue: boolean + strFriendlyChainName: string, joAccount: state.TAccount, + isExitIfEmpty: boolean, isPrintValue: boolean ) { strFriendlyChainName = strFriendlyChainName || ""; if( ! ( typeof joAccount == "object" ) ) { @@ -210,7 +211,7 @@ export function findNodeIndex( joSChainNodeConfiguration: any ) { return 0; } -function parseHelp( imaState: any, joArg: any ) { // exits process on "--help" +function parseHelp( imaState: state.TIMAState, joArg: any ) { // exits process on "--help" if( joArg.name != "help" ) return false; printAbout(); @@ -221,14 +222,14 @@ function parseHelp( imaState: any, joArg: any ) { // exits process on "--help" process.exit( 0 ); } -function parseVersion( imaState: any, joArg: any ) { // exits process on "--version" +function parseVersion( imaState: state.TIMAState, joArg: any ) { // exits process on "--version" if( joArg.name != "version" ) return false; printAbout(); process.exit( 0 ); } -function parseBasicArgs( imaState: any, joArg: any ) { +function parseBasicArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "colors" ) { log.enableColorization( true ); return true; @@ -256,7 +257,7 @@ function parseBasicArgs( imaState: any, joArg: any ) { return false; } -function parseChainAccessArgs( imaState: any, joArg: any ) { +function parseChainAccessArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); imaState.chainProperties.mn.strURL = joArg.value; @@ -310,7 +311,7 @@ function parseChainAccessArgs( imaState: any, joArg: any ) { return false; } -function parseTransactionManagerArgs( imaState: any, joArg: any ) { +function parseTransactionManagerArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "tm-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); const strURL = "" + joArg.value; @@ -350,7 +351,7 @@ function parseTransactionManagerArgs( imaState: any, joArg: any ) { return false; } -function parseSgxArgs( imaState: any, joArg: any ) { +function parseSgxArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "sgx-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); imaState.chainProperties.mn.joAccount.strSgxURL = joArg.value; @@ -475,7 +476,7 @@ function parseSgxArgs( imaState: any, joArg: any ) { return false; } -function parseCredentialsArgs( imaState: any, joArg: any ) { +function parseCredentialsArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "address-main-net" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.chainProperties.mn.joAccount.address_ = joArg.value; @@ -514,7 +515,7 @@ function parseCredentialsArgs( imaState: any, joArg: any ) { return false; } -function parseAbiArgs( imaState: any, joArg: any ) { +function parseAbiArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "abi-skale-manager" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); imaState.strPathAbiJsonSkaleManager = imaUtils.normalizePath( joArg.value ); @@ -538,7 +539,7 @@ function parseAbiArgs( imaState: any, joArg: any ) { return false; } -function parseErcArgs( imaState: any, joArg: any ) { +function parseErcArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "erc20-main-net" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); imaState.chainProperties.mn.strPathJsonErc20 = imaUtils.normalizePath( joArg.value ); @@ -623,7 +624,7 @@ function parseErcArgs( imaState: any, joArg: any ) { return false; } -function parseTransactionArgs( imaState: any, joArg: any ) { +function parseTransactionArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "sleep-between-tx" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaHelperAPIs.setSleepBetweenTransactionsOnSChainMilliseconds( joArg.value ); @@ -721,7 +722,7 @@ function parseTransactionArgs( imaState: any, joArg: any ) { return false; } -function parsePaymentAmountArgs( imaState: any, joArg: any ) { +function parsePaymentAmountArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "value" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = owaspUtils.parseMoneySpecToWei( "" + joArg.value, true ); @@ -792,7 +793,7 @@ function parsePaymentAmountArgs( imaState: any, joArg: any ) { return false; } -function parseTransferArgs( imaState: any, joArg: any ) { +function parseTransferArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "s2s-forward" ) { imaHelperAPIs.setForwardS2S(); return true; @@ -960,7 +961,7 @@ function parseTransferArgs( imaState: any, joArg: any ) { return false; } -function parseMulticallArgs( imaState: any, joArg: any ) { +function parseMulticallArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "enable-multicall" ) { imaState.isEnabledMultiCall = true; return true; @@ -972,7 +973,7 @@ function parseMulticallArgs( imaState: any, joArg: any ) { return false; } -function parsePendingWorkAnalysisArgs( imaState: any, joArg: any ) { +function parsePendingWorkAnalysisArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "pwa" ) { imaState.isPWA = true; return true; @@ -997,7 +998,7 @@ function parsePendingWorkAnalysisArgs( imaState: any, joArg: any ) { return false; } -function parseLoggingArgs( imaState: any, joArg: any ) { +function parseLoggingArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "gathered" ) { imaState.isPrintGathered = true; return true; @@ -1048,7 +1049,7 @@ function parseLoggingArgs( imaState: any, joArg: any ) { return false; } -function parseBlsArgs( imaState: any, joArg: any ) { +function parseBlsArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "sign-messages" ) { imaState.bSignMessages = true; return true; @@ -1071,7 +1072,7 @@ function parseBlsArgs( imaState: any, joArg: any ) { return false; } -function parseMonitoringArgs( imaState: any, joArg: any ) { +function parseMonitoringArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "monitoring-port" ) { owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nMonitoringPort = owaspUtils.toInteger( joArg.value ); @@ -1085,7 +1086,7 @@ function parseMonitoringArgs( imaState: any, joArg: any ) { return false; } -function parseReimbursementArgs( imaState: any, joArg: any ) { +function parseReimbursementArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "reimbursement-chain" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.strReimbursementChain = joArg.value.trim(); @@ -1108,7 +1109,7 @@ function parseReimbursementArgs( imaState: any, joArg: any ) { return true; } if( joArg.name == "reimbursement-estimate" ) { - imaState.nReimbursementEstimate = true; + imaState.isReimbursementEstimate = true; return true; } if( joArg.name == "reimbursement-range" ) { @@ -1119,7 +1120,7 @@ function parseReimbursementArgs( imaState: any, joArg: any ) { return false; } -function parseOracleArgs( imaState: any, joArg: any ) { +function parseOracleArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "enable-oracle" ) { imaOracleOperations.setEnabledOracle( true ); return true; @@ -1131,7 +1132,7 @@ function parseOracleArgs( imaState: any, joArg: any ) { return false; } -function parseNetworkDiscoveryArgs( imaState: any, joArg: any ) { +function parseNetworkDiscoveryArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "network-browser-path" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.optsS2S.strNetworkBrowserPath = "" + joArg.value; @@ -1140,7 +1141,7 @@ function parseNetworkDiscoveryArgs( imaState: any, joArg: any ) { return false; } -function parseBlockScannerArgs( imaState: any, joArg: any ) { +function parseBlockScannerArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "bs-step-size" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaHelperAPIs.setBlocksCountInInIterativeStepOfEventsScan( @@ -1163,7 +1164,7 @@ function parseBlockScannerArgs( imaState: any, joArg: any ) { return false; } -function parseJsonRpcServerArgs( imaState: any, joArg: any ) { +function parseJsonRpcServerArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "json-rpc-port" ) { owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nJsonRpcPort = owaspUtils.toInteger( joArg.value ); @@ -1172,7 +1173,7 @@ function parseJsonRpcServerArgs( imaState: any, joArg: any ) { return false; } -function parseCrossImaCommunicationArgs( imaState: any, joArg: any ) { +function parseCrossImaCommunicationArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "cross-ima" ) { imaState.isCrossImaBlsMode = true; return true; @@ -1184,7 +1185,7 @@ function parseCrossImaCommunicationArgs( imaState: any, joArg: any ) { return false; } -function parseShowConfigArgs( imaState: any, joArg: any ) { +function parseShowConfigArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "show-config" ) { imaState.bShowConfigMode = true; return true; @@ -1192,7 +1193,7 @@ function parseShowConfigArgs( imaState: any, joArg: any ) { return false; } -function parseOtherArgs( imaState: any, joArg: any ) { +function parseOtherArgs( imaState: state.TIMAState, joArg: any ) { if( joArg.name == "auto-exit" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaState.nAutoExitAfterSeconds = owaspUtils.toInteger( joArg.value ); @@ -1202,7 +1203,7 @@ function parseOtherArgs( imaState: any, joArg: any ) { } export function parse( joExternalHandlers: any, argv?: any[] ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); argv = argv || process.argv; const cntArgs = argv.length; for( let idxArg = 2; idxArg < cntArgs; ++idxArg ) { @@ -1315,7 +1316,7 @@ async function asyncCheckUrlAtStartup( u: URL | string, name: string ) { } function commonInitPrintSysInfo() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( isPrintGathered ) { log.debug( "This process {sunny} is {}", "versions", process.versions ); @@ -1360,7 +1361,7 @@ function commonInitPrintSysInfo() { } function commonInitCheckAbiPaths() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.strPathAbiJsonSkaleManager && ( typeof imaState.strPathAbiJsonSkaleManager == "string" ) && imaState.strPathAbiJsonSkaleManager.length > 0 @@ -1414,7 +1415,7 @@ function commonInitCheckAbiPaths() { } function commonInitCheckContractPresences() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.bHaveSkaleManagerABI ) { imaUtils.checkKeysExistInABI( "skale-manager", imaState.strPathAbiJsonSkaleManager, @@ -1513,7 +1514,7 @@ function commonInitCheckContractPresences() { } function commonInitPrintFoundContracts() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); // deposit_box_eth_address --> deposit_box_eth_abi // deposit_box_erc20_address --> deposit_box_erc20_abi @@ -1531,7 +1532,7 @@ function commonInitPrintFoundContracts() { // message_proxy_chain_address --> message_proxy_chain_abi const oct = function( - joContract?: owaspUtils.ethersMod.ethers.Contract ) { // optional contract address + joContract?: owaspUtils.ethersMod.ethers.Contract | null ) { // optional contract address if( joContract && "address" in joContract && joContract.address ) return log.fmtInformation( "{}", joContract.address ); return log.fmtError( "contract is not available" ); @@ -1617,7 +1618,7 @@ function commonInitPrintFoundContracts() { } function commonInitCheckErc20() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); let n1 = 0; let n2 = 0; @@ -1773,7 +1774,7 @@ function commonInitCheckErc20() { } function commonInitCheckErc721() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); let n1 = 0; let n2 = 0; @@ -1931,7 +1932,7 @@ function commonInitCheckErc721() { } function commonInitCheckErc1155() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); let n1 = 0; let n2 = 0; @@ -2090,7 +2091,7 @@ function commonInitCheckErc1155() { } function commonInitCheckGeneralArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); const isPrintSecurityValues = ( !!( imaState.isPrintSecurityValues ) ); if( isPrintGathered ) { @@ -2209,7 +2210,7 @@ function commonInitCheckGeneralArgs() { } function commonInitCheckCredentialsArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); const isPrintSecurityValues = ( !!( imaState.isPrintSecurityValues ) ); try { @@ -2260,7 +2261,7 @@ function commonInitCheckCredentialsArgs() { } function commonInitCheckTransferAmountArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( "Amount of wei to transfer", imaState.nAmountOfWei, @@ -2270,7 +2271,7 @@ function commonInitCheckTransferAmountArgs() { } function commonInitTransferringArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( "M->S transfer block size", imaState.nTransferBlockSizeM2S, @@ -2378,7 +2379,7 @@ function commonInitTransferringArgs() { } function commonInitCheckAccessArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( "S-Chain node number(zero based)", @@ -2393,7 +2394,7 @@ function commonInitCheckAccessArgs() { } function commonInitErcTokensArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { ensureHaveValue( @@ -2516,7 +2517,7 @@ function commonInitErcTokensArgs() { } function commonInitGasMultipliersAndTransactionArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( isPrintGathered ) { log.debug( log.fmtInformation( "Main Net Gas Price Multiplier is" ), @@ -2595,7 +2596,7 @@ function commonInitGasMultipliersAndTransactionArgs() { } function commonInitLoggingArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( imaState.strLogFilePath.length > 0 ) { ensureHaveValue( @@ -2620,7 +2621,7 @@ function commonInitLoggingArgs() { } function commonInitAutomaticExitArgs() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); const isPrintSecurityValues = ( !!( imaState.isPrintSecurityValues ) ); ensureHaveValue( @@ -2630,7 +2631,7 @@ function commonInitAutomaticExitArgs() { } export function commonInit() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); commonInitPrintSysInfo(); commonInitCheckAbiPaths(); commonInitCheckContractPresences(); @@ -2651,7 +2652,7 @@ export function commonInit() { } // commonInit export function imaInitEthersProviders() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.chainProperties.mn.strURL && typeof imaState.chainProperties.mn.strURL == "string" && imaState.chainProperties.mn.strURL.length > 0 @@ -2692,212 +2693,221 @@ export function imaInitEthersProviders() { } // imaInitEthersProviders function initContractsIMA() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.chainProperties.mn.bHaveAbiIMA ) { const cp = imaState.chainProperties.mn; - const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; - const joABI = cp.joAbiIMA; - imaState.joDepositBoxETH = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_eth_address, - joABI.deposit_box_eth_abi, - ep - ); // only main net - imaState.joDepositBoxERC20 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc20_address, - joABI.deposit_box_erc20_abi, - ep - ); // only main net - imaState.joDepositBoxERC721 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc721_address, - joABI.deposit_box_erc721_abi, - ep - ); // only main net - imaState.joDepositBoxERC1155 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc1155_address, - joABI.deposit_box_erc1155_abi, - ep ); - // only main net - imaState.joDepositBoxERC721WithMetadata = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc721_with_metadata_address, - joABI.deposit_box_erc721_with_metadata_abi, - ep - ); // only main net - imaState.joCommunityPool = - new owaspUtils.ethersMod.ethers.Contract( - joABI.community_pool_address, - joABI.community_pool_abi, - ep - ); // only main net - imaState.joLinker = - new owaspUtils.ethersMod.ethers.Contract( - joABI.linker_address, joABI.linker_abi, ep ); // only main net - imaState.joMessageProxyMainNet = - new owaspUtils.ethersMod.ethers.Contract( - joABI.message_proxy_mainnet_address, joABI.message_proxy_mainnet_abi, ep ); + if( cp.ethersProvider ) { + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; + const joABI = cp.joAbiIMA; + imaState.joDepositBoxETH = + new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_eth_address, + joABI.deposit_box_eth_abi, + ep + ); // only main net + imaState.joDepositBoxERC20 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc20_address, + joABI.deposit_box_erc20_abi, + ep + ); // only main net + imaState.joDepositBoxERC721 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc721_address, + joABI.deposit_box_erc721_abi, + ep + ); // only main net + imaState.joDepositBoxERC1155 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc1155_address, + joABI.deposit_box_erc1155_abi, + ep ); + // only main net + imaState.joDepositBoxERC721WithMetadata = + new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc721_with_metadata_address, + joABI.deposit_box_erc721_with_metadata_abi, + ep + ); // only main net + imaState.joCommunityPool = + new owaspUtils.ethersMod.ethers.Contract( + joABI.community_pool_address, + joABI.community_pool_abi, + ep + ); // only main net + imaState.joLinker = + new owaspUtils.ethersMod.ethers.Contract( + joABI.linker_address, joABI.linker_abi, ep ); // only main net + imaState.joMessageProxyMainNet = + new owaspUtils.ethersMod.ethers.Contract( + joABI.message_proxy_mainnet_address, joABI.message_proxy_mainnet_abi, ep ); + } } if( imaState.chainProperties.sc.bHaveAbiIMA ) { const cp = imaState.chainProperties.sc; - const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; - const joABI = cp.joAbiIMA; - imaState.joTokenManagerETH = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_eth_address, - joABI.token_manager_eth_abi, - ep ); // only s-chain - imaState.joTokenManagerERC20 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc20_address, - joABI.token_manager_erc20_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_address, - joABI.token_manager_erc721_abi, - ep ); // only s-chain - imaState.joTokenManagerERC1155 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc1155_address, - joABI.token_manager_erc1155_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721WithMetadata = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_with_metadata_address, - joABI.token_manager_erc721_with_metadata_abi, - ep ); // only s-chain - imaState.joCommunityLocker = - new owaspUtils.ethersMod.ethers.Contract( - joABI.community_locker_address, - joABI.community_locker_abi, - ep ); // only s-chain - imaState.joMessageProxySChain = - new owaspUtils.ethersMod.ethers.Contract( - joABI.message_proxy_chain_address, - joABI.message_proxy_chain_abi, - ep ); - imaState.joTokenManagerLinker = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_linker_address, - joABI.token_manager_linker_abi, - ep ); - imaState.joEthErc20 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.eth_erc20_address, - joABI.eth_erc20_abi, - ep ); // only s-chain + if( cp.ethersProvider ) { + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = + cp.ethersProvider; + const joABI = cp.joAbiIMA; + imaState.joTokenManagerETH = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_eth_address, + joABI.token_manager_eth_abi, + ep ); // only s-chain + imaState.joTokenManagerERC20 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc20_address, + joABI.token_manager_erc20_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_address, + joABI.token_manager_erc721_abi, + ep ); // only s-chain + imaState.joTokenManagerERC1155 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc1155_address, + joABI.token_manager_erc1155_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721WithMetadata = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_with_metadata_address, + joABI.token_manager_erc721_with_metadata_abi, + ep ); // only s-chain + imaState.joCommunityLocker = + new owaspUtils.ethersMod.ethers.Contract( + joABI.community_locker_address, + joABI.community_locker_abi, + ep ); // only s-chain + imaState.joMessageProxySChain = + new owaspUtils.ethersMod.ethers.Contract( + joABI.message_proxy_chain_address, + joABI.message_proxy_chain_abi, + ep ); + imaState.joTokenManagerLinker = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_linker_address, + joABI.token_manager_linker_abi, + ep ); + imaState.joEthErc20 = + new owaspUtils.ethersMod.ethers.Contract( + joABI.eth_erc20_address, + joABI.eth_erc20_abi, + ep ); // only s-chain + } } if( imaState.chainProperties.tc.bHaveAbiIMA ) { const cp = imaState.chainProperties.tc; - const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; - const joABI = cp.joAbiIMA; - imaState.joTokenManagerETHTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_eth_address, - joABI.token_manager_eth_abi, - ep ); // only s-chain - imaState.joTokenManagerERC20Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc20_address, - joABI.token_manager_erc20_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_address, - joABI.token_manager_erc721_abi, - ep ); // only s-chain - imaState.joTokenManagerERC1155Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc1155_address, - joABI.token_manager_erc1155_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721WithMetadataTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_with_metadata_address, - joABI.token_manager_erc721_with_metadata_abi, - ep ); // only s-chain - imaState.joCommunityLockerTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.community_locker_address, - joABI.community_locker_abi, - ep ); // only s-chain - imaState.joMessageProxySChainTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.message_proxy_chain_address, - joABI.message_proxy_chain_abi, - ep ); - imaState.joTokenManagerLinkerTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_linker_address, - joABI.token_manager_linker_abi, - ep ); - imaState.joEthErc20Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.eth_erc20_address, - joABI.eth_erc20_abi, - ep ); // only s-chain + if( cp.ethersProvider ) { + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; + const joABI = cp.joAbiIMA; + imaState.joTokenManagerETHTarget = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_eth_address, + joABI.token_manager_eth_abi, + ep ); // only s-chain + imaState.joTokenManagerERC20Target = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc20_address, + joABI.token_manager_erc20_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721Target = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_address, + joABI.token_manager_erc721_abi, + ep ); // only s-chain + imaState.joTokenManagerERC1155Target = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc1155_address, + joABI.token_manager_erc1155_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721WithMetadataTarget = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_with_metadata_address, + joABI.token_manager_erc721_with_metadata_abi, + ep ); // only s-chain + imaState.joCommunityLockerTarget = + new owaspUtils.ethersMod.ethers.Contract( + joABI.community_locker_address, + joABI.community_locker_abi, + ep ); // only s-chain + imaState.joMessageProxySChainTarget = + new owaspUtils.ethersMod.ethers.Contract( + joABI.message_proxy_chain_address, + joABI.message_proxy_chain_abi, + ep ); + imaState.joTokenManagerLinkerTarget = + new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_linker_address, + joABI.token_manager_linker_abi, + ep ); + imaState.joEthErc20Target = + new owaspUtils.ethersMod.ethers.Contract( + joABI.eth_erc20_address, + joABI.eth_erc20_abi, + ep ); // only s-chain + } } } function initContractsSkaleManager() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.bHaveSkaleManagerABI ) { const cp = imaState.chainProperties.mn; - const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; - const joABI = imaState.joAbiSkaleManager; - imaState.joConstantsHolder = - new owaspUtils.ethersMod.ethers.Contract( - joABI.constants_holder_address, - joABI.constants_holder_abi, - ep ); - imaState.joNodes = - new owaspUtils.ethersMod.ethers.Contract( - joABI.nodes_address, - joABI.nodes_abi, - ep ); - imaState.joKeyStorage = - new owaspUtils.ethersMod.ethers.Contract( - joABI.key_storage_address, - joABI.key_storage_abi, - ep ); - imaState.joSChains = - new owaspUtils.ethersMod.ethers.Contract( - joABI.schains_address, - joABI.schains_abi, - ep ); - imaState.joSChainsInternal = - new owaspUtils.ethersMod.ethers.Contract( - joABI.schains_internal_address, - joABI.schains_internal_abi, - ep ); - imaState.joSkaleDKG = - new owaspUtils.ethersMod.ethers.Contract( - joABI.skale_d_k_g_address, - joABI.skale_d_k_g_abi, - ep ); - imaState.joSkaleManager = - new owaspUtils.ethersMod.ethers.Contract( - joABI.skale_manager_address, - joABI.skale_manager_abi, - ep ); - imaState.joSkaleToken = - new owaspUtils.ethersMod.ethers.Contract( - joABI.skale_token_address, - joABI.skale_token_abi, - ep ); - imaState.joValidatorService = - new owaspUtils.ethersMod.ethers.Contract( - joABI.validator_service_address, - joABI.validator_service_abi, - ep ); - imaState.joWallets = - new owaspUtils.ethersMod.ethers.Contract( - joABI.wallets_address, - joABI.wallets_abi, - ep ); + if( cp.ethersProvider ) { + const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; + const joABI = imaState.joAbiSkaleManager; + imaState.joConstantsHolder = + new owaspUtils.ethersMod.ethers.Contract( + joABI.constants_holder_address, + joABI.constants_holder_abi, + ep ); + imaState.joNodes = + new owaspUtils.ethersMod.ethers.Contract( + joABI.nodes_address, + joABI.nodes_abi, + ep ); + imaState.joKeyStorage = + new owaspUtils.ethersMod.ethers.Contract( + joABI.key_storage_address, + joABI.key_storage_abi, + ep ); + imaState.joSChains = + new owaspUtils.ethersMod.ethers.Contract( + joABI.schains_address, + joABI.schains_abi, + ep ); + imaState.joSChainsInternal = + new owaspUtils.ethersMod.ethers.Contract( + joABI.schains_internal_address, + joABI.schains_internal_abi, + ep ); + imaState.joSkaleDKG = + new owaspUtils.ethersMod.ethers.Contract( + joABI.skale_d_k_g_address, + joABI.skale_d_k_g_abi, + ep ); + imaState.joSkaleManager = + new owaspUtils.ethersMod.ethers.Contract( + joABI.skale_manager_address, + joABI.skale_manager_abi, + ep ); + imaState.joSkaleToken = + new owaspUtils.ethersMod.ethers.Contract( + joABI.skale_token_address, + joABI.skale_token_abi, + ep ); + imaState.joValidatorService = + new owaspUtils.ethersMod.ethers.Contract( + joABI.validator_service_address, + joABI.validator_service_abi, + ep ); + imaState.joWallets = + new owaspUtils.ethersMod.ethers.Contract( + joABI.wallets_address, + joABI.wallets_abi, + ep ); + } } } diff --git a/src/clpTools.ts b/src/clpTools.ts index f7cc8903..c76e8291 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -61,10 +61,12 @@ const gInfoRegistrationCost: any = { }; export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaCLI.initContracts(); const strLogPrefix = "Reg 1: "; log.information( "{p}Will check chain registration now...", strLogPrefix ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); let bSuccess = await imaReg.checkIsRegisteredSChainInDepositBoxes( // step 1 imaState.chainProperties.mn.ethersProvider, imaState.joLinker, @@ -88,7 +90,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) imaState.joCommunityLocker, // only s-chain imaState.joTokenManagerLinker, // only s-chain imaState.chainProperties.sc.strChainName, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.transactionCustomizer //, ); bSuccess = ( jarrReceipts != null && jarrReceipts.length > 0 ) ? true : false; @@ -110,8 +112,10 @@ export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) } export async function checkRegistrationStep1() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaCLI.initContracts(); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); const bRetVal = await imaReg.checkIsRegisteredSChainInDepositBoxes( // step 1 imaState.chainProperties.mn.ethersProvider, imaState.joLinker, @@ -131,7 +135,7 @@ export function printSummaryRegistrationCosts( details?: any ) { } export function commandLineTaskRegister() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Full registration(all steps)", fn: async function() { @@ -143,7 +147,7 @@ export function commandLineTaskRegister() { } export function commandLineTaskRegister1() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Registration step 1, register S-Chain in deposit box", fn: async function() { @@ -155,7 +159,7 @@ export function commandLineTaskRegister1() { } export function commandLineTaskCheckRegistration() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Full registration status check(all steps)", fn: async function() { @@ -171,7 +175,7 @@ export function commandLineTaskCheckRegistration() { } export function commandLineTaskCheckRegistration1() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Registration status check step 1, register S-Chain in deposit box", fn: async function() { @@ -187,7 +191,7 @@ export function commandLineTaskCheckRegistration1() { } export function commandLineTaskMintErc20() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "mint ERC20", fn: async function() { @@ -196,10 +200,12 @@ export function commandLineTaskMintErc20() { try { const strAddressMintTo = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); + if( ! imaState.chainProperties.tc.ethersProvider ) + throw new Error( "No provider for target chain" ); bMintIsOK = await imaToken.mintErc20( imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, imaState.chainProperties.tc.joAccount, strAddressMintTo, @@ -220,7 +226,7 @@ export function commandLineTaskMintErc20() { } export function commandLineTaskMintErc721() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "mint ERC721", fn: async function() { @@ -229,16 +235,20 @@ export function commandLineTaskMintErc721() { try { const strAddressMintTo = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); - const idTokens = imaState.haveArrayOfTokenIdentifiers ? imaState.idTokens : []; + const idTokens: any[] = + ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) + ? imaState.idTokens : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { for( let i = 0; i < idTokens.length; ++ i ) { const idToken = idTokens[i]; + if( ! imaState.chainProperties.tc.ethersProvider ) + throw new Error( "No provider for target chain" ); bMintIsOK = await imaToken.mintErc721( imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, imaState.chainProperties.tc.joAccount, strAddressMintTo, @@ -261,7 +271,7 @@ export function commandLineTaskMintErc721() { } export function commandLineTaskMintErc1155() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "mint ERC1155", fn: async function() { @@ -270,16 +280,20 @@ export function commandLineTaskMintErc1155() { try { const strAddressMintTo = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); - const idTokens = imaState.haveArrayOfTokenIdentifiers ? imaState.idTokens : []; + const idTokens: any[] = + ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) + ? imaState.idTokens : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { for( let i = 0; i < idTokens.length; ++ i ) { const idToken = idTokens[i]; + if( ! imaState.chainProperties.tc.ethersProvider ) + throw new Error( "No provider for target chain" ); bMintIsOK = await imaToken.mintErc1155( imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, imaState.chainProperties.tc.joAccount, strAddressMintTo, @@ -305,7 +319,7 @@ export function commandLineTaskMintErc1155() { } export function commandLineTaskBurnErc20() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "burn ERC20", fn: async function() { @@ -314,10 +328,12 @@ export function commandLineTaskBurnErc20() { try { const strAddressBurnFrom = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); + if( ! imaState.chainProperties.tc.ethersProvider ) + throw new Error( "No provider for target chain" ); bBurnIsOK = await imaToken.burnErc20( imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, imaState.chainProperties.tc.joAccount, strAddressBurnFrom, @@ -340,23 +356,27 @@ export function commandLineTaskBurnErc20() { } export function commandLineTaskBurnErc721() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "burn ERC721", fn: async function() { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc721.length > 0 ) { try { - const idTokens = imaState.haveArrayOfTokenIdentifiers ? imaState.idTokens : []; + const idTokens: any[] = + ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) + ? imaState.idTokens : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { for( let i = 0; i < idTokens.length; ++ i ) { const idToken = idTokens[i]; + if( ! imaState.chainProperties.tc.ethersProvider ) + throw new Error( "No provider for target chain" ); bBurnIsOK = await imaToken.burnErc721( imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, imaState.chainProperties.tc.joAccount, idToken, @@ -364,7 +384,7 @@ export function commandLineTaskBurnErc721() { .joErc721[imaState.chainProperties .tc.strCoinNameErc721 + "_address"], imaState.chainProperties.tc - .oErc721[imaState.chainProperties + .joErc721[imaState.chainProperties .tc.strCoinNameErc721 + "_abi"], imaState.chainProperties.tc.transactionCustomizer ) ? true : false; @@ -380,7 +400,7 @@ export function commandLineTaskBurnErc721() { } export function commandLineTaskBurnErc1155() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "burn ERC1155", fn: async function() { @@ -389,16 +409,20 @@ export function commandLineTaskBurnErc1155() { try { const strAddressBurnFrom = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); - const idTokens = imaState.haveArrayOfTokenIdentifiers ? imaState.idTokens : []; + const idTokens: any[] = + ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) + ? imaState.idTokens : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { for( let i = 0; i < idTokens.length; ++ i ) { const idToken = idTokens[i]; + if( ! imaState.chainProperties.tc.ethersProvider ) + throw new Error( "No provider for target chain" ); bBurnIsOK = await imaToken.burnErc1155( imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, imaState.chainProperties.tc.joAccount, strAddressBurnFrom, @@ -426,15 +450,18 @@ export function commandLineTaskBurnErc1155() { export async function commandLineTaskShowBalanceEth( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[] ) { - const imaState = state.get(); - let assetAddress = null; + const imaState: state.TIMAState = state.get(); + let assetAddress: string | null = null; if( imaState.chainProperties.mn.ethersProvider ) { arrBalancesMN.push( { assetName: "RealETH", balance: await imaEth.getBalanceEth( true, // isMainNet imaState.chainProperties.mn.ethersProvider, - imaState.chainProperties.mn.chainId, imaState.chainProperties.mn.joAccount ) + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.mn.joAccount ) } ); + if( ! imaState.joDepositBoxETH ) + throw new Error( "No DepositBoxETH contract" ); arrBalancesMN.push( { assetName: "CanReceiveETH", balance: await imaEth.viewEthPaymentFromSchainOnMainNet( @@ -443,7 +470,7 @@ export async function commandLineTaskShowBalanceEth( } ); } try { - assetAddress = imaState.joEthErc20.address; + assetAddress = imaState.joEthErc20 ? imaState.joEthErc20.address : ""; } catch ( err ) { assetAddress = null; } @@ -452,14 +479,16 @@ export async function commandLineTaskShowBalanceEth( assetName: "S-Chain Real ETH as ERC20", assetAddress, balance: await imaEth.getBalanceEth( false, // isMainNet - imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.ethersProvider, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.joEthErc20 ) } ); arrBalancesSC.push( { assetName: "S-Chain ETH Fuel", balance: await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.sc.chainId, imaState.chainProperties.sc.joAccount ) + imaState.chainProperties.sc.chainId.toString(), + imaState.chainProperties.sc.joAccount ) } ); } if( imaState.chainProperties.tc.ethersProvider ) { @@ -467,14 +496,16 @@ export async function commandLineTaskShowBalanceEth( assetName: "Target S-Chain Real ETH as ERC20", assetAddress, balance: await imaEth.getBalanceEth( false, // isMainNet - imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.sc.chainId, + imaState.chainProperties.tc.ethersProvider, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.tc.joAccount, imaState.joEthErc20 ) } ); arrBalancesTC.push( { assetName: "Target S-Chain ETH Fuel", balance: await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, imaState.chainProperties.tc.joAccount ) + imaState.chainProperties.tc.chainId.toString(), + imaState.chainProperties.tc.joAccount ) } ); } } @@ -482,7 +513,7 @@ export async function commandLineTaskShowBalanceEth( export async function commandLineTaskShowBalanceErc20( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[] ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider && imaState.chainProperties.mn.strCoinNameErc20.length > 0 @@ -495,7 +526,8 @@ export async function commandLineTaskShowBalanceErc20( assetName: "ERC20", assetAddress, balance: await imaToken.getBalanceErc20( true, // isMainNet - imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.ethersProvider, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.mn.strCoinNameErc20, imaState.chainProperties.mn.joErc20 ) @@ -512,7 +544,8 @@ export async function commandLineTaskShowBalanceErc20( assetName: "ERC20", assetAddress, balance: await imaToken.getBalanceErc20( false, // isMainNet - imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.ethersProvider, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strCoinNameErc20, imaState.chainProperties.sc.joErc20 ) @@ -529,7 +562,8 @@ export async function commandLineTaskShowBalanceErc20( assetName: "ERC20", assetAddress, balance: await imaToken.getBalanceErc20( true, // isMainNet - imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.mn.chainId, + imaState.chainProperties.tc.ethersProvider, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.tc.joAccount, imaState.chainProperties.tc.strCoinNameErc20, imaState.chainProperties.tc.joErc20 ) @@ -540,7 +574,7 @@ export async function commandLineTaskShowBalanceErc20( export async function commandLineTaskShowBalanceErc721( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[], idTokens: any[] ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider && imaState.chainProperties.mn.strCoinNameErc721.length > 0 @@ -557,7 +591,7 @@ export async function commandLineTaskShowBalanceErc721( idToken, owner: await imaToken.getOwnerOfErc721( true, // isMainNet imaState.chainProperties.mn.ethersProvider, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.mn.strCoinNameErc721, imaState.chainProperties.mn.joErc721, idToken ) @@ -579,7 +613,7 @@ export async function commandLineTaskShowBalanceErc721( idToken, owner: await imaToken.getOwnerOfErc721( false, // isMainNet imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strCoinNameErc721, imaState.chainProperties.sc.joErc721, idToken ) @@ -601,7 +635,7 @@ export async function commandLineTaskShowBalanceErc721( idToken, owner: await imaToken.getOwnerOfErc721( false, // isMainNet imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.joAccount, imaState.chainProperties.tc.strCoinNameErc721, imaState.chainProperties.tc.joErc721, idToken ) @@ -613,7 +647,7 @@ export async function commandLineTaskShowBalanceErc721( export async function commandLineTaskShowBalanceErc1155( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[], idTokens: any[] ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider && imaState.chainProperties.mn.strCoinNameErc1155.length > 0 @@ -630,7 +664,7 @@ export async function commandLineTaskShowBalanceErc1155( idToken, balance: await imaToken.getBalanceErc1155( true, // isMainNet imaState.chainProperties.mn.ethersProvider, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.mn.strCoinNameErc1155, imaState.chainProperties.mn.joErc1155, idToken ) @@ -652,7 +686,7 @@ export async function commandLineTaskShowBalanceErc1155( idToken, balance: await imaToken.getBalanceErc1155( false, // isMainNet imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strCoinNameErc1155, imaState.chainProperties.sc.joErc1155, idToken ) @@ -674,7 +708,7 @@ export async function commandLineTaskShowBalanceErc1155( idToken, balance: await imaToken.getBalanceErc1155( false, // isMainNet imaState.chainProperties.tc.ethersProvider, - imaState.chainProperties.tc.chainId, + imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.joAccount, imaState.chainProperties.tc.strCoinNameErc1155, imaState.chainProperties.tc.joErc1155, idToken ) @@ -684,7 +718,7 @@ export async function commandLineTaskShowBalanceErc1155( } export function commandLineTaskShowBalance() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "show balance", fn: async function() { @@ -694,7 +728,9 @@ export function commandLineTaskShowBalance() { arrBalancesMN, arrBalancesSC, arrBalancesTC ); await commandLineTaskShowBalanceErc20( arrBalancesMN, arrBalancesSC, arrBalancesTC ); - const idTokens = imaState.haveArrayOfTokenIdentifiers ? imaState.idTokens : []; + const idTokens: any[] = + ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) + ? imaState.idTokens : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { @@ -742,30 +778,42 @@ export function commandLineTaskShowBalance() { } export function commandLineTaskPaymentM2S() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "one M->S single payment", fn: async function() { if( imaState.chainProperties.mn.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one M->S single ERC721 payment: {}", imaState.idToken ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + const joDepositBoxERC721 = imaState.isWithMetadata721 + ? imaState.joDepositBoxERC721WithMetadata + : imaState.joDepositBoxERC721; + if( ! joDepositBoxERC721 ) + throw new Error( "No DepositBoxERC721 contract" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + const joTokenManagerERC721 = imaState.isWithMetadata721 + ? imaState.joTokenManagerERC721WithMetadata + : imaState.joTokenManagerERC721; + if( ! joTokenManagerERC721 ) + throw new Error( "No TokenManagerERC721 contract" ); return await imaToken.doErc721PaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.sc.joAccount, - imaState.isWithMetadata721 - ? imaState.joDepositBoxERC721WithMetadata - : imaState.joDepositBoxERC721, // only main net + joDepositBoxERC721, // only main net imaState.joMessageProxyMainNet, // for checking logs imaState.chainProperties.sc.strChainName, imaState.idToken, // which ERC721 token id to send imaState.nAmountOfWei, // how much to send - imaState.isWithMetadata721 - ? imaState.joTokenManagerERC721WithMetadata - : imaState.joTokenManagerERC721, // only s-chain + joTokenManagerERC721, // only s-chain imaState.chainProperties.mn.strCoinNameErc721, imaState.chainProperties.mn.joErc721, imaState.chainProperties.sc.strCoinNameErc721, @@ -776,11 +824,21 @@ export function commandLineTaskPaymentM2S() { if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { // ERC20 payment log.information( "one M->S single ERC20 payment: {}", imaState.nAmountOfToken ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joDepositBoxERC20 ) + throw new Error( "No DepositBoxERC20 contract" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joTokenManagerERC20 ) + throw new Error( "No TokenManagerERC20 contract" ); return await imaToken.doErc20PaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.sc.joAccount, imaState.joDepositBoxERC20, // only main net @@ -796,29 +854,34 @@ export function commandLineTaskPaymentM2S() { imaState.chainProperties.mn.transactionCustomizer ); } - if( - imaState.chainProperties.mn.strCoinNameErc1155.length > 0 && - imaState.idToken && - imaState.idToken !== null && + if( imaState.chainProperties.mn.strCoinNameErc1155.length > 0 && + imaState.idToken && imaState.idToken !== null && imaState.idToken !== undefined && - imaState.nAmountOfToken && - imaState.nAmountOfToken !== null && + imaState.nAmountOfToken && imaState.nAmountOfToken !== null && imaState.nAmountOfToken !== undefined && - ( ( !imaState.idTokens ) || - imaState.idTokens === null || + ( ( !imaState.idTokens ) || imaState.idTokens === null || imaState.idTokens === undefined ) && - ( ( !imaState.arrAmountsOfTokens ) || - imaState.arrAmountsOfTokens === null || + ( ( !imaState.arrAmountsOfTokens ) || imaState.arrAmountsOfTokens === null || imaState.arrAmountsOfTokens === undefined ) ) { // ERC1155 payment log.information( "one M->S single ERC1155 payment: {} {}", imaState.idToken, imaState.nAmountOfToken ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joDepositBoxERC1155 ) + throw new Error( "No DepositBoxERC1155 contract" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joTokenManagerERC1155 ) + throw new Error( "No TokenManagerERC1155 contract" ); return await imaToken.doErc1155PaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.sc.joAccount, imaState.joDepositBoxERC1155, // only main net @@ -853,11 +916,21 @@ export function commandLineTaskPaymentM2S() { // ERC1155 Batch payment log.information( "one M->S single ERC1155 Batch payment: {} {}", imaState.idTokens, imaState.arrAmountsOfTokens ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joDepositBoxERC1155 ) + throw new Error( "No DepositBoxERC1155 contract" ); + if( ! imaState.joTokenManagerERC1155 ) + throw new Error( "No TokenManagerERC1155 contract" ); return await imaToken.doErc1155BatchPaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.sc.joAccount, imaState.joDepositBoxERC1155, // only main net @@ -876,9 +949,15 @@ export function commandLineTaskPaymentM2S() { } // ETH payment log.information( "one M->S single ETH payment: {}", imaState.nAmountOfWei ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joDepositBoxETH ) + throw new Error( "No DepositBoxETH contract" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); return await imaEth.doEthPaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.chainProperties.sc.joAccount, imaState.joDepositBoxETH, // only main net @@ -892,27 +971,41 @@ export function commandLineTaskPaymentM2S() { } export function commandLineTaskPaymentS2M() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "one S->M single payment", fn: async function() { if( imaState.chainProperties.sc.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one S->M single ERC721 payment: {}", imaState.idToken ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + const joTokenManagerERC721 = imaState.isWithMetadata721 + ? imaState.joTokenManagerERC721WithMetadata + : imaState.joTokenManagerERC721; + if( ! joTokenManagerERC721 ) + throw new Error( "No TokenManagerERC721 contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No oMessageProxySChain contract" ); + const joDepositBoxERC721 = imaState.isWithMetadata721 + ? imaState.joDepositBoxERC721WithMetadata + : imaState.joDepositBoxERC721; + if( ! joTokenManagerERC721 ) + throw new Error( "No DepositBoxERC721 contract" ); + if( ! joDepositBoxERC721 ) + throw new Error( "No DepositBoxERC721 contract" ); return await imaToken.doErc721PaymentFromSChain( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.joAccount, - imaState.isWithMetadata721 - ? imaState.joTokenManagerERC721WithMetadata - : imaState.joTokenManagerERC721, // only s-chain + joTokenManagerERC721, // only s-chain imaState.joMessageProxySChain, // for checking logs - imaState.isWithMetadata721 - ? imaState.joDepositBoxERC721WithMetadata - : imaState.joDepositBoxERC721, // only main net + joDepositBoxERC721, // only main net imaState.idToken, // which ERC721 token id to send imaState.nAmountOfWei, // how much to send imaState.chainProperties.mn.strCoinNameErc721, @@ -925,11 +1018,21 @@ export function commandLineTaskPaymentS2M() { if( imaState.chainProperties.sc.strCoinNameErc20.length > 0 ) { // ERC20 payment log.information( "one S->M single ERC20 payment: {}", imaState.nAmountOfToken ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joTokenManagerERC20 ) + throw new Error( "No TokenManagerERC20 contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); + if( ! imaState.joDepositBoxERC20 ) + throw new Error( "No DepositBoxERC20 contract" ); return await imaToken.doErc20PaymentFromSChain( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.joAccount, imaState.joTokenManagerERC20, // only s-chain @@ -962,11 +1065,21 @@ export function commandLineTaskPaymentS2M() { // ERC1155 payment log.information( "one S->M single ERC1155 payment: {} {}", imaState.idToken, imaState.nAmountOfToken ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joTokenManagerERC1155 ) + throw new Error( "No TokenManagerERC1155 contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); + if( ! imaState.joDepositBoxERC1155 ) + throw new Error( "No DepositBoxERC1155 contract" ); return await imaToken.doErc1155PaymentFromSChain( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.joAccount, imaState.joTokenManagerERC1155, // only s-chain @@ -1000,11 +1113,21 @@ export function commandLineTaskPaymentS2M() { // ERC1155 payment log.information( "one S->M single ERC1155 payment: {} {}", imaState.idTokens, imaState.arrAmountsOfTokens ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joTokenManagerERC1155 ) + throw new Error( "No TokenManagerERC1155 contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); + if( ! imaState.joDepositBoxERC1155 ) + throw new Error( "No DepositBoxERC1155 contract" ); return await imaToken.doErc1155BatchPaymentFromSChain( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.joAccount, imaState.joTokenManagerERC1155, // only s-chain @@ -1022,9 +1145,15 @@ export function commandLineTaskPaymentS2M() { } // ETH payment log.information( "one S->M single ETH payment: {}", imaState.nAmountOfWei ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joTokenManagerETH ) + throw new Error( "No TokenManagerETH contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); return await imaEth.doEthPaymentFromSChain( imaState.chainProperties.sc.ethersProvider, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.joAccount, imaState.joTokenManagerETH, // only s-chain @@ -1037,19 +1166,19 @@ export function commandLineTaskPaymentS2M() { } export function commandLineTaskPaymentS2S() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "one S->S single payment", fn: async function() { const isForward = imaHelperAPIs.isForwardS2S(); const sc = imaState.chainProperties.sc; const tc = imaState.chainProperties.tc; - const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = + const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = isForward ? sc.ethersProvider : tc.ethersProvider; const chainIdSrc = isForward ? sc.chainId : tc.chainId; const joAccountSrc = isForward ? sc.joAccount : tc.joAccount; - const joTokenManagerERC20Src: owaspUtils.ethersMod.ethers.Contract = isForward + const joTokenManagerERC20Src: owaspUtils.ethersMod.ethers.Contract | null = isForward ? imaState.joTokenManagerERC20 : imaState.joTokenManagerERC20Target; - const joTokenManagerERC721Src: owaspUtils.ethersMod.ethers.Contract = isForward + const joTokenManagerERC721Src: owaspUtils.ethersMod.ethers.Contract | null = isForward ? ( imaState.isWithMetadata721 ? imaState.joTokenManagerERC721WithMetadata : imaState.joTokenManagerERC721 ) @@ -1057,7 +1186,7 @@ export function commandLineTaskPaymentS2S() { ? imaState.joTokenManagerERC721WithMetadataTarget : imaState.joTokenManagerERC721Target ); - const joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract = isForward + const joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract | null = isForward ? imaState.joTokenManagerERC1155 : imaState.joTokenManagerERC1155Target; const strChainNameDst = isForward ? tc.strChainName : sc.strChainName; const strCoinNameErc20Src = isForward ? sc.strCoinNameErc20 : tc.strCoinNameErc20; @@ -1096,10 +1225,14 @@ export function commandLineTaskPaymentS2S() { if( strCoinNameErc721Src.length > 0 ) { // ERC721 payment log.information( "one S->S single ERC721 payment: {}", imaState.idToken ); + if( ! ethersProviderSrc ) + throw new Error( "No S2S source provider" ); + if( ! joTokenManagerERC721Src ) + throw new Error( "No S2S source TokenManagerERC721 contract" ); return await imaToken.doErc721PaymentS2S( isForward, ethersProviderSrc, - chainIdSrc, + chainIdSrc.toString(), strChainNameDst, joAccountSrc, joTokenManagerERC721Src, @@ -1114,10 +1247,14 @@ export function commandLineTaskPaymentS2S() { if( strCoinNameErc20Src.length > 0 ) { // ERC20 payment log.information( "one S->S single ERC20 payment: {}", imaState.nAmountOfToken ); + if( ! ethersProviderSrc ) + throw new Error( "No S2S source provider" ); + if( ! joTokenManagerERC20Src ) + throw new Error( "No S2S source TokenManagerERC20Src contract" ); return await imaToken.doErc20PaymentS2S( isForward, ethersProviderSrc, - chainIdSrc, + chainIdSrc.toString(), strChainNameDst, joAccountSrc, joTokenManagerERC20Src, @@ -1147,10 +1284,14 @@ export function commandLineTaskPaymentS2S() { // ERC1155 payment log.information( "one S->S single ERC1155 payment: {} {}", imaState.idToken, imaState.nAmountOfToken ); + if( ! ethersProviderSrc ) + throw new Error( "No S2S source provider" ); + if( ! joTokenManagerERC1155Src ) + throw new Error( "No S2S source joTokenManagerERC1155 contract" ); return await imaToken.doErc1155PaymentS2S( isForward, ethersProviderSrc, - chainIdSrc, + chainIdSrc.toString(), strChainNameDst, joAccountSrc, joTokenManagerERC1155Src, @@ -1181,10 +1322,14 @@ export function commandLineTaskPaymentS2S() { // ERC1155 Batch payment log.information( "one S->S single ERC1155 Batch payment: {} {}", imaState.idTokens, imaState.arrAmountsOfTokens ); + if( ! ethersProviderSrc ) + throw new Error( "No S2S source provider" ); + if( ! joTokenManagerERC1155Src ) + throw new Error( "No S2S source joTokenManagerERC1155 contract" ); return await imaToken.doErc1155BatchPaymentS2S( isForward, ethersProviderSrc, - chainIdSrc, + chainIdSrc.toString(), strChainNameDst, joAccountSrc, joTokenManagerERC1155Src, @@ -1206,14 +1351,18 @@ export function commandLineTaskPaymentS2S() { } export function commandLineTaskReceiveS2M() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "receive one S->M single ETH payment", fn: async function() { log.information( "receive one S->M single ETH payment:" ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joDepositBoxETH ) + throw new Error( "No DepositBoxETH contract" ); return await imaEth.receiveEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.joAccount, imaState.joDepositBoxETH, imaState.chainProperties.mn.transactionCustomizer @@ -1223,11 +1372,16 @@ export function commandLineTaskReceiveS2M() { } export function commandLineTaskViewS2M() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "view one S->M single ETH payment", fn: async function() { log.information( "view one S->M single ETH payment:" ); + log.information( "receive one S->M single ETH payment:" ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joDepositBoxETH ) + throw new Error( "No DepositBoxETH contract" ); const xWei = await imaEth.viewEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.joAccount, @@ -1244,17 +1398,25 @@ export function commandLineTaskViewS2M() { } export function commandLineTaskTransferM2S() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "single M->S transfer loop", fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // main-net --> s-chain transfer - const joRuntimeOpts: any = { + const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); return await IMA.doTransfer( // main-net --> s-chain "M2S", joRuntimeOpts, @@ -1266,8 +1428,8 @@ export function commandLineTaskTransferM2S() { imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.strChainName, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), null, imaState.joTokenManagerETH, // for logs validation on s-chain imaState.nTransferBlockSizeM2S, @@ -1284,17 +1446,25 @@ export function commandLineTaskTransferM2S() { } export function commandLineTaskTransferS2M() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "single S->M transfer loop", fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer - const joRuntimeOpts: any = { + const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); return await IMA.doTransfer( // s-chain --> main-net "S2M", joRuntimeOpts, @@ -1306,8 +1476,8 @@ export function commandLineTaskTransferS2M() { imaState.chainProperties.mn.joAccount, imaState.chainProperties.sc.strChainName, imaState.chainProperties.mn.strChainName, - imaState.chainProperties.sc.chainId, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.sc.chainId.toString(), + imaState.chainProperties.mn.chainId.toString(), imaState.joDepositBoxETH, // for logs validation on mainnet null, imaState.nTransferBlockSizeS2M, @@ -1324,7 +1494,7 @@ export function commandLineTaskTransferS2M() { } export function commandLineTaskTransferS2S() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "single S->S transfer loop", fn: async function() { @@ -1332,11 +1502,17 @@ export function commandLineTaskTransferS2S() { return; if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer - const joRuntimeOpts: any = { + const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); + if( ! imaState.joTokenManagerETH ) + throw new Error( "No TokenManagerETH contract" ); return await IMA.doAllS2S( // s-chain --> s-chain joRuntimeOpts, imaState, @@ -1345,7 +1521,7 @@ export function commandLineTaskTransferS2S() { imaState.joMessageProxySChain, imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.chainId.toString(), imaState.joTokenManagerETH, // for logs validation on s-chain imaState.nTransferBlockSizeM2S, imaState.nTransferStepsS2S, @@ -1360,18 +1536,18 @@ export function commandLineTaskTransferS2S() { } export function commandLineTaskTransfer() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Single M<->S transfer loop iteration", fn: async function() { if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); - const joRuntimeOpts: any = { + const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - const optsLoop: any = { + const optsLoop: loop.TLoopOptions = { joRuntimeOpts, isDelayFirstRun: false, enableStepOracle: true, @@ -1385,7 +1561,7 @@ export function commandLineTaskTransfer() { } export function commandLineTaskLoop() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "M<->S and S->S transfer loop, startup in parallel mode", fn: async function() { @@ -1400,19 +1576,17 @@ export function commandLineTaskLoop() { } if( isPrintSummaryRegistrationCosts ) printSummaryRegistrationCosts(); - const opts: any = { + const opts: loop.TParallelLoopRunOptions = { imaState, details: log }; - return await loop.runParallelLoops( - opts - ); + return await loop.runParallelLoops( opts ); } } ); } export function commandLineTaskLoopSimple() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "M<->S and S->S transfer loop, startup simple mode", fn: async function() { @@ -1427,12 +1601,12 @@ export function commandLineTaskLoopSimple() { } if( isPrintSummaryRegistrationCosts ) printSummaryRegistrationCosts(); - const joRuntimeOpts: any = { + const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - const optsLoop: any = { + const optsLoop: loop.TLoopOptions = { joRuntimeOpts, isDelayFirstRun: false, enableStepOracle: true, @@ -1446,8 +1620,8 @@ export function commandLineTaskLoopSimple() { } async function handleBrowseSkaleModesRpcInfoResult( - strLogPrefix: string, joCall: any, joIn: any, joOut: any ) { - const imaState = state.get(); + strLogPrefix: string, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + const imaState: state.TIMAState = state.get(); log.information( "{p}S-Chain network information: {}", strLogPrefix, joOut.result ); let nCountReceivedImaDescriptions = 0; @@ -1460,8 +1634,8 @@ async function handleBrowseSkaleModesRpcInfoResult( continue; } const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); - const rpcCallOpts: any = null; - let joCall: any = null; + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; + let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) @@ -1491,7 +1665,7 @@ async function handleBrowseSkaleModesRpcInfoResult( } export function commandLineTaskBrowseSChain() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.bIsNeededCommonInit = false; imaState.arrActions.push( { name: "Browse S-Chain network", @@ -1502,8 +1676,8 @@ export function commandLineTaskBrowseSChain() { process.exit( 155 ); } log.information( "{p}Downloading S-Chain network information...", strLogPrefix ); - const rpcCallOpts: any = null; - let joCall: any = null; + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; + let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( imaState.chainProperties.sc.strURL, rpcCallOpts ); if( ! joCall ) { @@ -1527,16 +1701,20 @@ export function commandLineTaskBrowseSChain() { } export function commandLineTaskReimbursementShowBalance() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Show Balance", fn: async function() { + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joCommunityPool ) + throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementShowBalance( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, imaState.chainProperties.mn.joAccount.address(), imaState.chainProperties.mn.strChainName, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.transactionCustomizer, imaState.strReimbursementChain, true @@ -1547,16 +1725,20 @@ export function commandLineTaskReimbursementShowBalance() { } export function commandLineTaskReimbursementEstimateAmount() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Estimate Amount", fn: async function() { + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joCommunityPool ) + throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementEstimateAmount( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, imaState.chainProperties.mn.joAccount.address(), imaState.chainProperties.mn.strChainName, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.transactionCustomizer, imaState.strReimbursementChain, true @@ -1567,16 +1749,20 @@ export function commandLineTaskReimbursementEstimateAmount() { } export function commandLineTaskReimbursementRecharge() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Recharge User Wallet", fn: async function() { + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joCommunityPool ) + throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementWalletRecharge( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, imaState.chainProperties.mn.joAccount, imaState.chainProperties.mn.strChainName, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.transactionCustomizer, imaState.strReimbursementChain, imaState.nReimbursementRecharge @@ -1587,16 +1773,20 @@ export function commandLineTaskReimbursementRecharge() { } export function commandLineTaskReimbursementWithdraw() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Withdraw User Wallet", fn: async function() { + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.joCommunityPool ) + throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementWalletWithdraw( imaState.chainProperties.mn.ethersProvider, imaState.joCommunityPool, imaState.chainProperties.mn.joAccount, imaState.chainProperties.mn.strChainName, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.transactionCustomizer, imaState.strReimbursementChain, imaState.nReimbursementWithdraw @@ -1607,16 +1797,20 @@ export function commandLineTaskReimbursementWithdraw() { } export function commandLineTaskReimbursementSetRange() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Set Minimal time interval from S2M and S2S transfers", fn: async function() { + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joCommunityLocker ) + throw new Error( "No CommunityLocker contract" ); await imaReimbursement.reimbursementSetRange( imaState.chainProperties.sc.ethersProvider, imaState.joCommunityLocker, imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.chainId.toString(), imaState.chainProperties.sc.transactionCustomizer, imaState.strChainNameOriginChain, imaState.nReimbursementRange diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 80de8532..74a945c1 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -129,7 +129,7 @@ export function getSChainDiscoveredNodesCount( joSChainNetworkInfo: any ): numbe } export async function waitUntilSChainStarted() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); log.debug( "Checking S-Chain is accessible and sane..." ); if( ( !imaState.chainProperties.sc.strURL ) || imaState.chainProperties.sc.strURL.length === 0 @@ -207,7 +207,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole log.information( "Notice: long this S-Chain re-discovery is in progress now..." ); return; } - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); fnAfter = fnAfter || function() {}; gFlagIsInSChainDiscovery = true; const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); @@ -290,7 +290,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( if( gTimerSChainDiscovery != null ) return; fnAfter = fnAfter || function() {}; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.joSChainDiscovery.repeatIntervalMilliseconds <= 0 ) { if( ! isSilentReDiscovery ) log.information( "This S-Chain re-discovery will not be preformed" ); @@ -333,7 +333,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( function handleDiscoverSkaleImaInfoResult( optsDiscover: any, strNodeDescColorized: string, - joNode: any, joCall: any, joIn: any, joOut: any + joNode: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ): void { joNode.imaInfo = joOut.result; if( isSChainNodeFullyDiscovered( joNode ) ) @@ -373,8 +373,8 @@ async function discoverSChainWalkNodes( optsDiscover: any ) { } } } catch ( err ) { } - const rpcCallOpts: any = null; - let joCall: any = null; + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; + let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); if( ! joCall ) @@ -467,7 +467,7 @@ async function discoverSChainWait( optsDiscover: any ) { } async function handleDiscoverSkaleNodesRpcInfoResult( - optsDiscover: any, scURL: string, joCall: any, joIn: any, joOut: any ) { + optsDiscover: any, scURL: string, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { if( ! optsDiscover.isSilentReDiscovery ) { log.trace( "{p}OK, got (own) S-Chain network information: {}", optsDiscover.strLogPrefix, joOut.result ); @@ -559,10 +559,10 @@ export async function discoverSChainNetwork( optsDiscover.nCountToWait = 0; if( !optsDiscover.isSilentReDiscovery ) log.information( "{p}This S-Chain discovery will start...", optsDiscover.strLogPrefix ); - let joCall: any = null; + let joCall: rpcCall.TRPCCall | null = null; try { const scURL = optsDiscover.imaState.chainProperties.sc.strURL; - const rpcCallOpts: any = null; + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; joCall = await rpcCall.create( scURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${scURL}` ); @@ -600,7 +600,7 @@ function checkPeriodicDiscoveryNoLongerNeeded( joSChainNetworkInfo: any, isSilentReDiscovery: boolean ) { if( ! joSChainNetworkInfo ) return false; - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); const cntAlreadyDiscovered = getSChainDiscoveredNodesCount( joSChainNetworkInfo ); if( ! isSilentReDiscovery ) { @@ -622,7 +622,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( ) { if( gIntervalPeriodicDiscovery ) return; // already started - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); let joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; if( checkPeriodicDiscoveryNoLongerNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { diff --git a/src/imaCore.ts b/src/imaCore.ts index 970579bc..26e98209 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -36,6 +36,64 @@ import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; import * as skaleObserver from "./observer.js"; import * as threadInfo from "./threadInfo.js"; +export interface TTransferOptions { + strDirection: string + joRuntimeOpts: loop.TRuntimeOpts + ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider + joMessageProxySrc: owaspUtils.ethersMod.Contract + joAccountSrc: state.TAccount + ethersProviderDst: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider + joMessageProxyDst: owaspUtils.ethersMod.Contract + joAccountDst: state.TAccount + chainNameSrc: string + chainNameDst: string + chainIdSrc: string + chainIdDst: string + joDepositBoxMainNet: owaspUtils.ethersMod.Contract | null // for logs validation on mainnet + joTokenManagerSChain: owaspUtils.ethersMod.Contract | null // for logs validation on s-chain + nTransactionsCountInBlock: number + nTransferSteps: number + nMaxTransactionsCount: number + nBlockAwaitDepth: number + nBlockAge: number + fnSignMessages: any + joExtraSignOpts?: loop.TExtraSignOpts | null + transactionCustomizerDst: imaTx.TransactionCustomizer + imaState: state.TIMAState + nTransferLoopCounter: number + strTransferErrorCategoryName: string + strGatheredDetailsName: string + details: any + jarrReceipts: any[] + bErrorInSigningMessages: boolean + strLogPrefixShort: string + strLogPrefix: string + nStepsDone: number + strActionName: string + nIdxCurrentMsg: number + nOutMsgCnt: number + nIncMsgCnt: number + cntProcessed: number + arrMessageCounters: any[] + jarrMessages: any[] + nIdxCurrentMsgBlockStart: number + cntAccumulatedForBlock: number + arrLogRecordReferences: any[] + cntNodesShouldPass: number + cntNodesMayFail: number +} + +export interface TOutgoingMessageAnalysisOptions { + idxMessage: number + idxImaMessage: number + joMessage: any + joNode: any | null + idxNode: number + cntNodes: number + cntPassedNodes: number + cntFailedNodes: number +} + log.enableColorization( false ); log.addStdout(); @@ -154,7 +212,7 @@ let gTransferLoopCounter = 0; // [to] // address[] memory to // [amount] // uint256[] memory amount / *uint256[2] memory blsSignature* / // ) -async function doQueryOutgoingMessageCounter( optsTransfer: any ) { +async function doQueryOutgoingMessageCounter( optsTransfer: TTransferOptions ) { let nPossibleIntegerValue = 0; optsTransfer.details.debug( "{p}SRC MessageProxy address is.....{}", optsTransfer.strLogPrefixShort, optsTransfer.joMessageProxySrc.address ); @@ -262,7 +320,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer: any ) { return true; } -async function analyzeGatheredRecords( optsTransfer: any, r: any ) { +async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ) { let joValues: any = null; const strChainHashWeAreLookingFor = owaspUtils.ethersMod.ethers.utils.id( optsTransfer.chainNameDst ); @@ -307,7 +365,7 @@ async function analyzeGatheredRecords( optsTransfer: any, r: any ) { return joValues; } -async function gatherMessages( optsTransfer: any ) { +async function gatherMessages( optsTransfer: TTransferOptions ) { optsTransfer.arrMessageCounters = []; optsTransfer.jarrMessages = []; optsTransfer.nIdxCurrentMsgBlockStart = 0 + optsTransfer.nIdxCurrentMsg; @@ -456,7 +514,7 @@ async function gatherMessages( optsTransfer: any ) { } async function preCheckAllMessagesSign( - optsTransfer: any, err: Error | string, jarrMessages: any[], joGlueResult: any ) { + optsTransfer: TTransferOptions, err: Error | string, jarrMessages: any[], joGlueResult: any ) { const strDidInvokedSigningCallbackMessage = log.fmtDebug( "{p}Did invoked message signing callback, first real message index is: {}, have {} " + "message(s) to process {}", optsTransfer.strLogPrefix, @@ -481,7 +539,7 @@ async function preCheckAllMessagesSign( } async function callbackAllMessagesSign( - optsTransfer: any, err: Error | string, jarrMessages: any[], joGlueResult: any ) { + optsTransfer: TTransferOptions, err: Error | string, jarrMessages: any[], joGlueResult: any ) { if( ! await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) return; const nBlockSize = optsTransfer.arrMessageCounters.length; @@ -550,7 +608,7 @@ async function callbackAllMessagesSign( weiHowMuchPostIncomingMessages, null ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( optsTransfer.chainNameDst !== "Mainnet" ) ? true : false }; @@ -624,7 +682,7 @@ async function callbackAllMessagesSign( } } -async function handleAllMessagesSigning( optsTransfer: any ) { +async function handleAllMessagesSigning( optsTransfer: TTransferOptions ) { try { let strErrFinal: string = ""; await optsTransfer.fnSignMessages( optsTransfer.nTransferLoopCounter, @@ -655,7 +713,8 @@ async function handleAllMessagesSigning( optsTransfer: any ) { } async function checkOutgoingMessageEventInOneNode( - optsTransfer: any, optsOutgoingMessageAnalysis: any ) { + optsTransfer: TTransferOptions, + optsOutgoingMessageAnalysis: TOutgoingMessageAnalysisOptions ) { const sc = optsTransfer.imaState.chainProperties.sc; const strUrlHttp = optsOutgoingMessageAnalysis.joNode.endpoints.ip.http; optsTransfer.details.trace( @@ -742,7 +801,7 @@ async function checkOutgoingMessageEventInOneNode( return true; } -async function checkOutgoingMessageEvent( optsTransfer: any, joSChain: any ) { +async function checkOutgoingMessageEvent( optsTransfer: TTransferOptions, joSChain: any ) { const cntNodes = joSChain.nodes.length; const cntMessages = optsTransfer.jarrMessages.length; for( let idxMessage = 0; idxMessage < cntMessages; ++ idxMessage ) { @@ -752,7 +811,7 @@ async function checkOutgoingMessageEvent( optsTransfer: any, joSChain: any ) { "{p}{bright} message analysis for message {} of {} with IMA message index {} and " + "message envelope data: {}", optsTransfer.strLogPrefix, optsTransfer.strDirection, idxMessage + 1, cntMessages, idxImaMessage, joMessage ); - const optsOutgoingMessageAnalysis: any = { + const optsOutgoingMessageAnalysis: TOutgoingMessageAnalysisOptions = { idxMessage, idxImaMessage, joMessage, @@ -818,7 +877,7 @@ async function checkOutgoingMessageEvent( optsTransfer: any, joSChain: any ) { return true; } -async function doMainTransferLoopActions( optsTransfer: any ) { +async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { // classic scanner with optional usage of optimized IMA messages search algorithm // outer loop is block former/creator, then transfer optsTransfer.nIdxCurrentMsg = optsTransfer.nIncMsgCnt; @@ -925,11 +984,11 @@ async function doMainTransferLoopActions( optsTransfer: any ) { let gIsOneTransferInProgressInThisThread = false; export async function doTransfer( - strDirection: string, joRuntimeOpts: any, + strDirection: string, joRuntimeOpts: loop.TRuntimeOpts, ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joMessageProxySrc: owaspUtils.ethersMod.ethers.Contract, joAccountSrc: any, + joMessageProxySrc: owaspUtils.ethersMod.ethers.Contract, joAccountSrc: state.TAccount, ethersProviderDst: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joMessageProxyDst: owaspUtils.ethersMod.ethers.Contract, joAccountDst: any, + joMessageProxyDst: owaspUtils.ethersMod.ethers.Contract, joAccountDst: state.TAccount, chainNameSrc: string, chainNameDst: string, chainIdSrc: string, chainIdDst: string, joDepositBoxMainNet: owaspUtils.ethersMod.ethers.Contract | null, // for logs validation on mainnet @@ -938,10 +997,10 @@ export async function doTransfer( nTransactionsCountInBlock: number, nTransferSteps: number, nMaxTransactionsCount: number, nBlockAwaitDepth: number, nBlockAge: number, - fnSignMessages: any, joExtraSignOpts: any, + fnSignMessages: any, joExtraSignOpts: loop.TExtraSignOpts | null, transactionCustomizerDst: imaTx.TransactionCustomizer ) { - const optsTransfer: any = { + const optsTransfer: TTransferOptions = { strDirection, joRuntimeOpts, ethersProviderSrc, @@ -983,7 +1042,9 @@ export async function doTransfer( jarrMessages: [], nIdxCurrentMsgBlockStart: 0, cntAccumulatedForBlock: 0, - arrLogRecordReferences: [] + arrLogRecordReferences: [], + cntNodesShouldPass: 0, + cntNodesMayFail: 0 }; ++ gTransferLoopCounter; optsTransfer.strGatheredDetailsName = @@ -1016,7 +1077,7 @@ export async function doTransfer( optsTransfer.fnSignMessages = async function( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: any, fnAfter: any + joExtraSignOpts: loop.TExtraSignOpts, fnAfter: any ) { optsTransfer.details.debug( "{p}Message signing callback was not provided to IMA, first real message " + @@ -1090,12 +1151,12 @@ export async function doTransfer( } export async function doAllS2S( // s-chain --> s-chain - joRuntimeOpts: any, - imaState: any, + joRuntimeOpts: loop.TRuntimeOpts, + imaState: state.TIMAState, skaleObserver: any, ethersProviderDst: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joMessageProxyDst: owaspUtils.ethersMod.ethers.Contract, - joAccountDst: any, + joAccountDst: state.TAccount, chainNameDst: string, chainIdDst: string, joTokenManagerSChain: owaspUtils.ethersMod.ethers.Contract, // for logs validation on s-chain @@ -1144,7 +1205,7 @@ export async function doAllS2S( // s-chain --> s-chain sc.joAbiIMA.message_proxy_chain_address, sc.joAbiIMA.message_proxy_chain_abi, ethersProviderSrc ); - const joExtraSignOpts: any = { + const joExtraSignOpts: loop.TExtraSignOpts = { chainNameSrc, chainIdSrc, chainNameDst, diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index d9880c60..8e5ff089 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -30,12 +30,13 @@ import * as imaTx from "./imaTx.js"; import * as imaGasUsage from "./imaGasUsageOperations.js"; import * as imaEventLogScan from "./imaEventLogScan.js"; import * as threadInfo from "./threadInfo.js"; +import type * as state from "./state.js"; export async function getBalanceEth( isMainNet: boolean, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null, chainId: string, - joAccount?: any, + joAccount?: state.TAccount, contractERC20?: any ) { const strLogPrefix = "getBalanceEth() call "; @@ -69,8 +70,8 @@ export async function getBalanceEth( export async function doEthPaymentFromMainNet( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joDepositBox: owaspUtils.ethersMod.ethers.Contract, joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainIdSChain: string, @@ -166,8 +167,8 @@ export async function doEthPaymentFromMainNet( export async function doEthPaymentFromSChain( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joTokenManagerETH: owaspUtils.ethersMod.ethers.Contract, joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs weiHowMuch: any, // how much WEI money to send @@ -200,7 +201,7 @@ export async function doEthPaymentFromSChain( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: true }; const joReceipt = await imaTx.payedCall( @@ -255,7 +256,7 @@ export async function doEthPaymentFromSChain( export async function receiveEthPaymentFromSchainOnMainNet( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, - joAccountMN: any, + joAccountMN: state.TAccount, joDepositBoxETH: owaspUtils.ethersMod.ethers.Contract, transactionCustomizerMainNet: imaTx.TransactionCustomizer ) { @@ -314,7 +315,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( export async function viewEthPaymentFromSchainOnMainNet( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joAccountMN: any, + joAccountMN: state.TAccount, joDepositBoxETH: owaspUtils.ethersMod.ethers.Contract ) { const details = log.createMemoryStream(); diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index c5c311ce..2e16354d 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -79,7 +79,7 @@ export async function safeWaitForNextBlockToAppear( export async function safeGetBlockNumber( details: any, cntAttempts: number, - ethersProvider: any, + ethersProvider: owaspUtils.ethersMod.providers.JsonRpcProvider, retValOnFail?: any, throwIfServerOffline?: boolean ) { const strFnName: string = "getBlockNumber"; @@ -105,7 +105,7 @@ export async function safeGetBlockNumber( } details.trace( "Repeat call to {} via {url}, attempt {}", strFnName + "()", u, idxAttempt ); try { - ret = await ethersProvider[strFnName](); + ret = await ( ethersProvider as any )[strFnName](); return ret; } catch ( err ) { ret = retValOnFail; diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index c589e315..453652b2 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -29,6 +29,7 @@ import * as imaOracle from "./oracle.js"; import * as imaTx from "./imaTx.js"; import * as imaGasUsage from "./imaGasUsageOperations.js"; import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; +import type * as state from "./state.js"; let gFlagIsEnabledOracle: boolean = false; @@ -192,7 +193,7 @@ async function handleOracleSigned( isIgnoreSetGasPrice, gasPrice, estimatedGasSetGasPrice, weiHowMuch ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( optsGasPriseSetup.chainIdSChain !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( optsGasPriseSetup.details, @@ -217,8 +218,8 @@ export async function doOracleGasPriceSetup( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, transactionCustomizerSChain: imaTx.TransactionCustomizer, - joCommunityLocker: any, - joAccountSC: any, + joCommunityLocker: owaspUtils.ethersMod.Contract, + joAccountSC: state.TAccount, chainIdMainNet: string, chainIdSChain: string, fnSignMsgOracle: any diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 71ef7a99..07bbad47 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -28,12 +28,13 @@ import * as imaHelperAPIs from "./imaHelperAPIs.js"; import * as imaTx from "./imaTx.js"; import * as threadInfo from "./threadInfo.js"; import type * as owaspUtils from "./owaspUtils.js"; +import type * as state from "./state.js"; export async function invokeHasChain( details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, // Main-Net or S-Chin - joLinker: any, // Main-Net or S-Chin - joAccount: any, // Main-Net or S-Chin + joLinker: owaspUtils.ethersMod.Contract, // Main-Net or S-Chin + joAccount: state.TAccount, // Main-Net or S-Chin chainIdSChain: string ) { const strLogPrefix = "Wait for added chain status: "; @@ -55,8 +56,8 @@ export async function invokeHasChain( export async function waitForHasChain( details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, // Main-Net or S-Chin - joLinker: any, // Main-Net or S-Chin - joAccount: any, // Main-Net or S-Chin + joLinker: owaspUtils.ethersMod.Contract, // Main-Net or S-Chin + joAccount: state.TAccount, // Main-Net or S-Chin chainIdSChain: string, cntWaitAttempts?: number, nSleepMilliseconds?: number @@ -80,12 +81,12 @@ export async function waitForHasChain( // export async function checkIsRegisteredSChainInDepositBoxes( // step 1 ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joLinker: any, - joAccountMN: any, + joLinker: owaspUtils.ethersMod.Contract | null, + joAccountMN: state.TAccount, chainIdSChain: string ) { const details = log.createMemoryStream(); - details.debug( "Main-net Linker address is...........{}", joLinker.address ); + details.debug( "Main-net Linker address is...........{}", joLinker ? joLinker.address : "N/A" ); details.debug( "S-Chain ID is.......................{}", chainIdSChain ); const strLogPrefix = "RegChk S in depositBox: "; details.debug( "{p}{p}", strLogPrefix, imaHelperAPIs.longSeparator ); @@ -95,6 +96,8 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 try { strActionName = "checkIsRegisteredSChainInDepositBoxes(reg-step1)"; const addressFrom = joAccountMN.address(); + if( ! joLinker ) + throw new Error( "No Linker contract" ); const bIsRegistered = await joLinker.callStatic.hasSchain( chainIdSChain, { from: addressFrom } ); details.success( "{p}checkIsRegisteredSChainInDepositBoxes(reg-step1) status is: {}", @@ -115,15 +118,15 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 export async function registerSChainInDepositBoxes( // step 1 ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joLinker: owaspUtils.ethersMod.ethers.Contract, - joAccountMN: any, - joTokenManagerETH: owaspUtils.ethersMod.ethers.Contract, // only s-chain - joTokenManagerERC20: owaspUtils.ethersMod.ethers.Contract, // only s-chain - joTokenManagerERC721: owaspUtils.ethersMod.ethers.Contract, // only s-chain - joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain - joTokenManagerERC721WithMetadata: owaspUtils.ethersMod.ethers.Contract, // only s-chain - joCommunityLocker: owaspUtils.ethersMod.ethers.Contract, // only s-chain - joTokenManagerLinker: owaspUtils.ethersMod.ethers.Contract, + joLinker: owaspUtils.ethersMod.ethers.Contract | null, + joAccountMN: state.TAccount, + joTokenManagerETH: owaspUtils.ethersMod.ethers.Contract | null, // only s-chain + joTokenManagerERC20: owaspUtils.ethersMod.ethers.Contract | null, // only s-chain + joTokenManagerERC721: owaspUtils.ethersMod.ethers.Contract | null, // only s-chain + joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract | null, // only s-chain + joTokenManagerERC721WithMetadata: owaspUtils.ethersMod.ethers.Contract | null, // only s-chain + joCommunityLocker: owaspUtils.ethersMod.ethers.Contract | null, // only s-chain + joTokenManagerLinker: owaspUtils.ethersMod.ethers.Contract | null, chainNameSChain: string, chainNameMainNet: string, transactionCustomizerMainNet: imaTx.TransactionCustomizer, @@ -132,7 +135,7 @@ export async function registerSChainInDepositBoxes( // step 1 ) { const details = log.createMemoryStream(); const jarrReceipts: any[] = []; - details.debug( "Main-net Linker address is..........{}", joLinker.address ); + details.debug( "Main-net Linker address is..........{}", joLinker ? joLinker.address : "N/A" ); details.debug( "S-Chain ID is.......................{}", chainNameSChain ); const strLogPrefix = "Reg S in depositBoxes: "; details.debug( "{p}{}", strLogPrefix, imaHelperAPIs.longSeparator ); @@ -142,6 +145,22 @@ export async function registerSChainInDepositBoxes( // step 1 try { strActionName = "Register S-chain in deposit boxes, step 1, connectSchain"; details.debug( "{p}Will register S-Chain in lock_and_data on Main-net", strLogPrefix ); + if( ! joTokenManagerLinker ) + throw new Error( "No TokenManagerLinker contract" ) + if( ! joCommunityLocker ) + throw new Error( "No CommunityLocker contract" ) + if( ! joTokenManagerETH ) + throw new Error( "No TokenManagerETH contract" ) + if( ! joTokenManagerERC20 ) + throw new Error( "No TokenManagerERC20 contract" ) + if( ! joTokenManagerERC721 ) + throw new Error( "No TokenManagerERC721 contract" ) + if( ! joTokenManagerERC1155 ) + throw new Error( "No TokenManagerERC1155 contract" ) + if( ! joTokenManagerERC721WithMetadata ) + throw new Error( "No TokenManagerERC721WithMetadata contract" ) + if( ! joLinker ) + throw new Error( "No Linker contract" ) const arrArguments = [ chainNameSChain, [ joTokenManagerLinker.address, // call params diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index 2edfde3d..e3714103 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -27,12 +27,13 @@ import * as log from "./log.js"; import * as owaspUtils from "./owaspUtils.js"; import * as imaTx from "./imaTx.js"; import * as imaGasUsage from "./imaGasUsageOperations.js"; +import type * as state from "./state.js"; export async function reimbursementShowBalance( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joCommunityPool: any, + joCommunityPool: owaspUtils.ethersMod.Contract, joReceiverMainNet: any, - strChainNameMainNet: any, + strChainNameMainNet: string, chainIdMainNet: string, transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, @@ -71,7 +72,7 @@ export async function reimbursementShowBalance( export async function reimbursementEstimateAmount( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joCommunityPool: any, + joCommunityPool: owaspUtils.ethersMod.Contract, joReceiverMainNet: any, strChainNameMainNet: string, chainIdMainNet: string, @@ -154,13 +155,13 @@ export async function reimbursementEstimateAmount( export async function reimbursementWalletRecharge( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joCommunityPool: any, - joAccountMN: any, + joCommunityPool: owaspUtils.ethersMod.Contract, + joAccountMN: state.TAccount, strChainNameMainNet: string, - chainIdMainNet: any, + chainIdMainNet: string, transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, - nReimbursementRecharge: any + nReimbursementRecharge: string | number | null ) { const details = log.createMemoryStream(); const jarrReceipts: any = []; @@ -216,13 +217,13 @@ export async function reimbursementWalletRecharge( export async function reimbursementWalletWithdraw( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joCommunityPool: any, - joAccountMN: any, + joCommunityPool: owaspUtils.ethersMod.Contract, + joAccountMN: state.TAccount, strChainNameMainNet: string, chainIdMainNet: string, transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, - nReimbursementWithdraw: any + nReimbursementWithdraw: string | number | null ) { const details = log.createMemoryStream(); const jarrReceipts: any = []; @@ -283,8 +284,8 @@ export async function reimbursementWalletWithdraw( export async function reimbursementSetRange( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joCommunityLocker: any, - joAccountSC: any, + joCommunityLocker: owaspUtils.ethersMod.Contract, + joAccountSC: state.TAccount, strChainNameSChain: string, chainIdSChain: string, transactionCustomizerSChain: imaTx.TransactionCustomizer, @@ -320,7 +321,7 @@ export async function reimbursementSetRange( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = { isCheckTransactionToSchain: true }; + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: true }; const joReceipt = await imaTx.payedCall( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index c8ab0649..26595c70 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -87,12 +87,12 @@ async function run() { if( gIsDebugLogging ) log.debug( "--- TX hash ---> {}", txHash ); - const rpcCallOpts: any = { + const rpcCallOpts: rpcCall.TRPCCallOpts | null = { cert: fs.readFileSync( strPathCert, "utf8" ), key: fs.readFileSync( strPathKey, "utf8" ) }; - const joCall: any = await rpcCall.create( strSgxWalletURL, rpcCallOpts ); + const joCall: rpcCall.TRPCCall = await rpcCall.create( strSgxWalletURL, rpcCallOpts ); if( ! joCall ) throw new Error( `Failed to create JSON RPC call object to ${strSgxWalletURL}` ); const joIn: any = { diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 4f37c9ac..c8f05017 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -30,12 +30,13 @@ import * as imaTx from "./imaTx.js"; import * as imaGasUsage from "./imaGasUsageOperations.js"; import * as imaEventLogScan from "./imaEventLogScan.js"; import * as threadInfo from "./threadInfo.js"; +import type * as state from "./state.js"; export async function getBalanceErc20( isMainNet: boolean, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, - joAccount: any, + joAccount: state.TAccount, strCoinName: string, joABI: any ) { @@ -64,7 +65,7 @@ export async function getOwnerOfErc721( isMainNet: boolean, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, - joAccount: any, + joAccount: state.TAccount, strCoinName: string, joABI: any, idToken: any @@ -93,7 +94,7 @@ export async function getBalanceErc1155( isMainNet: boolean, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, - joAccount: any, + joAccount: state.TAccount, strCoinName: string, joABI: any, idToken: any @@ -124,8 +125,8 @@ export async function doErc721PaymentFromMainNet( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joDepositBoxERC721: owaspUtils.ethersMod.ethers.Contract, joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, @@ -262,8 +263,8 @@ export async function doErc20PaymentFromMainNet( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joDepositBoxERC20: owaspUtils.ethersMod.ethers.Contract, joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, @@ -399,8 +400,8 @@ export async function doErc1155PaymentFromMainNet( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joDepositBoxERC1155: owaspUtils.ethersMod.ethers.Contract, joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, @@ -545,7 +546,7 @@ export async function doErc1155BatchPaymentFromMainNet( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, joAccountDst: any, + joAccountSrc: state.TAccount, joAccountDst: state.TAccount, joDepositBoxERC1155: owaspUtils.ethersMod.ethers.Contract, joMessageProxyMainNet: owaspUtils.ethersMod.ethers.Contract, // for checking logs chainNameSChain: string, @@ -675,8 +676,8 @@ export async function doErc20PaymentFromSChain( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joTokenManagerERC20: owaspUtils.ethersMod.ethers.Contract, // only s-chain joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net @@ -725,7 +726,7 @@ export async function doErc20PaymentFromSChain( weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts: any = { isCheckTransactionToSchain: true }; + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC20", contractERC20, "approve", arrArgumentsApprove, @@ -819,8 +820,8 @@ export async function doErc721PaymentFromSChain( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joTokenManagerERC721: owaspUtils.ethersMod.ethers.Contract, // only s-chain joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net @@ -871,7 +872,7 @@ export async function doErc721PaymentFromSChain( gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts: any = { isCheckTransactionToSchain: true }; + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC721", contractERC721, "approve", arrArgumentsApprove, @@ -967,8 +968,8 @@ export async function doErc1155PaymentFromSChain( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net @@ -1019,7 +1020,7 @@ export async function doErc1155PaymentFromSChain( gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts: any = { isCheckTransactionToSchain: true }; + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, @@ -1114,8 +1115,8 @@ export async function doErc1155BatchPaymentFromSChain( ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdMainNet: string, chainIdSChain: string, - joAccountSrc: any, - joAccountDst: any, + joAccountSrc: state.TAccount, + joAccountDst: state.TAccount, joTokenManagerERC1155: owaspUtils.ethersMod.ethers.Contract, // only s-chain joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs joDepositBox: owaspUtils.ethersMod.ethers.Contract, // only main net @@ -1162,7 +1163,7 @@ export async function doErc1155BatchPaymentFromSChain( gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); if( strErrorOfDryRunApprove ) throw new Error( strErrorOfDryRunApprove ); - const opts: any = { isCheckTransactionToSchain: true }; + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: true }; const joReceiptApprove = await imaTx.payedCall( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, @@ -1260,7 +1261,7 @@ export async function doErc20PaymentS2S( ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, - joAccountSrc: any, + joAccountSrc: state.TAccount, joTokenManagerERC20Src: owaspUtils.ethersMod.ethers.Contract, nAmountOfToken: any, // how much ERC20 tokens to send nAmountOfWei: any, // how much to send @@ -1400,7 +1401,7 @@ export async function doErc721PaymentS2S( ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, - joAccountSrc: any, + joAccountSrc: state.TAccount, joTokenManagerERC721Src: owaspUtils.ethersMod.ethers.Contract, tokenId: any, // which ERC721 token id to send nAmountOfWei: any, // how much to send @@ -1544,7 +1545,7 @@ export async function doErc1155PaymentS2S( ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, - joAccountSrc: any, + joAccountSrc: state.TAccount, joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract, tokenId: any, // which ERC721 token id to send nAmountOfToken: any, // how much ERC1155 tokens to send @@ -1689,7 +1690,7 @@ export async function doErc1155BatchPaymentS2S( ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainIdSrc: string, strChainNameDst: string, - joAccountSrc: any, + joAccountSrc: state.TAccount, joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract, arrTokenIds: any[], // which ERC1155 token id to send arrTokenAmounts: any[], // which ERC1155 token id to send @@ -1835,7 +1836,7 @@ export async function mintErc20( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, - joAccount: any, + joAccount: state.TAccount, strAddressMintTo: string, nAmount: any, strTokenContractAddress: string, @@ -1878,7 +1879,7 @@ export async function mintErc20( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, @@ -1905,7 +1906,7 @@ export async function mintErc721( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, - joAccount: any, + joAccount: state.TAccount, strAddressMintTo: string, idToken: any, strTokenContractAddress: string, @@ -1948,7 +1949,7 @@ export async function mintErc721( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, @@ -1975,7 +1976,7 @@ export async function mintErc1155( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: any, - joAccount: any, + joAccount: state.TAccount, strAddressMintTo: string, idToken: any, nAmount: any, @@ -2022,7 +2023,7 @@ export async function mintErc1155( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, @@ -2049,7 +2050,7 @@ export async function burnErc20( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, - joAccount: any, + joAccount: state.TAccount, strAddressBurnFrom: string, nAmount: any, strTokenContractAddress: string, @@ -2092,7 +2093,7 @@ export async function burnErc20( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, @@ -2119,7 +2120,7 @@ export async function burnErc721( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, - joAccount: any, + joAccount: state.TAccount, idToken: any, strTokenContractAddress: string, joTokenContractABI: any, @@ -2159,7 +2160,7 @@ export async function burnErc721( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, @@ -2186,7 +2187,7 @@ export async function burnErc1155( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, chainId: string, chainName: string, - joAccount: any, + joAccount: state.TAccount, strAddressBurnFrom: string, idToken: any, nAmount: any, @@ -2232,7 +2233,7 @@ export async function burnErc1155( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); - const opts: any = + const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; const joReceipt = await imaTx.payedCall( details, ethersProvider, diff --git a/src/imaTx.ts b/src/imaTx.ts index 67834a2f..2c1ee710 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -26,6 +26,7 @@ import * as path from "path"; import * as url from "url"; import * as childProcessModule from "child_process"; +import type * as state from "./state.js"; import Redis from "ioredis"; import * as ethereumJsUtilModule from "ethereumjs-util"; @@ -39,6 +40,33 @@ import * as imaEventLogScan from "./imaEventLogScan.js"; import * as threadInfo from "./threadInfo.js"; +export interface TCustomPayedCallOptions { + isCheckTransactionToSchain?: boolean +} + +export interface TRunTimePayedCallOptions { + details: any + ethersProvider: owaspUtils.ethersMod.providers.JsonRpcProvider + strContractName: string + joContract: owaspUtils.ethersMod.Contract + strMethodName: string + arrArguments: any[] + joAccount: state.TAccount + strActionName: string + gasPrice: any + estimatedGas: any + weiHowMuch: any + opts: TCustomPayedCallOptions + strContractCallDescription: string + strLogPrefix: string + joACI: any | null + unsignedTx: any | null + rawTx: any | null + txHash: any | null + joReceipt: any | null + callOpts: any +} + // eslint-disable-next-line @typescript-eslint/naming-convention const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); @@ -72,7 +100,7 @@ export async function dryRunCall( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: string, arrArguments: any[], - joAccount: any, strActionName: string, isDryRunResultIgnore: boolean, + joAccount: state.TAccount, strActionName: string, isDryRunResultIgnore: boolean, gasPrice: any, gasValue: any, weiHowMuch: any, opts?: any ) { @@ -121,7 +149,7 @@ export async function dryRunCall( } } -async function payedCallPrepare( optsPayedCall: any ) { +async function payedCallPrepare( optsPayedCall: TRunTimePayedCallOptions ) { optsPayedCall.joACI = getAccountConnectivityInfo( optsPayedCall.joAccount ); if( optsPayedCall.gasPrice ) { optsPayedCall.callOpts.gasPrice = @@ -162,7 +190,7 @@ async function payedCallPrepare( optsPayedCall: any ) { optsPayedCall.txHash ); } -async function payedCallTM( optsPayedCall: any ) { +async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ) { const txAdjusted: any = optsPayedCall.unsignedTx; // JSON.parse( JSON.stringify( optsPayedCall.rawTx ) ); const arrNamesConvertToHex = [ "gas", "gasLimit", "optsPayedCall.gasPrice", "value" ]; @@ -202,10 +230,10 @@ async function payedCallTM( optsPayedCall: any ) { } } -async function payedCallSGX( optsPayedCall: any ) { +async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ) { const tx = optsPayedCall.unsignedTx; let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); - if( chainId == "string" ) + if( typeof chainId == "string" && chainId ) chainId = owaspUtils.parseIntOrHex( chainId ); optsPayedCall.details.trace( "{p}Chain ID is: {}", optsPayedCall.strLogPrefix, chainId ); @@ -252,12 +280,12 @@ function postConvertBN( jo: any, name: any ) { jo[name] = owaspUtils.toBN( jo[name] ); } -async function payedCallDirect( optsPayedCall: any ) { +async function payedCallDirect( optsPayedCall: TRunTimePayedCallOptions ) { const ethersWallet = new owaspUtils.ethersMod.ethers.Wallet( owaspUtils.ensureStartsWith0x( optsPayedCall.joAccount.privateKey ), optsPayedCall.ethersProvider ); let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); - if( chainId == "string" ) + if( typeof chainId == "string" && chainId ) chainId = owaspUtils.parseIntOrHex( chainId ); optsPayedCall.details.trace( "{p}Chain ID is: {}", optsPayedCall.strLogPrefix, chainId ); if( ( !( chainId in optsPayedCall.unsignedTx ) ) || @@ -284,11 +312,11 @@ export async function payedCall( details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: any, arrArguments: any[], - joAccount: any, strActionName: string, + joAccount: state.TAccount, strActionName: string, gasPrice: any, estimatedGas: any, weiHowMuch: any, opts?: any ) { - const optsPayedCall: any = { + const optsPayedCall: TRunTimePayedCallOptions = { details, ethersProvider, strContractName, @@ -383,7 +411,7 @@ export async function checkTransactionToSchain( unsignedTx: any, details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - joAccount: any + joAccount: state.TAccount ) { const strLogPrefix = "PoW-mining: "; try { @@ -452,7 +480,7 @@ export async function calculatePowNumber( } } -export function getAccountConnectivityInfo( joAccount: any ) { +export function getAccountConnectivityInfo( joAccount: state.TAccount ) { const joACI: any = { isBad: true, strType: "bad", @@ -648,7 +676,7 @@ export class TransactionCustomizer { ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: string, arrArguments: any[], - joAccount: any, strActionName: string, + joAccount: state.TAccount, strActionName: string, gasPrice: any, gasValueRecommended: any, weiHowMuch: any, opts?: any ) { diff --git a/src/loop.ts b/src/loop.ts index 653e729f..dc07a213 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -37,16 +37,49 @@ import * as imaBLS from "./bls.js"; import * as skaleObserver from "./observer.js"; import * as pwa from "./pwa.js"; import * as state from "./state.js"; +import type * as worker_threads from "worker_threads"; // eslint-disable-next-line @typescript-eslint/naming-convention const __dirname: string = path.dirname( url.fileURLToPath( import.meta.url ) ); +export interface TExtraSignOpts { + chainNameSrc: string + chainIdSrc: string + chainNameDst: string + chainIdDst: string + joAccountSrc?: state.TAccount + joAccountDst?: state.TAccount + ethersProviderSrc?: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider + ethersProviderDst?: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider +} + +export interface TRuntimeOpts { + isInsideWorker: boolean + idxChainKnownForS2S: number + cntChainsKnownForS2S: number + joExtraSignOpts?: TExtraSignOpts +} + +export interface TLoopOptions { + joRuntimeOpts: TRuntimeOpts + isDelayFirstRun: boolean + enableStepOracle: boolean + enableStepM2S: boolean + enableStepS2M: boolean + enableStepS2S: boolean +} + +export interface TParallelLoopRunOptions { + imaState: state.TIMAState + details: any +} + // Run transfer loop export function checkTimeFraming( - d: Date | null, strDirection: string, joRuntimeOpts: any ): boolean { + d: Date | null, strDirection: string, joRuntimeOpts: TRuntimeOpts ): boolean { try { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.nTimeFrameSeconds <= 0 || imaState.nNodesCount <= 1 ) return true; // time framing is disabled @@ -107,10 +140,14 @@ export function checkTimeFraming( "/", log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts.chainIdSrc ), "\n" ); } else { + const s1: string = log.fmtInformation( "{}", + joRuntimeOpts.joExtraSignOpts + ? joRuntimeOpts.joExtraSignOpts.chainNameDst : "N/A" ) + const s2: string = log.fmtInformation( "{}", + joRuntimeOpts.joExtraSignOpts + ? joRuntimeOpts.joExtraSignOpts.chainIdDst : "N/A" ) strFrameInfo += log.fmtDebug( " S-Chain destination", "........", - log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts.chainNameDst ), - "/", log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts.chainIdDst ), - "\n" ); + s1, "/", s2, "\n" ); } } strFrameInfo += log.fmtDebug( @@ -129,8 +166,8 @@ export function checkTimeFraming( return true; }; -async function singleTransferLoopPartOracle( optsLoop: any, strLogPrefix: string ) { - const imaState = state.get(); +async function singleTransferLoopPartOracle( optsLoop: TLoopOptions, strLogPrefix: string ) { + const imaState: state.TIMAState = state.get(); let b0 = true; if( optsLoop.enableStepOracle && imaOracleOperations.getEnabledOracle() ) { log.notice( "{p}Will invoke Oracle gas price setup in {}...", @@ -144,14 +181,20 @@ async function singleTransferLoopPartOracle( optsLoop: any, strLogPrefix: string if( checkTimeFraming( null, "oracle", optsLoop.joRuntimeOpts ) ) { imaState.loopState.oracle.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "oracle" ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joCommunityLocker ) + throw new Error( "No CommunityLocker contract" ); b0 = await imaOracleOperations.doOracleGasPriceSetup( imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.transactionCustomizer, imaState.joCommunityLocker, imaState.chainProperties.sc.joAccount, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), imaBLS.doSignU256 ); imaState.loopState.oracle.isInProgress = false; @@ -174,8 +217,8 @@ async function singleTransferLoopPartOracle( optsLoop: any, strLogPrefix: string return b0; } -async function singleTransferLoopPartM2S( optsLoop: any, strLogPrefix: string ) { - const imaState = state.get(); +async function singleTransferLoopPartM2S( optsLoop: TLoopOptions, strLogPrefix: string ) { + const imaState: state.TIMAState = state.get(); let b1 = true; if( optsLoop.enableStepM2S ) { log.notice( "{p}Will invoke M2S transfer in {}...", @@ -189,6 +232,14 @@ async function singleTransferLoopPartM2S( optsLoop: any, strLogPrefix: string ) if( checkTimeFraming( null, "m2s", optsLoop.joRuntimeOpts ) ) { imaState.loopState.m2s.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "m2s" ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain ) contract" ); b1 = await IMA.doTransfer( // main-net --> s-chain "M2S", optsLoop.joRuntimeOpts, @@ -200,8 +251,8 @@ async function singleTransferLoopPartM2S( optsLoop: any, strLogPrefix: string ) imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.strChainName, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.mn.chainId, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId.toString(), null, imaState.joTokenManagerETH, // for logs validation on s-chain imaState.nTransferBlockSizeM2S, @@ -235,8 +286,8 @@ async function singleTransferLoopPartM2S( optsLoop: any, strLogPrefix: string ) return b1; } -async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) { - const imaState = state.get(); +async function singleTransferLoopPartS2M( optsLoop: TLoopOptions, strLogPrefix: string ) { + const imaState: state.TIMAState = state.get(); let b2 = true; if( optsLoop.enableStepS2M ) { log.notice( "{p}Will invoke S2M transfer in {}...", @@ -250,6 +301,14 @@ async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) if( checkTimeFraming( null, "s2m", optsLoop.joRuntimeOpts ) ) { imaState.loopState.s2m.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "s2m" ); + if( ! imaState.chainProperties.mn.ethersProvider ) + throw new Error( "No provider for MN" ); + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxyMainNet ) + throw new Error( "No MessageProxyMainNet contract" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); b2 = await IMA.doTransfer( // s-chain --> main-net "S2M", optsLoop.joRuntimeOpts, @@ -264,8 +323,8 @@ async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) imaState.chainProperties.sc.strChainName, imaState.chainProperties.mn.strChainName, - imaState.chainProperties.sc.chainId, - imaState.chainProperties.mn.chainId, + imaState.chainProperties.sc.chainId.toString(), + imaState.chainProperties.mn.chainId.toString(), imaState.joDepositBoxETH, // for logs validation on mainnet null, @@ -301,12 +360,18 @@ async function singleTransferLoopPartS2M( optsLoop: any, strLogPrefix: string ) return b2; } -async function singleTransferLoopPartS2S( optsLoop: any, strLogPrefix: string ) { - const imaState = state.get(); +async function singleTransferLoopPartS2S( optsLoop: TLoopOptions, strLogPrefix: string ) { + const imaState: state.TIMAState = state.get(); let b3 = true; if( optsLoop.enableStepS2S && imaState.optsS2S.isEnabled ) { log.notice( "{p}Will invoke all S2S transfers...", strLogPrefix ); try { + if( ! imaState.chainProperties.sc.ethersProvider ) + throw new Error( "No provider for SC" ); + if( ! imaState.joMessageProxySChain ) + throw new Error( "No MessageProxySChain contract" ); + if( ! imaState.joTokenManagerETH ) + throw new Error( "No TokenManagerETH contract" ); b3 = await IMA.doAllS2S( // s-chain --> s-chain optsLoop.joRuntimeOpts, imaState, @@ -315,12 +380,12 @@ async function singleTransferLoopPartS2S( optsLoop: any, strLogPrefix: string ) imaState.joMessageProxySChain, imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.sc.chainId, + imaState.chainProperties.sc.chainId.toString(), imaState.joTokenManagerETH, // for logs validation on s-chain imaState.nTransferBlockSizeS2S, imaState.nTransferStepsS2S, imaState.nMaxTransactionsS2S, - imaState.nBlockAwaitDepthMSS, + imaState.nBlockAwaitDepthS2S, imaState.nBlockAgeS2S, imaBLS.doSignMessagesS2S, imaState.chainProperties.sc.transactionCustomizer @@ -344,8 +409,8 @@ function printLoopPartSkippedWarning( strLoopPartName: string ) { "progress right now", strLoopPartName ); } -export async function singleTransferLoop( optsLoop: any ) { - const imaState = state.get(); +export async function singleTransferLoop( optsLoop: TLoopOptions ) { + const imaState: state.TIMAState = state.get(); const strLogPrefix = `Single Loop in ${threadInfo.threadDescription( false )} `; try { log.debug( "{p}{p}", strLogPrefix, imaHelperAPIs.longSeparator ); @@ -405,15 +470,15 @@ export async function singleTransferLoop( optsLoop: any ) { imaState.loopState.s2s.isInProgress = false; return false; } -export async function singleTransferLoopWithRepeat( optsLoop: any ) { - const imaState = state.get(); +export async function singleTransferLoopWithRepeat( optsLoop: TLoopOptions ) { + const imaState: state.TIMAState = state.get(); await singleTransferLoop( optsLoop ); setTimeout( function() { singleTransferLoopWithRepeat( optsLoop ).then( function() {} ).catch( function() {} ); }, imaState.nLoopPeriodSeconds * 1000 ); }; -export async function runTransferLoop( optsLoop: any ) { - const imaState = state.get(); +export async function runTransferLoop( optsLoop: TLoopOptions ) { + const imaState: state.TIMAState = state.get(); const isDelayFirstRun = owaspUtils.toBoolean( optsLoop.isDelayFirstRun ); if( isDelayFirstRun ) { setTimeout( function() { @@ -426,10 +491,10 @@ export async function runTransferLoop( optsLoop: any ) { // Parallel thread based loop -const gArrWorkers: any[] = []; -const gArrClients: any[] = []; +const gArrWorkers: worker_threads.Worker[] = []; +const gArrClients: networkLayer.OutOfWorkerSocketClientPipe[] = []; -function constructChainProperties( opts: any ) { +function constructChainProperties( opts: TParallelLoopRunOptions ) { return { mn: { joAccount: { @@ -494,8 +559,8 @@ function constructChainProperties( opts: any ) { }; } -function getDefaultOptsLoop( idxWorker: number ) { - const optsLoop: any = { +function getDefaultOptsLoop( idxWorker: number ): TLoopOptions { + const optsLoop: TLoopOptions = { joRuntimeOpts: { isInsideWorker: true, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }, @@ -508,14 +573,21 @@ function getDefaultOptsLoop( idxWorker: number ) { return optsLoop; } -export async function ensureHaveWorkers( opts: any ) { +interface TWorkerData { + url: string + colorization: { + isEnabled: boolean + } +} + +export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { if( gArrWorkers.length > 0 ) return gArrWorkers; const cntWorkers = 2; log.debug( "Loop module will create its ", cntWorkers, " worker(s) in ", threadInfo.threadDescription(), "..." ); for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) { - const workerData: any = { + const workerData: TWorkerData = { url: "ima_loop_server" + idxWorker, colorization: { isEnabled: log.isEnabledColorization() } }; @@ -615,6 +687,7 @@ export async function ensureHaveWorkers( opts: any ) { isWithMetadata721: false, joTokenManagerETH: null, + joTokenManagerETHTarget: null, joTokenManagerERC20: null, joTokenManagerERC20Target: null, joTokenManagerERC721: null, @@ -673,7 +746,7 @@ export async function ensureHaveWorkers( opts: any ) { gArrWorkers.length, " worker(s) in ", threadInfo.threadDescription() ); } -export async function runParallelLoops( opts: any ) { +export async function runParallelLoops( opts: TParallelLoopRunOptions ) { log.notice( "Will start parallel IMA transfer loops in {}...", threadInfo.threadDescription() ); await ensureHaveWorkers( opts ); log.success( "Done, did started parallel IMA transfer loops in {}, have {} worker(s) and {} " + @@ -693,7 +766,7 @@ export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) } export async function spreadUpdatedSChainNetwork( isFinal: boolean ) { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const joMessage: any = { method: "spreadUpdatedSChainNetwork", isFinal: ( !!isFinal ), diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 772f0ef7..29b442ca 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -36,7 +36,7 @@ import * as pwa from "./pwa.js"; import * as log from "./log.js"; import * as threadInfo from "./threadInfo.js"; -let imaState: any = state.get(); +let imaState: state.TIMAState = state.get(); if( parentPort ) { parentPort.on( "message", jo => { @@ -62,15 +62,15 @@ function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { class ObserverServer extends SocketServer { initComplete?: boolean; - opts: any; + opts: loop.TParallelLoopRunOptions | null; intervalPeriodicSchainsCaching?: number | null bIsPeriodicCachingStepInProgress?: boolean; constructor ( acceptor: any ) { super( acceptor ); + this.opts = null; const self: any = this; self.initComplete = false; log.enableColorization( workerData.colorization.isEnabled ); - self.opts = null; self.intervalPeriodicSchainsCaching = null; self.bIsPeriodicCachingStepInProgress = false; self.mapApiHandlers.init = diff --git a/src/main.ts b/src/main.ts index eef38d8c..db1e9141 100644 --- a/src/main.ts +++ b/src/main.ts @@ -55,7 +55,7 @@ process.on( "unhandledRejection", function( reason: any, p: any ) { } ); function parseCommandLine() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); log.autoEnableColorizationFromCommandLineArgs(); const strPrintedArguments = process.argv.join( " " ); imaCLI.parse( { @@ -86,18 +86,22 @@ function parseCommandLine() { let haveReimbursementCommands = false; if( imaState.isShowReimbursementBalance ) { haveReimbursementCommands = true; + log.trace( "Will require reimbursement chain name to show reimbursement balance" ); clpTools.commandLineTaskReimbursementShowBalance(); } - if( imaState.nReimbursementEstimate ) { + if( imaState.isReimbursementEstimate ) { haveReimbursementCommands = true; + log.trace( "Will require reimbursement chain name to do reimbursement estimation" ); clpTools.commandLineTaskReimbursementEstimateAmount(); } if( imaState.nReimbursementRecharge ) { haveReimbursementCommands = true; + log.trace( "Will require reimbursement chain name to do reimbursement recharge" ); clpTools.commandLineTaskReimbursementRecharge(); } if( imaState.nReimbursementWithdraw ) { haveReimbursementCommands = true; + log.trace( "Will require reimbursement chain name to do reimbursement withdraw" ); clpTools.commandLineTaskReimbursementWithdraw(); } if( haveReimbursementCommands ) { @@ -140,7 +144,7 @@ function parseCommandLine() { let gServerMonitoringWS: any = null; function initMonitoringServer(): void { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.nMonitoringPort <= 0 ) return; const strLogPrefix = "Monitoring: "; @@ -221,7 +225,7 @@ function initMonitoringServer(): void { ]; for( const paramName of arrRuntimeParamNames ) { if( paramName in imaState ) - joAnswer.runtime_params[paramName] = imaState[paramName]; + joAnswer.runtime_params[paramName] = ( imaState as any )[paramName]; } } break; @@ -254,7 +258,7 @@ function initMonitoringServer(): void { let gExpressJsonRpcAppIMA: any = null; function initJsonRpcServer(): void { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( imaState.nJsonRpcPort <= 0 ) return; const strLogPrefix = "JSON RPC: "; @@ -342,7 +346,7 @@ function initJsonRpcServer(): void { } async function doTheJob() { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strLogPrefix = "Job 1: "; let idxAction = 0; const cntActions = imaState.arrActions.length; @@ -386,7 +390,7 @@ function handleFirstSChainDiscoveryAttemptDone( process.exit( 166 ); } log.success( "S-Chain network was discovered: {}", joSChainNetworkInfo ); - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); imaState.joSChainNetworkInfo = joSChainNetworkInfo; discoveryTools.continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, function() { @@ -399,7 +403,7 @@ function handleFirstSChainDiscoveryAttemptDone( async function main() { log.autoEnableColorizationFromCommandLineArgs(); - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); const strTmpAddressFromEnvMainNet = owaspUtils.toEthPrivateKey( process.env.ACCOUNT_FOR_ETHEREUM ); const strTmpAddressFromEnvSChain = diff --git a/src/observer.ts b/src/observer.ts index 62b25999..e93d5c7f 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -40,7 +40,7 @@ export function findSChainIndexInArrayByName( arrSChains: any[], strSChainName: let gConnectedChainsData: any = null; export function autoUpdateLastCachedSChains(): boolean { - const imaState = state.get(); + const imaState: state.TIMAState = state.get(); if( ! imaState.optsS2S.strNetworkBrowserPath ) return false; const jo: any = imaUtils.jsonFileLoad( imaState.optsS2S.strNetworkBrowserPath, null ); diff --git a/src/oracle.ts b/src/oracle.ts index c5bcfc8b..b631b0ef 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -82,7 +82,7 @@ export function findPowNumber( strRequestPart: string, details: any, isVerbose?: async function handleOracleCheckResultResult( oracleOpts: any, details: any, isVerboseTraceDetails: boolean, - joCall: any, joIn: any, joOut: any + joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_checkResult) result is: {}", joOut ); @@ -107,7 +107,7 @@ async function handleOracleCheckResultResult( async function handleOracleSubmitRequestResult( oracleOpts: any, details: any, isVerboseTraceDetails: boolean, - joCall: any, joIn: any, joOut: any + joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { const nMillisecondsSleepBefore = "nMillisecondsSleepBefore" in oracleOpts ? oracleOpts.nMillisecondsSleepBefore : 1000; @@ -160,7 +160,8 @@ async function handleOracleSubmitRequestResult( export async function oracleGetGasPrice( oracleOpts: any, details: any ) { details = details || log; const url: string = oracleOpts.url; - let gp: any = null; let joCall: any = null; + let gp: any = null; + let joCall: rpcCall.TRPCCall | null = null; try { const isVerbose = "isVerbose" in oracleOpts ? oracleOpts.isVerbose : false; let isVerboseTraceDetails = "isVerboseTraceDetails" in oracleOpts diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 9fbe1183..27d4c6f0 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -387,7 +387,7 @@ export function verifyArgumentIsPathToExistingFolder( joArg?: any ): any { } } -export function verifyArgumentIsArrayOfIntegers( joArg?: any ): any { +export function verifyArgumentIsArrayOfIntegers( joArg?: any ): any[] { try { verifyArgumentWithNonEmptyValue( joArg ); if( joArg.value.length < 3 ) { diff --git a/src/pwa.ts b/src/pwa.ts index e3e72ad6..8e75ee57 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -27,6 +27,7 @@ import * as log from "./log.js"; import * as rpcCall from "./rpcCall.js"; import * as imaBLS from "./bls.js"; import * as imaUtils from "./utils.js"; +import type * as state from "./state.js"; function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): number[] { if( nNodesCount <= 1 ) @@ -87,7 +88,7 @@ function getNodeProgressAndTimestamp( joNode: any, strLoopWorkType: string, nInd } export async function checkOnLoopStart( - imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) @@ -153,7 +154,7 @@ export async function checkOnLoopStart( } export async function handleLoopStateArrived( - imaState: any, nNodeNumber: number, strLoopWorkType: string, nIndexS2S: number, + imaState: state.TIMAState, nNodeNumber: number, strLoopWorkType: string, nIndexS2S: number, isStart: boolean, ts: any, signature: any ) { const se = isStart ? "start" : "end"; @@ -205,7 +206,7 @@ export async function handleLoopStateArrived( } async function notifyOnLoopImpl( - imaState: any, strLoopWorkType: string, isStart: boolean, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, isStart: boolean, nIndexS2S?: number ) { const se = isStart ? "start" : "end"; try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined @@ -238,16 +239,17 @@ async function notifyOnLoopImpl( continue; // skip this node const joNode: any = jarrNodes[i]; const strNodeURL = imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ); - const rpcCallOpts: any = null; - let joCall: any = await rpcCall.create( strNodeURL, rpcCallOpts ) - .catch( async function( err: Error | string ) { - log.error( - "PWA failed to perform] loop-{} notification RPC call to node #{} with " + - "URL {url}, error is: {err}", se, i, strNodeURL, err ); - if( joCall ) - await joCall.disconnect(); - joCall = null; - } ); + const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; + const joCall = + await rpcCall.create( strNodeURL, rpcCallOpts ) + .catch( async function( err: Error | string ) { + log.error( + "PWA failed to perform] loop-{} notification RPC call to node " + + "#{} with URL {url}, error is: {err}", + se, i, strNodeURL, err ); + if( joCall ) + await joCall.disconnect(); + } ); if( ! joCall ) return false; const joIn: any = { @@ -276,11 +278,11 @@ async function notifyOnLoopImpl( } export async function notifyOnLoopStart( - imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { return await notifyOnLoopImpl( imaState, strLoopWorkType, true, nIndexS2S ); } export async function notifyOnLoopEnd( - imaState: any, strLoopWorkType: string, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { return await notifyOnLoopImpl( imaState, strLoopWorkType, false, nIndexS2S ); } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 6eadffa3..7c1999fd 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -30,9 +30,28 @@ import * as net from "net"; import { validateURL, isUrlWS } from "./owaspUtils.js"; import * as log from "./log.js"; +export interface TRPCCallOpts { + cert?: string + key?: string + ca?: string +} + +export interface TRPCCall { + url: string + joRpcOptions: TRPCCallOpts | null + mapPendingByCallID: any + wsConn: ws.WebSocket | null + isAutoReconnect: boolean + isDisconnectMode: boolean + reconnect: any + reconnect_if_needed: any + call: any + disconnect: any +} + const gSecondsConnectionTimeout = 60; -export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any ) { +export async function waitWebSocketIsOpen( socket: ws.WebSocket, fnDone: any, fnStep: any ) { fnDone = fnDone || async function( nStep: number ) {}; fnDone = fnStep || async function( nStep: number ) { return true; }; let nStep = 0; @@ -66,7 +85,7 @@ export async function waitWebSocketIsOpen( socket: any, fnDone: any, fnStep: any await promiseComplete; } -export async function doConnect( joCall: any, opts: any, fn?: any ) { +export async function doConnect( joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: any ) { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -75,32 +94,34 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { if( isUrlWS( joCall.url ) ) { let strWsError: string = ""; joCall.wsConn = new ws.WebSocket( joCall.url ); - joCall.wsConn.on( "open", async function() { + joCall.wsConn.on( "open", function() { if( fn ) - await fn( joCall, null ); + fn( joCall, null ); } ); - joCall.wsConn.on( "close", async function() { + joCall.wsConn.on( "close", function() { strWsError = "web socket was closed, please check provided URL is valid and accessible"; joCall.wsConn = null; } ); - joCall.wsConn.on( "error", async function( err: any ) { + joCall.wsConn.on( "error", function( err: any ) { strWsError = err.toString() || "internal web socket error"; log.error( "{url} web socket error: {err}", joCall.url, err ); const wsConn = joCall.wsConn; joCall.wsConn = null; - wsConn.close(); + if( wsConn ) + wsConn.close(); doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); } ); - joCall.wsConn.on( "fail", async function( err: any ) { + joCall.wsConn.on( "fail", function( err: any ) { strWsError = err.toString() || "internal web socket failure"; log.error( "{url} web socket fail: {err}", joCall.url, err ); const wsConn = joCall.wsConn; joCall.wsConn = null; - wsConn.close(); + if( wsConn ) + wsConn.close(); doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); } ); - joCall.wsConn.on( "message", async function incoming( data: any ) { + joCall.wsConn.on( "message", function incoming( data: any ) { const joOut = JSON.parse( data ); if( joOut.id in joCall.mapPendingByCallID ) { const entry = joCall.mapPendingByCallID[joOut.id]; @@ -111,7 +132,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { } clearTimeout( entry.out ); if( entry.fn ) - await entry.fn( entry.joIn, joOut, null ); + entry.fn( entry.joIn, joOut, null ); } } ); await waitWebSocketIsOpen( joCall.wsConn, @@ -128,7 +149,8 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { log.error( "{url} web socket wait timeout detected", joCall.url ); const wsConn = joCall.wsConn; joCall.wsConn = null; - wsConn.close(); + if( wsConn ) + wsConn.close(); doReconnectWsStep( joCall, opts ) .then( function() {} ).catch( function() {} ); return false; // stop waiting @@ -152,7 +174,7 @@ export async function doConnect( joCall: any, opts: any, fn?: any ) { return joCall; } -export async function doConnectIfNeeded( joCall: any, opts: any, fn: any ) { +export async function doConnectIfNeeded( joCall: TRPCCall, opts: TRPCCallOpts | null, fn: any ) { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -171,12 +193,12 @@ export async function doConnectIfNeeded( joCall: any, opts: any, fn: any ) { return joCall; } -async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { +async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: any ) { if( ! joCall.isAutoReconnect ) return; if( joCall.isDisconnectMode ) return; - doConnect( joCall, opts, async function( joCall: any, err: any ) { + doConnect( joCall, opts, async function( joCall: TRPCCall, err: any ) { if( err ) { doReconnectWsStep( joCall, opts ) .then( function() {} ).catch( function() {} ); @@ -187,7 +209,7 @@ async function doReconnectWsStep( joCall: any, opts: any, fn?: any ) { } ).then( function() {} ).catch( function() {} ); } -async function doDisconnect( joCall: any, fn: any ) { +async function doDisconnect( joCall: TRPCCall, fn: any ) { try { joCall.isDisconnectMode = true; const wsConn = joCall.wsConn ? joCall.wsConn : null; @@ -206,7 +228,7 @@ async function doDisconnect( joCall: any, fn: any ) { } } -export async function doCall( joCall: any, joIn: any, fn: any ) { +export async function doCall( joCall: TRPCCall, joIn: any, fn: any ) { joIn = enrichTopLevelFieldsInJSON( joIn ); if( joCall.wsConn ) { const entry: any = { @@ -344,14 +366,14 @@ export async function doCall( joCall: any, joIn: any, fn: any ) { } } -export async function rpcCallCreate( strURL: string, opts: any ) { +export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) { if( !validateURL( strURL ) ) throw new Error( `JSON RPC CALLER cannot create a call object invalid URL: ${strURL}` ); if( !( strURL && typeof strURL == "string" && strURL.length > 0 ) ) { throw new Error( "rpcCallCreate() was invoked with " + `bad parameters: ${JSON.stringify( arguments )}` ); } - const joCall: any = { + const joCall: TRPCCall = { url: "" + strURL, joRpcOptions: opts ? opts : null, mapPendingByCallID: { }, @@ -368,7 +390,7 @@ export async function rpcCallCreate( strURL: string, opts: any ) { call: async function( joIn: any, fnAfter: any ) { const self = this; const promiseComplete = new Promise( function( resolve: any, reject: any ) { - self.reconnect_if_needed( async function( joCall: any, err: any ) { + self.reconnect_if_needed( async function( joCall: TRPCCall, err: any ) { if( err ) { if( fnAfter ) await fnAfter( joIn, null, err ); diff --git a/src/state.ts b/src/state.ts index a7176420..38873eed 100644 --- a/src/state.ts +++ b/src/state.ts @@ -1,7 +1,18 @@ import * as owaspUtils from "./owaspUtils.js"; import * as imaTx from "./imaTx.js"; -export const gDefaultValueForLoopState: any = { +export interface TLoopStateSubPart { + isInProgress: boolean + wasInProgress: boolean +} +export interface TLoopState { + oracle: TLoopStateSubPart + m2s: TLoopStateSubPart + s2m: TLoopStateSubPart + s2s: TLoopStateSubPart +} + +export const gDefaultValueForLoopState: TLoopState = { oracle: { isInProgress: false, wasInProgress: false @@ -20,7 +31,47 @@ export const gDefaultValueForLoopState: any = { } }; -function constructChainProperties() { +export interface TAccount { + address_?: string + privateKey: string | null + address: any + strTransactionManagerURL: string + nTmPriority: number + strSgxURL: string + strSgxKeyName: string + strPathSslKey: string + strPathSslCert: string + strBlsKeyName: string +} + +export interface TOneChainProperties { + joAccount: TAccount + transactionCustomizer: imaTx.TransactionCustomizer + ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null + strURL: string + strChainName: string + chainId: string | number + strPathAbiJson: string + joAbiIMA: any + bHaveAbiIMA: boolean + joErc20: any | null + joErc721: any | null + joErc1155: any | null + strCoinNameErc20: string // in-JSON coin name + strCoinNameErc721: string // in-JSON coin name + strCoinNameErc1155: string // in-JSON coin name + strPathJsonErc20: string + strPathJsonErc721: string + strPathJsonErc1155: string +} + +export interface TPropertiesOfChains { + mn: TOneChainProperties + sc: TOneChainProperties + tc: TOneChainProperties +} + +function constructChainProperties(): TPropertiesOfChains { return { mn: { joAccount: { @@ -32,7 +83,7 @@ function constructChainProperties() { owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_ETHEREUM ), nTmPriority: - owaspUtils.toStringURL( + owaspUtils.toInteger( process.env.TRANSACTION_MANAGER_PRIORITY_ETHEREUM ) || 5, strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_ETHEREUM ), strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_ETHEREUM ), @@ -48,7 +99,7 @@ function constructChainProperties() { strChainName: ( process.env.CHAIN_NAME_ETHEREUM || "Mainnet" ).toString().trim(), chainId: owaspUtils.toInteger( process.env.CID_ETHEREUM ) || -4, - strPathAbiJson: null, + strPathAbiJson: "", joAbiIMA: { }, bHaveAbiIMA: false, joErc20: null, @@ -70,7 +121,7 @@ function constructChainProperties() { strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN ), nTmPriority: - owaspUtils.toStringURL( + owaspUtils.toInteger( process.env.TRANSACTION_MANAGER_PRIORITY_S_CHAIN ) || 5, strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN ), strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN ), @@ -86,7 +137,7 @@ function constructChainProperties() { strChainName: ( process.env.CHAIN_NAME_SCHAIN || "id-S-chain" ).toString().trim(), chainId: owaspUtils.toInteger( process.env.CID_SCHAIN ) || -4, - strPathAbiJson: null, + strPathAbiJson: "", joAbiIMA: { }, bHaveAbiIMA: false, joErc20: null, @@ -109,7 +160,7 @@ function constructChainProperties() { owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN_TARGET ), nTmPriority: - owaspUtils.toStringURL( + owaspUtils.toInteger( process.env.TRANSACTION_MANAGER_PRIORITY_S_CHAIN_TARGET ) || 5, strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN_TARGET ), strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN_TARGET ), @@ -125,7 +176,7 @@ function constructChainProperties() { strChainName: ( process.env.CHAIN_NAME_SCHAIN_TARGET || "id-T-chain" ).toString().trim(), chainId: owaspUtils.toInteger( process.env.CID_SCHAIN_TARGET ) || -4, - strPathAbiJson: null, + strPathAbiJson: "", joAbiIMA: { }, bHaveAbiIMA: false, joErc20: null, @@ -141,9 +192,168 @@ function constructChainProperties() { }; } -let imaState: any = null; +export interface TIMAState { + loopState: TLoopState + + strLogFilePath: string + nLogMaxSizeBeforeRotation: number + nLogMaxFilesCount: number + isPrintGathered: boolean + isPrintSecurityValues: boolean + isPrintPWA: boolean + isDynamicLogInDoTransfer: boolean + isDynamicLogInBlsSigner: boolean + + bIsNeededCommonInit: boolean + // use BLS message signing, turned on with --sign-messages + bSignMessages: boolean + // scanned S-Chain network description + joSChainNetworkInfo: any + // path to bls_glue app, must have if --sign-messages specified + strPathBlsGlue: string + // path to hash_g1 app, must have if --sign-messages specified + strPathHashG1: string + // path to verify_bls app, optional, + // if specified then we will verify gathered BLS signature + strPathBlsVerify: string + + // true - just show configuration values and exit + bShowConfigMode: boolean + + isEnabledMultiCall: boolean + + bNoWaitSChainStarted: boolean + nMaxWaitSChainAttempts: number // 20 + + nAmountOfWei: any + nAmountOfToken: any + arrAmountsOfTokens: any[] | null + idToken: any + idTokens: any[] | null + + nTransferBlockSizeM2S: number + nTransferBlockSizeS2M: number + nTransferBlockSizeS2S: number + nTransferStepsM2S: number + nTransferStepsS2M: number + nTransferStepsS2S: number + nMaxTransactionsM2S: number + nMaxTransactionsS2M: number + nMaxTransactionsS2S: number + + nBlockAwaitDepthM2S: number + nBlockAwaitDepthS2M: number + nBlockAwaitDepthS2S: number + nBlockAgeM2S: number + nBlockAgeS2M: number + nBlockAgeS2S: number + + nLoopPeriodSeconds: number + + nNodeNumber: number // S-Chain node number(zero based) + nNodesCount: number + nTimeFrameSeconds: number // 0-disable, 60-recommended + nNextFrameGap: number + + nAutoExitAfterSeconds: number // 0-disable + + joCommunityPool: owaspUtils.ethersMod.Contract | null // only main net + joDepositBoxETH: owaspUtils.ethersMod.Contract | null // only main net + joDepositBoxERC20: owaspUtils.ethersMod.Contract | null // only main net + joDepositBoxERC721: owaspUtils.ethersMod.Contract | null // only main net + joDepositBoxERC1155: owaspUtils.ethersMod.Contract | null // only main net + joDepositBoxERC721WithMetadata: owaspUtils.ethersMod.Contract | null // only main net + joLinker: owaspUtils.ethersMod.Contract | null // only main net + + isWithMetadata721: boolean + + joTokenManagerETH: owaspUtils.ethersMod.Contract | null // only s-chain + joTokenManagerETHTarget: owaspUtils.ethersMod.Contract | null + joTokenManagerERC20: owaspUtils.ethersMod.Contract | null // only s-chain + joTokenManagerERC20Target: owaspUtils.ethersMod.Contract | null // only s-chain + joTokenManagerERC721: owaspUtils.ethersMod.Contract | null // only sc target + joTokenManagerERC721Target: owaspUtils.ethersMod.Contract | null // only sc target + joTokenManagerERC1155: owaspUtils.ethersMod.Contract | null // only s-chain + joTokenManagerERC1155Target: owaspUtils.ethersMod.Contract | null // only sc target + joTokenManagerERC721WithMetadata: owaspUtils.ethersMod.Contract | null // only sc target + joTokenManagerERC721WithMetadataTarget: owaspUtils.ethersMod.Contract | null // only sc target + joCommunityLocker: owaspUtils.ethersMod.Contract | null // only s-chain + joCommunityLockerTarget: owaspUtils.ethersMod.Contract | null // only sc target + joMessageProxyMainNet: owaspUtils.ethersMod.Contract | null + joMessageProxySChain: owaspUtils.ethersMod.Contract | null + joMessageProxySChainTarget: owaspUtils.ethersMod.Contract | null // only sc target + joTokenManagerLinker: owaspUtils.ethersMod.Contract | null + joTokenManagerLinkerTarget: owaspUtils.ethersMod.Contract | null // only sc target + joEthErc20: owaspUtils.ethersMod.Contract | null // only s-chain + joEthErc20Target: owaspUtils.ethersMod.Contract | null // only sc target + + joConstantsHolder?: owaspUtils.ethersMod.Contract | null + joNodes?: owaspUtils.ethersMod.Contract | null + joKeyStorage?: owaspUtils.ethersMod.Contract | null + joSChains?: owaspUtils.ethersMod.Contract | null + joSChainsInternal?: owaspUtils.ethersMod.Contract | null + joSkaleDKG?: owaspUtils.ethersMod.Contract | null + joSkaleManager?: owaspUtils.ethersMod.Contract | null + joSkaleToken?: owaspUtils.ethersMod.Contract | null + joValidatorService?: owaspUtils.ethersMod.Contract | null + joWallets?: owaspUtils.ethersMod.Contract | null + + chainProperties: TPropertiesOfChains + + strPathAbiJsonSkaleManager: string + joAbiSkaleManager: any + bHaveSkaleManagerABI: boolean + + strChainNameOriginChain: string + + strAddrErc20Explicit: string + strAddrErc20ExplicitTarget: string // S<->S target + strAddrErc721Explicit: string + strAddrErc721ExplicitTarget: string // S<->S target + strAddrErc1155Explicit: string + strAddrErc1155ExplicitTarget: string // S<->S target + + isPWA: boolean + nTimeoutSecondsPWA: number + + nMonitoringPort: number // 0 - default, means monitoring server is disabled + bLogMonitoringServer: boolean + + strReimbursementChain: string + isShowReimbursementBalance: boolean + nReimbursementRecharge: string | number | null + nReimbursementWithdraw: string | number | null + nReimbursementRange: number // < 0 - do not change anything + isReimbursementEstimate?: boolean + + joSChainDiscovery: { + isSilentReDiscovery: boolean + // zero to disable (for debugging only) + repeatIntervalMilliseconds: number + periodicDiscoveryInterval: number + } + + // S-Chain to S-Chain transfer options + optsS2S: { + // is S-Chain to S-Chain transfers enabled + isEnabled: boolean + strNetworkBrowserPath: string | null + } + + nJsonRpcPort: number // 0 to disable + isCrossImaBlsMode: boolean + + arrActions: any[] // array of actions to run -export function get() { + receiver?: any | null + + haveOneTokenIdentifier: boolean + haveArrayOfTokenIdentifiers: boolean +}; + +let imaState: TIMAState | null = null; + +export function get(): TIMAState { if( imaState ) return imaState; imaState = { @@ -183,6 +393,7 @@ export function get() { nAmountOfToken: 0, arrAmountsOfTokens: null, idToken: 0, + idTokens: null, nTransferBlockSizeM2S: 4, nTransferBlockSizeS2M: 4, @@ -221,23 +432,24 @@ export function get() { isWithMetadata721: false, joTokenManagerETH: null, // only s-chain + joTokenManagerETHTarget: null, joTokenManagerERC20: null, // only s-chain joTokenManagerERC20Target: null, // only s-chain - joTokenManagerERC721: null, // only s-chain target - joTokenManagerERC721Target: null, // only s-chain target + joTokenManagerERC721: null, // only sc target + joTokenManagerERC721Target: null, // only sc target joTokenManagerERC1155: null, // only s-chain - joTokenManagerERC1155Target: null, // only s-chain target - joTokenManagerERC721WithMetadata: null, // only s-chain target - joTokenManagerERC721WithMetadataTarget: null, // only s-chain target + joTokenManagerERC1155Target: null, // only sc target + joTokenManagerERC721WithMetadata: null, // only sc target + joTokenManagerERC721WithMetadataTarget: null, // only sc target joCommunityLocker: null, // only s-chain - joCommunityLockerTarget: null, // only s-chain target + joCommunityLockerTarget: null, // only sc target joMessageProxyMainNet: null, joMessageProxySChain: null, - joMessageProxySChainTarget: null, // only s-chain target + joMessageProxySChainTarget: null, // only sc target joTokenManagerLinker: null, - joTokenManagerLinkerTarget: null, // only s-chain target + joTokenManagerLinkerTarget: null, // only sc target joEthErc20: null, // only s-chain - joEthErc20Target: null, // only s-chain target + joEthErc20Target: null, // only sc target chainProperties: constructChainProperties(), @@ -284,12 +496,15 @@ export function get() { nJsonRpcPort: 0, // 0 to disable isCrossImaBlsMode: false, - arrActions: [] // array of actions to run + arrActions: [], // array of actions to run + + haveOneTokenIdentifier: false, + haveArrayOfTokenIdentifiers: false }; return imaState; } -export function set( imaStateNew: any ) { +export function set( imaStateNew: TIMAState ) { imaState = imaStateNew; return imaState; } diff --git a/src/utils.ts b/src/utils.ts index 76d10b8d..a1c66919 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -29,6 +29,7 @@ import * as fs from "fs"; import * as path from "path"; import * as os from "os"; import * as threadInfo from "./threadInfo.js"; +import type * as state from "./state.js"; import { v4 as uuid } from "uuid"; export { uuid }; @@ -181,7 +182,7 @@ export async function waitForClonedTokenToAppear( } export async function waitForClonedTokenAppearErc20( - sc: any, tokenERC20SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string + sc: any, tokenERC20SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC20SC && typeof tokenERC20SC.abi == "object" && "address" in tokenERC20SC && typeof tokenERC20SC.address == "string" @@ -197,7 +198,7 @@ export async function waitForClonedTokenAppearErc20( } export async function waitForClonedTokenAppearErc721( - sc: any, tokenERC721SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string + sc: any, tokenERC721SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" @@ -214,7 +215,7 @@ export async function waitForClonedTokenAppearErc721( } export async function waitForClonedTokenAppearErc721WithMetadata( - sc: any, tokenERC721SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string + sc: any, tokenERC721SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" @@ -231,7 +232,7 @@ export async function waitForClonedTokenAppearErc721WithMetadata( } export async function waitForClonedTokenAppearErc1155( - sc: any, tokenERC1155SC: any, joAccountSC: any, tokensMN: any, strMainnetName: string + sc: any, tokenERC1155SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string ) { if( "abi" in tokenERC1155SC && typeof tokenERC1155SC.abi == "object" && "address" in tokenERC1155SC && typeof tokenERC1155SC.address == "string" From 218bd975f6ac3e35889dc0c5f9cedc676c6f8901 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 20 Dec 2023 11:48:16 +0000 Subject: [PATCH 23/53] code porting to TypeScript --- src/about.txt | 3 - src/bls.ts | 281 ++++++++++++++++++++---------- src/clpTools.ts | 17 +- src/discoveryTools.ts | 155 +++++++++++++--- src/imaCore.ts | 91 ++++++---- src/imaEthOperations.ts | 25 +-- src/imaEventLogScan.ts | 14 +- src/imaHelperAPIs.ts | 4 +- src/imaOracleOperations.ts | 271 +++++++++++++++------------- src/imaRegistrationOperations.ts | 22 ++- src/imaReimbursementOperations.ts | 20 +-- src/imaTokenOperations.ts | 90 +++++----- src/imaTx.ts | 20 +-- src/log.ts | 130 ++++++++++++-- src/loop.ts | 2 +- src/main.ts | 14 +- src/observer.ts | 76 +++++++- src/oracle.ts | 8 +- src/owaspUtils.ts | 15 +- src/pwa.ts | 12 +- src/rpcCall.ts | 211 +++++++++++++--------- src/state.ts | 16 +- src/utils.ts | 35 ++-- 23 files changed, 1027 insertions(+), 505 deletions(-) diff --git a/src/about.txt b/src/about.txt index b774a391..e760358a 100644 --- a/src/about.txt +++ b/src/about.txt @@ -194,9 +194,6 @@ IMA JSON RPC SERVER options: --no-cross-ima .........................Disable calls to IMA JSON RPC servers to compute BLS signature parts and operation state inside time frames. Use calls to skaled. Default mode. TEST options: --browse-s-chain .......................Download own S-Chain's network information. -OPTIMIZATION options: - --enable-multicall .....................Enable optimizations via multi-call. Default mode. - --disable-multicall ....................Disable optimizations via multi-call. LOGGING options: --expose ...............................Expose low-level log details after successful operations. By default details exposed only on errors. --no-expose ............................Expose low-level log details only after errors. Default expose mode. diff --git a/src/bls.ts b/src/bls.ts index 3013f7fd..0e33c74f 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -38,6 +38,20 @@ import * as threadInfo from "./threadInfo.js"; import * as utils from "./socketUtils.js"; import * as state from "./state.js"; import type * as loop from "./loop.js"; +import type * as IMA from "./imaCore.js"; + +export interface TQAInformation { + skaledNumber: number + "optsSignOperation.sequenceId": string + ts: string +} + +export interface TSignResult { + errorMessage?: string | null + signatureShare?: string + status?: number + error?: string | null +} export interface TGatheringTracker { nCountReceivedPrevious: number @@ -55,18 +69,18 @@ export interface TSignOperationOptions { jarrMessages: any[] nIdxCurrentMsgBlockStart: number strFromChainName: string - joExtraSignOpts: loop.TExtraSignOpts - fn: any + joExtraSignOpts?: loop.TExtraSignOpts | null + fn: IMA.TFunctionAfterSigningMessages bHaveResultReportCalled: boolean strLogPrefix: string strLogPrefixA: string strLogPrefixB: string joGatheringTracker: TGatheringTracker arrSignResults: any[] - details: any + details: log.TLogger strGatheredDetailsName: string sequenceId: string - jarrNodes: any[] + jarrNodes: discoveryTools.TSChainNode[] nThreshold: number nParticipants: number nCountOfBlsPartsToCollect: number @@ -77,11 +91,17 @@ export interface TSignOperationOptions { fromChainID: string | number } +export interface TBSU256CallData { + params: { + valueToSign: string + } +} + export interface TBSU256Options { - joCallData: any + joCallData: TBSU256CallData imaState: state.TIMAState strLogPrefix: string - details: any + details: log.TLogger joRetVal: any | null isSuccess: boolean nThreshold: number @@ -89,13 +109,29 @@ export interface TBSU256Options { u256: any | null strMessageHash: string joAccount: state.TAccount | null + qa?: TQAInformation +} + +export interface THandleVerifyAndSignCallDataParams { + startMessageIdx: number + srcChainName: string + dstChainName: string + srcChainID: string + dstChainID: string + direction: string + messages: any[] + qa?: TQAInformation +} + +export interface THandleVerifyAndSignCallData { + params: THandleVerifyAndSignCallDataParams } export interface THandleVerifyAndSignOptions { - joCallData: any + joCallData: THandleVerifyAndSignCallData imaState: state.TIMAState strLogPrefix: string - details: any + details: log.TLogger joRetVal: any isSuccess: boolean nIdxCurrentMsgBlockStart: number @@ -111,12 +147,34 @@ export interface THandleVerifyAndSignOptions { nParticipants: number } +export interface TSignU256Options { + u256: any + fn: IMA.TFunctionAfterSigningMessages + details: log.TLogger + imaState: state.TIMAState + strLogPrefix: string + joGatheringTracker: { + nCountReceivedPrevious: number + nCountReceived: number + nCountErrors: number + nCountSkipped: number + nWaitIntervalStepMilliseconds: number + nWaitIntervalMaxSteps: number // 10 is 1 second + } + arrSignResults: any[] + jarrNodes: discoveryTools.TSChainNode[] + nThreshold: number + nParticipants: number + nCountOfBlsPartsToCollect: number + errGathering: Error | string | null +} + const anyShellMod: any = shellMod as any; const shell = anyShellMod.default const Keccak = sha3Module.Keccak; -function discoverBlsThreshold( joSChainNetworkInfo: any ): number { +function discoverBlsThreshold( joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo ): number { const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) @@ -130,7 +188,7 @@ function discoverBlsThreshold( joSChainNetworkInfo: any ): number { return -1; } -function discoverBlsParticipants( joSChainNetworkInfo: any ): number { +function discoverBlsParticipants( joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo ): number { const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; if( ! joSChainNetworkInfo ) @@ -145,7 +203,7 @@ function discoverBlsParticipants( joSChainNetworkInfo: any ): number { } function checkBlsThresholdAndBlsParticipants( - nThreshold: number, nParticipants: number, strOperation: string, details: any + nThreshold: number, nParticipants: number, strOperation: string, details: log.TLogger ): boolean { details = details || log; if( nThreshold <= 0 ) { @@ -167,8 +225,9 @@ function checkBlsThresholdAndBlsParticipants( } function discoverPublicKeyByIndex( - nNodeIndex: number, joSChainNetworkInfo: any, details: any, isThrowException: boolean -): any { + nNodeIndex: number, joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo, + details: log.TLogger, isThrowException: boolean +): discoveryTools.TBLSPublicKey | null { details = details || log; const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; @@ -187,12 +246,12 @@ function discoverPublicKeyByIndex( cntNodes, nNodeIndex, joNode ); if( isThrowException ) throw new Error( `BLS 1/${cntNodes} public key discovery failed for node #${nNodeIndex}` ); - return null; } function discoverCommonPublicKey( - details: any, joSChainNetworkInfo: any, isThrowException: boolean ): any { + details: log.TLogger, joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo, + isThrowException: boolean ): discoveryTools.TBLSCommonPublicKey | null { const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; const jarrNodes = joSChainNetworkInfo.network; @@ -345,10 +404,12 @@ function allocBlsTmpActionDir(): string { } function performBlsGlue( - details: any, strDirection: string, jarrMessages: any[], + details: log.TLogger, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, arrSignResults: any[] ): any { const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const strLogPrefix = `${strDirection}/BLS/Glue: `; let joGlueResult: any = null; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); @@ -436,8 +497,10 @@ function performBlsGlue( return joGlueResult; } -function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ): any { +function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: any[] ): any { const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const strLogPrefix = "BLS/Glue: "; let joGlueResult: any = null; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); @@ -528,14 +591,16 @@ function performBlsGlueU256( details: any, u256: any, arrSignResults: any[] ): a } function performBlsVerifyI( - details: any, strDirection: string, nZeroBasedNodeIndex: number, + details: log.TLogger, strDirection: string, nZeroBasedNodeIndex: number, joResultFromNode: any, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joPublicKey: any + joPublicKey: discoveryTools.TBLSPublicKey ): boolean { if( !joResultFromNode ) return true; const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const strLogPrefix = `${strDirection}/BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -558,7 +623,7 @@ function performBlsVerifyI( keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.trace( "{p}BLS node #{} - hashed verify message is {}", strLogPrefix, nZeroBasedNodeIndex, strMessageHash ); - const joMsg: any = { message: strMessageHash }; + const joMsg = { message: strMessageHash }; details.debug( "{p}BLS node #{} - composed {} composed from {} using glue {} and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, jarrMessages, joResultFromNode, joPublicKey ); @@ -595,11 +660,15 @@ function performBlsVerifyI( } function performBlsVerifyIU256( - details: any, nZeroBasedNodeIndex: number, joResultFromNode: any, u256: any, joPublicKey: any + details: log.TLogger, + nZeroBasedNodeIndex: number, joResultFromNode: any, u256: any, + joPublicKey: discoveryTools.TBLSPublicKey ): boolean { if( ! joResultFromNode ) return true; const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const strLogPrefix = `BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -612,7 +681,7 @@ function performBlsVerifyIU256( }; let strOutput = ""; try { - const joMsg: any = { message: keccak256U256( u256, true ) }; + const joMsg = { message: keccak256U256( u256, true ) }; details.debug( "{p}BLS u256 node #{} verify message {} composed from {} using glue {} " + "and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, u256, joResultFromNode, joPublicKey ); @@ -649,13 +718,15 @@ function performBlsVerifyIU256( } function performBlsVerify( - details: any, strDirection: string, joGlueResult: any, + details: log.TLogger, strDirection: string, joGlueResult: any, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joCommonPublicKey: any + joCommonPublicKey: discoveryTools.TBLSCommonPublicKey ): boolean { if( !joGlueResult ) return true; const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); if( ! checkBlsThresholdAndBlsParticipants( @@ -678,14 +749,14 @@ function performBlsVerify( keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.trace( "{p}BLS/summary verify message - hashed verify message is {}", strLogPrefix, strMessageHash ); - const joMsg: any = { message: strMessageHash }; + const joMsg = { message: strMessageHash }; details.debug( "{p}BLS/summary verify message - composed JSON {} from messages array {}" + " using glue {} and common public key {}", strLogPrefix, joMsg, jarrMessages, joGlueResult, joCommonPublicKey ); imaUtils.jsonFileSave( strActionDir + "/glue-result.json", joGlueResult ); imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); - const joCommonPublicKeyToSave: any = { + const joCommonPublicKeyToSave: discoveryTools.TBLSCommonPublicKey = { commonBLSPublicKey0: joCommonPublicKey.commonBLSPublicKey0, commonBLSPublicKey1: joCommonPublicKey.commonBLSPublicKey1, commonBLSPublicKey2: joCommonPublicKey.commonBLSPublicKey2, @@ -720,11 +791,14 @@ function performBlsVerify( } function performBlsVerifyU256( - details: any, joGlueResult: any, u256: any, joCommonPublicKey: any + details: log.TLogger, joGlueResult: any, u256: any, + joCommonPublicKey: discoveryTools.TBLSCommonPublicKey ): boolean { if( !joGlueResult ) return true; const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); if( ! checkBlsThresholdAndBlsParticipants( @@ -737,14 +811,14 @@ function performBlsVerifyU256( let strOutput = ""; const strLogPrefix = "BLS u256/Summary: "; try { - const joMsg: any = { message: keccak256U256( u256, true ) }; + const joMsg = { message: keccak256U256( u256, true ) }; details.debug( "{p}BLS u256/summary verify message {} composed from {} using glue {}" + " and common public key {}", strLogPrefix, joMsg, u256, joGlueResult, joCommonPublicKey ); imaUtils.jsonFileSave( strActionDir + "/glue-result.json", joGlueResult ); imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); - const joCommonPublicKeyToSave: any = { + const joCommonPublicKeyToSave: discoveryTools.TBLSCommonPublicKey = { commonBLSPublicKey0: joCommonPublicKey.commonBLSPublicKey0, commonBLSPublicKey1: joCommonPublicKey.commonBLSPublicKey1, commonBLSPublicKey2: joCommonPublicKey.commonBLSPublicKey2, @@ -780,9 +854,9 @@ function performBlsVerifyU256( } async function checkCorrectnessOfMessagesToSign( - details: any, strLogPrefix: string, strDirection: string, + details: log.TLogger, strLogPrefix: string, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, - joExtraSignOpts: loop.TExtraSignOpts | null + joExtraSignOpts?: loop.TExtraSignOpts | null ) { const imaState: state.TIMAState = state.get(); let joMessageProxy: owaspUtils.ethersMod.ethers.Contract | null = null; @@ -909,7 +983,7 @@ async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.jarrMessages.length, optsSignOperation.jarrMessages ); optsSignOperation.details.exposeDetailsTo( - log, optsSignOperation.strGatheredDetailsName, false ); + log.globalStream(), optsSignOperation.strGatheredDetailsName, false ); optsSignOperation.details.close(); await checkCorrectnessOfMessagesToSign( optsSignOperation.details, optsSignOperation.strLogPrefix, @@ -917,7 +991,7 @@ async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions optsSignOperation.jarrMessages, optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.joExtraSignOpts ); - await optsSignOperation.fn( null, optsSignOperation.jarrMessages ); + await optsSignOperation.fn( null, optsSignOperation.jarrMessages, null ); return true; } await checkCorrectnessOfMessagesToSign( @@ -946,12 +1020,12 @@ async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions optsSignOperation.details ) ) { optsSignOperation.bHaveResultReportCalled = true; optsSignOperation.details.exposeDetailsTo( - log, optsSignOperation.strGatheredDetailsName, false ); + log.globalStream(), optsSignOperation.strGatheredDetailsName, false ); optsSignOperation.details.close(); await optsSignOperation.fn( "signature error(1), S-Chain information " + "was not discovered properly and BLS threshold/participants are unknown", - optsSignOperation.jarrMessages ); + optsSignOperation.jarrMessages, null ); return false; } optsSignOperation.nCountOfBlsPartsToCollect = 0 + optsSignOperation.nThreshold; @@ -988,6 +1062,8 @@ async function gatherSigningCheckFinish( optsSignOperation: TSignOperationOption optsSignOperation.details.success( "{p}Got BLS glue result: {}", optsSignOperation.strLogPrefixB, joGlueResult ); if( optsSignOperation.imaState.strPathBlsVerify.length > 0 ) { + if( ! optsSignOperation.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const joCommonPublicKey = discoverCommonPublicKey( optsSignOperation.details, optsSignOperation.imaState.joSChainNetworkInfo, false ); if( ! joCommonPublicKey ) { @@ -1038,7 +1114,7 @@ async function gatherSigningCheckOverflow( optsSignOperation: TSignOperationOpti optsSignOperation.fn( `signature error(2), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, - optsSignOperation.jarrMessages + optsSignOperation.jarrMessages, null ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( @@ -1069,7 +1145,7 @@ async function gatherSigningStartImpl( optsSignOperation: TSignOperationOptions optsSignOperation.fn( `signature error(3), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, - optsSignOperation.jarrMessages + optsSignOperation.jarrMessages, null ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.critical( @@ -1095,7 +1171,7 @@ async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions "node(s), tracker data is: " + `${JSON.stringify( optsSignOperation.joGatheringTracker )} , ` + `error is: ${optsSignOperation.errGathering.toString()}`, - optsSignOperation.jarrMessages + optsSignOperation.jarrMessages, null ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( @@ -1103,9 +1179,9 @@ async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions "signature parts({}) and timeout reached, error details: {err}", cntSuccess, err ); optsSignOperation.details.exposeDetailsTo( - log, optsSignOperation.strGatheredDetailsName, false ); + log.globalStream(), optsSignOperation.strGatheredDetailsName, false ); optsSignOperation.details.close(); - optsSignOperation.details = null; + optsSignOperation.details = log.globalStream(); } ); } return; @@ -1117,16 +1193,16 @@ async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions await optsSignOperation.fn( `Failed to gather BLS signatures in ${optsSignOperation.jarrNodes.length} node(s), ` + `tracker data is: ${JSON.stringify( optsSignOperation.joGatheringTracker )}`, - optsSignOperation.jarrMessages + optsSignOperation.jarrMessages, null ).catch( function( err: Error | string ) { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(6) in BLS sign result handler, not enough successful BLS signature " + "parts({}) and timeout reached, error details: {err}", cntSuccess, err ); optsSignOperation.details.exposeDetailsTo( - log, optsSignOperation.strGatheredDetailsName, false ); + log.globalStream(), optsSignOperation.strGatheredDetailsName, false ); optsSignOperation.details.close(); - optsSignOperation.details = null; + optsSignOperation.details = log.globalStream(); } ); } } @@ -1159,6 +1235,8 @@ async function doSignConfigureChainAccessParams( optsSignOperation: TSignOperati optsSignOperation.targetChainID = optsSignOperation.imaState.chainProperties.mn.chainId; optsSignOperation.fromChainID = optsSignOperation.imaState.chainProperties.sc.chainId; } else if( optsSignOperation.strDirection == "S2S" ) { + if( ! optsSignOperation.joExtraSignOpts ) + throw new Error( "No S2S signing options provided" ); optsSignOperation.targetChainName = "" + optsSignOperation.joExtraSignOpts.chainNameDst; optsSignOperation.fromChainName = "" + optsSignOperation.joExtraSignOpts.chainNameSrc; @@ -1233,9 +1311,13 @@ async function doSignProcessHandleCall( }; optsSignOperation.details.trace( "{p}Will verify sign result for node {}", optsSignOperation.strLogPrefixA, nZeroBasedNodeIndex ); + if( ! optsSignOperation.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const joPublicKey = discoverPublicKeyByIndex( nZeroBasedNodeIndex, optsSignOperation.imaState.joSChainNetworkInfo, optsSignOperation.details, true ); + if( ! joPublicKey ) + throw new Error( `No BLS public key for node ${nZeroBasedNodeIndex}` ); if( performBlsVerifyI( optsSignOperation.details, optsSignOperation.strDirection, nZeroBasedNodeIndex, joResultFromNode, @@ -1301,18 +1383,18 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperatio optsSignOperation.strLogPrefix, strNodeDescColorized, err, optsSignOperation.sequenceId ); if( joCall ) - joCall.disconnect(); + joCall.disconnect().then( function() {} ).catch( function() {} ); } ); if( ! joCall ) return; await doSignConfigureChainAccessParams( optsSignOperation ); - const joParams: any = { + const joParams: THandleVerifyAndSignCallDataParams = { direction: "" + optsSignOperation.strDirection, startMessageIdx: optsSignOperation.nIdxCurrentMsgBlockStart, dstChainName: optsSignOperation.targetChainName, srcChainName: optsSignOperation.fromChainName, - dstChainID: optsSignOperation.targetChainID, - srcChainID: optsSignOperation.fromChainID, + dstChainID: optsSignOperation.targetChainID.toString(), + srcChainID: optsSignOperation.fromChainID.toString(), messages: optsSignOperation.jarrMessages, qa: { skaledNumber: 0 + i, @@ -1334,7 +1416,7 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperatio async function doSignMessagesImpl( nTransferLoopCounter: number, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: loop.TExtraSignOpts, fn: any + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { const optsSignOperation: TSignOperationOptions = { imaState: state.get(), @@ -1344,7 +1426,8 @@ async function doSignMessagesImpl( nIdxCurrentMsgBlockStart, strFromChainName, joExtraSignOpts, - fn, + fn: fn || async function( + err: Error | string | null, jarrMessages: any[], joGlueResult: any | null ) {}, bHaveResultReportCalled: false, strLogPrefix: "", strLogPrefixA: "", @@ -1358,7 +1441,7 @@ async function doSignMessagesImpl( nWaitIntervalMaxSteps: 10 * 60 * 3 // 10 is 1 second }, arrSignResults: [], - details: log, + details: log.globalStream(), strGatheredDetailsName: "", sequenceId: "", jarrNodes: [], @@ -1384,7 +1467,7 @@ async function doSignMessagesImpl( }; optsSignOperation.details = optsSignOperation.imaState.isDynamicLogInBlsSigner - ? log : log.createMemoryStream(); + ? log.globalStream() : log.createMemoryStream(); optsSignOperation.strGatheredDetailsName = optsSignOperation.strDirection + "-" + "doSignMessagesImpl-#" + optsSignOperation.nTransferLoopCounter + "-" + optsSignOperation.strFromChainName + "-msg#" + @@ -1418,7 +1501,7 @@ async function doSignMessagesImpl( if( ! optsSignOperation.bHaveResultReportCalled ) { optsSignOperation.bHaveResultReportCalled = true; await optsSignOperation.fn( "Failed BLS sign due to exception: " + - `${owaspUtils.extractErrorMessage( err )}`, optsSignOperation.jarrMessages + `${owaspUtils.extractErrorMessage( err )}`, optsSignOperation.jarrMessages, null ).catch( function( err: Error | string ) { log.critical( "Failed BLS sign due to error-reporting callback exception: {err}", err ); @@ -1427,7 +1510,7 @@ async function doSignMessagesImpl( "Failed BLS sign due to error-reporting callback exception: {err}", err ); optsSignOperation.details.exposeDetailsTo( - log, optsSignOperation.strGatheredDetailsName, false ); + log.globalStream(), optsSignOperation.strGatheredDetailsName, false ); optsSignOperation.details.close(); } } ); @@ -1436,7 +1519,7 @@ async function doSignMessagesImpl( optsSignOperation.details.success( "{p} completed", optsSignOperation.strGatheredDetailsName ); if( optsSignOperation.details ) { optsSignOperation.details.exposeDetailsTo( - log, optsSignOperation.strGatheredDetailsName, true ); + log.globalStream(), optsSignOperation.strGatheredDetailsName, true ); optsSignOperation.details.close(); } } @@ -1444,7 +1527,7 @@ async function doSignMessagesImpl( export async function doSignMessagesM2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { await doSignMessagesImpl( nTransferLoopCounter, "M2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1454,7 +1537,7 @@ export async function doSignMessagesM2S( export async function doSignMessagesS2M( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { await doSignMessagesImpl( nTransferLoopCounter, "S2M", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1464,18 +1547,20 @@ export async function doSignMessagesS2M( export async function doSignMessagesS2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: loop.TExtraSignOpts, fn: any ) { + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { await doSignMessagesImpl( nTransferLoopCounter, "S2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, joExtraSignOpts, fn ) } -async function prepareSignU256( optsSignU256: any ) { +async function prepareSignU256( optsSignU256: TSignU256Options ) { optsSignU256.details.debug( "{p}Will sign {} value...", optsSignU256.strLogPrefix, optsSignU256.u256 ); optsSignU256.details.trace( "{p}Will query to sign {} skaled node(s)...", optsSignU256.strLogPrefix, optsSignU256.jarrNodes.length ); + if( ! optsSignU256.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); optsSignU256.nThreshold = discoverBlsThreshold( optsSignU256.imaState.joSChainNetworkInfo ); optsSignU256.nParticipants = discoverBlsParticipants( optsSignU256.imaState.joSChainNetworkInfo ); @@ -1491,7 +1576,7 @@ async function prepareSignU256( optsSignU256: any ) { await optsSignU256.fn( "signature error(1, u256), S-Chain information " + "was not discovered properly and BLS threshold/participants are unknown", - optsSignU256.u256 ); + optsSignU256.u256, null ); return false; } optsSignU256.nCountOfBlsPartsToCollect = 0 + optsSignU256.nThreshold; @@ -1502,7 +1587,7 @@ async function prepareSignU256( optsSignU256: any ) { } async function doSignU256OneImplHandleCallResult( - i: number, optsSignU256: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + i: number, optsSignU256: TSignU256Options, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignU256.jarrNodes[i]; @@ -1555,9 +1640,13 @@ async function doSignU256OneImplHandleCallResult( }; optsSignU256.details.trace( "{p}Will verify sign result for node {}", strLogPrefixA, nZeroBasedNodeIndex ); + if( ! optsSignU256.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const joPublicKey = discoverPublicKeyByIndex( nZeroBasedNodeIndex, optsSignU256.imaState.joSChainNetworkInfo, optsSignU256.details, true ); + if( ! joPublicKey ) + throw new Error( `No BLS public key for node ${nZeroBasedNodeIndex}` ); if( performBlsVerifyIU256( optsSignU256.details, nZeroBasedNodeIndex, joResultFromNode, optsSignU256.u256, joPublicKey ) ) { @@ -1598,7 +1687,7 @@ async function doSignU256OneImplHandleCallResult( await joCall.disconnect(); } -async function doSignU256OneImpl( i: number, optsSignU256: any ) { +async function doSignU256OneImpl( i: number, optsSignU256: TSignU256Options ) { const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; const joNode = optsSignU256.jarrNodes[i]; @@ -1636,7 +1725,7 @@ async function doSignU256OneImpl( i: number, optsSignU256: any ) { } } -async function gatherSigningCheckFinish256( optsSignU256: any ) { +async function gatherSigningCheckFinish256( optsSignU256: TSignU256Options ) { const cntSuccess = optsSignU256.arrSignResults.length; if( optsSignU256.joGatheringTracker.nCountReceivedPrevious != optsSignU256.joGatheringTracker.nCountReceived ) { @@ -1659,12 +1748,15 @@ async function gatherSigningCheckFinish256( optsSignU256: any ) { optsSignU256.details.success( "{p}Got BLS glue u256 result: {}", strLogPrefixB, joGlueResult ); if( optsSignU256.imaState.strPathBlsVerify.length > 0 ) { + if( ! optsSignU256.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const joCommonPublicKey = discoverCommonPublicKey( optsSignU256.details, optsSignU256.imaState.joSChainNetworkInfo, false ); if( ! joCommonPublicKey ) { + if( ! optsSignU256.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const strError = "No BLS common public key"; - optsSignU256.details.error( "{p}{}", - optsSignU256.strLogPrefixB, strError ); + optsSignU256.details.error( "{p}{}", strLogPrefixB, strError ); } else if( performBlsVerifyU256( optsSignU256.details, joGlueResult, optsSignU256.u256, joCommonPublicKey ) ) { const strSuccessfulResultDescription = @@ -1697,13 +1789,13 @@ async function gatherSigningCheckFinish256( optsSignU256: any ) { return true; } -async function gatherSigningCheckOverflow256( optsSignU256: any ) { +async function gatherSigningCheckOverflow256( optsSignU256: TSignU256Options ) { if( optsSignU256.joGatheringTracker.nCountReceived < optsSignU256.jarrNodes.length ) return false; optsSignU256.fn( "signature error(2, u256), got " + `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + - `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256 + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256, null ).catch( function( err: Error | string ) { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.critical( @@ -1717,7 +1809,7 @@ async function gatherSigningCheckOverflow256( optsSignU256: any ) { return true; } -async function doSignU256Gathering( optsSignU256: any ) { +async function doSignU256Gathering( optsSignU256: TSignU256Options ) { optsSignU256.details.debug( "{p}Waiting for BLS glue result ", optsSignU256.strLogPrefix ); optsSignU256.errGathering = null; for( let idxStep = 0; idxStep < optsSignU256.joGatheringTracker.nWaitIntervalMaxSteps; @@ -1734,7 +1826,7 @@ async function doSignU256Gathering( optsSignU256: any ) { "signature error(3, u256), got " + `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, - optsSignU256.u256 + optsSignU256.u256, null ).catch( function( err: Error | string ) { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.error( @@ -1747,8 +1839,9 @@ async function doSignU256Gathering( optsSignU256: any ) { } ); } -export async function doSignU256( u256: any, details: any, fn: any ) { - const optsSignU256: any = { +export async function doSignU256( u256: any, details: log.TLogger, + fn: IMA.TFunctionAfterSigningMessages ) { + const optsSignU256: TSignU256Options = { u256, fn, details, @@ -1763,12 +1856,14 @@ export async function doSignU256( u256: any, details: any, fn: any ) { nWaitIntervalMaxSteps: 10 * 60 * 3 // 10 is 1 second }, arrSignResults: [], - jarrNodes: {}, + jarrNodes: [], nThreshold: 1, nParticipants: 1, nCountOfBlsPartsToCollect: 1, errGathering: null }; + if( ! optsSignU256.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); optsSignU256.jarrNodes = optsSignU256.imaState.joSChainNetworkInfo.network; optsSignU256.details.trace( "{p}Invoking signing u256 procedure...", optsSignU256.strLogPrefix ); @@ -1779,7 +1874,7 @@ export async function doSignU256( u256: any, details: any, fn: any ) { ) ) { optsSignU256.details.warning( "{p}BLS u256 signing is unavailable", optsSignU256.strLogPrefix ); - await optsSignU256.fn( "BLS u256 signing is unavailable", optsSignU256.u256 ); + await optsSignU256.fn( "BLS u256 signing is unavailable", optsSignU256.u256, null ); return; } if( ! ( await prepareSignU256( optsSignU256 ) ) ) @@ -1814,6 +1909,8 @@ export async function doVerifyReadyHash( Y: arrTmp[1] } }; + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); if( ! checkBlsThresholdAndBlsParticipants( @@ -1829,9 +1926,7 @@ export async function doVerifyReadyHash( nZeroBasedNodeIndex, imaState.joSChainNetworkInfo, details, true ); details.trace( "{p}BLS node #{} - hashed verify message is {}", strLogPrefix, nZeroBasedNodeIndex, strMessageHash ); - const joMsg: any = { - message: strMessageHash - }; + const joMsg = { message: strMessageHash }; details.debug( "{p}BLS node #{} - composed {} using hash {} and glue {} and public key {}", strLogPrefix, nZeroBasedNodeIndex, joMsg, strMessageHash, joResultFromNode, joPublicKey ); @@ -1867,18 +1962,18 @@ export async function doVerifyReadyHash( isSuccess = false; } if( isExposeOutput || ( !isSuccess ) ) - details.exposeDetailsTo( log, "BLS-raw-verifier", isSuccess ); + details.exposeDetailsTo( log.globalStream(), "BLS-raw-verifier", isSuccess ); details.close(); return isSuccess; } async function doSignReadyHashHandleCallResult( - strLogPrefix: string, details: any, + strLogPrefix: string, details: log.TLogger, strMessageHash: string, isExposeOutput: boolean, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { details.trace( "{p}Call to ", "SGX done, answer is: {}", strLogPrefix, joOut ); - let joSignResult = joOut; + let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && typeof joOut.result == "object" ) joSignResult = joOut.result; @@ -1909,10 +2004,12 @@ async function doSignReadyHashHandleCallResult( export async function doSignReadyHash( strMessageHash: string, isExposeOutput: any ) { const imaState: state.TIMAState = state.get(); const strLogPrefix = ""; - const details: any = log.createMemoryStream(); - let joSignResult: any = null; + const details: log.TLogger = log.createMemoryStream(); + let joSignResult: TSignResult | null = null; let joCall: rpcCall.TRPCCall | null = null; try { + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); details.debug( "{p}Will BLS-sign ready hash.", strLogPrefix ); @@ -1975,7 +2072,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a joSignResult && typeof joSignResult == "object" && ( !joSignResult.error ) ) ? true : false; if( isExposeOutput || ( !isSuccess ) ) - details.exposeDetailsTo( log, "BLS-raw-signer", isSuccess ); + details.exposeDetailsTo( log.globalStream(), "BLS-raw-signer", isSuccess ); details.close(); return joSignResult; } @@ -2005,6 +2102,8 @@ async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign.strFromChainName, optsHandleVerifyAndSign.strFromChainID, optsHandleVerifyAndSign.strToChainName, optsHandleVerifyAndSign.strToChainID, optsHandleVerifyAndSign.jarrMessages ); + if( ! optsHandleVerifyAndSign.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); optsHandleVerifyAndSign.nThreshold = discoverBlsThreshold( optsHandleVerifyAndSign.imaState.joSChainNetworkInfo ); optsHandleVerifyAndSign.nParticipants = @@ -2079,13 +2178,13 @@ async function prepareS2sOfSkaleImaVerifyAndSign( } async function handleBlsSignMessageHashResult( - optsHandleVerifyAndSign: THandleVerifyAndSignOptions, joCallData: any, + optsHandleVerifyAndSign: THandleVerifyAndSignOptions, joCallData: THandleVerifyAndSignCallData, joAccount: state.TAccount, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { optsHandleVerifyAndSign.details.trace( "{p}{bright} Call to SGX done, " + "answer is: {}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.strDirection, joOut ); - let joSignResult = joOut; + let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && typeof joOut.result == "object" ) joSignResult = joOut.result; @@ -2124,7 +2223,7 @@ async function handleBlsSignMessageHashResult( return joSignResult; } -export async function handleSkaleImaVerifyAndSign( joCallData: any ) { +export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndSignCallData ) { const optsHandleVerifyAndSign: THandleVerifyAndSignOptions = { joCallData, imaState: state.get(), @@ -2212,7 +2311,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { `RPC call failed, error is: ${owaspUtils.extractErrorMessage( err )}` ); } optsHandleVerifyAndSign.details.exposeDetailsTo( - log, "IMA messages verifier/signer", optsHandleVerifyAndSign.isSuccess ); + log.globalStream(), "IMA messages verifier/signer", optsHandleVerifyAndSign.isSuccess ); optsHandleVerifyAndSign.details.close(); return optsHandleVerifyAndSign.joRetVal; } @@ -2220,6 +2319,8 @@ export async function handleSkaleImaVerifyAndSign( joCallData: any ) { async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { optsBSU256.details.debug( "{p}Will U256-BLS-sign {}", optsBSU256.strLogPrefix, optsBSU256.joCallData ); + if( ! optsBSU256.imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); optsBSU256.nThreshold = discoverBlsThreshold( optsBSU256.imaState.joSChainNetworkInfo ); optsBSU256.nParticipants = discoverBlsParticipants( optsBSU256.imaState.joSChainNetworkInfo ); optsBSU256.details.trace( "{p}Discovered BLS threshold is {}.", @@ -2253,11 +2354,12 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { } async function handleBlsSignMessageHash256Result( - optsBSU256: TBSU256Options, joCallData: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any + optsBSU256: TBSU256Options, joCallData: TBSU256CallData, + joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { optsBSU256.details.trace( "{p}Call to SGX done, answer is: {}", optsBSU256.strLogPrefix, joOut ); - let joSignResult = joOut; + let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && typeof joOut.result == "object" ) joSignResult = joOut.result; @@ -2292,7 +2394,7 @@ async function handleBlsSignMessageHash256Result( return joSignResult; } -export async function handleSkaleImaBSU256( joCallData: any ) { +export async function handleSkaleImaBSU256( joCallData: TBSU256CallData ) { const optsBSU256: TBSU256Options = { joCallData, imaState: state.get(), @@ -2360,7 +2462,8 @@ export async function handleSkaleImaBSU256( joCallData: any ) { throw new Error( "JSON RPC call(handleSkaleImaBSU256) to SGX failed, " + `RPC call failed, error is: ${owaspUtils.extractErrorMessage( err )}` ); } - optsBSU256.details.exposeDetailsTo( log, "U256-BLS-signer", optsBSU256.isSuccess ); + optsBSU256.details.exposeDetailsTo( + log.globalStream(), "U256-BLS-signer", optsBSU256.isSuccess ); optsBSU256.details.close(); return optsBSU256.joRetVal; } diff --git a/src/clpTools.ts b/src/clpTools.ts index c76e8291..764c1718 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -55,7 +55,12 @@ export async function checkRegistrationAll() { return b1; } -const gInfoRegistrationCost: any = { +export interface TRegistrationCostInformation { + mn: any[] + sc: any[] +} + +const gInfoRegistrationCost: TRegistrationCostInformation = { mn: [], sc: [] }; @@ -458,7 +463,7 @@ export async function commandLineTaskShowBalanceEth( balance: await imaEth.getBalanceEth( true, // isMainNet imaState.chainProperties.mn.ethersProvider, imaState.chainProperties.mn.chainId.toString(), - imaState.chainProperties.mn.joAccount ) + imaState.chainProperties.mn.joAccount, null ) } ); if( ! imaState.joDepositBoxETH ) throw new Error( "No DepositBoxETH contract" ); @@ -488,7 +493,7 @@ export async function commandLineTaskShowBalanceEth( balance: await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain imaState.chainProperties.sc.ethersProvider, imaState.chainProperties.sc.chainId.toString(), - imaState.chainProperties.sc.joAccount ) + imaState.chainProperties.sc.joAccount, null ) } ); } if( imaState.chainProperties.tc.ethersProvider ) { @@ -505,7 +510,7 @@ export async function commandLineTaskShowBalanceEth( balance: await imaEth.getBalanceEth( true, // isMainNet=true here, but we call S-Chain imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), - imaState.chainProperties.tc.joAccount ) + imaState.chainProperties.tc.joAccount, null ) } ); } } @@ -1499,7 +1504,7 @@ export function commandLineTaskTransferS2S() { name: "single S->S transfer loop", fn: async function() { if( ! imaState.optsS2S.isEnabled ) - return; + return true; if( ! imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer const joRuntimeOpts: loop.TRuntimeOpts = { @@ -1578,7 +1583,7 @@ export function commandLineTaskLoop() { printSummaryRegistrationCosts(); const opts: loop.TParallelLoopRunOptions = { imaState, - details: log + details: log.globalStream() }; return await loop.runParallelLoops( opts ); } diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 74a945c1..de9f2ca1 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -29,6 +29,107 @@ import * as state from "./state.js"; import * as imaUtils from "./utils.js"; import * as threadInfo from "./threadInfo.js"; +export type TFunctionAfterDiscovery = ( + err?: Error | string | null, + joSChainNetworkInfo?: TSChainNetworkInfo | null +) => void; + +export type TFunctionAfterRediscovery = ( + status: boolean +) => void; + +export interface TBLSPublicKey { + BLSPublicKey0: string + BLSPublicKey1: string + BLSPublicKey2: string + BLSPublicKey3: string +} + +export interface TBLSCommonPublicKey { + commonBLSPublicKey0: string + commonBLSPublicKey1: string + commonBLSPublicKey2: string + commonBLSPublicKey3: string +} + +export interface TNodeImaInfo extends TBLSPublicKey, TBLSCommonPublicKey { + n: number + t: number + thisNodeIndex: number +} + +export interface TPWAStateItem { + isInProgress: boolean + ts: number +} + +export interface TPWAState { + oracle: TPWAStateItem + m2s: TPWAStateItem + s2m: TPWAStateItem + s2s: { mapS2S: any } +} + +export interface TSChainNode { + httpRpcPort?: number + httpRpcPort6?: number + httpsRpcPort?: number + httpsRpcPort6?: number + ip?: string + ip6?: string + nodeID: number + schainIndex: number + wsRpcPort?: number + wsRpcPort6?: number + wssRpcPort?: number + wssRpcPort6?: number + imaInfo: TNodeImaInfo + pwaState?: TPWAState +} + +export interface TThisNodeProperties { + acceptors: number + bindIP: string + bindIP6: string + "enable-admin-apis"?: boolean + "enable-debug-behavior-apis"?: boolean + "enable-performance-tracker-apis"?: boolean + "enable-personal-apis"?: true + httpRpcPort?: number + httpRpcPort6?: number + httpsRpcPort?: number + httpsRpcPort6?: number + nodeID: number + schainName: string + thisNodeIndex: number + "unsafe-transactions"?: boolean + wsRpcPort?: number + wsRpcPort6?: number + wssRpcPort?: number + wssRpcPort6?: number +} + +export interface TSChainNetworkInfo { + network: TSChainNode[] + node: TThisNodeProperties + schainID: number +} + +export interface TDiscoveryOptions { + fnAfter: TFunctionAfterDiscovery | null + isSilentReDiscovery: boolean + joPrevSChainNetworkInfo: TSChainNetworkInfo | null + nCountToWait: number + imaState: state.TIMAState + strLogPrefix: string + joSChainNetworkInfo: TSChainNetworkInfo | null + jarrNodes: TSChainNode[] + cntNodes: number + cntFailed: number + nCountReceivedImaDescriptions: number + nCountAvailable: number +} + export function formatBalanceInfo( bi: any, strAddress: string ): string { let s = ""; s += log.fmtInformation( "{p}", bi.assetName ); @@ -53,7 +154,7 @@ export function formatBalanceInfo( bi: any, strAddress: string ): string { return s; } -function getSChainNodesCount( joSChainNetworkInfo: any ): number { +function getSChainNodesCount( joSChainNetworkInfo: TSChainNetworkInfo ): number { try { if( ! joSChainNetworkInfo ) return 0; @@ -65,7 +166,7 @@ function getSChainNodesCount( joSChainNetworkInfo: any ): number { } } -export function isSChainNodeFullyDiscovered( joNode: any ): boolean { +export function isSChainNodeFullyDiscovered( joNode: TSChainNode ): boolean { if( ! joNode ) return false; if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo == "object" && @@ -102,7 +203,8 @@ export function isSChainNodeFullyDiscovered( joNode: any ): boolean { return false; } -export function getSChainDiscoveredNodesCount( joSChainNetworkInfo: any ): number { +export function getSChainDiscoveredNodesCount( + joSChainNetworkInfo: TSChainNetworkInfo | null ): number { try { if( ! joSChainNetworkInfo ) return 0; @@ -178,7 +280,8 @@ let gTimerSChainDiscovery: any = null; let gFlagIsInSChainDiscovery: boolean = false; function composeStillUnknownNodesMessage( - joSChainNetworkInfo: any, cntStillUnknown: number, cntNodesOnChain: number ): string { + joSChainNetworkInfo: TSChainNetworkInfo, + cntStillUnknown: number, cntNodesOnChain: number ): string { let strMessage = log.fmtSuccess( ", {} of {} still unknown (", cntStillUnknown, cntNodesOnChain ); try { @@ -202,12 +305,15 @@ function composeStillUnknownNodesMessage( return strMessage; } -async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boolean, fnAfter: any ) { +async function handlePeriodicDiscoveryAttemptActions( + isSilentReDiscovery: boolean, fnAfter: TFunctionAfterDiscovery | null ) { if( gFlagIsInSChainDiscovery ) { log.information( "Notice: long this S-Chain re-discovery is in progress now..." ); return; } const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); fnAfter = fnAfter || function() {}; gFlagIsInSChainDiscovery = true; const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); @@ -246,12 +352,12 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole "discovered...", nCountToWait, cntDiscovered ); } let isError = false; - const joSChainNetworkInfo = await discoverSChainNetwork( + const joSChainNetworkInfo: TSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait ).catch( function( err: Error | string ) { isError = true; log.critical( "S-Chain network re-discovery failed: {err}", err ); - } ); + } ) as TSChainNetworkInfo; if( ! isError ) { const cntDiscoveredNow = getSChainDiscoveredNodesCount( joSChainNetworkInfo ); let strMessage = @@ -286,7 +392,7 @@ async function handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery: boole } export async function continueSChainDiscoveryInBackgroundIfNeeded( - isSilentReDiscovery: boolean, fnAfter: any ) { + isSilentReDiscovery: boolean, fnAfter: TFunctionAfterDiscovery | null ) { if( gTimerSChainDiscovery != null ) return; fnAfter = fnAfter || function() {}; @@ -297,6 +403,8 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( fnAfter(); return; // no S-Chain re-discovery, special mode } + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let nCountToWait = ( cntNodesOnChain > 2 ) ? Math.ceil( cntNodesOnChain * 2 / 3 + 1 ) @@ -332,7 +440,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( } function handleDiscoverSkaleImaInfoResult( - optsDiscover: any, strNodeDescColorized: string, + optsDiscover: TDiscoveryOptions, strNodeDescColorized: string, joNode: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ): void { joNode.imaInfo = joOut.result; @@ -345,7 +453,7 @@ function handleDiscoverSkaleImaInfoResult( } } -async function discoverSChainWalkNodes( optsDiscover: any ) { +async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { optsDiscover.cntFailed = 0; for( let i = 0; i < optsDiscover.cntNodes; ++ i ) { const nCurrentNodeIdx = 0 + i; @@ -398,7 +506,7 @@ async function discoverSChainWalkNodes( optsDiscover: any ) { } } -async function discoverSChainWait( optsDiscover: any ) { +async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { if( ! optsDiscover.isSilentReDiscovery ) { log.debug( "{p}Waiting for response from at least {} node(s)...", optsDiscover.strLogPrefix, optsDiscover.nCountToWait ); @@ -467,7 +575,8 @@ async function discoverSChainWait( optsDiscover: any ) { } async function handleDiscoverSkaleNodesRpcInfoResult( - optsDiscover: any, scURL: string, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + optsDiscover: TDiscoveryOptions, scURL: string, + joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { if( ! optsDiscover.isSilentReDiscovery ) { log.trace( "{p}OK, got (own) S-Chain network information: {}", optsDiscover.strLogPrefix, joOut.result ); @@ -537,9 +646,9 @@ async function handleDiscoverSkaleNodesRpcInfoResult( } export async function discoverSChainNetwork( - fnAfter: any, isSilentReDiscovery: boolean, + fnAfter: TFunctionAfterDiscovery | null, isSilentReDiscovery: boolean, joPrevSChainNetworkInfo: any, nCountToWait: number ) { - const optsDiscover: any = { + const optsDiscover: TDiscoveryOptions = { fnAfter, isSilentReDiscovery: ( !!isSilentReDiscovery ), joPrevSChainNetworkInfo: joPrevSChainNetworkInfo || null, @@ -586,7 +695,7 @@ export async function discoverSChainNetwork( } optsDiscover.joSChainNetworkInfo = null; if( optsDiscover.fnAfter ) - optsDiscover.fnAfter( err, null ); + optsDiscover.fnAfter( err as Error, null ); if( joCall ) await joCall.disconnect(); throw err; @@ -597,10 +706,12 @@ export async function discoverSChainNetwork( let gIntervalPeriodicDiscovery: any = null; function checkPeriodicDiscoveryNoLongerNeeded( - joSChainNetworkInfo: any, isSilentReDiscovery: boolean ) { + joSChainNetworkInfo: TSChainNetworkInfo | null, isSilentReDiscovery: boolean ) { if( ! joSChainNetworkInfo ) return false; const imaState: state.TIMAState = state.get(); + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); const cntAlreadyDiscovered = getSChainDiscoveredNodesCount( joSChainNetworkInfo ); if( ! isSilentReDiscovery ) { @@ -618,7 +729,7 @@ function checkPeriodicDiscoveryNoLongerNeeded( } export async function doPeriodicSChainNetworkDiscoveryIfNeeded( - isSilentReDiscovery: boolean, fnAfterRediscover: any + isSilentReDiscovery: boolean, fnAfterRediscover?: TFunctionAfterRediscovery ) { if( gIntervalPeriodicDiscovery ) return; // already started @@ -630,6 +741,8 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( log.success( "Periodic S-Chain re-discovery is not needed right from startup" ); return; // not needed right from very beginning } + if( ! imaState.joSChainNetworkInfo ) + throw new Error( "No own S-Chain network information" ); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let periodicDiscoveryInterval = imaState.joSChainDiscovery.periodicDiscoveryInterval; if( periodicDiscoveryInterval <= 0 ) @@ -638,7 +751,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( log.debug( "Periodic S-Chain re-discovery will be done with {} interval...", periodicDiscoveryInterval ); } - fnAfterRediscover = fnAfterRediscover || function() { }; + fnAfterRediscover = fnAfterRediscover || function( status: boolean ) { }; gIntervalPeriodicDiscovery = setInterval( function() { let nCountToWait = ( cntNodesOnChain > 2 ) ? Math.ceil( cntNodesOnChain * 2 / 3 ) @@ -655,12 +768,14 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { if( ! isSilentReDiscovery ) log.information( "Final periodic S-Chain re-discovery done" ); - fnAfterRediscover( true ); + if( fnAfterRediscover ) + fnAfterRediscover( true ); return; // not needed anymore, all nodes completely discovered } if( ! isSilentReDiscovery ) log.information( "Partial periodic S-Chain re-discovery done" ); - fnAfterRediscover( false ); + if( fnAfterRediscover ) + fnAfterRediscover( false ); } ).catch( function() {} ); }, periodicDiscoveryInterval ); if( ! isSilentReDiscovery ) { diff --git a/src/imaCore.ts b/src/imaCore.ts index 26e98209..6c36edbb 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -36,6 +36,14 @@ import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; import * as skaleObserver from "./observer.js"; import * as threadInfo from "./threadInfo.js"; +export type TFunctionAfterSigningMessages = + ( err: Error | string | null, jarrMessages: any[], joGlueResult: any | null + ) => Promise < void >; +export type TFunctionDoSignMessages = + ( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, + chainNameSrc: string, joExtraSignOpts?: loop.TExtraSignOpts | null, + fnAfter?: TFunctionAfterSigningMessages ) => Promise < void >; + export interface TTransferOptions { strDirection: string joRuntimeOpts: loop.TRuntimeOpts @@ -56,14 +64,14 @@ export interface TTransferOptions { nMaxTransactionsCount: number nBlockAwaitDepth: number nBlockAge: number - fnSignMessages: any + fnSignMessages: TFunctionDoSignMessages joExtraSignOpts?: loop.TExtraSignOpts | null transactionCustomizerDst: imaTx.TransactionCustomizer imaState: state.TIMAState nTransferLoopCounter: number strTransferErrorCategoryName: string strGatheredDetailsName: string - details: any + details: log.TLogger jarrReceipts: any[] bErrorInSigningMessages: boolean strLogPrefixShort: string @@ -87,7 +95,7 @@ export interface TOutgoingMessageAnalysisOptions { idxMessage: number idxImaMessage: number joMessage: any - joNode: any | null + joNode: skaleObserver.TSChainNode | null idxNode: number cntNodes: number cntPassedNodes: number @@ -101,10 +109,10 @@ const perMessageGasForTransfer = 1000000; const additionalS2MTransferOverhead = 200000; async function findOutReferenceLogRecord( - details: any, strLogPrefix: string, + details: log.TLogger, strLogPrefix: string, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joMessageProxy: owaspUtils.ethersMod.ethers.Contract, - bnBlockId: any, nMessageNumberToFind: any, isVerbose?: boolean + bnBlockId: any, nMessageNumberToFind: number, isVerbose?: boolean ) { const bnMessageNumberToFind = owaspUtils.toBN( nMessageNumberToFind.toString() ); const strEventName = "PreviousMessageReference"; @@ -118,7 +126,7 @@ async function findOutReferenceLogRecord( } for( let idxLogRecord = 0; idxLogRecord < cntLogRecord; ++ idxLogRecord ) { const joEvent = arrLogRecords[idxLogRecord]; - const ev: any = { + const ev = { currentMessage: joEvent.args[0], previousOutgoingMessageBlockId: joEvent.args[1] }; @@ -145,7 +153,7 @@ async function findOutReferenceLogRecord( } async function findOutAllReferenceLogRecords( - details: any, strLogPrefix: string, + details: log.TLogger, strLogPrefix: string, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joMessageProxy: owaspUtils.ethersMod.ethers.Contract, bnBlockId: any, nIncMsgCnt: number, nOutMsgCnt: number, isVerbose?: boolean @@ -332,7 +340,7 @@ async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ) const joEvent = r[i]; optsTransfer.details.debug( "{p}Will review found event record {} with data {}", optsTransfer.strLogPrefix, i, joEvent ); - const ev: any = { + const ev = { dstChainHash: joEvent.args[0], msgCounter: joEvent.args[1], srcContract: joEvent.args[2], @@ -356,7 +364,7 @@ async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ) optsTransfer.details.critical( "{p}Can't get events from MessageProxy", optsTransfer.strLogPrefix ); optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, false ); + log.globalStream(), optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); optsTransfer.details.close(); @@ -429,7 +437,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ) { "block number during {bright}: {err}, stack is:\n{stack}", optsTransfer.strLogPrefix, optsTransfer.strActionName, err, err ); optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, false ); + log.globalStream(), optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); optsTransfer.details.close(); @@ -481,7 +489,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ) { "during {bright}: {err}, stack is:\n{stack}", optsTransfer.strLogPrefix, optsTransfer.strActionName, err, err ); optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, false ); + log.globalStream(), optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); optsTransfer.details.close(); @@ -514,7 +522,8 @@ async function gatherMessages( optsTransfer: TTransferOptions ) { } async function preCheckAllMessagesSign( - optsTransfer: TTransferOptions, err: Error | string, jarrMessages: any[], joGlueResult: any ) { + optsTransfer: TTransferOptions, err: Error | string | null, + jarrMessages: any[], joGlueResult: any ) { const strDidInvokedSigningCallbackMessage = log.fmtDebug( "{p}Did invoked message signing callback, first real message index is: {}, have {} " + "message(s) to process {}", optsTransfer.strLogPrefix, @@ -539,7 +548,8 @@ async function preCheckAllMessagesSign( } async function callbackAllMessagesSign( - optsTransfer: TTransferOptions, err: Error | string, jarrMessages: any[], joGlueResult: any ) { + optsTransfer: TTransferOptions, err: Error | string | null, + jarrMessages: any[], joGlueResult: any ) { if( ! await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) return; const nBlockSize = optsTransfer.arrMessageCounters.length; @@ -549,7 +559,7 @@ async function callbackAllMessagesSign( optsTransfer.strLogPrefix, optsTransfer.strActionName, nBlockSize, optsTransfer.arrMessageCounters ); optsTransfer.details.debug( strWillCallPostIncomingMessagesAction ); - let signature = joGlueResult ? joGlueResult.signature : null; + let signature: owaspUtils.TXYSignature | null = joGlueResult ? joGlueResult.signature : null; if( !signature ) signature = { X: "0", Y: "0" }; let hashPoint = joGlueResult ? joGlueResult.hashPoint : null; @@ -558,7 +568,7 @@ async function callbackAllMessagesSign( let hint = joGlueResult ? joGlueResult.hint : null; if( !hint ) hint = "0"; - const sign: any = { + const sign: owaspUtils.TBLSSignature = { blsSignature: [ signature.X, signature.Y ], // BLS glue of signatures hashA: hashPoint.X, // G1.X from joGlueResult.hashSrc hashB: hashPoint.Y, // G1.Y from joGlueResult.hashSrc @@ -688,9 +698,8 @@ async function handleAllMessagesSigning( optsTransfer: TTransferOptions ) { await optsTransfer.fnSignMessages( optsTransfer.nTransferLoopCounter, optsTransfer.jarrMessages, optsTransfer.nIdxCurrentMsgBlockStart, optsTransfer.chainNameSrc, optsTransfer.joExtraSignOpts, - async function( err: Error | string, jarrMessages: any[], joGlueResult: any ) { + async function( err: Error | string | null, jarrMessages: any[], joGlueResult: any ) { await callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ); - } ).catch( function( err: Error | string ) { // callback fn as argument of optsTransfer.fnSignMessages optsTransfer.bErrorInSigningMessages = true; @@ -715,6 +724,12 @@ async function handleAllMessagesSigning( optsTransfer: TTransferOptions ) { async function checkOutgoingMessageEventInOneNode( optsTransfer: TTransferOptions, optsOutgoingMessageAnalysis: TOutgoingMessageAnalysisOptions ) { + if( ! optsOutgoingMessageAnalysis.joNode ) { + optsTransfer.details.error( + "{p}{bright} no S-Chain node provided", + optsTransfer.strLogPrefix, optsTransfer.strDirection ); + return false; + } const sc = optsTransfer.imaState.chainProperties.sc; const strUrlHttp = optsOutgoingMessageAnalysis.joNode.endpoints.ip.http; optsTransfer.details.trace( @@ -801,7 +816,8 @@ async function checkOutgoingMessageEventInOneNode( return true; } -async function checkOutgoingMessageEvent( optsTransfer: TTransferOptions, joSChain: any ) { +async function checkOutgoingMessageEvent( + optsTransfer: TTransferOptions, joSChain: skaleObserver.TSChainInformation ) { const cntNodes = joSChain.nodes.length; const cntMessages = optsTransfer.jarrMessages.length; for( let idxMessage = 0; idxMessage < cntMessages; ++ idxMessage ) { @@ -854,7 +870,7 @@ async function checkOutgoingMessageEvent( optsTransfer: TTransferOptions, joSCha "allowed to fail {}", optsTransfer.strLogPrefix, optsTransfer.strDirection, optsOutgoingMessageAnalysis.cntFailedNodes, optsTransfer.cntNodesMayFail ); optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, false ); + log.globalStream(), optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); @@ -867,7 +883,7 @@ async function checkOutgoingMessageEvent( optsTransfer: TTransferOptions, joSCha "needed count {}", optsTransfer.strLogPrefix, optsTransfer.strDirection, optsOutgoingMessageAnalysis.cntFailedNodes, optsTransfer.cntNodesShouldPass ); optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, false ); + log.globalStream(), optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); optsTransfer.details.close(); @@ -957,12 +973,14 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { optsTransfer.details.information( strWillInvokeSigningCallbackMessage ); // will re-open optsTransfer.details B log here for next step, // it can be delayed so we will flush accumulated optsTransfer.details A now - if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) - optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, true ); + if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) { + optsTransfer.details.exposeDetailsTo( + log.globalStream(), optsTransfer.strGatheredDetailsName, true ); + } optsTransfer.details.close(); optsTransfer.details = optsTransfer.imaState.isDynamicLogInDoTransfer - ? log : log.createMemoryStream(); + ? log.globalStream() : log.createMemoryStream(); optsTransfer.strGatheredDetailsName = `${optsTransfer.strDirection}/#` + `${optsTransfer.nTransferLoopCounter}-doTransfer-B-${optsTransfer.chainNameSrc}` + `-->${optsTransfer.chainNameDst}`; @@ -997,7 +1015,7 @@ export async function doTransfer( nTransactionsCountInBlock: number, nTransferSteps: number, nMaxTransactionsCount: number, nBlockAwaitDepth: number, nBlockAge: number, - fnSignMessages: any, joExtraSignOpts: loop.TExtraSignOpts | null, + fnSignMessages: TFunctionDoSignMessages, joExtraSignOpts: loop.TExtraSignOpts | null, transactionCustomizerDst: imaTx.TransactionCustomizer ) { const optsTransfer: TTransferOptions = { @@ -1027,7 +1045,7 @@ export async function doTransfer( nTransferLoopCounter: 0 + gTransferLoopCounter, strTransferErrorCategoryName: "loop-" + strDirection, strGatheredDetailsName: "", - details: null, + details: log.globalStream(), jarrReceipts: [], bErrorInSigningMessages: false, strLogPrefixShort: "", @@ -1051,7 +1069,7 @@ export async function doTransfer( `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter}-doTransfer-A-` + `${optsTransfer.chainNameSrc}-->${optsTransfer.chainNameDst}`; optsTransfer.details = optsTransfer.imaState.isDynamicLogInDoTransfer - ? log : log.createMemoryStream(); + ? log.globalStream() : log.createMemoryStream(); optsTransfer.strLogPrefixShort = `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter} `; optsTransfer.strLogPrefix = `${optsTransfer.strLogPrefixShort}transfer loop from ` + @@ -1059,9 +1077,10 @@ export async function doTransfer( if( gIsOneTransferInProgressInThisThread ) { optsTransfer.details.warning( "{p}Transfer loop step is skipped because previous one " + "is still in progress", optsTransfer.strLogPrefix ); - if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) - optsTransfer.details.exposeDetailsTo( log, optsTransfer.strGatheredDetailsName, true ); - + if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) { + optsTransfer.details.exposeDetailsTo( + log.globalStream(), optsTransfer.strGatheredDetailsName, true ); + } optsTransfer.details.close(); return false; } @@ -1077,14 +1096,16 @@ export async function doTransfer( optsTransfer.fnSignMessages = async function( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts: loop.TExtraSignOpts, fnAfter: any + joExtraSignOpts?: loop.TExtraSignOpts | null, + fnAfter?: TFunctionAfterSigningMessages ) { optsTransfer.details.debug( "{p}Message signing callback was not provided to IMA, first real message " + "index is: {}, have {} message(s) to process {}", optsTransfer.strLogPrefix, nIdxCurrentMsgBlockStart, optsTransfer.jarrMessages.length, optsTransfer.jarrMessages ); - await fnAfter( null, jarrMessages ); // null - no error, null - no signatures + if( fnAfter ) // null - no error, null - no signatures + await fnAfter( null, jarrMessages, null ); }; } else { optsTransfer.details.debug( "{p}Using externally provided signing function", @@ -1113,7 +1134,7 @@ export async function doTransfer( optsTransfer.details.critical( "{p}Error in {} during {bright}: {err}, " + "stack is:\n{stack}", optsTransfer.strLogPrefix, optsTransfer.strGatheredDetailsName, optsTransfer.strActionName, err, err ); - optsTransfer.details.exposeDetailsTo( log, + optsTransfer.details.exposeDetailsTo( log.globalStream(), optsTransfer.strGatheredDetailsName, false ); imaTransferErrorHandling.saveTransferError( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); @@ -1126,7 +1147,7 @@ export async function doTransfer( if( optsTransfer.details ) { if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) { optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, true ); + log.globalStream(), optsTransfer.strGatheredDetailsName, true ); } optsTransfer.details.close(); } @@ -1143,7 +1164,7 @@ export async function doTransfer( optsTransfer.strLogPrefix, err, threadInfo.threadDescription(), err ); if( log.exposeDetailsGet() && optsTransfer.details.exposeDetailsTo ) { optsTransfer.details.exposeDetailsTo( - log, optsTransfer.strGatheredDetailsName, true ); + log.globalStream(), optsTransfer.strGatheredDetailsName, true ); } optsTransfer.details.close(); return false; @@ -1165,7 +1186,7 @@ export async function doAllS2S( // s-chain --> s-chain nMaxTransactionsCount: number, nBlockAwaitDepth: number, nBlockAge: number, - fnSignMessages: any, + fnSignMessages: TFunctionDoSignMessages, transactionCustomizerDst: imaTx.TransactionCustomizer ) { let cntOK = 0; let cntFail = 0; let nIndexS2S = 0; diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 8e5ff089..dc298b32 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -36,8 +36,8 @@ export async function getBalanceEth( isMainNet: boolean, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null, chainId: string, - joAccount?: state.TAccount, - contractERC20?: any + joAccount: state.TAccount | null, + contractERC20: owaspUtils.ethersMod.Contract | null ) { const strLogPrefix = "getBalanceEth() call "; try { @@ -145,13 +145,13 @@ export async function doEthPaymentFromMainNet( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doEthPaymentFromMainNet", false ); + details.exposeDetailsTo( log.globalStream(), "doEthPaymentFromMainNet", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ETH PAYMENT FROM MAIN NET", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doEthPaymentFromMainNet", true ); + details.exposeDetailsTo( log.globalStream(), "doEthPaymentFromMainNet", true ); details.close(); return true; } @@ -242,13 +242,13 @@ export async function doEthPaymentFromSChain( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doEthPaymentFromSChain", false ); + details.exposeDetailsTo( log.globalStream(), "doEthPaymentFromSChain", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ETH PAYMENT FROM S-CHAIN", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doEthPaymentFromSChain", true ); + details.exposeDetailsTo( log.globalStream(), "doEthPaymentFromSChain", true ); details.close(); return true; } @@ -302,13 +302,14 @@ export async function receiveEthPaymentFromSchainOnMainNet( } catch ( err ) { details.critical( "{p}Receive payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "receiveEthPaymentFromSchainOnMainNet", false ); + details.exposeDetailsTo( log.globalStream(), + "receiveEthPaymentFromSchainOnMainNet", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "RECEIVE ETH ON MAIN NET", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "receiveEthPaymentFromSchainOnMainNet", true ); + details.exposeDetailsTo( log.globalStream(), "receiveEthPaymentFromSchainOnMainNet", true ); details.close(); return true; } @@ -332,14 +333,16 @@ export async function viewEthPaymentFromSchainOnMainNet( details.success( "{p}You can receive(wei): {}", strLogPrefix, xWei ); const xEth = owaspUtils.ethersMod.ethers.utils.formatEther( owaspUtils.toBN( xWei ) ); details.success( "{p}You can receive(eth): {}", strLogPrefix, xEth ); - if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "viewEthPaymentFromSchainOnMainNet", true ); + if( log.exposeDetailsGet() ) { + details.exposeDetailsTo( log.globalStream(), + "viewEthPaymentFromSchainOnMainNet", true ); + } details.close(); return xWei; } catch ( err ) { details.critical( "{p}View payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "viewEthPaymentFromSchainOnMainNet", false ); + details.exposeDetailsTo( log.globalStream(), "viewEthPaymentFromSchainOnMainNet", false ); details.close(); return null; } diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 9fadf1f2..606a36eb 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -29,7 +29,7 @@ import * as rpcCall from "./rpcCall.js"; import * as imaHelperAPIs from "./imaHelperAPIs.js"; import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; -export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumber: any ) { +export function createProgressiveEventsScanPlan( details: log.TLogger, nLatestBlockNumber: any ) { // assume Main Net mines 6 blocks per minute const blocksInOneMinute = 6; const blocksInOneHour = blocksInOneMinute * 60; @@ -85,7 +85,7 @@ export function createProgressiveEventsScanPlan( details: any, nLatestBlockNumbe } export async function safeGetPastEventsProgressive( - details: any, strLogPrefix: string, + details: log.TLogger, strLogPrefix: string, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, attempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any @@ -165,7 +165,7 @@ export async function safeGetPastEventsProgressive( } export async function getContractCallEvents( - details: any, strLogPrefix: string, + details: log.TLogger, strLogPrefix: string, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockNumber: any, strTxHash: string, joFilter: any @@ -196,7 +196,7 @@ export async function getContractCallEvents( } export async function safeGetTransactionCount( - details: any, cntAttempts: number, + details: log.TLogger, cntAttempts: number, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, address: string, param: any, retValOnFail: any, throwIfServerOffline: boolean @@ -242,7 +242,7 @@ export async function safeGetTransactionCount( } export async function safeGetTransactionReceipt( - details: any, cntAttempts: number, + details: log.TLogger, cntAttempts: number, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, txHash: string, retValOnFail?: any, throwIfServerOffline?: boolean ) { @@ -287,7 +287,7 @@ export async function safeGetTransactionReceipt( } export async function safeGetPastEvents( - details: any, strLogPrefix: string, + details: log.TLogger, strLogPrefix: string, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, cntAttempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any, @@ -366,7 +366,7 @@ export async function safeGetPastEvents( } export async function safeGetPastEventsIterative( - details: any, strLogPrefix: string, + details: log.TLogger, strLogPrefix: string, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, attempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 2e16354d..14c0b6f4 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -62,7 +62,7 @@ export const currentTimestamp = (): number => { }; export async function safeWaitForNextBlockToAppear( - details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider ) { + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider ) { const nBlockNumber: any = owaspUtils.toBN( await safeGetBlockNumber( details, 10, ethersProvider ) ); details.trace( "Waiting for next block to appear..." ); @@ -78,7 +78,7 @@ export async function safeWaitForNextBlockToAppear( } export async function safeGetBlockNumber( - details: any, cntAttempts: number, + details: log.TLogger, cntAttempts: number, ethersProvider: owaspUtils.ethersMod.providers.JsonRpcProvider, retValOnFail?: any, throwIfServerOffline?: boolean ) { diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 453652b2..e78899c0 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -30,6 +30,31 @@ import * as imaTx from "./imaTx.js"; import * as imaGasUsage from "./imaGasUsageOperations.js"; import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; import type * as state from "./state.js"; +import type * as IMA from "./imaCore.js"; + +export type TFunctionSignMsgOracle = + ( u256: any, details: log.TLogger, fnAfter: IMA.TFunctionAfterSigningMessages + ) => Promise ; + +export interface TGasPriceSetupOptions { + ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider + ethersProviderSChain: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider + transactionCustomizerSChain: imaTx.TransactionCustomizer + joCommunityLocker: owaspUtils.ethersMod.Contract + joAccountSC: state.TAccount + chainIdMainNet: string + chainIdSChain: string + fnSignMsgOracle: TFunctionSignMsgOracle + details: log.TLogger + jarrReceipts: any[] + strLogPrefix: string + strActionName: string + latestBlockNumber: any | null + latestBlock: any | null + bnTimestampOfBlock: any | null + bnTimeZoneOffset: any | null + gasPriceOnMainNet: any | null +} let gFlagIsEnabledOracle: boolean = false; @@ -40,48 +65,48 @@ export function setEnabledOracle( isEnabled: boolean ): void { gFlagIsEnabledOracle = ( !!isEnabled ); } -async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { - optsGasPriseSetup.strActionName = - "prepareOracleGasPriceSetup.optsGasPriseSetup.latestBlockNumber()"; - optsGasPriseSetup.latestBlockNumber = - await optsGasPriseSetup.ethersProviderMainNet.getBlockNumber(); - optsGasPriseSetup.details.trace( "Latest block on Main Net is {}", - optsGasPriseSetup.latestBlockNumber ); - optsGasPriseSetup.strActionName = - "prepareOracleGasPriceSetup.optsGasPriseSetup.bnTimestampOfBlock()"; - optsGasPriseSetup.latestBlock = - await optsGasPriseSetup.ethersProviderMainNet - .getBlock( optsGasPriseSetup.latestBlockNumber ); - optsGasPriseSetup.bnTimestampOfBlock = - owaspUtils.toBN( optsGasPriseSetup.latestBlock.timestamp ); - optsGasPriseSetup.details.trace( "Local timestamp on Main Net is {}={} (original)", - optsGasPriseSetup.bnTimestampOfBlock.toString(), - owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimestampOfBlock.toHexString() ) ); - optsGasPriseSetup.bnTimeZoneOffset = owaspUtils.toBN( new Date( parseInt( - optsGasPriseSetup.bnTimestampOfBlock.toString(), 10 ) ).getTimezoneOffset() ); - optsGasPriseSetup.details.trace( "Local time zone offset is {}={} (original)", - optsGasPriseSetup.bnTimeZoneOffset.toString(), - owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimeZoneOffset.toHexString() ) ); - optsGasPriseSetup.bnTimestampOfBlock = - optsGasPriseSetup.bnTimestampOfBlock.add( optsGasPriseSetup.bnTimeZoneOffset ); - optsGasPriseSetup.details.trace( "UTC timestamp on Main Net is {}={} (original)", - optsGasPriseSetup.bnTimestampOfBlock.toString(), - owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimestampOfBlock.toHexString() ) ); +async function prepareOracleGasPriceSetup( optsGasPriceSetup: TGasPriceSetupOptions ) { + optsGasPriceSetup.strActionName = + "prepareOracleGasPriceSetup.optsGasPriceSetup.latestBlockNumber()"; + optsGasPriceSetup.latestBlockNumber = + await optsGasPriceSetup.ethersProviderMainNet.getBlockNumber(); + optsGasPriceSetup.details.trace( "Latest block on Main Net is {}", + optsGasPriceSetup.latestBlockNumber ); + optsGasPriceSetup.strActionName = + "prepareOracleGasPriceSetup.optsGasPriceSetup.bnTimestampOfBlock()"; + optsGasPriceSetup.latestBlock = + await optsGasPriceSetup.ethersProviderMainNet + .getBlock( optsGasPriceSetup.latestBlockNumber ); + optsGasPriceSetup.bnTimestampOfBlock = + owaspUtils.toBN( optsGasPriceSetup.latestBlock.timestamp ); + optsGasPriceSetup.details.trace( "Local timestamp on Main Net is {}={} (original)", + optsGasPriceSetup.bnTimestampOfBlock.toString(), + owaspUtils.ensureStartsWith0x( optsGasPriceSetup.bnTimestampOfBlock.toHexString() ) ); + optsGasPriceSetup.bnTimeZoneOffset = owaspUtils.toBN( new Date( parseInt( + optsGasPriceSetup.bnTimestampOfBlock.toString(), 10 ) ).getTimezoneOffset() ); + optsGasPriceSetup.details.trace( "Local time zone offset is {}={} (original)", + optsGasPriceSetup.bnTimeZoneOffset.toString(), + owaspUtils.ensureStartsWith0x( optsGasPriceSetup.bnTimeZoneOffset.toHexString() ) ); + optsGasPriceSetup.bnTimestampOfBlock = + optsGasPriceSetup.bnTimestampOfBlock.add( optsGasPriceSetup.bnTimeZoneOffset ); + optsGasPriceSetup.details.trace( "UTC timestamp on Main Net is {}={} (original)", + optsGasPriceSetup.bnTimestampOfBlock.toString(), + owaspUtils.ensureStartsWith0x( optsGasPriceSetup.bnTimestampOfBlock.toHexString() ) ); const bnValueToSubtractFromTimestamp = owaspUtils.toBN( 60 ); - optsGasPriseSetup.details.trace( + optsGasPriceSetup.details.trace( "Value to subtract from timestamp is {}={}(to adjust it to past a bit)", bnValueToSubtractFromTimestamp, owaspUtils.ensureStartsWith0x( bnValueToSubtractFromTimestamp.toHexString() ) ); - optsGasPriseSetup.bnTimestampOfBlock = - optsGasPriseSetup.bnTimestampOfBlock.sub( bnValueToSubtractFromTimestamp ); - optsGasPriseSetup.details.trace( "Timestamp on Main Net is {}={} (adjusted to past a bit)", - optsGasPriseSetup.bnTimestampOfBlock.toHexString(), - owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimestampOfBlock.toHexString() ) ); - optsGasPriseSetup.strActionName = "prepareOracleGasPriceSetup.getGasPrice()"; - optsGasPriseSetup.gasPriceOnMainNet = null; + optsGasPriceSetup.bnTimestampOfBlock = + optsGasPriceSetup.bnTimestampOfBlock.sub( bnValueToSubtractFromTimestamp ); + optsGasPriceSetup.details.trace( "Timestamp on Main Net is {}={} (adjusted to past a bit)", + optsGasPriceSetup.bnTimestampOfBlock.toHexString(), + owaspUtils.ensureStartsWith0x( optsGasPriceSetup.bnTimestampOfBlock.toHexString() ) ); + optsGasPriceSetup.strActionName = "prepareOracleGasPriceSetup.getGasPrice()"; + optsGasPriceSetup.gasPriceOnMainNet = null; if( getEnabledOracle() ) { const oracleOpts = { - url: owaspUtils.ethersProviderToUrl( optsGasPriseSetup.ethersProviderSChain ), + url: owaspUtils.ethersProviderToUrl( optsGasPriceSetup.ethersProviderSChain ), callOpts: { }, nMillisecondsSleepBefore: 1000, nMillisecondsSleepPeriod: 3000, @@ -91,58 +116,61 @@ async function prepareOracleGasPriceSetup( optsGasPriseSetup: any ) { isVerboseTraceDetails: ( log.verboseGet() >= log.verboseName2Number( "debug" ) ) ? true : false }; - optsGasPriseSetup.details.debug( + optsGasPriceSetup.details.debug( "Will fetch Main Net gas price via call to Oracle with options {}...", oracleOpts ); try { - optsGasPriseSetup.gasPriceOnMainNet = owaspUtils.ensureStartsWith0x( + optsGasPriceSetup.gasPriceOnMainNet = owaspUtils.ensureStartsWith0x( ( await imaOracle.oracleGetGasPrice( - oracleOpts, optsGasPriseSetup.details ) ).toString( 16 ) ); + oracleOpts, optsGasPriceSetup.details ) ).toString( 16 ) ); } catch ( err ) { - optsGasPriseSetup.gasPriceOnMainNet = null; - optsGasPriseSetup.details.error( "Failed to fetch Main Net gas price via call " + + optsGasPriceSetup.gasPriceOnMainNet = null; + optsGasPriceSetup.details.error( "Failed to fetch Main Net gas price via call " + "to Oracle, error is: {err}, stack is:\n{stack}", err, err ); } } - if( optsGasPriseSetup.gasPriceOnMainNet === null ) { - optsGasPriseSetup.details.debug( "Will fetch Main Net gas price directly..." ); - optsGasPriseSetup.gasPriceOnMainNet = owaspUtils.ensureStartsWith0x( + if( optsGasPriceSetup.gasPriceOnMainNet === null ) { + optsGasPriceSetup.details.debug( "Will fetch Main Net gas price directly..." ); + optsGasPriceSetup.gasPriceOnMainNet = owaspUtils.ensureStartsWith0x( owaspUtils.toBN( - await optsGasPriseSetup.ethersProviderMainNet.getGasPrice() ).toHexString() ); + await optsGasPriceSetup.ethersProviderMainNet.getGasPrice() ).toHexString() ); } - optsGasPriseSetup.details.success( "Done, Oracle did computed new Main Net gas price={}={}", - owaspUtils.toBN( optsGasPriseSetup.gasPriceOnMainNet ).toString(), - optsGasPriseSetup.gasPriceOnMainNet ); + optsGasPriceSetup.details.success( "Done, Oracle did computed new Main Net gas price={}={}", + owaspUtils.toBN( optsGasPriceSetup.gasPriceOnMainNet ).toString(), + optsGasPriceSetup.gasPriceOnMainNet ); const joGasPriceOnMainNetOld = - await optsGasPriseSetup.joCommunityLocker.callStatic.mainnetGasPrice( - { from: optsGasPriseSetup.joAccountSC.address() } ); + await optsGasPriceSetup.joCommunityLocker.callStatic.mainnetGasPrice( + { from: optsGasPriceSetup.joAccountSC.address() } ); const bnGasPriceOnMainNetOld = owaspUtils.toBN( joGasPriceOnMainNetOld ); - optsGasPriseSetup.details.trace( + optsGasPriceSetup.details.trace( "Previous Main Net gas price saved and kept in CommunityLocker={}={}", bnGasPriceOnMainNetOld.toString(), bnGasPriceOnMainNetOld.toHexString() ); - if( bnGasPriceOnMainNetOld.eq( owaspUtils.toBN( optsGasPriseSetup.gasPriceOnMainNet ) ) ) { - optsGasPriseSetup.details.trace( "Previous Main Net gas price is equal to new one, " + + if( bnGasPriceOnMainNetOld.eq( owaspUtils.toBN( optsGasPriceSetup.gasPriceOnMainNet ) ) ) { + optsGasPriceSetup.details.trace( "Previous Main Net gas price is equal to new one, " + " will skip setting it in CommunityLocker" ); - if( log.exposeDetailsGet() ) - optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", true ); - optsGasPriseSetup.details.close(); - + if( log.exposeDetailsGet() ) { + optsGasPriceSetup.details.exposeDetailsTo( + log.globalStream(), "doOracleGasPriceSetup", true ); + } + optsGasPriceSetup.details.close(); } } async function handleOracleSigned( - optsGasPriseSetup: any, strError: string, u256: any, joGlueResult: any ) { + optsGasPriceSetup: TGasPriceSetupOptions, strError: Error | string | null, + u256: any, joGlueResult: any | null ) { if( strError ) { - optsGasPriseSetup.details.critical( + optsGasPriceSetup.details.critical( "{p}Error in doOracleGasPriceSetup() during {bright}: {err}", - optsGasPriseSetup.strLogPrefix, optsGasPriseSetup.strActionName, strError ); - optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", false ); + optsGasPriceSetup.strLogPrefix, optsGasPriceSetup.strActionName, strError ); + optsGasPriceSetup.details.exposeDetailsTo( + log.globalStream(), "doOracleGasPriceSetup", false ); imaTransferErrorHandling.saveTransferError( - "oracle", optsGasPriseSetup.details.toString() ); - optsGasPriseSetup.details.close(); + "oracle", optsGasPriceSetup.details.toString() ); + optsGasPriceSetup.details.close(); return; } - optsGasPriseSetup.strActionName = "doOracleGasPriceSetup.formatSignature"; - let signature = joGlueResult ? joGlueResult.signature : null; + optsGasPriceSetup.strActionName = "doOracleGasPriceSetup.formatSignature"; + let signature: owaspUtils.TXYSignature | null = joGlueResult ? joGlueResult.signature : null; if( ! signature ) signature = { X: "0", Y: "0" }; let hashPoint = joGlueResult ? joGlueResult.hashPoint : null; @@ -151,17 +179,17 @@ async function handleOracleSigned( let hint = joGlueResult ? joGlueResult.hint : null; if( ! hint ) hint = "0"; - const sign: any = { + const sign: owaspUtils.TBLSSignature = { blsSignature: [ signature.X, signature.Y ], // BLS glue of signatures hashA: hashPoint.X, // G1.X from joGlueResult.hashSrc hashB: hashPoint.Y, // G1.Y from joGlueResult.hashSrc counter: hint }; - optsGasPriseSetup.strActionName = + optsGasPriceSetup.strActionName = "Oracle gas price setup via CommunityLocker.setGasPrice()"; const arrArgumentsSetGasPrice = [ u256, - owaspUtils.ensureStartsWith0x( optsGasPriseSetup.bnTimestampOfBlock.toHexString() ), + owaspUtils.ensureStartsWith0x( optsGasPriceSetup.bnTimestampOfBlock.toHexString() ), sign // bls signature components ]; const joDebugArgs = [ @@ -170,46 +198,46 @@ async function handleOracleSigned( hashPoint.Y, // G1.Y from joGlueResult.hashSrc hint ]; - optsGasPriseSetup.details.debug( "{p}....debug args for : {}", - optsGasPriseSetup.strLogPrefix, joDebugArgs ); + optsGasPriceSetup.details.debug( "{p}....debug args for : {}", + optsGasPriceSetup.strLogPrefix, joDebugArgs ); const weiHowMuch = undefined; - const gasPrice = await optsGasPriseSetup.transactionCustomizerSChain.computeGasPrice( - optsGasPriseSetup.ethersProviderSChain, 200000000000 ); - optsGasPriseSetup.details.trace( "{p}Using computed gasPrice={}", - optsGasPriseSetup.strLogPrefix, gasPrice ); - const estimatedGasSetGasPrice = await optsGasPriseSetup.transactionCustomizerSChain.computeGas( - optsGasPriseSetup.details, optsGasPriseSetup.ethersProviderSChain, - "CommunityLocker", optsGasPriseSetup.joCommunityLocker, - "setGasPrice", arrArgumentsSetGasPrice, optsGasPriseSetup.joAccountSC, - optsGasPriseSetup.strActionName, gasPrice, 10000000, weiHowMuch ); - optsGasPriseSetup.details.trace( "{p}Using estimated gas={}", - optsGasPriseSetup.strLogPrefix, estimatedGasSetGasPrice ); + const gasPrice = await optsGasPriceSetup.transactionCustomizerSChain.computeGasPrice( + optsGasPriceSetup.ethersProviderSChain, 200000000000 ); + optsGasPriceSetup.details.trace( "{p}Using computed gasPrice={}", + optsGasPriceSetup.strLogPrefix, gasPrice ); + const estimatedGasSetGasPrice = await optsGasPriceSetup.transactionCustomizerSChain.computeGas( + optsGasPriceSetup.details, optsGasPriceSetup.ethersProviderSChain, + "CommunityLocker", optsGasPriceSetup.joCommunityLocker, + "setGasPrice", arrArgumentsSetGasPrice, optsGasPriceSetup.joAccountSC, + optsGasPriceSetup.strActionName, gasPrice, 10000000, weiHowMuch ); + optsGasPriceSetup.details.trace( "{p}Using estimated gas={}", + optsGasPriceSetup.strLogPrefix, estimatedGasSetGasPrice ); const isIgnoreSetGasPrice = false; - const strErrorOfDryRun = await imaTx.dryRunCall( optsGasPriseSetup.details, - optsGasPriseSetup.ethersProviderSChain, - "CommunityLocker", optsGasPriseSetup.joCommunityLocker, + const strErrorOfDryRun = await imaTx.dryRunCall( optsGasPriceSetup.details, + optsGasPriceSetup.ethersProviderSChain, + "CommunityLocker", optsGasPriceSetup.joCommunityLocker, "setGasPrice", arrArgumentsSetGasPrice, - optsGasPriseSetup.joAccountSC, optsGasPriseSetup.strActionName, + optsGasPriceSetup.joAccountSC, optsGasPriceSetup.strActionName, isIgnoreSetGasPrice, gasPrice, estimatedGasSetGasPrice, weiHowMuch ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = { - isCheckTransactionToSchain: ( optsGasPriseSetup.chainIdSChain !== "Mainnet" ) ? true : false + isCheckTransactionToSchain: ( optsGasPriceSetup.chainIdSChain !== "Mainnet" ) ? true : false }; - const joReceipt = await imaTx.payedCall( optsGasPriseSetup.details, - optsGasPriseSetup.ethersProviderSChain, - "CommunityLocker", optsGasPriseSetup.joCommunityLocker, + const joReceipt = await imaTx.payedCall( optsGasPriceSetup.details, + optsGasPriceSetup.ethersProviderSChain, + "CommunityLocker", optsGasPriceSetup.joCommunityLocker, "setGasPrice", arrArgumentsSetGasPrice, - optsGasPriseSetup.joAccountSC, optsGasPriseSetup.strActionName, + optsGasPriceSetup.joAccountSC, optsGasPriceSetup.strActionName, gasPrice, estimatedGasSetGasPrice, weiHowMuch, opts ); if( joReceipt && typeof joReceipt == "object" ) { - optsGasPriseSetup.jarrReceipts.push( { + optsGasPriceSetup.jarrReceipts.push( { description: "doOracleGasPriceSetup/setGasPrice", receipt: joReceipt } ); imaGasUsage.printGasUsageReportFromArray( "(intermediate result) ORACLE GAS PRICE SETUP ", - optsGasPriseSetup.jarrReceipts, optsGasPriseSetup.details ); + optsGasPriceSetup.jarrReceipts, optsGasPriceSetup.details ); } imaTransferErrorHandling.saveTransferSuccess( "oracle" ); } @@ -222,11 +250,11 @@ export async function doOracleGasPriceSetup( joAccountSC: state.TAccount, chainIdMainNet: string, chainIdSChain: string, - fnSignMsgOracle: any + fnSignMsgOracle: TFunctionSignMsgOracle ) { if( ! getEnabledOracle() ) return true; - const optsGasPriseSetup: any = { + const optsGasPriceSetup: TGasPriceSetupOptions = { ethersProviderMainNet, ethersProviderSChain, transactionCustomizerSChain, @@ -245,44 +273,49 @@ export async function doOracleGasPriceSetup( bnTimeZoneOffset: null, gasPriceOnMainNet: null }; - if( optsGasPriseSetup.fnSignMsgOracle == null || - optsGasPriseSetup.fnSignMsgOracle == undefined ) { - optsGasPriseSetup.details.trace( "{p}Using internal u256 signing stub function", - optsGasPriseSetup.strLogPrefix ); - optsGasPriseSetup.fnSignMsgOracle = - async function( u256: any, details: any, fnAfter: any ) { + if( optsGasPriceSetup.fnSignMsgOracle == null || + optsGasPriceSetup.fnSignMsgOracle == undefined ) { + optsGasPriceSetup.details.trace( "{p}Using internal u256 signing stub function", + optsGasPriceSetup.strLogPrefix ); + optsGasPriceSetup.fnSignMsgOracle = + async function( u256: any, details: log.TLogger, + fnAfter: IMA.TFunctionAfterSigningMessages ) { details.trace( "{p}u256 signing callback was not provided", - optsGasPriseSetup.strLogPrefix ); + optsGasPriceSetup.strLogPrefix ); await fnAfter( null, u256, null ); // null - no error, null - no signatures }; } else { - optsGasPriseSetup.details.trace( "{p}Using externally provided u256 signing function", - optsGasPriseSetup.strLogPrefix ); + optsGasPriceSetup.details.trace( "{p}Using externally provided u256 signing function", + optsGasPriceSetup.strLogPrefix ); } try { - await prepareOracleGasPriceSetup( optsGasPriseSetup ); - optsGasPriseSetup.strActionName = - "doOracleGasPriceSetup.optsGasPriseSetup.fnSignMsgOracle()"; - await optsGasPriseSetup.fnSignMsgOracle( - optsGasPriseSetup.gasPriceOnMainNet, optsGasPriseSetup.details, - async function( strError: string, u256: any, joGlueResult: any ) { - await handleOracleSigned( optsGasPriseSetup, strError, u256, joGlueResult ); + await prepareOracleGasPriceSetup( optsGasPriceSetup ); + optsGasPriceSetup.strActionName = + "doOracleGasPriceSetup.optsGasPriceSetup.fnSignMsgOracle()"; + await optsGasPriceSetup.fnSignMsgOracle( + optsGasPriceSetup.gasPriceOnMainNet, optsGasPriceSetup.details, + async function( + strError: Error | string | null, u256: any, joGlueResult: any | null ) { + await handleOracleSigned( optsGasPriceSetup, strError, u256, joGlueResult ); } ); } catch ( err ) { - optsGasPriseSetup.details.critical( + optsGasPriceSetup.details.critical( "{p}Error in doOracleGasPriceSetup() during {bright}: {err}, stack is:\n{stack}", - optsGasPriseSetup.strLogPrefix, optsGasPriseSetup.strActionName, + optsGasPriceSetup.strLogPrefix, optsGasPriceSetup.strActionName, err, err ); - optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", false ); + optsGasPriceSetup.details.exposeDetailsTo( + log.globalStream(), "doOracleGasPriceSetup", false ); imaTransferErrorHandling.saveTransferError( - "oracle", optsGasPriseSetup.details.toString() ); - optsGasPriseSetup.details.close(); + "oracle", optsGasPriceSetup.details.toString() ); + optsGasPriceSetup.details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ORACLE GAS PRICE SETUP ", - optsGasPriseSetup.jarrReceipts, optsGasPriseSetup.details ); - if( log.exposeDetailsGet() ) - optsGasPriseSetup.details.exposeDetailsTo( log, "doOracleGasPriceSetup", true ); - optsGasPriseSetup.details.close(); + optsGasPriceSetup.jarrReceipts, optsGasPriceSetup.details ); + if( log.exposeDetailsGet() ) { + optsGasPriceSetup.details.exposeDetailsTo( + log.globalStream(), "doOracleGasPriceSetup", true ); + } + optsGasPriceSetup.details.close(); return true; } diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 07bbad47..7a194d99 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -31,7 +31,7 @@ import type * as owaspUtils from "./owaspUtils.js"; import type * as state from "./state.js"; export async function invokeHasChain( - details: any, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, // Main-Net or S-Chin joLinker: owaspUtils.ethersMod.Contract, // Main-Net or S-Chin joAccount: state.TAccount, // Main-Net or S-Chin @@ -54,7 +54,7 @@ export async function invokeHasChain( } export async function waitForHasChain( - details: any, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, // Main-Net or S-Chin joLinker: owaspUtils.ethersMod.Contract, // Main-Net or S-Chin joAccount: state.TAccount, // Main-Net or S-Chin @@ -102,15 +102,18 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 await joLinker.callStatic.hasSchain( chainIdSChain, { from: addressFrom } ); details.success( "{p}checkIsRegisteredSChainInDepositBoxes(reg-step1) status is: {}", strLogPrefix, bIsRegistered ); - if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "checkIsRegisteredSChainInDepositBoxes", true ); + if( log.exposeDetailsGet() ) { + details.exposeDetailsTo( + log.globalStream(), "checkIsRegisteredSChainInDepositBoxes", true ); + } details.close(); return bIsRegistered; } catch ( err ) { details.critical( "{p}Error in checkIsRegisteredSChainInDepositBoxes(reg-step1)() during {bright}: " + "{err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "checkIsRegisteredSChainInDepositBoxes", false ); + details.exposeDetailsTo( + log.globalStream(), "checkIsRegisteredSChainInDepositBoxes", false ); details.close(); } return false; @@ -207,12 +210,15 @@ export async function registerSChainInDepositBoxes( // step 1 } catch ( err ) { details.critical( "{p}Error in registerSChainInDepositBoxes() during {bright}: {err}" + ", stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "registerSChainInDepositBoxes", false ); + details.exposeDetailsTo( + log.globalStream(), "registerSChainInDepositBoxes", false ); details.close(); return null; } - if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "registerSChainInDepositBoxes", true ); + if( log.exposeDetailsGet() ) { + details.exposeDetailsTo( + log.globalStream(), "registerSChainInDepositBoxes", true ); + } details.close(); return jarrReceipts; } diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index e3714103..736f77a2 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -58,13 +58,13 @@ export async function reimbursementShowBalance( log.information( s ); details.information( s ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "reimbursementShowBalance", true ); + details.exposeDetailsTo( log.globalStream(), "reimbursementShowBalance", true ); details.close(); return xWei; } catch ( err ) { details.critical( "{p}Payment error in reimbursementShowBalance(): {err}, " + "stack is:\n{stack}", strLogPrefix, err, err ); - details.exposeDetailsTo( log, "reimbursementShowBalance", false ); + details.exposeDetailsTo( log.globalStream(), "reimbursementShowBalance", false ); details.close(); return 0; } @@ -141,13 +141,13 @@ export async function reimbursementEstimateAmount( details.information( s ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "reimbursementEstimateAmount", true ); + details.exposeDetailsTo( log.globalStream(), "reimbursementEstimateAmount", true ); details.close(); return amountToRecharge; } catch ( err ) { details.critical( "{p} Payment error in reimbursementEstimateAmount(): {err}, " + "stack is:\n{stack}", strLogPrefix, err, err ); - details.exposeDetailsTo( log, "reimbursementEstimateAmount", false ); + details.exposeDetailsTo( log.globalStream(), "reimbursementEstimateAmount", false ); details.close(); return 0; } @@ -203,14 +203,14 @@ export async function reimbursementWalletRecharge( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "reimbursementWalletRecharge", false ); + details.exposeDetailsTo( log.globalStream(), "reimbursementWalletRecharge", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "REIMBURSEMENT_WALLET_RECHARGE", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "reimbursementWalletRecharge", true ); + details.exposeDetailsTo( log.globalStream(), "reimbursementWalletRecharge", true ); details.close(); return true; } @@ -270,14 +270,14 @@ export async function reimbursementWalletWithdraw( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "reimbursementWalletWithdraw", false ); + details.exposeDetailsTo( log.globalStream(), "reimbursementWalletWithdraw", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "REIMBURSEMENT_WALLET_WITHDRAW", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "reimbursementWalletWithdraw", true ); + details.exposeDetailsTo( log.globalStream(), "reimbursementWalletWithdraw", true ); details.close(); return true; } @@ -335,14 +335,14 @@ export async function reimbursementSetRange( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "reimbursementSetRange", false ); + details.exposeDetailsTo( log.globalStream(), "reimbursementSetRange", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "REIMBURSEMENT_SET_RANGE", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "reimbursementSetRange", true ); + details.exposeDetailsTo( log.globalStream(), "reimbursementSetRange", true ); details.close(); return true; } diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index c8f05017..2d82c2ad 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -76,7 +76,7 @@ export async function getOwnerOfErc721( joABI && ( strCoinName + "_address" ) in joABI ) ) return ""; const strAddress = joAccount.address(); - const contractERC721: any = new owaspUtils.ethersMod.ethers.Contract( + const contractERC721 = new owaspUtils.ethersMod.ethers.Contract( joABI[strCoinName + "_address"], joABI[strCoinName + "_abi"], ethersProvider @@ -246,14 +246,14 @@ export async function doErc721PaymentFromMainNet( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc721PaymentFromMainNet", false ); + details.exposeDetailsTo( log.globalStream(), "doErc721PaymentFromMainNet", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-721 PAYMENT FROM MAIN NET", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc721PaymentFromMainNet", true ); + details.exposeDetailsTo( log.globalStream(), "doErc721PaymentFromMainNet", true ); details.close(); return true; } @@ -383,14 +383,14 @@ export async function doErc20PaymentFromMainNet( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc20PaymentFromMainNet", false ); + details.exposeDetailsTo( log.globalStream(), "doErc20PaymentFromMainNet", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-20 PAYMENT FROM MAIN NET", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc20PaymentFromMainNet", true ); + details.exposeDetailsTo( log.globalStream(), "doErc20PaymentFromMainNet", true ); details.close(); return true; } @@ -530,14 +530,14 @@ export async function doErc1155PaymentFromMainNet( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc1155PaymentFromMainNet", false ); + details.exposeDetailsTo( log.globalStream(), "doErc1155PaymentFromMainNet", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-1155 PAYMENT FROM MAIN NET", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc1155PaymentFromMainNet", true ); + details.exposeDetailsTo( log.globalStream(), "doErc1155PaymentFromMainNet", true ); details.close(); return true; } @@ -659,14 +659,14 @@ export async function doErc1155BatchPaymentFromMainNet( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc1155BatchPaymentFromMainNet", false ); + details.exposeDetailsTo( log.globalStream(), "doErc1155BatchPaymentFromMainNet", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-1155 PAYMENT FROM MAIN NET", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc1155BatchPaymentFromMainNet", true ); + details.exposeDetailsTo( log.globalStream(), "doErc1155BatchPaymentFromMainNet", true ); details.close(); return true; } @@ -803,14 +803,14 @@ export async function doErc20PaymentFromSChain( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc20PaymentFromSChain", false ); + details.exposeDetailsTo( log.globalStream(), "doErc20PaymentFromSChain", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-20 PAYMENT FROM S-CHAIN", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc20PaymentFromSChain", true ); + details.exposeDetailsTo( log.globalStream(), "doErc20PaymentFromSChain", true ); details.close(); return true; } @@ -951,14 +951,14 @@ export async function doErc721PaymentFromSChain( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc721PaymentFromSChain", false ); + details.exposeDetailsTo( log.globalStream(), "doErc721PaymentFromSChain", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-721 PAYMENT FROM S-CHAIN", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc721PaymentFromSChain", true ); + details.exposeDetailsTo( log.globalStream(), "doErc721PaymentFromSChain", true ); details.close(); return true; } @@ -1098,14 +1098,14 @@ export async function doErc1155PaymentFromSChain( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc1155PaymentFromSChain", false ); + details.exposeDetailsTo( log.globalStream(), "doErc1155PaymentFromSChain", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-1155 PAYMENT FROM S-CHAIN", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc1155PaymentFromSChain", true ); + details.exposeDetailsTo( log.globalStream(), "doErc1155PaymentFromSChain", true ); details.close(); return true; } @@ -1244,14 +1244,14 @@ export async function doErc1155BatchPaymentFromSChain( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "doErc1155BatchPaymentFromSChain", false ); + details.exposeDetailsTo( log.globalStream(), "doErc1155BatchPaymentFromSChain", false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( "ERC-1155 PAYMENT FROM S-CHAIN", jarrReceipts, details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "doErc1155BatchPaymentFromSChain", true ); + details.exposeDetailsTo( log.globalStream(), "doErc1155BatchPaymentFromSChain", true ); details.close(); return true; } @@ -1381,16 +1381,16 @@ export async function doErc20PaymentS2S( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( - log, `doErc20PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); + details.exposeDetailsTo( log.globalStream(), + `doErc20PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); return false; } imaGasUsage.printGasUsageReportFromArray( `ERC-20 PAYMENT FROM S2S/${( isForward ? "forward" : "reverse" )}`, jarrReceipts, details ); if( log.exposeDetailsGet() ) { - details.exposeDetailsTo( - log, `doErc20PaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); + details.exposeDetailsTo( log.globalStream(), + `doErc20PaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); } details.close(); return true; @@ -1524,8 +1524,8 @@ export async function doErc721PaymentS2S( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( - log, `doErc721PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); + details.exposeDetailsTo( log.globalStream(), + `doErc721PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); return false; } @@ -1533,8 +1533,8 @@ export async function doErc721PaymentS2S( `ERC-721 PAYMENT FROM S2S/${( isForward ? "forward" : "reverse" )}`, jarrReceipts, details ); if( log.exposeDetailsGet() ) { - details.exposeDetailsTo( - log, `doErc721PaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); + details.exposeDetailsTo( log.globalStream(), + `doErc721PaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); } details.close(); return true; @@ -1669,8 +1669,8 @@ export async function doErc1155PaymentS2S( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( - log, `doErc1155PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); + details.exposeDetailsTo( log.globalStream(), + `doErc1155PaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); return false; } @@ -1678,8 +1678,8 @@ export async function doErc1155PaymentS2S( `ERC-1155 PAYMENT FROM S2S/${( isForward ? "forward" : "reverse" )}`, jarrReceipts, details ); if( log.exposeDetailsGet() ) { - details.exposeDetailsTo( - log, `doErc1155PaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); + details.exposeDetailsTo( log.globalStream(), + `doErc1155PaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); } details.close(); return true; @@ -1816,8 +1816,8 @@ export async function doErc1155BatchPaymentS2S( } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( - log, `doErc1155BatchPaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); + details.exposeDetailsTo( log.globalStream(), + `doErc1155BatchPaymentS2S/${( isForward ? "forward" : "reverse" )}`, false ); details.close(); return false; } @@ -1825,8 +1825,8 @@ export async function doErc1155BatchPaymentS2S( `ERC-1155-batch PAYMENT FROM S2S/${( isForward ? "forward" : "reverse" )}`, jarrReceipts, details ); if( log.exposeDetailsGet() ) { - details.exposeDetailsTo( - log, `doErc1155BatchPaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); + details.exposeDetailsTo( log.globalStream(), + `doErc1155BatchPaymentS2S/${( isForward ? "forward" : "reverse" )}`, true ); } details.close(); return true; @@ -1890,13 +1890,13 @@ export async function mintErc20( receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "mintErc20", true ); + details.exposeDetailsTo( log.globalStream(), "mintErc20", true ); details.close(); return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "mintErc20()", false ); + details.exposeDetailsTo( log.globalStream(), "mintErc20()", false ); details.close(); return false; } @@ -1960,13 +1960,13 @@ export async function mintErc721( receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "mintErc721", true ); + details.exposeDetailsTo( log.globalStream(), "mintErc721", true ); details.close(); return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "mintErc721()", false ); + details.exposeDetailsTo( log.globalStream(), "mintErc721()", false ); details.close(); return false; } @@ -2034,13 +2034,13 @@ export async function mintErc1155( receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "mintErc1155", true ); + details.exposeDetailsTo( log.globalStream(), "mintErc1155", true ); details.close(); return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "mintErc1155()", false ); + details.exposeDetailsTo( log.globalStream(), "mintErc1155()", false ); details.close(); return false; } @@ -2104,13 +2104,13 @@ export async function burnErc20( receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "burnErc20", true ); + details.exposeDetailsTo( log.globalStream(), "burnErc20", true ); details.close(); return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "burnErc20()", false ); + details.exposeDetailsTo( log.globalStream(), "burnErc20()", false ); details.close(); return false; } @@ -2171,13 +2171,13 @@ export async function burnErc721( receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "burnErc721", true ); + details.exposeDetailsTo( log.globalStream(), "burnErc721", true ); details.close(); return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "burnErc721()", false ); + details.exposeDetailsTo( log.globalStream(), "burnErc721()", false ); details.close(); return false; } @@ -2245,13 +2245,13 @@ export async function burnErc1155( receipt: joReceipt } ], details ); if( log.exposeDetailsGet() ) - details.exposeDetailsTo( log, "burnErc1155", true ); + details.exposeDetailsTo( log.globalStream(), "burnErc1155", true ); details.close(); return joReceipt; // can be used as "true" boolean value } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", strLogPrefix, strActionName, err, err ); - details.exposeDetailsTo( log, "burnErc1155()", false ); + details.exposeDetailsTo( log.globalStream(), "burnErc1155()", false ); details.close(); return false; } diff --git a/src/imaTx.ts b/src/imaTx.ts index 2c1ee710..1b6bc305 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -45,7 +45,7 @@ export interface TCustomPayedCallOptions { } export interface TRunTimePayedCallOptions { - details: any + details: log.TLogger ethersProvider: owaspUtils.ethersMod.providers.JsonRpcProvider strContractName: string joContract: owaspUtils.ethersMod.Contract @@ -96,7 +96,7 @@ export function dryRunIgnore( isIgnored: boolean ): boolean { } export async function dryRunCall( - details: any, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: string, arrArguments: any[], @@ -309,7 +309,7 @@ async function payedCallDirect( optsPayedCall: TRunTimePayedCallOptions ) { } export async function payedCall( - details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: any, arrArguments: any[], joAccount: state.TAccount, strActionName: string, @@ -409,7 +409,7 @@ export async function payedCall( export async function checkTransactionToSchain( unsignedTx: any, - details: any, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joAccount: state.TAccount ) { @@ -460,7 +460,7 @@ export async function checkTransactionToSchain( } export async function calculatePowNumber( - address: string, nonce: any, gas: any, details: any, strLogPrefix: string ) { + address: string, nonce: any, gas: any, details: log.TLogger, strLogPrefix: string ) { try { let _address = owaspUtils.ensureStartsWith0x( address ); _address = ethereumJsUtilModule.toChecksumAddress( _address ); @@ -521,7 +521,7 @@ function tmGenerateRandomHex( size: number ): string { .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ) } -function tmMakeId( details: any ) { +function tmMakeId( details: log.TLogger ) { const prefix = "tx-"; const unique = tmGenerateRandomHex( 16 ); const id = prefix + unique + "js"; @@ -543,7 +543,7 @@ function tmMakeScore( priority: number ) { return priority * Math.pow( 10, ts.toString().length ) + ts; } -async function tmSend( details: any, tx: any, priority: number = 5 ) { +async function tmSend( details: log.TLogger, tx: any, priority: number = 5 ) { details.trace( "TM - sending tx {} ts: {}", tx, imaHelperAPIs.currentTimestamp() ); const id = tmMakeId( details ); const score = tmMakeScore( priority ); @@ -571,7 +571,7 @@ async function tmGetRecord( txId: any ) { } async function tmWait( - details: any, + details: log.TLogger, txId: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, nWaitSeconds: number = 36000 ) { @@ -606,7 +606,7 @@ async function tmWait( } async function tmEnsureTransaction( - details: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, priority: any, txAdjusted: any, cntAttempts?: number, sleepMilliseconds?: number ) { @@ -672,7 +672,7 @@ export class TransactionCustomizer { return gasPrice; } async computeGas( - details: any, + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: string, arrArguments: any[], diff --git a/src/log.ts b/src/log.ts index cc778824..d601a005 100644 --- a/src/log.ts +++ b/src/log.ts @@ -28,11 +28,63 @@ import * as fs from "fs"; export { cc }; -let gArrStreams: any[] = []; +export type TFunctionWrite = ( ...args: any[] ) => void; +export type TFunctionClose = () => void; +export type TFunctionOpen = () => void; +export type TFunctionSize = () => number; +export type TFunctionRotate = ( nBytesToWrite: number ) => void; +export type TFunctionToString = () => string; +export type TFunctionExposeDetailsTo = + ( otherStream: TLogger, strTitle: string, isSuccess: boolean ) => void; + +export interface TLogger { + id: number + strPath: string + nMaxSizeBeforeRotation: number + nMaxFilesCount: number + objStream: any | null + haveOwnTimestamps: boolean + isPausedTimeStamps: boolean + strOwnIndent: string + write: TFunctionWrite + writeRaw: TFunctionWrite + close: TFunctionClose + open: TFunctionOpen + size: TFunctionSize + rotate: TFunctionRotate + toString: TFunctionToString + exposeDetailsTo: TFunctionExposeDetailsTo + // high-level formatters + fatal: TFunctionWrite + critical: TFunctionWrite + error: TFunctionWrite + warning: TFunctionWrite + attention: TFunctionWrite + information: TFunctionWrite + info: TFunctionWrite + notice: TFunctionWrite + note: TFunctionWrite + debug: TFunctionWrite + trace: TFunctionWrite + success: TFunctionWrite +} + +export type TFunctionIsBeginningOfAccumulatedLog = () => boolean; +export type TFunctionIsLastLineEndsWithCarriageReturn = () => boolean; +export type TFunctionClear = () => void; + +export interface TLoggerMemory extends TLogger { + arrAccumulatedLogTextLines: string[] + isBeginningOfAccumulatedLog: TFunctionIsBeginningOfAccumulatedLog + isLastLineEndsWithCarriageReturn: TFunctionIsLastLineEndsWithCarriageReturn + clear: TFunctionClear +}; + +let gArrStreams: TLogger[] = []; let gFlagLogWithTimeStamps: boolean = true; -let gIdentifierAllocatorCounter = 0; +let gIdentifierAllocatorCounter = 1; const safeURL = cc.safeURL; const replaceAll = cc.replaceAll; @@ -109,7 +161,7 @@ export function removeAllStreams(): void { gArrStreams = []; } -export function getStreamWithFilePath( strFilePath: string ): any { +export function getStreamWithFilePath( strFilePath: string ): TLogger | null { try { let i = 0; const cnt = gArrStreams.length; for( i = 0; i < cnt; ++i ) { @@ -125,9 +177,48 @@ export function getStreamWithFilePath( strFilePath: string ): any { return null; } -export function createStandardOutputStream(): any { +let gStreamGlobal: TLogger | null; + +export function globalStream(): TLogger { + if( ! gStreamGlobal ) { + gStreamGlobal = { + id: 0, + strPath: "global", + nMaxSizeBeforeRotation: -1, + nMaxFilesCount: -1, + objStream: null, + haveOwnTimestamps: false, + isPausedTimeStamps: false, + strOwnIndent: "", + write, + writeRaw, + close: function() { }, + open: function() { }, + size: function() { return 0; }, + rotate: function( nBytesToWrite: number ) { }, + toString: function(): string { return ""; }, + exposeDetailsTo, + // high-level formatters + fatal, + critical, + error, + warning, + attention, + information, + info, + notice, + note, + debug, + trace, + success + }; + } + return gStreamGlobal; +}; + +export function createStandardOutputStream(): TLogger | null { try { - const objEntry: any = { + const objEntry: TLogger = { id: gIdentifierAllocatorCounter ++, strPath: "stdout", nMaxSizeBeforeRotation: -1, @@ -157,9 +248,9 @@ export function createStandardOutputStream(): any { open: function() { try { this.objStream = process.stdout; } catch ( err ) { } }, size: function() { return 0; }, rotate: function( nBytesToWrite: number ) { }, - toString: function(): string { return "" + this.strFilePath; }, + toString: function(): string { return "" + this.strPath; }, exposeDetailsTo: - function( otherStream: any, strTitle: string, isSuccess: boolean ): void { }, + function( otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters fatal: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) @@ -236,13 +327,14 @@ export function insertStandardOutputStream(): boolean { return true; } -export function createMemoryOutputStream(): any { +export function createMemoryOutputStream(): TLogger { try { - const objEntry: any = { + const objEntry: TLoggerMemory = { id: gIdentifierAllocatorCounter ++, strPath: "memory", nMaxSizeBeforeRotation: -1, nMaxFilesCount: -1, + objStream: null, arrAccumulatedLogTextLines: [], haveOwnTimestamps: true, isPausedTimeStamps: false, @@ -291,7 +383,7 @@ export function createMemoryOutputStream(): any { open: function() { this.clear(); }, size: function() { return 0; }, rotate: - function( nBytesToWrite: number ) { this.this.arrAccumulatedLogTextLines = []; }, + function( nBytesToWrite: number ) { this.arrAccumulatedLogTextLines = []; }, toString: function(): string { let s = ""; for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) @@ -299,7 +391,7 @@ export function createMemoryOutputStream(): any { return s; }, exposeDetailsTo: - function( otherStream: any, strTitle: string, isSuccess: boolean ): void { + function( otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { if( ! ( this.arrAccumulatedLogTextLines && this.arrAccumulatedLogTextLines.length > 0 ) ) return; @@ -398,7 +490,7 @@ export function createMemoryOutputStream(): any { return objEntry; } catch ( err ) { } - return null; + return globalStream(); } export function insertMemoryOutputStream(): boolean { @@ -413,9 +505,10 @@ export function insertMemoryOutputStream(): boolean { } export function createFileOutput( - strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): any { + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number +): TLogger | null { try { - const objEntry: any = { + const objEntry: TLogger = { id: gIdentifierAllocatorCounter ++, strPath: "" + strFilePath, nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation || 0 ), @@ -490,7 +583,7 @@ export function createFileOutput( }, toString: function(): string { return "" + strFilePath; }, exposeDetailsTo: - function( otherStream: any, strTitle: string, isSuccess: boolean ): void { }, + function( otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters fatal: function( ...args: any[] ): void { if( verboseGet() >= verboseName2Number( "fatal" ) ) @@ -560,7 +653,7 @@ export function createFileOutput( return null; } export function insertFileOutput( - strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): any { + strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): boolean { let objEntry = getStreamWithFilePath( "" + strFilePath ); if( objEntry !== null ) return true; @@ -876,7 +969,7 @@ export function addMemory(): boolean { return insertMemoryOutputStream(); } -export function createMemoryStream(): any { +export function createMemoryStream(): TLogger { return createMemoryOutputStream(); } @@ -897,7 +990,8 @@ export function close(): void { // for compatibility with created streams } -export function exposeDetailsTo( otherStream: any, strTitle: string, isSuccess: boolean ): void { +export function exposeDetailsTo( + otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { // for compatibility with created streams } diff --git a/src/loop.ts b/src/loop.ts index dc07a213..52443d3b 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -71,7 +71,7 @@ export interface TLoopOptions { export interface TParallelLoopRunOptions { imaState: state.TIMAState - details: any + details: log.TLogger } // Run transfer loop diff --git a/src/main.ts b/src/main.ts index db1e9141..235557d0 100644 --- a/src/main.ts +++ b/src/main.ts @@ -383,7 +383,7 @@ async function doTheJob() { } function handleFirstSChainDiscoveryAttemptDone( - err: any, joSChainNetworkInfo: any, + err: any, joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo, isSilentReDiscovery: boolean, fnOnPeriodicDiscoveryResultAvailable: any ): void { if( err ) { // error information is printed by discoveryTools.discoverSChainNetwork() @@ -450,14 +450,16 @@ async function main() { } const nCountToWait = -1; discoveryTools.discoverSChainNetwork( - function( err: Error | string, joSChainNetworkInfo: any ) { - handleFirstSChainDiscoveryAttemptDone( - err, joSChainNetworkInfo, isSilentReDiscovery, - fnOnPeriodicDiscoveryResultAvailable ); + function( err?: Error | string | null, + joSChainNetworkInfo?: discoveryTools.TSChainNetworkInfo | null ) { + if( joSChainNetworkInfo ) { + handleFirstSChainDiscoveryAttemptDone( + err, joSChainNetworkInfo, isSilentReDiscovery, + fnOnPeriodicDiscoveryResultAvailable ); + } doTheJob().then( function() {} ).catch( function() {} ); // Finish of IMA Agent startup, // everything else is in async calls executed later - return 0; }, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait ).catch( function( err: Error | string ) { const strError = owaspUtils.extractErrorMessage( err ); diff --git a/src/observer.ts b/src/observer.ts index e93d5c7f..493c3a57 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -28,7 +28,66 @@ import * as imaUtils from "./utils.js"; import * as log from "./log.js"; import * as threadInfo from "./threadInfo.js"; -export function findSChainIndexInArrayByName( arrSChains: any[], strSChainName: string ) { +export interface TSChainNode { + name: string + ip: string + publicIP: string + port: string + startBlock: string + lastRewardDate: string + finishTime: string + status: string + validatorId: string + domainName: string + schainHashes: string[] + endpoints: { + ports: { + http: string + https: string + ws: string + wss: string + infoHttp: string + } + domain: { + http: string + https: string + ws: string + wss: string + infoHttp: string + } + ip: { + http: string + https: string + ws: string + wss: string + infoHttp: string + } + } +} + +export interface TSChainInformation { + name: string + mainnetOwner: string + indexInOwnerList: string + partOfNode: string + lifetime: string + startDate: string + startBlock: string + deposit: string + index: string + generation: string + originator: string + chainId: number + nodes: TSChainNode[] +} + +export interface TSChainsInformation { + updatedAt: number + schains: TSChainInformation[] +} + +export function findSChainIndexInArrayByName( + arrSChains: TSChainInformation[], strSChainName: string ) { for( let idxSChain = 0; idxSChain < arrSChains.length; ++ idxSChain ) { const joSChain = arrSChains[idxSChain]; if( joSChain.name.toString() == strSChainName.toString() ) @@ -37,13 +96,14 @@ export function findSChainIndexInArrayByName( arrSChains: any[], strSChainName: return -1; } -let gConnectedChainsData: any = null; +let gConnectedChainsData: TSChainsInformation | null = null; export function autoUpdateLastCachedSChains(): boolean { const imaState: state.TIMAState = state.get(); if( ! imaState.optsS2S.strNetworkBrowserPath ) return false; - const jo: any = imaUtils.jsonFileLoad( imaState.optsS2S.strNetworkBrowserPath, null ); + const jo: TSChainsInformation = + imaUtils.jsonFileLoad( imaState.optsS2S.strNetworkBrowserPath, null ); if( ! ( jo && "schains" in jo && "updatedAt" in jo ) ) { log.error( "Connected S-chains cache in thread {} was not updated from file {}, bad data format", @@ -60,26 +120,26 @@ export function autoUpdateLastCachedSChains(): boolean { return true; } -export function getLastCachedSChains(): any[] { +export function getLastCachedSChains(): TSChainInformation[] { autoUpdateLastCachedSChains(); if( ! gConnectedChainsData ) return []; return JSON.parse( JSON.stringify( gConnectedChainsData.schains ) ); } -export function pickRandomSChainNodeIndex( joSChain: any ): number { +export function pickRandomSChainNodeIndex( joSChain: TSChainInformation ): number { let min = 0; let max = joSChain.nodes.length - 1; min = Math.ceil( min ); max = Math.floor( max ); const idxNode = Math.floor( Math.random() * ( max - min + 1 ) ) + min; return idxNode; } -export function pickRandomSChainNode( joSChain: any ): any { +export function pickRandomSChainNode( joSChain: TSChainInformation ): TSChainNode { const idxNode = pickRandomSChainNodeIndex( joSChain ); return joSChain.nodes[idxNode]; } -export function pickRandomSChainUrl( joSChain: any ): string { - const joNode = pickRandomSChainNode( joSChain ); +export function pickRandomSChainUrl( joSChain: TSChainInformation ): string { + const joNode: TSChainNode = pickRandomSChainNode( joSChain ); return "" + joNode.endpoints.ip.http; } diff --git a/src/oracle.ts b/src/oracle.ts index b631b0ef..85d05a29 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -45,7 +45,7 @@ function getUtcTimestampString( d?: Date ): string { return t; } -export function findPowNumber( strRequestPart: string, details: any, isVerbose?: boolean ) { +export function findPowNumber( strRequestPart: string, details: log.TLogger, isVerbose?: boolean ) { details = details || log; if( isVerbose ) details.debug( "source part of request to find PoW number is {}", strRequestPart ); @@ -81,7 +81,7 @@ export function findPowNumber( strRequestPart: string, details: any, isVerbose?: } async function handleOracleCheckResultResult( - oracleOpts: any, details: any, isVerboseTraceDetails: boolean, + oracleOpts: any, details: log.TLogger, isVerboseTraceDetails: boolean, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { if( isVerboseTraceDetails ) @@ -106,7 +106,7 @@ async function handleOracleCheckResultResult( } async function handleOracleSubmitRequestResult( - oracleOpts: any, details: any, isVerboseTraceDetails: boolean, + oracleOpts: any, details: log.TLogger, isVerboseTraceDetails: boolean, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { const nMillisecondsSleepBefore = "nMillisecondsSleepBefore" in oracleOpts @@ -157,7 +157,7 @@ async function handleOracleSubmitRequestResult( throw new Error( "RPC call(oracle_checkResult) all attempts timed out" ); } -export async function oracleGetGasPrice( oracleOpts: any, details: any ) { +export async function oracleGetGasPrice( oracleOpts: any, details: log.TLogger ) { details = details || log; const url: string = oracleOpts.url; let gp: any = null; diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 27d4c6f0..49454085 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -31,6 +31,19 @@ import * as log from "./log.js"; import * as ethersMod from "ethers"; import * as fs from "fs"; + +export interface TXYSignature { + X: string + Y: string +} + +export interface TBLSSignature { + blsSignature: any[2] // BLS glue of signatures, X then Y + hashA: string // G1.X from joGlueResult.hashSrc + hashB: string // G1.Y from joGlueResult.hashSrc + counter: string | number | null +} + const BigNumber = ethersMod.ethers.BigNumber; const safeURL = log.safeURL; @@ -772,7 +785,7 @@ export function toHexStringSafe( val?: any ): string { return "" + val; } -export function setInterval2( fn: any, t: number, stepMilliSeconds?: number ): any { +export function setInterval2( fn: () => void, t: number, stepMilliSeconds?: number ): any { const iv: any = { real_iv: null, stepMilliSeconds: stepMilliSeconds || 1000, diff --git a/src/pwa.ts b/src/pwa.ts index 8e75ee57..feed6e46 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -28,6 +28,7 @@ import * as rpcCall from "./rpcCall.js"; import * as imaBLS from "./bls.js"; import * as imaUtils from "./utils.js"; import type * as state from "./state.js"; +import type * as discoveryTools from "./discoveryTools.js"; function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): number[] { if( nNodesCount <= 1 ) @@ -71,16 +72,17 @@ function composeEmptyStateForPendingWorkAnalysis(): any { }; } -function getNodeProgressAndTimestamp( joNode: any, strLoopWorkType: string, nIndexS2S: number ) { +function getNodeProgressAndTimestamp( + joNode: discoveryTools.TSChainNode, strLoopWorkType: string, nIndexS2S: number ) { if( ! ( "pwaState" in joNode ) ) joNode.pwaState = composeEmptyStateForPendingWorkAnalysis(); strLoopWorkType = strLoopWorkType.toLowerCase(); - if( ! ( strLoopWorkType in joNode.pwaState ) ) { + if( ( !joNode.pwaState ) || ( ! ( strLoopWorkType in joNode.pwaState ) ) ) { throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type, ` + "cannot access info" ); } if( strLoopWorkType != "s2s" ) - return joNode.pwaState[strLoopWorkType]; + return ( joNode.pwaState as any )[strLoopWorkType]; if( ! ( nIndexS2S in joNode.pwaState[strLoopWorkType].mapS2S ) ) joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S] = { isInProgress: false, ts: 0 }; @@ -114,7 +116,7 @@ export async function checkOnLoopStart( const nUtcUnixTimeStamp = Math.floor( ( new Date() ).getTime() / 1000 ); for( let i = 0; i < arrWalkNodeIndices.length; ++i ) { const walkNodeIndex = arrWalkNodeIndices[i]; - const joNode: any = jarrNodes[walkNodeIndex]; + const joNode = jarrNodes[walkNodeIndex]; const joProps: any = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); if( joProps && typeof joProps == "object" && "isInProgress" in joProps && joProps.isInProgress && @@ -237,7 +239,7 @@ async function notifyOnLoopImpl( const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; if( isThisNode ) continue; // skip this node - const joNode: any = jarrNodes[i]; + const joNode = jarrNodes[i]; const strNodeURL = imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ); const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; const joCall = diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 7c1999fd..86b1ce13 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -36,24 +36,55 @@ export interface TRPCCallOpts { ca?: string } +export type TFunctionConnectionResultHandler = + ( joCall: TRPCCall, err: Error | string | null + ) => Promise < void >; + +export type TFunctionCallResultHandler = + ( joIn: any, joOut: any, err: Error | string | null + ) => Promise < void >; + +export type TFunctionReconnect = + ( fnAfter: TFunctionConnectionResultHandler ) => Promise < void >; +export type TFunctionReconnectIfNeeded = + ( fnAfter: TFunctionConnectionResultHandler ) => Promise < void >; +export type TFunctionCall = + ( joIn: any, fnAfter?: TFunctionCallResultHandler ) => Promise < any >; +export type TFunctionDisconnect = ( + fnAfter?: TFunctionConnectionResultHandler +) => Promise < void >; + +export type TCallID = string | number | bigint; +export interface TCallHandlerEntry { + joIn: any + fn: TFunctionCallResultHandler + out: any + iv?: NodeJS.Timeout | null +} +export type TMapPendingByCallID = Map < TCallID, TCallHandlerEntry >; + export interface TRPCCall { url: string joRpcOptions: TRPCCallOpts | null - mapPendingByCallID: any + mapPendingByCallID: TMapPendingByCallID wsConn: ws.WebSocket | null isAutoReconnect: boolean isDisconnectMode: boolean - reconnect: any - reconnect_if_needed: any - call: any - disconnect: any + reconnect: TFunctionReconnect + reconnectIfNeeded: TFunctionReconnectIfNeeded + call: TFunctionCall + disconnect: TFunctionDisconnect } const gSecondsConnectionTimeout = 60; -export async function waitWebSocketIsOpen( socket: ws.WebSocket, fnDone: any, fnStep: any ) { - fnDone = fnDone || async function( nStep: number ) {}; - fnDone = fnStep || async function( nStep: number ) { return true; }; +export type TFunctionWsStep = ( nStep: number ) => Promise < boolean >; +export type TFunctionWsDone = ( nStep: number ) => Promise < void >; + +export async function waitWebSocketIsOpen( socket: ws.WebSocket, + fnDone?: TFunctionWsDone, fnStep?: TFunctionWsStep ) { + fnDone = fnDone || async function( nStep: number ) { }; + fnStep = fnStep || async function( nStep: number ) { return true; }; let nStep = 0; const promiseComplete = new Promise( function( resolve, reject ) { let isInsideAsyncHandler = false; @@ -65,13 +96,17 @@ export async function waitWebSocketIsOpen( socket: ws.WebSocket, fnDone: any, fn if( socket.readyState === 1 ) { // Notice, connection is made if we are here clearInterval( iv ); - await fnDone( nStep ); + if( fnDone ) + await fnDone( nStep ); resolve( true ); } else { - if( ! await fnStep( nStep ) ) { - clearInterval( iv ); - reject( new Error( "web socket wait timeout by callback " + - `on step ${nStep}` ) ); + if( fnStep ) { + const isContinue = await fnStep( nStep ); + if( ! isContinue ) { + clearInterval( iv ); + reject( new Error( "web socket wait timeout by callback " + + `on step ${nStep}` ) ); + } } } isInsideAsyncHandler = false; @@ -85,7 +120,8 @@ export async function waitWebSocketIsOpen( socket: ws.WebSocket, fnDone: any, fn await promiseComplete; } -export async function doConnect( joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: any ) { +export async function doConnect( + joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: TFunctionConnectionResultHandler ) { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -96,14 +132,14 @@ export async function doConnect( joCall: TRPCCall, opts: TRPCCallOpts | null, fn joCall.wsConn = new ws.WebSocket( joCall.url ); joCall.wsConn.on( "open", function() { if( fn ) - fn( joCall, null ); + fn( joCall, null ).then( function() {} ).catch( function() {} ); } ); joCall.wsConn.on( "close", function() { strWsError = "web socket was closed, please check provided URL is valid and accessible"; joCall.wsConn = null; } ); - joCall.wsConn.on( "error", function( err: any ) { + joCall.wsConn.on( "error", function( err: Error | string ) { strWsError = err.toString() || "internal web socket error"; log.error( "{url} web socket error: {err}", joCall.url, err ); const wsConn = joCall.wsConn; @@ -112,7 +148,7 @@ export async function doConnect( joCall: TRPCCall, opts: TRPCCallOpts | null, fn wsConn.close(); doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); } ); - joCall.wsConn.on( "fail", function( err: any ) { + joCall.wsConn.on( "fail", function( err: Error | string ) { strWsError = err.toString() || "internal web socket failure"; log.error( "{url} web socket fail: {err}", joCall.url, err ); const wsConn = joCall.wsConn; @@ -124,15 +160,19 @@ export async function doConnect( joCall: TRPCCall, opts: TRPCCallOpts | null, fn joCall.wsConn.on( "message", function incoming( data: any ) { const joOut = JSON.parse( data ); if( joOut.id in joCall.mapPendingByCallID ) { - const entry = joCall.mapPendingByCallID[joOut.id]; - delete joCall.mapPendingByCallID[joOut.id]; - if( entry.iv ) { - clearTimeout( entry.iv ); - entry.iv = null; + const entry = joCall.mapPendingByCallID.get( joOut.id ); + joCall.mapPendingByCallID.delete( joOut.id ); + if( entry ) { + if( entry.iv ) { + clearTimeout( entry.iv ); + entry.iv = null; + } + clearTimeout( entry.out ); + if( entry.fn ) { + entry.fn( entry.joIn, joOut, null ) + .then( function() {} ).catch( function() {} ); + } } - clearTimeout( entry.out ); - if( entry.fn ) - entry.fn( entry.joIn, joOut, null ); } } ); await waitWebSocketIsOpen( joCall.wsConn, @@ -169,12 +209,13 @@ export async function doConnect( joCall: TRPCCall, opts: TRPCCallOpts | null, fn } catch ( err ) { joCall.wsConn = null; if( fn ) - await fn( joCall, err ); + await fn( joCall, err as Error ); } return joCall; } -export async function doConnectIfNeeded( joCall: TRPCCall, opts: TRPCCallOpts | null, fn: any ) { +export async function doConnectIfNeeded( + joCall: TRPCCall, opts: TRPCCallOpts | null, fn: TFunctionConnectionResultHandler ) { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -188,17 +229,18 @@ export async function doConnectIfNeeded( joCall: TRPCCall, opts: TRPCCallOpts | await fn( joCall, null ); } catch ( err ) { if( fn ) - await fn( joCall, err ); + await fn( joCall, err as Error ); } return joCall; } -async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: any ) { +async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, + fn?: TFunctionConnectionResultHandler ) { if( ! joCall.isAutoReconnect ) return; if( joCall.isDisconnectMode ) return; - doConnect( joCall, opts, async function( joCall: TRPCCall, err: any ) { + doConnect( joCall, opts, async function( joCall: TRPCCall, err: Error | string | null ) { if( err ) { doReconnectWsStep( joCall, opts ) .then( function() {} ).catch( function() {} ); @@ -209,7 +251,7 @@ async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, f } ).then( function() {} ).catch( function() {} ); } -async function doDisconnect( joCall: TRPCCall, fn: any ) { +async function doDisconnect( joCall: TRPCCall, fn?: TFunctionConnectionResultHandler ) { try { joCall.isDisconnectMode = true; const wsConn = joCall.wsConn ? joCall.wsConn : null; @@ -224,23 +266,24 @@ async function doDisconnect( joCall: TRPCCall, fn: any ) { } } catch ( err ) { if( fn ) - await await fn( joCall, err ); + await fn( joCall, err as Error ); } } -export async function doCall( joCall: TRPCCall, joIn: any, fn: any ) { +export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResultHandler ) { joIn = enrichTopLevelFieldsInJSON( joIn ); if( joCall.wsConn ) { - const entry: any = { + const entry: TCallHandlerEntry = { joIn, fn, out: null }; - joCall.mapPendingByCallID[joIn.id] = entry; + joCall.mapPendingByCallID.set( joIn.id, entry ); entry.iv = setTimeout( function() { - clearTimeout( entry.iv ); + if( entry.iv ) + clearTimeout( entry.iv ); entry.iv = null; - delete joCall.mapPendingByCallID[joIn.id]; + joCall.mapPendingByCallID.delete( joIn.id ); }, 200 * 1000 ); joCall.wsConn.send( JSON.stringify( joIn ) ); } else { @@ -252,12 +295,12 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: any ) { return; } const strBody = JSON.stringify( joIn ); - let errCall: string | null = null; let joOut: any = null; + let errCall: string | null = null; let joOut: any | null = null; if( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" && joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" ) { const u = new URL( joCall.url ); - const options: any = { + const options = { hostname: u.hostname, port: u.port, path: "/", @@ -278,7 +321,7 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: any ) { let accumulatedBody = ""; const promiseComplete = new Promise( ( resolve, reject ) => { try { - const req = https.request( options, ( res: any ) => { + const req = https.request( options as https.RequestOptions, ( res: any ) => { res.setEncoding( "utf8" ); res.on( "data", function( body: any ) { accumulatedBody += body; @@ -294,32 +337,32 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: any ) { joOut = JSON.parse( accumulatedBody ); errCall = null; resolve( joOut ); - } catch ( err: any ) { + } catch ( err ) { joOut = null; - errCall = `Response body parse error: ${err}`; + errCall = `Response body parse error: ${err as any}`; reject( errCall ); } } ); } ); - req.on( "error", function( err: any ) { - log.error( "{url} REST error {err}", joCall.url, err ); + req.on( "error", function( err ) { + log.error( "{url} REST error {err}", joCall.url, err as any ); joOut = null; - errCall = `HTTP(S)/RPC call(event) error: ${err}`; + errCall = `HTTP(S)/RPC call(event) error: ${err as any}`; reject( errCall ); } ); req.write( strBody ); req.end(); - } catch ( err: any ) { - log.error( "{url} REST error {err}", joCall.url, err ); + } catch ( err ) { + log.error( "{url} REST error {err}", joCall.url, err as any ); joOut = null; - errCall = `HTTP(S)/RPC call(processing) error: ${err}`; + errCall = `HTTP(S)/RPC call(processing) error: ${err as any}`; reject( errCall ); } } ); await promiseComplete.catch( function( err: Error | string ) { log.error( "{url} HTTP call error {err}", joCall.url, err ); if( ! errCall ) - errCall = `HTTP(S)/RPC call(catch) error: ${err.toString()}`; + errCall = `HTTP(S)/RPC call(catch) error: ${err as any}`; } ); } else { try { @@ -352,10 +395,10 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: any ) { joOut = JSON.parse( body ); errCall = null; - } catch ( err: any ) { - log.error( "{url} request error {err}", joCall.url, err ); + } catch ( err ) { + log.error( "{url} request error {err}", joCall.url, err as any ); joOut = null; - errCall = `request error: ${err}`; + errCall = `request error: ${err as any}`; } } try { @@ -376,46 +419,48 @@ export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) const joCall: TRPCCall = { url: "" + strURL, joRpcOptions: opts ? opts : null, - mapPendingByCallID: { }, + mapPendingByCallID: new Map < TCallID, TCallHandlerEntry >(), wsConn: null, isAutoReconnect: ( opts && "isAutoReconnect" in opts && opts.isAutoReconnect ) ? true : false, isDisconnectMode: false, - reconnect: async function( fnAfter: any ) { - await doConnect( joCall, fnAfter ); + reconnect: async function( fnAfter: TFunctionConnectionResultHandler ) { + await doConnect( joCall, opts, fnAfter ); }, - reconnect_if_needed: async function( fnAfter: any ) { + reconnectIfNeeded: async function( fnAfter: TFunctionConnectionResultHandler ) { await doConnectIfNeeded( joCall, opts, fnAfter ); }, - call: async function( joIn: any, fnAfter: any ) { + call: async function( joIn: any, fnAfter?: TFunctionCallResultHandler ) { const self = this; - const promiseComplete = new Promise( function( resolve: any, reject: any ) { - self.reconnect_if_needed( async function( joCall: TRPCCall, err: any ) { - if( err ) { - if( fnAfter ) - await fnAfter( joIn, null, err ); - reject( err ); - return; - } - await doCall( joCall, joIn, async function( joIn: any, joOut: any, err: any ) { - if( fnAfter ) - await fnAfter( joIn, joOut, err ); - if( err ) + const promiseComplete = new Promise < any >( function( resolve, reject ) { + self.reconnectIfNeeded( + async function( joCall: TRPCCall, err: Error | string | null ) { + if( err ) { + if( fnAfter ) + await fnAfter( joIn, null, err ); reject( err ); - else - resolve( joOut ); - } ).catch( function( err: Error | string ) { - log.error( - "{url} JSON RPC call(performer) error: {err}", strURL, err ); - } ); - } ); + return; + } + await doCall( joCall, joIn, + async function( joIn: any, joOut: any, err: Error | string | null ) { + if( fnAfter ) + await fnAfter( joIn, joOut, err ); + if( err ) + reject( err ); + else + resolve( joOut ); + } ).catch( function( err: Error | string ) { + log.error( + "{url} JSON RPC call(performer) error: {err}", strURL, err ); + } ); + } ).then( function() {} ).catch( function() {} ); ; } ); return await promiseComplete.catch( function( err: Error | string ) { log.error( "{url} JSON RPC call(awaiter) error: {err}", strURL, err ); } ); }, - disconnect: async function( fnAfter?: any ) { + disconnect: async function( fnAfter?: TFunctionConnectionResultHandler ) { await doDisconnect( joCall, fnAfter ); } }; @@ -486,7 +531,7 @@ export function getValidHostAndPort( s: any ) { const u = getValidUrl( s ); if( ! u ) return null; - const jo: any = { + const jo = { strHost: u.hostname, nPort: u.port ? parseInt( u.port, 10 ) : getDefaultPort( u.protocol ) }; @@ -534,7 +579,7 @@ export async function checkTcpPromise( strHost: string, nPort: number, nTimeoutM `default TCP connection to ${strHost}:${nPort} timeout...` ); } } - conn.on( "timeout", function( err: any ) { + conn.on( "timeout", function( err: Error | string | null ) { if( isLog ) { console.log( `${gStrTcpConnectionHeader}TCP connection ` + @@ -543,7 +588,7 @@ export async function checkTcpPromise( strHost: string, nPort: number, nTimeoutM conn.destroy(); reject( err ); } ); - conn.on( "error", function( err: any ) { + conn.on( "error", function( err: Error | string ) { if( isLog ) { console.log( `${gStrTcpConnectionHeader}TCP connection ` + @@ -579,11 +624,11 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec `${gStrTcpConnectionHeader}TCP connection ` + `to ${strHost}:${nPort} check finished` ); } - } catch ( err: any ) { + } catch ( err ) { isOnline = false; console.log( `${gStrTcpConnectionHeader}TCP connection ` + - `to ${strHost}:${nPort} check failed with error: ${err}` ); + `to ${strHost}:${nPort} check failed with error: ${err as any}` ); } return isOnline; } @@ -591,7 +636,7 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec export async function checkUrl( u: URL | string, nTimeoutMilliseconds: number, isLog?: boolean ) { if( ! u ) return false; - const jo: any = getValidHostAndPort( u ); + const jo = getValidHostAndPort( u ); if( isLog ) { console.log( `${gStrTcpConnectionHeader}Extracted from URL ${u.toString()} data ` + `fields are: ${JSON.stringify( jo )}` ); diff --git a/src/state.ts b/src/state.ts index 38873eed..e5412270 100644 --- a/src/state.ts +++ b/src/state.ts @@ -1,10 +1,12 @@ import * as owaspUtils from "./owaspUtils.js"; import * as imaTx from "./imaTx.js"; +import type * as discoveryTools from "./discoveryTools.js"; export interface TLoopStateSubPart { isInProgress: boolean wasInProgress: boolean } + export interface TLoopState { oracle: TLoopStateSubPart m2s: TLoopStateSubPart @@ -12,6 +14,11 @@ export interface TLoopState { s2s: TLoopStateSubPart } +export interface TTokeInformation { + abi: object + address: string +} + export const gDefaultValueForLoopState: TLoopState = { oracle: { isInProgress: false, @@ -192,6 +199,11 @@ function constructChainProperties(): TPropertiesOfChains { }; } +export interface TIMAAction { + name: string + fn: () => Promise < boolean > +} + export interface TIMAState { loopState: TLoopState @@ -208,7 +220,7 @@ export interface TIMAState { // use BLS message signing, turned on with --sign-messages bSignMessages: boolean // scanned S-Chain network description - joSChainNetworkInfo: any + joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo | null // path to bls_glue app, must have if --sign-messages specified strPathBlsGlue: string // path to hash_g1 app, must have if --sign-messages specified @@ -343,7 +355,7 @@ export interface TIMAState { nJsonRpcPort: number // 0 to disable isCrossImaBlsMode: boolean - arrActions: any[] // array of actions to run + arrActions: TIMAAction[] // array of actions to run receiver?: any | null diff --git a/src/utils.ts b/src/utils.ts index a1c66919..bde1ffc0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -30,6 +30,7 @@ import * as path from "path"; import * as os from "os"; import * as threadInfo from "./threadInfo.js"; import type * as state from "./state.js"; +import type * as discoveryTools from "./discoveryTools.js"; import { v4 as uuid } from "uuid"; export { uuid }; @@ -37,6 +38,10 @@ export { uuid }; const ethersMod = owaspUtils.ethersMod; export { ethersMod }; +export interface TTokesABIHolder { + joABI: object +} + export function replaceAll( str: string, find: string, replace: string ): string { return str.replace( new RegExp( find, "g" ), replace ); } @@ -138,7 +143,7 @@ export async function waitForClonedTokenToAppear( strTokenSuffix: string, // example "erc20" addressCallFrom: string, cntAttempts: number, - tokensMN: any, + tokensMN: TTokesABIHolder, strMainnetName: string ) { const strTokenSuffixLC = strTokenSuffix.toLowerCase(); @@ -164,7 +169,7 @@ export async function waitForClonedTokenToAppear( await contractTokenManager.callStatic[ "clones" + log.capitalizeFirstLetter( strTokenSuffixLCshort )]( sc.ethersMod.ethers.utils.id( strMainnetName ), - tokensMN.joABI[strTokenSuffixUC + "_address"], + ( tokensMN.joABI as any )[strTokenSuffixUC + "_address"], { from: addressCallFrom } ); if( addressOnSChain != "0x0000000000000000000000000000000000000000" ) { @@ -182,7 +187,8 @@ export async function waitForClonedTokenToAppear( } export async function waitForClonedTokenAppearErc20( - sc: any, tokenERC20SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string + sc: any, tokenERC20SC: state.TTokeInformation, joAccountSC: state.TAccount, + tokensMN: TTokesABIHolder, strMainnetName: string ) { if( "abi" in tokenERC20SC && typeof tokenERC20SC.abi == "object" && "address" in tokenERC20SC && typeof tokenERC20SC.address == "string" @@ -193,12 +199,13 @@ export async function waitForClonedTokenAppearErc20( const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( sc, "erc20", addressCallFrom, 40, tokensMN, strMainnetName ); - tokenERC20SC.abi = JSON.parse( JSON.stringify( tokensMN.joABI.ERC20_abi ) ); + tokenERC20SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC20_abi ) ); tokenERC20SC.address = "" + addressOnSChain; } export async function waitForClonedTokenAppearErc721( - sc: any, tokenERC721SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string + sc: any, tokenERC721SC: state.TTokeInformation, joAccountSC: state.TAccount, + tokensMN: TTokesABIHolder, strMainnetName: string ) { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" @@ -210,12 +217,13 @@ export async function waitForClonedTokenAppearErc721( const addressOnSChain = await waitForClonedTokenToAppear( sc, "erc721", addressCallFrom, 40, tokensMN, strMainnetName ); - tokenERC721SC.abi = JSON.parse( JSON.stringify( tokensMN.joABI.ERC721_abi ) ); + tokenERC721SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC721_abi ) ); tokenERC721SC.address = "" + addressOnSChain; } export async function waitForClonedTokenAppearErc721WithMetadata( - sc: any, tokenERC721SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string + sc: any, tokenERC721SC: state.TTokeInformation, joAccountSC: state.TAccount, + tokensMN: TTokesABIHolder, strMainnetName: string ) { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" @@ -227,12 +235,14 @@ export async function waitForClonedTokenAppearErc721WithMetadata( const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( sc, "erc721_with_metadata", addressCallFrom, 40, tokensMN, strMainnetName ); - tokenERC721SC.abi = JSON.parse( JSON.stringify( tokensMN.joABI.ERC721_with_metadata_abi ) ); + tokenERC721SC.abi = + JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC721_with_metadata_abi ) ); tokenERC721SC.address = "" + addressOnSChain; } export async function waitForClonedTokenAppearErc1155( - sc: any, tokenERC1155SC: any, joAccountSC: state.TAccount, tokensMN: any, strMainnetName: string + sc: any, tokenERC1155SC: state.TTokeInformation, joAccountSC: state.TAccount, + tokensMN: TTokesABIHolder, strMainnetName: string ) { if( "abi" in tokenERC1155SC && typeof tokenERC1155SC.abi == "object" && "address" in tokenERC1155SC && typeof tokenERC1155SC.address == "string" @@ -243,7 +253,7 @@ export async function waitForClonedTokenAppearErc1155( const addressCallFrom = joAccountSC.address(); const addressOnSChain = await waitForClonedTokenToAppear( sc, "erc1155", addressCallFrom, 40, tokensMN, strMainnetName ); - tokenERC1155SC.abi = JSON.parse( JSON.stringify( tokensMN.joABI.ERC1155_abi ) ); + tokenERC1155SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC1155_abi ) ); tokenERC1155SC.address = "" + addressOnSChain; } @@ -401,7 +411,7 @@ export function checkKeysExistInABI( return true; } -export function composeSChainNodeUrl( joNode: any ): string { +export function composeSChainNodeUrl( joNode: discoveryTools.TSChainNode ): string { if( "ip" in joNode && typeof joNode.ip === "string" && joNode.ip.length > 0 ) { if( "httpRpcPort" in joNode && typeof joNode.httpRpcPort === "number" && @@ -442,7 +452,8 @@ export function composeSChainNodeUrl( joNode: any ): string { return ""; } -export function composeImaAgentNodeUrl( joNode: any, isThisNode: boolean ): string { +export function composeImaAgentNodeUrl( + joNode: discoveryTools.TSChainNode, isThisNode: boolean ): string { let nPort = -1; if( "imaAgentRpcPort" in joNode && typeof joNode.imaAgentRpcPort === "number" && From c633a09b433e6131311b3b668738f8c84cea557e Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 20 Dec 2023 11:49:36 +0000 Subject: [PATCH 24/53] code porting to TypeScript --- src/about.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/about.txt b/src/about.txt index e760358a..1dc79a22 100644 --- a/src/about.txt +++ b/src/about.txt @@ -96,7 +96,7 @@ PAYMENT TRANSACTION options: --gas-price-multiplier-tc ..............Sets Gas Price Multiplier for S<->S Target S-Chain transactions, Default value is 0.0. --gas-price-multiplier .................Sets Gas Price Multiplier for both Main Net and S-Chain(s). --gas-multiplier-mn ....................Sets Gas Value Multiplier for Main Net transactions, Default value is 1.25. Specify value 0.0 to disable Gas Price Customization for Main Net. - --gas-multiplier-sc ....................Sets Gas Value Multiplierfor S-Chain transactions, Default value is 1.25. + --gas-multiplier-sc ....................Sets Gas Value Multiplier S-Chain transactions, Default value is 1.25. --gas-multiplier-tc ....................Sets Gas Value Multiplier for S<->S Target S-Chain transactions, Default value is 1.25. --gas-multiplier .......................Sets Gas Value Multiplier for both Main Net and S-Chain(s). REGISTRATION commands: From 3e69a43b420765686402c0cd6971757896aa5ab3 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 18:58:00 +0000 Subject: [PATCH 25/53] linting improvement, space-unary-ops: off and spaced-comment: off rules removed --- src/.eslintrc.cjs | 2 - src/bls.ts | 134 ++++++++--------- src/cc.ts | 16 +- src/cli.ts | 18 +-- src/clpTools.ts | 250 +++++++++++++++---------------- src/discoveryTools.ts | 98 ++++++------ src/eventDispatcher.ts | 2 +- src/imaCore.ts | 58 +++---- src/imaEthOperations.ts | 4 +- src/imaEventLogScan.ts | 24 +-- src/imaGasUsageOperations.ts | 4 +- src/imaHelperAPIs.ts | 10 +- src/imaOracleOperations.ts | 8 +- src/imaRegistrationOperations.ts | 26 ++-- src/imaSgxExternalSigner.ts | 8 +- src/imaTokenOperations.ts | 74 ++++----- src/imaTransferErrorHandling.ts | 4 +- src/imaTx.ts | 18 +-- src/log.ts | 48 +++--- src/loop.ts | 46 +++--- src/main.ts | 16 +- src/observer.ts | 8 +- src/oracle.ts | 8 +- src/owaspUtils.ts | 12 +- src/pwa.ts | 38 ++--- src/rpcCall.ts | 20 +-- src/socket.ts | 112 +++++++------- src/socketServer.ts | 2 +- src/socketUtils.ts | 2 +- src/utils.ts | 4 +- 30 files changed, 536 insertions(+), 538 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 27acfcac..7f7eba87 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -31,8 +31,6 @@ module.exports = { "space-before-blocks": [ "error", "always" ], "array-bracket-spacing": [ "error", "always" ], "object-curly-spacing": [ "error", "always" ], - "space-unary-ops": "off", - "spaced-comment": "off", "curly": [ "error", "multi-or-nest" ], "nonblock-statement-body-position": [ "error", "below" ], "no-unneeded-ternary": "off", diff --git a/src/bls.ts b/src/bls.ts index 0e33c74f..bc5ed3d4 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -177,7 +177,7 @@ const Keccak = sha3Module.Keccak; function discoverBlsThreshold( joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo ): number { const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; - if( ! joSChainNetworkInfo ) + if( !joSChainNetworkInfo ) return -1; const jarrNodes = joSChainNetworkInfo.network; for( let i = 0; i < jarrNodes.length; ++i ) { @@ -191,7 +191,7 @@ function discoverBlsThreshold( joSChainNetworkInfo: discoveryTools.TSChainNetwor function discoverBlsParticipants( joSChainNetworkInfo: discoveryTools.TSChainNetworkInfo ): number { const imaState: state.TIMAState = state.get(); joSChainNetworkInfo = joSChainNetworkInfo || imaState.joSChainNetworkInfo; - if( ! joSChainNetworkInfo ) + if( !joSChainNetworkInfo ) return -1; const jarrNodes = joSChainNetworkInfo.network; for( let i = 0; i < jarrNodes.length; ++i ) { @@ -398,7 +398,7 @@ function getBlsGlueTmpDir(): string { function allocBlsTmpActionDir(): string { const strActionDir = getBlsGlueTmpDir() + "/" + imaUtils.replaceAll( imaUtils.uuid(), "-", "" ); - if( ! fs.existsSync( strActionDir ) ) + if( !fs.existsSync( strActionDir ) ) fs.mkdirSync( strActionDir, { recursive: true } ); return strActionDir; } @@ -408,7 +408,7 @@ function performBlsGlue( nIdxCurrentMsgBlockStart: number, strFromChainName: string, arrSignResults: any[] ): any { const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const strLogPrefix = `${strDirection}/BLS/Glue: `; let joGlueResult: any = null; @@ -416,7 +416,7 @@ function performBlsGlue( const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); details.debug( "{p}Discovered BLS threshold is {}.", strLogPrefix, nThreshold ); details.debug( "{p}Discovered number of BLS participants is {}.", strLogPrefix, nParticipants ); - if( ! checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS glue", details ) ) + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS glue", details ) ) return null; const strMessageHash = owaspUtils.removeStarting0x( @@ -499,7 +499,7 @@ function performBlsGlue( function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: any[] ): any { const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const strLogPrefix = "BLS/Glue: "; let joGlueResult: any = null; @@ -507,7 +507,7 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); details.debug( "{p}Discovered BLS threshold is {}.", strLogPrefix, nThreshold ); details.debug( "{p}Discovered number of BLS participants is {}.", strLogPrefix, nParticipants ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS glue-256", details ) ) return null; details.trace( "{p}Original long message is {}", strLogPrefix, keccak256U256( u256, false ) ); @@ -599,12 +599,12 @@ function performBlsVerifyI( if( !joResultFromNode ) return true; const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const strLogPrefix = `${strDirection}/BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS verify-I", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); @@ -664,15 +664,15 @@ function performBlsVerifyIU256( nZeroBasedNodeIndex: number, joResultFromNode: any, u256: any, joPublicKey: discoveryTools.TBLSPublicKey ): boolean { - if( ! joResultFromNode ) + if( !joResultFromNode ) return true; const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const strLogPrefix = `BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS verify-I-U256", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); @@ -725,11 +725,11 @@ function performBlsVerify( if( !joGlueResult ) return true; const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS verify", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); @@ -797,11 +797,11 @@ function performBlsVerifyU256( if( !joGlueResult ) return true; const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS verify-U256", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); @@ -879,7 +879,7 @@ async function checkCorrectnessOfMessagesToSign( ( joExtraSignOpts && "ethersProviderSrc" in joExtraSignOpts && joExtraSignOpts.ethersProviderSrc ) ? joExtraSignOpts.ethersProviderSrc : null; - if( ! ethersProvider ) { + if( !ethersProvider ) { throw new Error( "CRITICAL ERROR: No provider specified in extra signing options " + `for checking messages of direction ${strDirection}` ); } @@ -921,14 +921,14 @@ async function checkCorrectnessOfMessagesToSign( dstContract: joMessage.destinationContract, data: joMessage.data }; - if( ! joMessageProxy ) + if( !joMessageProxy ) throw new Error( "No message proxy available" ); const isValidMessage = await joMessageProxy.callStatic.verifyOutgoingMessageData( outgoingMessageData, { from: strCallerAccountAddress } ); details.trace( "{p}{bright} Got verification call result {}, real message index is: {}, " + "saved msgCounter is: {}", strLogPrefix, strDirection, - isValidMessage, + idxMessage, outgoingMessageData.msgCounter ); + isValidMessage, +idxMessage, outgoingMessageData.msgCounter ); if( !isValidMessage ) { throw new Error( "Bad message detected, " + `message is: ${JSON.stringify( joMessage )}` ); @@ -1013,7 +1013,7 @@ async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions optsSignOperation.strLogPrefix, optsSignOperation.nThreshold ); optsSignOperation.details.trace( "{p}Discovered number of BLS participants is {}.", optsSignOperation.strLogPrefix, optsSignOperation.nParticipants ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( optsSignOperation.nThreshold, optsSignOperation.nParticipants, "prepare sign messages " + optsSignOperation.strDirection, @@ -1062,11 +1062,11 @@ async function gatherSigningCheckFinish( optsSignOperation: TSignOperationOption optsSignOperation.details.success( "{p}Got BLS glue result: {}", optsSignOperation.strLogPrefixB, joGlueResult ); if( optsSignOperation.imaState.strPathBlsVerify.length > 0 ) { - if( ! optsSignOperation.imaState.joSChainNetworkInfo ) + if( !optsSignOperation.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const joCommonPublicKey = discoverCommonPublicKey( optsSignOperation.details, optsSignOperation.imaState.joSChainNetworkInfo, false ); - if( ! joCommonPublicKey ) { + if( !joCommonPublicKey ) { strError = "No BLS common public key"; optsSignOperation.details.error( "{p}{err}", optsSignOperation.strLogPrefixB, strError ); @@ -1133,7 +1133,7 @@ async function gatherSigningStartImpl( optsSignOperation: TSignOperationOptions optsSignOperation.strLogPrefix ); optsSignOperation.errGathering = null; for( let idxStep = 0; idxStep < optsSignOperation.joGatheringTracker.nWaitIntervalMaxSteps; - ++ idxStep ) { + ++idxStep ) { await threadInfo.sleep( optsSignOperation.joGatheringTracker.nWaitIntervalStepMilliseconds ); if( await gatherSigningCheckFinish( optsSignOperation ) ) @@ -1164,7 +1164,7 @@ async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions if( optsSignOperation.errGathering ) { optsSignOperation.details.error( "Failed BLS sign result awaiting(1): {err}", optsSignOperation.errGathering.toString() ); - if( ! optsSignOperation.bHaveResultReportCalled ) { + if( !optsSignOperation.bHaveResultReportCalled ) { optsSignOperation.bHaveResultReportCalled = true; await optsSignOperation.fn( `Failed to gather BLS signatures in ${optsSignOperation.jarrNodes.length} ` + @@ -1186,7 +1186,7 @@ async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions } return; } - if( ! optsSignOperation.bHaveResultReportCalled ) { + if( !optsSignOperation.bHaveResultReportCalled ) { optsSignOperation.details.error( "Failed BLS sign result awaiting(2): {err}", "No reports were arrived" ); optsSignOperation.bHaveResultReportCalled = true; @@ -1235,7 +1235,7 @@ async function doSignConfigureChainAccessParams( optsSignOperation: TSignOperati optsSignOperation.targetChainID = optsSignOperation.imaState.chainProperties.mn.chainId; optsSignOperation.fromChainID = optsSignOperation.imaState.chainProperties.sc.chainId; } else if( optsSignOperation.strDirection == "S2S" ) { - if( ! optsSignOperation.joExtraSignOpts ) + if( !optsSignOperation.joExtraSignOpts ) throw new Error( "No S2S signing options provided" ); optsSignOperation.targetChainName = "" + optsSignOperation.joExtraSignOpts.chainNameDst; @@ -1311,12 +1311,12 @@ async function doSignProcessHandleCall( }; optsSignOperation.details.trace( "{p}Will verify sign result for node {}", optsSignOperation.strLogPrefixA, nZeroBasedNodeIndex ); - if( ! optsSignOperation.imaState.joSChainNetworkInfo ) + if( !optsSignOperation.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const joPublicKey = discoverPublicKeyByIndex( nZeroBasedNodeIndex, optsSignOperation.imaState.joSChainNetworkInfo, optsSignOperation.details, true ); - if( ! joPublicKey ) + if( !joPublicKey ) throw new Error( `No BLS public key for node ${nZeroBasedNodeIndex}` ); if( performBlsVerifyI( optsSignOperation.details, optsSignOperation.strDirection, @@ -1385,7 +1385,7 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperatio if( joCall ) joCall.disconnect().then( function() {} ).catch( function() {} ); } ); - if( ! joCall ) + if( !joCall ) return; await doSignConfigureChainAccessParams( optsSignOperation ); const joParams: THandleVerifyAndSignCallDataParams = { @@ -1473,7 +1473,7 @@ async function doSignMessagesImpl( "-" + optsSignOperation.strFromChainName + "-msg#" + optsSignOperation.nIdxCurrentMsgBlockStart; try { - if( ! ( await prepareSignMessagesImpl( optsSignOperation ) ) ) + if( !( await prepareSignMessagesImpl( optsSignOperation ) ) ) return; for( let i = 0; i < optsSignOperation.jarrNodes.length; ++i ) { const cntSuccess = optsSignOperation.arrSignResults.length; @@ -1498,7 +1498,7 @@ async function doSignMessagesImpl( optsSignOperation.details.critical( "Failed BLS sign due to generic " + "flow exception: {err}, stack is:\n{stack}", err, err ); } - if( ! optsSignOperation.bHaveResultReportCalled ) { + if( !optsSignOperation.bHaveResultReportCalled ) { optsSignOperation.bHaveResultReportCalled = true; await optsSignOperation.fn( "Failed BLS sign due to exception: " + `${owaspUtils.extractErrorMessage( err )}`, optsSignOperation.jarrMessages, null @@ -1559,7 +1559,7 @@ async function prepareSignU256( optsSignU256: TSignU256Options ) { optsSignU256.strLogPrefix, optsSignU256.u256 ); optsSignU256.details.trace( "{p}Will query to sign {} skaled node(s)...", optsSignU256.strLogPrefix, optsSignU256.jarrNodes.length ); - if( ! optsSignU256.imaState.joSChainNetworkInfo ) + if( !optsSignU256.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); optsSignU256.nThreshold = discoverBlsThreshold( optsSignU256.imaState.joSChainNetworkInfo ); optsSignU256.nParticipants = @@ -1568,7 +1568,7 @@ async function prepareSignU256( optsSignU256: TSignU256Options ) { optsSignU256.strLogPrefix, optsSignU256.nThreshold ); optsSignU256.details.trace( "{p}Discovered number of BLS participants is {}.", optsSignU256.strLogPrefix, optsSignU256.nParticipants ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( optsSignU256.nThreshold, optsSignU256.nParticipants, "prepare sign-U256", @@ -1640,12 +1640,12 @@ async function doSignU256OneImplHandleCallResult( }; optsSignU256.details.trace( "{p}Will verify sign result for node {}", strLogPrefixA, nZeroBasedNodeIndex ); - if( ! optsSignU256.imaState.joSChainNetworkInfo ) + if( !optsSignU256.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const joPublicKey = discoverPublicKeyByIndex( nZeroBasedNodeIndex, optsSignU256.imaState.joSChainNetworkInfo, optsSignU256.details, true ); - if( ! joPublicKey ) + if( !joPublicKey ) throw new Error( `No BLS public key for node ${nZeroBasedNodeIndex}` ); if( performBlsVerifyIU256( optsSignU256.details, nZeroBasedNodeIndex, joResultFromNode, @@ -1700,7 +1700,7 @@ async function doSignU256OneImpl( i: number, optsSignU256: TSignU256Options ) { let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); optsSignU256.details.trace( "{p}Will invoke skale_imaBSU256 for to sign value {}", optsSignU256.strLogPrefix, optsSignU256.u256.toString() ); @@ -1748,12 +1748,12 @@ async function gatherSigningCheckFinish256( optsSignU256: TSignU256Options ) { optsSignU256.details.success( "{p}Got BLS glue u256 result: {}", strLogPrefixB, joGlueResult ); if( optsSignU256.imaState.strPathBlsVerify.length > 0 ) { - if( ! optsSignU256.imaState.joSChainNetworkInfo ) + if( !optsSignU256.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const joCommonPublicKey = discoverCommonPublicKey( optsSignU256.details, optsSignU256.imaState.joSChainNetworkInfo, false ); - if( ! joCommonPublicKey ) { - if( ! optsSignU256.imaState.joSChainNetworkInfo ) + if( !joCommonPublicKey ) { + if( !optsSignU256.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const strError = "No BLS common public key"; optsSignU256.details.error( "{p}{}", strLogPrefixB, strError ); @@ -1813,7 +1813,7 @@ async function doSignU256Gathering( optsSignU256: TSignU256Options ) { optsSignU256.details.debug( "{p}Waiting for BLS glue result ", optsSignU256.strLogPrefix ); optsSignU256.errGathering = null; for( let idxStep = 0; idxStep < optsSignU256.joGatheringTracker.nWaitIntervalMaxSteps; - ++ idxStep ) { + ++idxStep ) { await threadInfo.sleep( optsSignU256.joGatheringTracker.nWaitIntervalStepMilliseconds ); if( await gatherSigningCheckFinish256( optsSignU256 ) ) @@ -1862,7 +1862,7 @@ export async function doSignU256( u256: any, details: log.TLogger, nCountOfBlsPartsToCollect: 1, errGathering: null }; - if( ! optsSignU256.imaState.joSChainNetworkInfo ) + if( !optsSignU256.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); optsSignU256.jarrNodes = optsSignU256.imaState.joSChainNetworkInfo.network; optsSignU256.details.trace( "{p}Invoking signing u256 procedure...", @@ -1877,7 +1877,7 @@ export async function doSignU256( u256: any, details: log.TLogger, await optsSignU256.fn( "BLS u256 signing is unavailable", optsSignU256.u256, null ); return; } - if( ! ( await prepareSignU256( optsSignU256 ) ) ) + if( !( await prepareSignU256( optsSignU256 ) ) ) return; for( let i = 0; i < optsSignU256.jarrNodes.length; ++i ) await doSignU256OneImpl( i, optsSignU256 ); @@ -1909,11 +1909,11 @@ export async function doVerifyReadyHash( Y: arrTmp[1] } }; - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "verify ready hash", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); @@ -2008,7 +2008,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a let joSignResult: TSignResult | null = null; let joCall: rpcCall.TRPCCall | null = null; try { - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); @@ -2017,15 +2017,15 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a details.trace( "{p}Discovered number of BLS participants is {}.", strLogPrefix, nParticipants ); details.trace( "{p}hash value to sign is {}", strLogPrefix, strMessageHash ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "sign ready hash", details ) ) return false; let joAccount: state.TAccount = imaState.chainProperties.sc.joAccount; - if( ! joAccount.strSgxURL ) { + if( !joAccount.strSgxURL ) { joAccount = imaState.chainProperties.mn.joAccount; - if( ! joAccount.strSgxURL ) + if( !joAccount.strSgxURL ) throw new Error( "SGX URL is unknown, cannot sign U256" ); - if( ! joAccount.strBlsKeyName ) + if( !joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign U256" ); } let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; @@ -2041,7 +2041,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a details.warning( "Will sign via SGX without SSL options" ); const signerIndex = imaState.nNodeNumber; joCall = await rpcCall.create( joAccount.strSgxURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); const joIn: any = { jsonrpc: "2.0", @@ -2102,7 +2102,7 @@ async function prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign.strFromChainName, optsHandleVerifyAndSign.strFromChainID, optsHandleVerifyAndSign.strToChainName, optsHandleVerifyAndSign.strToChainID, optsHandleVerifyAndSign.jarrMessages ); - if( ! optsHandleVerifyAndSign.imaState.joSChainNetworkInfo ) + if( !optsHandleVerifyAndSign.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); optsHandleVerifyAndSign.nThreshold = discoverBlsThreshold( optsHandleVerifyAndSign.imaState.joSChainNetworkInfo ); @@ -2116,7 +2116,7 @@ async function prepareHandlingOfSkaleImaVerifyAndSign( "{p}{bright} verification algorithm discovered number of BLS participants is {}.", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.strDirection, optsHandleVerifyAndSign.nParticipants ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( optsHandleVerifyAndSign.nThreshold, optsHandleVerifyAndSign.nParticipants, "prepare handling of skale_imaVerifyAndSign", @@ -2150,7 +2150,7 @@ async function prepareS2sOfSkaleImaVerifyAndSign( } let joSChainSrc: any = null; let strUrlSrcSChain: string | null = null; - for( let idxSChain = 0; idxSChain < arrSChainsCached.length; ++ idxSChain ) { + for( let idxSChain = 0; idxSChain < arrSChainsCached.length; ++idxSChain ) { const joSChain = arrSChainsCached[idxSChain]; if( joSChain.name.toString() == strSChainNameSrc.toString() ) { joSChainSrc = joSChain; @@ -2245,7 +2245,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndS }; let joCall: rpcCall.TRPCCall | null = null; try { - if( ! ( await prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) ) ) + if( !( await prepareHandlingOfSkaleImaVerifyAndSign( optsHandleVerifyAndSign ) ) ) return null; optsHandleVerifyAndSign.joExtraSignOpts = null; if( optsHandleVerifyAndSign.strDirection == "S2S" ) @@ -2260,11 +2260,11 @@ export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndS optsHandleVerifyAndSign.details.debug( "{p}Will BLS-sign verified messages.", optsHandleVerifyAndSign.strLogPrefix ); let joAccount = optsHandleVerifyAndSign.imaState.chainProperties.sc.joAccount; - if( ! joAccount.strSgxURL ) { + if( !joAccount.strSgxURL ) { joAccount = optsHandleVerifyAndSign.imaState.chainProperties.mn.joAccount; - if( ! joAccount.strSgxURL ) + if( !joAccount.strSgxURL ) throw new Error( "SGX URL is unknown, cannot sign(handle) IMA message(s)" ); - if( ! joAccount.strBlsKeyName ) + if( !joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign IMA message(s)" ); } let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; @@ -2280,7 +2280,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndS optsHandleVerifyAndSign.details.warning( "Will sign via SGX without SSL options" ); const signerIndex = optsHandleVerifyAndSign.imaState.nNodeNumber; joCall = await rpcCall.create( joAccount.strSgxURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); const joIn = { jsonrpc: "2.0", @@ -2319,7 +2319,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndS async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { optsBSU256.details.debug( "{p}Will U256-BLS-sign {}", optsBSU256.strLogPrefix, optsBSU256.joCallData ); - if( ! optsBSU256.imaState.joSChainNetworkInfo ) + if( !optsBSU256.imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); optsBSU256.nThreshold = discoverBlsThreshold( optsBSU256.imaState.joSChainNetworkInfo ); optsBSU256.nParticipants = discoverBlsParticipants( optsBSU256.imaState.joSChainNetworkInfo ); @@ -2327,7 +2327,7 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { optsBSU256.strLogPrefix, optsBSU256.nThreshold ); optsBSU256.details.trace( "{p}Discovered number of BLS participants is {}.", optsBSU256.strLogPrefix, optsBSU256.nParticipants ); - if( ! checkBlsThresholdAndBlsParticipants( + if( !checkBlsThresholdAndBlsParticipants( optsBSU256.nThreshold, optsBSU256.nParticipants, "handle BSU256Prepare", @@ -2340,14 +2340,14 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { optsBSU256.details.trace( "{p}hash of U256 value to sign is {}", optsBSU256.strLogPrefix, optsBSU256.strMessageHash ); optsBSU256.details.trace( "{p}Will BLS-sign U256.", optsBSU256.strLogPrefix ); - if( ! optsBSU256.joAccount ) + if( !optsBSU256.joAccount ) throw new Error( "No account to perform blsSignMessageHash for U256" ) optsBSU256.joAccount = optsBSU256.imaState.chainProperties.sc.joAccount; - if( ! optsBSU256.joAccount.strSgxURL ) { + if( !optsBSU256.joAccount.strSgxURL ) { optsBSU256.joAccount = optsBSU256.imaState.chainProperties.mn.joAccount; - if( ! optsBSU256.joAccount.strSgxURL ) + if( !optsBSU256.joAccount.strSgxURL ) throw new Error( "SGX URL is unknown, cannot sign U256" ); - if( ! optsBSU256.joAccount.strBlsKeyName ) + if( !optsBSU256.joAccount.strBlsKeyName ) throw new Error( "BLS keys name is unknown, cannot sign U256" ); } return true; @@ -2410,9 +2410,9 @@ export async function handleSkaleImaBSU256( joCallData: TBSU256CallData ) { }; let joCall: rpcCall.TRPCCall | null = null; try { - if( ! ( await handleSkaleImaBSU256Prepare( optsBSU256 ) ) ) + if( !( await handleSkaleImaBSU256Prepare( optsBSU256 ) ) ) return null; - if( ! optsBSU256.joAccount ) + if( !optsBSU256.joAccount ) throw new Error( "No account to perform blsSignMessageHash for U256" ) let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; if( "strPathSslKey" in optsBSU256.joAccount && @@ -2430,7 +2430,7 @@ export async function handleSkaleImaBSU256( joCallData: TBSU256CallData ) { optsBSU256.details.warning( "Will sign via SGX without SSL options" ); const signerIndex = optsBSU256.imaState.nNodeNumber; joCall = await rpcCall.create( optsBSU256.joAccount.strSgxURL, rpcCallOpts ); - if( ! joCall ) { + if( !joCall ) { throw new Error( "Failed to create JSON RPC call object " + `to ${optsBSU256.joAccount.strSgxURL}` ); } diff --git a/src/cc.ts b/src/cc.ts index 63ed1e1f..235070c9 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -201,7 +201,7 @@ export function rainbow( s?: any ): string { return s ? s.toString() : JSON.stringify( s ); let res = ""; const cnt = s.length; - for( let i = 0; i < cnt; ++ i ) + for( let i = 0; i < cnt; ++i ) res = res + rainbowPart( s[i], i ); return res; } @@ -533,7 +533,7 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ): stri // eslint-disable-next-line max-len /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, function( match: any ) { - if( ! gFlagIsEnabled ) + if( !gFlagIsEnabled ) return match; let cls = "number"; if( /^"/.test( match ) ) { @@ -596,7 +596,7 @@ export function j1( x?: any, n?: number, strKeyNamePrefix?: string ): string { isDefaultKeyNamePrefix = true; } let s = safeStringifyJSON( x, n ); - if( ! gFlagIsEnabled ) + if( !gFlagIsEnabled ) return s || ""; s = "" + syntaxHighlightJSON( s, strKeyNamePrefix ); if( isDefaultKeyNamePrefix && s.length > 9 && s[0] == " " ) @@ -923,10 +923,10 @@ export function getDurationString( tsFrom: number, tsTo: number ): string { } export function capitalizeFirstLetter( s?: any ): string { - if( ! s ) + if( !s ) return JSON.stringify( s ); let s2 = s.toString(); - if( ! s2 ) + if( !s2 ) return s.toString(); s2 = s2.charAt( 0 ).toUpperCase() + s2.slice( 1 ); return s2; @@ -936,7 +936,7 @@ function errFnDottedName( s?: any ): string { const arr = s.split( "." ); const cnt = arr.length; let i; let s2 = ""; - for( i = 0; i < cnt; ++ i ) { + for( i = 0; i < cnt; ++i ) { if( i > 0 ) s2 += bright( "." ); s2 += sunny( arr[i] ); @@ -974,7 +974,7 @@ function errLocLn( s: string, isWithBraces?: boolean ): string { } export function stack( err?: any ): string { - if( ! err ) + if( !err ) return ""; if( err && "stack" in err ) { const st = err.stack @@ -985,7 +985,7 @@ export function stack( err?: any ): string { const arr = ( typeof err == "string" ) ? err.split( "\n" ) : err; const cnt = arr.length; let i; - for( i = 0; i < cnt; ++ i ) { + for( i = 0; i < cnt; ++i ) { let s = arr[i].replace( /\s+/g, " " ).trim(); if( s.indexOf( "at " ) == 0 ) { // stack entry diff --git a/src/cli.ts b/src/cli.ts index 70d6f9f3..d158374b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -94,7 +94,7 @@ export function ensureHaveValue( value = value ? value.toString() : ""; if( value.length === 0 ) { retVal = false; - if( ! isPrintValue ) + if( !isPrintValue ) console.log( log.fmtError( "WARNING:, missing value for ", fnNameColorizer( name ) ) ); if( isExitIfEmpty ) process.exit( 126 ); @@ -113,7 +113,7 @@ export function ensureHaveCredentials( isExitIfEmpty: boolean, isPrintValue: boolean ) { strFriendlyChainName = strFriendlyChainName || ""; - if( ! ( typeof joAccount == "object" ) ) { + if( !( typeof joAccount == "object" ) ) { log.error( "ARGUMENTS VALIDATION WARNING: bad account specified for {} chain", strFriendlyChainName ); if( isExitIfEmpty ) @@ -124,7 +124,7 @@ export function ensureHaveCredentials( typeof joAccount.strTransactionManagerURL == "string" && joAccount.strTransactionManagerURL.length > 0 ) { - ++ cntAccountVariantsSpecified; + ++cntAccountVariantsSpecified; ensureHaveValue( "" + strFriendlyChainName + "/TM/URL", joAccount.strTransactionManagerURL, isExitIfEmpty, isPrintValue @@ -134,7 +134,7 @@ export function ensureHaveCredentials( typeof joAccount.strSgxURL == "string" && joAccount.strSgxURL.length > 0 ) { - ++ cntAccountVariantsSpecified; + ++cntAccountVariantsSpecified; ensureHaveValue( "" + strFriendlyChainName + "/SGX/URL", joAccount.strSgxURL, isExitIfEmpty, isPrintValue @@ -162,7 +162,7 @@ export function ensureHaveCredentials( typeof joAccount.strSgxKeyName == "string" && joAccount.strSgxKeyName.length > 0 ) { - ++ cntAccountVariantsSpecified; + ++cntAccountVariantsSpecified; ensureHaveValue( "" + strFriendlyChainName + "/SGX/keyName", joAccount.strSgxKeyName, isExitIfEmpty, isPrintValue @@ -172,7 +172,7 @@ export function ensureHaveCredentials( typeof joAccount.privateKey == "string" && joAccount.privateKey.length > 0 ) { - ++ cntAccountVariantsSpecified; + ++cntAccountVariantsSpecified; ensureHaveValue( "" + strFriendlyChainName + "/privateKey", joAccount.privateKey, isExitIfEmpty, isPrintValue @@ -182,7 +182,7 @@ export function ensureHaveCredentials( typeof joAccount.address_ == "string" && joAccount.address_.length > 0 ) { - ++ cntAccountVariantsSpecified; + ++cntAccountVariantsSpecified; ensureHaveValue( "" + strFriendlyChainName + "/walletAddress", joAccount.address_, isExitIfEmpty, isPrintValue @@ -1806,7 +1806,7 @@ function commonInitCheckErc721() { if( n2 > 0 ) n2 = imaState.chainProperties.sc.strCoinNameErc721.length; if( n1 > 0 ) { - if( ! imaState.bShowConfigMode ) { + if( !imaState.bShowConfigMode ) { if( isPrintGathered ) { log.information( "Loaded Main-net ERC721 ABI {}", imaState.chainProperties.mn.strCoinNameErc721 ); @@ -1964,7 +1964,7 @@ function commonInitCheckErc1155() { if( n2 > 0 ) n2 = imaState.chainProperties.sc.strCoinNameErc1155.length; if( n1 > 0 ) { - if( ! imaState.bShowConfigMode ) { + if( !imaState.bShowConfigMode ) { if( isPrintGathered ) { log.information( "Loaded Main-net ERC1155 ABI {}", imaState.chainProperties.mn.strCoinNameErc1155 ); diff --git a/src/clpTools.ts b/src/clpTools.ts index 764c1718..17b38b33 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -70,7 +70,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) imaCLI.initContracts(); const strLogPrefix = "Reg 1: "; log.information( "{p}Will check chain registration now...", strLogPrefix ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); let bSuccess = await imaReg.checkIsRegisteredSChainInDepositBoxes( // step 1 imaState.chainProperties.mn.ethersProvider, @@ -119,7 +119,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) export async function checkRegistrationStep1() { const imaState: state.TIMAState = state.get(); imaCLI.initContracts(); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); const bRetVal = await imaReg.checkIsRegisteredSChainInDepositBoxes( // step 1 imaState.chainProperties.mn.ethersProvider, @@ -131,7 +131,7 @@ export async function checkRegistrationStep1() { } export function printSummaryRegistrationCosts( details?: any ) { - if( ! details ) + if( !details ) details = log; imaGasUsage.printGasUsageReportFromArray( "Main Net REGISTRATION", gInfoRegistrationCost.mn, details ); @@ -144,7 +144,7 @@ export function commandLineTaskRegister() { imaState.arrActions.push( { name: "Full registration(all steps)", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // registerAll return await registerAll( true ); } @@ -156,7 +156,7 @@ export function commandLineTaskRegister1() { imaState.arrActions.push( { name: "Registration step 1, register S-Chain in deposit box", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // registerStep1 return await registerStep1( true ); } @@ -168,7 +168,7 @@ export function commandLineTaskCheckRegistration() { imaState.arrActions.push( { name: "Full registration status check(all steps)", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // checkRegistrationAll const b = await checkRegistrationAll(); // nExitCode is: 0 - OKay - registered; non-zero - not registered or error @@ -184,7 +184,7 @@ export function commandLineTaskCheckRegistration1() { imaState.arrActions.push( { name: "Registration status check step 1, register S-Chain in deposit box", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // checkRegistrationStep1 const b = await checkRegistrationStep1(); // nExitCode is: 0 - OKay - registered; non-zero - not registered or error @@ -205,7 +205,7 @@ export function commandLineTaskMintErc20() { try { const strAddressMintTo = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); - if( ! imaState.chainProperties.tc.ethersProvider ) + if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bMintIsOK = await imaToken.mintErc20( @@ -246,9 +246,9 @@ export function commandLineTaskMintErc721() { if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; - if( ! imaState.chainProperties.tc.ethersProvider ) + if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bMintIsOK = await imaToken.mintErc721( @@ -291,9 +291,9 @@ export function commandLineTaskMintErc1155() { if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; - if( ! imaState.chainProperties.tc.ethersProvider ) + if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bMintIsOK = await imaToken.mintErc1155( @@ -333,7 +333,7 @@ export function commandLineTaskBurnErc20() { try { const strAddressBurnFrom = // same as caller/transaction signer imaState.chainProperties.tc.joAccount.address(); - if( ! imaState.chainProperties.tc.ethersProvider ) + if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bBurnIsOK = await imaToken.burnErc20( @@ -374,9 +374,9 @@ export function commandLineTaskBurnErc721() { if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; - if( ! imaState.chainProperties.tc.ethersProvider ) + if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bBurnIsOK = await imaToken.burnErc721( @@ -420,9 +420,9 @@ export function commandLineTaskBurnErc1155() { if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; - if( ! imaState.chainProperties.tc.ethersProvider ) + if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bBurnIsOK = await imaToken.burnErc1155( @@ -465,7 +465,7 @@ export async function commandLineTaskShowBalanceEth( imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.joAccount, null ) } ); - if( ! imaState.joDepositBoxETH ) + if( !imaState.joDepositBoxETH ) throw new Error( "No DepositBoxETH contract" ); arrBalancesMN.push( { assetName: "CanReceiveETH", @@ -584,7 +584,7 @@ export async function commandLineTaskShowBalanceErc721( if( imaState.chainProperties.mn.ethersProvider && imaState.chainProperties.mn.strCoinNameErc721.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; try { assetAddress = imaState.chainProperties.mn.joErc721[ @@ -606,7 +606,7 @@ export async function commandLineTaskShowBalanceErc721( if( imaState.chainProperties.sc.ethersProvider && imaState.chainProperties.sc.strCoinNameErc721.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; try { assetAddress = imaState.chainProperties.sc.joErc721[ @@ -628,7 +628,7 @@ export async function commandLineTaskShowBalanceErc721( if( imaState.chainProperties.tc.ethersProvider && imaState.chainProperties.tc.strCoinNameErc721.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; try { assetAddress = imaState.chainProperties.tc.joErc721[ @@ -657,7 +657,7 @@ export async function commandLineTaskShowBalanceErc1155( if( imaState.chainProperties.mn.ethersProvider && imaState.chainProperties.mn.strCoinNameErc1155.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; try { assetAddress = imaState.chainProperties.mn.joErc1155[ @@ -679,7 +679,7 @@ export async function commandLineTaskShowBalanceErc1155( if( imaState.chainProperties.sc.ethersProvider && imaState.chainProperties.sc.strCoinNameErc1155.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; try { assetAddress = imaState.chainProperties.sc.joErc1155[ @@ -701,7 +701,7 @@ export async function commandLineTaskShowBalanceErc1155( if( imaState.chainProperties.tc.ethersProvider && imaState.chainProperties.tc.strCoinNameErc1155.length > 0 ) { - for( let i = 0; i < idTokens.length; ++ i ) { + for( let i = 0; i < idTokens.length; ++i ) { const idToken = idTokens[i]; try { assetAddress = imaState.chainProperties.tc.joErc1155[ @@ -749,7 +749,7 @@ export function commandLineTaskShowBalance() { const strAddress = imaState.chainProperties.mn.joAccount.address(); log.information( "Main Net {} of {}:", ( arrBalancesMN.length > 1 ? "balances" : "balance" ), strAddress ); - for( let i = 0; i < arrBalancesMN.length; ++ i ) { + for( let i = 0; i < arrBalancesMN.length; ++i ) { const bi = arrBalancesMN[i]; log.information( " {}", discoveryTools.formatBalanceInfo( bi, strAddress ) ); @@ -759,7 +759,7 @@ export function commandLineTaskShowBalance() { const strAddress = imaState.chainProperties.sc.joAccount.address(); log.information( "S-Chain {} of {}:", ( arrBalancesMN.length > 1 ? "balances" : "balance" ), strAddress ); - for( let i = 0; i < arrBalancesSC.length; ++ i ) { + for( let i = 0; i < arrBalancesSC.length; ++i ) { const bi = arrBalancesSC[i]; log.information( " {}", discoveryTools.formatBalanceInfo( bi, strAddress ) ); @@ -769,7 +769,7 @@ export function commandLineTaskShowBalance() { const strAddress = imaState.chainProperties.mn.joAccount.address(); log.information( "Target S-Chain {} of {}:", arrBalancesTC.length > 1 ? "balances" : "balance", strAddress ); - for( let i = 0; i < arrBalancesTC.length; ++ i ) { + for( let i = 0; i < arrBalancesTC.length; ++i ) { const bi = arrBalancesTC[i]; log.information( " {}", discoveryTools.formatBalanceInfo( bi, strAddress ) ); @@ -790,21 +790,21 @@ export function commandLineTaskPaymentM2S() { if( imaState.chainProperties.mn.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one M->S single ERC721 payment: {}", imaState.idToken ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); const joDepositBoxERC721 = imaState.isWithMetadata721 ? imaState.joDepositBoxERC721WithMetadata : imaState.joDepositBoxERC721; - if( ! joDepositBoxERC721 ) + if( !joDepositBoxERC721 ) throw new Error( "No DepositBoxERC721 contract" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); const joTokenManagerERC721 = imaState.isWithMetadata721 ? imaState.joTokenManagerERC721WithMetadata : imaState.joTokenManagerERC721; - if( ! joTokenManagerERC721 ) + if( !joTokenManagerERC721 ) throw new Error( "No TokenManagerERC721 contract" ); return await imaToken.doErc721PaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, @@ -829,15 +829,15 @@ export function commandLineTaskPaymentM2S() { if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { // ERC20 payment log.information( "one M->S single ERC20 payment: {}", imaState.nAmountOfToken ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joDepositBoxERC20 ) + if( !imaState.joDepositBoxERC20 ) throw new Error( "No DepositBoxERC20 contract" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joTokenManagerERC20 ) + if( !imaState.joTokenManagerERC20 ) throw new Error( "No TokenManagerERC20 contract" ); return await imaToken.doErc20PaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, @@ -872,15 +872,15 @@ export function commandLineTaskPaymentM2S() { // ERC1155 payment log.information( "one M->S single ERC1155 payment: {} {}", imaState.idToken, imaState.nAmountOfToken ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joDepositBoxERC1155 ) + if( !imaState.joDepositBoxERC1155 ) throw new Error( "No DepositBoxERC1155 contract" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joTokenManagerERC1155 ) + if( !imaState.joTokenManagerERC1155 ) throw new Error( "No TokenManagerERC1155 contract" ); return await imaToken.doErc1155PaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, @@ -921,15 +921,15 @@ export function commandLineTaskPaymentM2S() { // ERC1155 Batch payment log.information( "one M->S single ERC1155 Batch payment: {} {}", imaState.idTokens, imaState.arrAmountsOfTokens ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joDepositBoxERC1155 ) + if( !imaState.joDepositBoxERC1155 ) throw new Error( "No DepositBoxERC1155 contract" ); - if( ! imaState.joTokenManagerERC1155 ) + if( !imaState.joTokenManagerERC1155 ) throw new Error( "No TokenManagerERC1155 contract" ); return await imaToken.doErc1155BatchPaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, @@ -954,11 +954,11 @@ export function commandLineTaskPaymentM2S() { } // ETH payment log.information( "one M->S single ETH payment: {}", imaState.nAmountOfWei ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joDepositBoxETH ) + if( !imaState.joDepositBoxETH ) throw new Error( "No DepositBoxETH contract" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); return await imaEth.doEthPaymentFromMainNet( imaState.chainProperties.mn.ethersProvider, @@ -983,23 +983,23 @@ export function commandLineTaskPaymentS2M() { if( imaState.chainProperties.sc.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one S->M single ERC721 payment: {}", imaState.idToken ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); const joTokenManagerERC721 = imaState.isWithMetadata721 ? imaState.joTokenManagerERC721WithMetadata : imaState.joTokenManagerERC721; - if( ! joTokenManagerERC721 ) + if( !joTokenManagerERC721 ) throw new Error( "No TokenManagerERC721 contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No oMessageProxySChain contract" ); const joDepositBoxERC721 = imaState.isWithMetadata721 ? imaState.joDepositBoxERC721WithMetadata : imaState.joDepositBoxERC721; - if( ! joTokenManagerERC721 ) + if( !joTokenManagerERC721 ) throw new Error( "No DepositBoxERC721 contract" ); - if( ! joDepositBoxERC721 ) + if( !joDepositBoxERC721 ) throw new Error( "No DepositBoxERC721 contract" ); return await imaToken.doErc721PaymentFromSChain( imaState.chainProperties.mn.ethersProvider, @@ -1023,15 +1023,15 @@ export function commandLineTaskPaymentS2M() { if( imaState.chainProperties.sc.strCoinNameErc20.length > 0 ) { // ERC20 payment log.information( "one S->M single ERC20 payment: {}", imaState.nAmountOfToken ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joTokenManagerERC20 ) + if( !imaState.joTokenManagerERC20 ) throw new Error( "No TokenManagerERC20 contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); - if( ! imaState.joDepositBoxERC20 ) + if( !imaState.joDepositBoxERC20 ) throw new Error( "No DepositBoxERC20 contract" ); return await imaToken.doErc20PaymentFromSChain( imaState.chainProperties.mn.ethersProvider, @@ -1070,15 +1070,15 @@ export function commandLineTaskPaymentS2M() { // ERC1155 payment log.information( "one S->M single ERC1155 payment: {} {}", imaState.idToken, imaState.nAmountOfToken ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joTokenManagerERC1155 ) + if( !imaState.joTokenManagerERC1155 ) throw new Error( "No TokenManagerERC1155 contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); - if( ! imaState.joDepositBoxERC1155 ) + if( !imaState.joDepositBoxERC1155 ) throw new Error( "No DepositBoxERC1155 contract" ); return await imaToken.doErc1155PaymentFromSChain( imaState.chainProperties.mn.ethersProvider, @@ -1118,15 +1118,15 @@ export function commandLineTaskPaymentS2M() { // ERC1155 payment log.information( "one S->M single ERC1155 payment: {} {}", imaState.idTokens, imaState.arrAmountsOfTokens ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joTokenManagerERC1155 ) + if( !imaState.joTokenManagerERC1155 ) throw new Error( "No TokenManagerERC1155 contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); - if( ! imaState.joDepositBoxERC1155 ) + if( !imaState.joDepositBoxERC1155 ) throw new Error( "No DepositBoxERC1155 contract" ); return await imaToken.doErc1155BatchPaymentFromSChain( imaState.chainProperties.mn.ethersProvider, @@ -1150,11 +1150,11 @@ export function commandLineTaskPaymentS2M() { } // ETH payment log.information( "one S->M single ETH payment: {}", imaState.nAmountOfWei ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joTokenManagerETH ) + if( !imaState.joTokenManagerETH ) throw new Error( "No TokenManagerETH contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); return await imaEth.doEthPaymentFromSChain( imaState.chainProperties.sc.ethersProvider, @@ -1207,17 +1207,17 @@ export function commandLineTaskPaymentS2S() { let strAddrErc721ExplicitTarget = imaState.strAddrErc721ExplicitTarget; let strAddrErc1155Explicit = imaState.strAddrErc1155Explicit; let strAddrErc1155ExplicitTarget = imaState.strAddrErc1155ExplicitTarget; - if( ( ! strAddrErc20Explicit ) && sc.joErc20 && sc.strCoinNameErc20 ) + if( ( !strAddrErc20Explicit ) && sc.joErc20 && sc.strCoinNameErc20 ) strAddrErc20Explicit = sc.joErc20[sc.strCoinNameErc20 + "_address"]; - if( ( ! strAddrErc20ExplicitTarget ) && tc.joErc20 && tc.strCoinNameErc20 ) + if( ( !strAddrErc20ExplicitTarget ) && tc.joErc20 && tc.strCoinNameErc20 ) strAddrErc20ExplicitTarget = tc.joErc20[tc.strCoinNameErc20 + "_address"]; - if( ( ! strAddrErc721Explicit ) && sc.joErc721 && sc.strCoinNameErc721 ) + if( ( !strAddrErc721Explicit ) && sc.joErc721 && sc.strCoinNameErc721 ) strAddrErc721Explicit = sc.joErc721[sc.strCoinNameErc721 + "_address"]; - if( ( ! strAddrErc721ExplicitTarget ) && tc.joErc721 && tc.strCoinNameErc721 ) + if( ( !strAddrErc721ExplicitTarget ) && tc.joErc721 && tc.strCoinNameErc721 ) strAddrErc721ExplicitTarget = tc.joErc721[tc.strCoinNameErc721 + "_address"]; - if( ( ! strAddrErc1155Explicit ) && sc.joErc1155 && sc.strCoinNameErc1155 ) + if( ( !strAddrErc1155Explicit ) && sc.joErc1155 && sc.strCoinNameErc1155 ) strAddrErc1155Explicit = sc.joErc1155[sc.strCoinNameErc1155 + "_address"]; - if( ( ! strAddrErc1155ExplicitTarget ) && tc.joErc1155 && tc.strCoinNameErc1155 ) + if( ( !strAddrErc1155ExplicitTarget ) && tc.joErc1155 && tc.strCoinNameErc1155 ) strAddrErc1155ExplicitTarget = tc.joErc1155[tc.strCoinNameErc1155 + "_address"]; const strAddrErc20Dst = isForward ? strAddrErc20ExplicitTarget : strAddrErc20Explicit; @@ -1230,9 +1230,9 @@ export function commandLineTaskPaymentS2S() { if( strCoinNameErc721Src.length > 0 ) { // ERC721 payment log.information( "one S->S single ERC721 payment: {}", imaState.idToken ); - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No S2S source provider" ); - if( ! joTokenManagerERC721Src ) + if( !joTokenManagerERC721Src ) throw new Error( "No S2S source TokenManagerERC721 contract" ); return await imaToken.doErc721PaymentS2S( isForward, @@ -1252,9 +1252,9 @@ export function commandLineTaskPaymentS2S() { if( strCoinNameErc20Src.length > 0 ) { // ERC20 payment log.information( "one S->S single ERC20 payment: {}", imaState.nAmountOfToken ); - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No S2S source provider" ); - if( ! joTokenManagerERC20Src ) + if( !joTokenManagerERC20Src ) throw new Error( "No S2S source TokenManagerERC20Src contract" ); return await imaToken.doErc20PaymentS2S( isForward, @@ -1289,9 +1289,9 @@ export function commandLineTaskPaymentS2S() { // ERC1155 payment log.information( "one S->S single ERC1155 payment: {} {}", imaState.idToken, imaState.nAmountOfToken ); - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No S2S source provider" ); - if( ! joTokenManagerERC1155Src ) + if( !joTokenManagerERC1155Src ) throw new Error( "No S2S source joTokenManagerERC1155 contract" ); return await imaToken.doErc1155PaymentS2S( isForward, @@ -1327,9 +1327,9 @@ export function commandLineTaskPaymentS2S() { // ERC1155 Batch payment log.information( "one S->S single ERC1155 Batch payment: {} {}", imaState.idTokens, imaState.arrAmountsOfTokens ); - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No S2S source provider" ); - if( ! joTokenManagerERC1155Src ) + if( !joTokenManagerERC1155Src ) throw new Error( "No S2S source joTokenManagerERC1155 contract" ); return await imaToken.doErc1155BatchPaymentS2S( isForward, @@ -1361,9 +1361,9 @@ export function commandLineTaskReceiveS2M() { name: "receive one S->M single ETH payment", fn: async function() { log.information( "receive one S->M single ETH payment:" ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joDepositBoxETH ) + if( !imaState.joDepositBoxETH ) throw new Error( "No DepositBoxETH contract" ); return await imaEth.receiveEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, @@ -1383,9 +1383,9 @@ export function commandLineTaskViewS2M() { fn: async function() { log.information( "view one S->M single ETH payment:" ); log.information( "receive one S->M single ETH payment:" ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joDepositBoxETH ) + if( !imaState.joDepositBoxETH ) throw new Error( "No DepositBoxETH contract" ); const xWei = await imaEth.viewEthPaymentFromSchainOnMainNet( imaState.chainProperties.mn.ethersProvider, @@ -1407,20 +1407,20 @@ export function commandLineTaskTransferM2S() { imaState.arrActions.push( { name: "single M->S transfer loop", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // main-net --> s-chain transfer const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); return await IMA.doTransfer( // main-net --> s-chain "M2S", @@ -1455,20 +1455,20 @@ export function commandLineTaskTransferS2M() { imaState.arrActions.push( { name: "single S->M transfer loop", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); return await IMA.doTransfer( // s-chain --> main-net "S2M", @@ -1503,20 +1503,20 @@ export function commandLineTaskTransferS2S() { imaState.arrActions.push( { name: "single S->S transfer loop", fn: async function() { - if( ! imaState.optsS2S.isEnabled ) + if( !imaState.optsS2S.isEnabled ) return true; - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }; - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); - if( ! imaState.joTokenManagerETH ) + if( !imaState.joTokenManagerETH ) throw new Error( "No TokenManagerETH contract" ); return await IMA.doAllS2S( // s-chain --> s-chain joRuntimeOpts, @@ -1545,7 +1545,7 @@ export function commandLineTaskTransfer() { imaState.arrActions.push( { name: "Single M<->S transfer loop iteration", fn: async function() { - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); const joRuntimeOpts: loop.TRuntimeOpts = { isInsideWorker: false, @@ -1571,7 +1571,7 @@ export function commandLineTaskLoop() { name: "M<->S and S->S transfer loop, startup in parallel mode", fn: async function() { state.setPreventExitAfterLastAction( true ); - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // M<->S transfer loop let isPrintSummaryRegistrationCosts = false; if( !await checkRegistrationStep1() ) { @@ -1596,7 +1596,7 @@ export function commandLineTaskLoopSimple() { name: "M<->S and S->S transfer loop, startup simple mode", fn: async function() { state.setPreventExitAfterLastAction( true ); - if( ! imaState.bNoWaitSChainStarted ) + if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // M<->S transfer loop let isPrintSummaryRegistrationCosts = false; if( !await checkRegistrationStep1() ) { @@ -1631,9 +1631,9 @@ async function handleBrowseSkaleModesRpcInfoResult( strLogPrefix, joOut.result ); let nCountReceivedImaDescriptions = 0; const jarrNodes = joOut.result.network; - for( let i = 0; i < jarrNodes.length; ++ i ) { + for( let i = 0; i < jarrNodes.length; ++i ) { const joNode = jarrNodes[i]; - if( ! joNode ) { + if( !joNode ) { log.critical( "{p}Discovery node {} is completely unknown and will be skipped", strLogPrefix, i ); continue; @@ -1643,13 +1643,13 @@ async function handleBrowseSkaleModesRpcInfoResult( let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); const jIn: any = { method: "skale_imaInfo", params: { } }; if( discoveryTools.isSendImaAgentIndex() ) jIn.params.fromImaAgentIndex = imaState.nNodeNumber; const joOut = await joCall.call( joIn ); - ++ nCountReceivedImaDescriptions; + ++nCountReceivedImaDescriptions; log.information( "{p}Node {} IMA information: {}", strLogPrefix, joNode.nodeID, joOut.result ); await joCall.disconnect(); @@ -1685,7 +1685,7 @@ export function commandLineTaskBrowseSChain() { let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( imaState.chainProperties.sc.strURL, rpcCallOpts ); - if( ! joCall ) { + if( !joCall ) { throw new Error( "Failed to create JSON RPC call object " + `to ${imaState.chainProperties.sc.strURL}` ); } @@ -1710,9 +1710,9 @@ export function commandLineTaskReimbursementShowBalance() { imaState.arrActions.push( { name: "Gas Reimbursement - Show Balance", fn: async function() { - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joCommunityPool ) + if( !imaState.joCommunityPool ) throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementShowBalance( imaState.chainProperties.mn.ethersProvider, @@ -1734,9 +1734,9 @@ export function commandLineTaskReimbursementEstimateAmount() { imaState.arrActions.push( { name: "Gas Reimbursement - Estimate Amount", fn: async function() { - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joCommunityPool ) + if( !imaState.joCommunityPool ) throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementEstimateAmount( imaState.chainProperties.mn.ethersProvider, @@ -1758,9 +1758,9 @@ export function commandLineTaskReimbursementRecharge() { imaState.arrActions.push( { name: "Gas Reimbursement - Recharge User Wallet", fn: async function() { - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joCommunityPool ) + if( !imaState.joCommunityPool ) throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementWalletRecharge( imaState.chainProperties.mn.ethersProvider, @@ -1782,9 +1782,9 @@ export function commandLineTaskReimbursementWithdraw() { imaState.arrActions.push( { name: "Gas Reimbursement - Withdraw User Wallet", fn: async function() { - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.joCommunityPool ) + if( !imaState.joCommunityPool ) throw new Error( "No CommunityPool contract" ); await imaReimbursement.reimbursementWalletWithdraw( imaState.chainProperties.mn.ethersProvider, @@ -1806,9 +1806,9 @@ export function commandLineTaskReimbursementSetRange() { imaState.arrActions.push( { name: "Gas Reimbursement - Set Minimal time interval from S2M and S2S transfers", fn: async function() { - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joCommunityLocker ) + if( !imaState.joCommunityLocker ) throw new Error( "No CommunityLocker contract" ); await imaReimbursement.reimbursementSetRange( imaState.chainProperties.sc.ethersProvider, diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index de9f2ca1..19210248 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -156,7 +156,7 @@ export function formatBalanceInfo( bi: any, strAddress: string ): string { function getSChainNodesCount( joSChainNetworkInfo: TSChainNetworkInfo ): number { try { - if( ! joSChainNetworkInfo ) + if( !joSChainNetworkInfo ) return 0; const jarrNodes = joSChainNetworkInfo.network; const cntNodes = jarrNodes.length; @@ -167,7 +167,7 @@ function getSChainNodesCount( joSChainNetworkInfo: TSChainNetworkInfo ): number } export function isSChainNodeFullyDiscovered( joNode: TSChainNode ): boolean { - if( ! joNode ) + if( !joNode ) return false; if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo == "object" && "t" in joNode.imaInfo && typeof joNode.imaInfo.t == "number" && @@ -206,20 +206,20 @@ export function isSChainNodeFullyDiscovered( joNode: TSChainNode ): boolean { export function getSChainDiscoveredNodesCount( joSChainNetworkInfo: TSChainNetworkInfo | null ): number { try { - if( ! joSChainNetworkInfo ) + if( !joSChainNetworkInfo ) return 0; - if( ! ( "network" in joSChainNetworkInfo && joSChainNetworkInfo.network ) ) + if( !( "network" in joSChainNetworkInfo && joSChainNetworkInfo.network ) ) return 0; const jarrNodes = joSChainNetworkInfo.network; const cntNodes = jarrNodes.length; if( cntNodes <= 0 ) return 0; let cntDiscovered = 0; - for( let i = 0; i < cntNodes; ++ i ) { + for( let i = 0; i < cntNodes; ++i ) { try { const joNode = joSChainNetworkInfo.network[i]; if( isSChainNodeFullyDiscovered( joNode ) ) - ++ cntDiscovered; + ++cntDiscovered; } catch ( err ) { return 0; } @@ -261,7 +261,7 @@ export async function waitUntilSChainStarted() { bSuccess = false; } if( !bSuccess ) - ++ idxWaitAttempt; + ++idxWaitAttempt; if( idxWaitAttempt >= imaState.nMaxWaitSChainAttempts ) { log.warning( "Incomplete, S-Chain sanity check failed after {} attempts.", idxWaitAttempt ); @@ -297,7 +297,7 @@ function composeStillUnknownNodesMessage( const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); const strNodeDescColorized = log.fmtAttention( "#{}({url})", i, strNodeURL ); strMessage += strNodeDescColorized; - ++ cntBad; + ++cntBad; } catch ( err ) { } } } catch ( err ) { } @@ -312,7 +312,7 @@ async function handlePeriodicDiscoveryAttemptActions( return; } const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); fnAfter = fnAfter || function() {}; gFlagIsInSChainDiscovery = true; @@ -325,14 +325,14 @@ async function handlePeriodicDiscoveryAttemptActions( nCountToWait = cntNodesOnChain; const cntDiscovered = getSChainDiscoveredNodesCount( imaState.joSChainNetworkInfo ); if( cntDiscovered >= cntNodesOnChain ) { - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.information( "Everything is discovered about this S-Chain. ", "No re-discovery is needed" ); } if( gTimerSChainDiscovery != null ) { clearInterval( gTimerSChainDiscovery ); gTimerSChainDiscovery = null; - if( ! isSilentReDiscovery ) + if( !isSilentReDiscovery ) log.information( "This S-Chain re-discovery stopped" ); } // fnAfter() will be called here inside async call at beginning @@ -340,13 +340,13 @@ async function handlePeriodicDiscoveryAttemptActions( return; } if( cntDiscovered < cntNodesOnChain ) { - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { const cntUnDiscoveredYet = cntNodesOnChain - cntDiscovered; log.information( "Have {} of {} nodes of this S-Chain not discovered yet " + "on re-discovery step.", cntUnDiscoveredYet, cntNodesOnChain ); } } - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.information( "This S-Chain discovery will be done for re-discover task" ); log.information( "Will re-discover {}-nodes S-Chain network, {} node(s) already " + "discovered...", nCountToWait, cntDiscovered ); @@ -358,7 +358,7 @@ async function handlePeriodicDiscoveryAttemptActions( isError = true; log.critical( "S-Chain network re-discovery failed: {err}", err ); } ) as TSChainNetworkInfo; - if( ! isError ) { + if( !isError ) { const cntDiscoveredNow = getSChainDiscoveredNodesCount( joSChainNetworkInfo ); let strMessage = log.fmtSuccess( "S-Chain network was re-discovered, {} of {} node(s)" + @@ -368,7 +368,7 @@ async function handlePeriodicDiscoveryAttemptActions( strMessage += composeStillUnknownNodesMessage( joSChainNetworkInfo, cntStillUnknown, cntNodesOnChain ); } - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { strMessage += log.fmtSuccess( ", complete re-discovered S-Chain " + "network info: {}", joSChainNetworkInfo ); } @@ -398,12 +398,12 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( fnAfter = fnAfter || function() {}; const imaState: state.TIMAState = state.get(); if( imaState.joSChainDiscovery.repeatIntervalMilliseconds <= 0 ) { - if( ! isSilentReDiscovery ) + if( !isSilentReDiscovery ) log.information( "This S-Chain re-discovery will not be preformed" ); fnAfter(); return; // no S-Chain re-discovery, special mode } - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let nCountToWait = ( cntNodesOnChain > 2 ) @@ -413,21 +413,21 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( nCountToWait = cntNodesOnChain; const cntDiscovered = getSChainDiscoveredNodesCount( imaState.joSChainNetworkInfo ); if( cntDiscovered >= cntNodesOnChain ) { - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.attention( "Everything is discovered about this S-Chain. " + "No re-discovery is needed" ); } if( gTimerSChainDiscovery != null ) { clearInterval( gTimerSChainDiscovery ); gTimerSChainDiscovery = null; - if( ! isSilentReDiscovery ) + if( !isSilentReDiscovery ) log.notice( "This S-Chain re-discovery stopped" ); } fnAfter(); return; } if( cntDiscovered < cntNodesOnChain ) { - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { const cntUnDiscoveredYet = cntNodesOnChain - cntDiscovered; log.information( "Have {} of {} nodes of this S-Chain not discovered yet before " + "continuing re-discovery.", cntUnDiscoveredYet, cntNodesOnChain ); @@ -445,7 +445,7 @@ function handleDiscoverSkaleImaInfoResult( ): void { joNode.imaInfo = joOut.result; if( isSChainNodeFullyDiscovered( joNode ) ) - ++ optsDiscover.nCountReceivedImaDescriptions; + ++optsDiscover.nCountReceivedImaDescriptions; if( !optsDiscover.isSilentReDiscovery ) { log.success( "{p}OK, got {} node {} IMA information({} of {}).", optsDiscover.strLogPrefix, strNodeDescColorized, joNode.nodeID, @@ -455,12 +455,12 @@ function handleDiscoverSkaleImaInfoResult( async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { optsDiscover.cntFailed = 0; - for( let i = 0; i < optsDiscover.cntNodes; ++ i ) { + for( let i = 0; i < optsDiscover.cntNodes; ++i ) { const nCurrentNodeIdx = 0 + i; const joNode = optsDiscover.jarrNodes[nCurrentNodeIdx]; const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); const strNodeDescColorized = log.fmtAttention( "#{}({url})", nCurrentNodeIdx, strNodeURL ); - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.information( "{p}Will try to discover S-Chain node {}...", optsDiscover.strLogPrefix, strNodeDescColorized ); } @@ -472,7 +472,7 @@ async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { optsDiscover.joPrevSChainNetworkInfo.network[nCurrentNodeIdx]; if( isSChainNodeFullyDiscovered( joPrevNode ) ) { joNode.imaInfo = JSON.parse( JSON.stringify( joPrevNode.imaInfo ) ); - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.information( "{p}OK, in case of {} node {} will use previous discovery result.", optsDiscover.strLogPrefix, strNodeDescColorized, joNode.nodeID ); @@ -485,7 +485,7 @@ async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { let joCall: rpcCall.TRPCCall | null = null; try { joCall = await rpcCall.create( strNodeURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${strNodeURL}` ); const joIn: any = { method: "skale_imaInfo", params: { } }; if( isSendImaAgentIndex() ) @@ -494,12 +494,12 @@ async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { handleDiscoverSkaleImaInfoResult( optsDiscover, strNodeDescColorized, joNode, joCall, joIn, joOut ); } catch ( err ) { - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.critical( "{p}JSON RPC call(err) to S-Chain node {} failed: {err}, stack is:\n{stack}", optsDiscover.strLogPrefix, strNodeDescColorized, err, err ); } - ++ optsDiscover.cntFailed; + ++optsDiscover.cntFailed; if( joCall ) await joCall.disconnect(); } @@ -507,7 +507,7 @@ async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { } async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.debug( "{p}Waiting for response from at least {} node(s)...", optsDiscover.strLogPrefix, optsDiscover.nCountToWait ); } @@ -524,7 +524,7 @@ async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { // notice, below provided up-to-date count of available and fully discovered nodes: optsDiscover.nCountReceivedImaDescriptions = getSChainDiscoveredNodesCount( optsDiscover.joSChainNetworkInfo ); - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.debug( "Waiting (S-Chain discovery) attempt {} of {} for S-Chain nodes, " + "total {}, available {}, expected at least {}, discovered {}", @@ -548,12 +548,12 @@ async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); return; } - ++ nWaitAttempt; + ++nWaitAttempt; if( nWaitAttempt >= cntWaitAttempts ) { clearInterval( iv ); const strErrorDescription = "S-Chain network discovery wait timeout, " + "network will be re-discovered later"; - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.warning( "{p}This S-Chain discovery will finish due to: {err}", optsDiscover.strLogPrefix, strErrorDescription ); } @@ -566,7 +566,7 @@ async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { } return; } - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.debug( "{p}S-Chain discovery waiting attempt {} of {} for {} node answer(s)", optsDiscover.strLogPrefix, nWaitAttempt, cntWaitAttempts, ( optsDiscover.nCountToWait - optsDiscover.nCountReceivedImaDescriptions ) ); @@ -577,7 +577,7 @@ async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { async function handleDiscoverSkaleNodesRpcInfoResult( optsDiscover: TDiscoveryOptions, scURL: string, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.trace( "{p}OK, got (own) S-Chain network information: {}", optsDiscover.strLogPrefix, joOut.result ); log.success( "{p}OK, got S-Chain {url} network information.", @@ -585,10 +585,10 @@ async function handleDiscoverSkaleNodesRpcInfoResult( } optsDiscover.nCountReceivedImaDescriptions = 0; optsDiscover.joSChainNetworkInfo = joOut.result; - if( ! optsDiscover.joSChainNetworkInfo ) { + if( !optsDiscover.joSChainNetworkInfo ) { const err2 = new Error( "Got wrong response, network information description was not detected" ); - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.critical( "{p}Network was not detected via call to {url}: {err}", optsDiscover.strLogPrefix, scURL, err2 ); } @@ -606,18 +606,18 @@ async function handleDiscoverSkaleNodesRpcInfoResult( } if( optsDiscover.nCountToWait > optsDiscover.cntNodes ) optsDiscover.nCountToWait = optsDiscover.cntNodes; - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.information( "{p}Will gather details of {} of {} node(s)...", optsDiscover.strLogPrefix, optsDiscover.nCountToWait, optsDiscover.cntNodes ); } await discoverSChainWalkNodes( optsDiscover ); optsDiscover.nCountAvailable = optsDiscover.cntNodes - optsDiscover.cntFailed; - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.debug( "Waiting for S-Chain nodes, total {}, available {}, expected at least {}", optsDiscover.cntNodes, optsDiscover.nCountAvailable, optsDiscover.nCountToWait ); } if( optsDiscover.nCountAvailable < optsDiscover.nCountToWait ) { - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.critical( "{p}Not enough nodes available on S-Chain, total {}, " + "available {}, expected at least {}", @@ -673,7 +673,7 @@ export async function discoverSChainNetwork( const scURL = optsDiscover.imaState.chainProperties.sc.strURL; const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; joCall = await rpcCall.create( scURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${scURL}` ); const joIn: any = { method: "skale_nodesRpcInfo", params: { } }; if( isSendImaAgentIndex() ) @@ -687,7 +687,7 @@ export async function discoverSChainNetwork( optsDiscover.strLogPrefix, err, err ); } ); } catch ( err ) { - if( ! optsDiscover.isSilentReDiscovery ) { + if( !optsDiscover.isSilentReDiscovery ) { log.critical( "{p}JSON RPC call(discoverSChainNetwork) to S-Chain failed: " + "{err}, stack is:\n{stack}", optsDiscover.strLogPrefix, @@ -707,14 +707,14 @@ let gIntervalPeriodicDiscovery: any = null; function checkPeriodicDiscoveryNoLongerNeeded( joSChainNetworkInfo: TSChainNetworkInfo | null, isSilentReDiscovery: boolean ) { - if( ! joSChainNetworkInfo ) + if( !joSChainNetworkInfo ) return false; const imaState: state.TIMAState = state.get(); - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); const cntAlreadyDiscovered = getSChainDiscoveredNodesCount( joSChainNetworkInfo ); - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.notice( "Periodic S-Chain re-discovery already have {} of {} node(s) discovered", cntAlreadyDiscovered, cntNodesOnChain ); } @@ -737,17 +737,17 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( let joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; if( checkPeriodicDiscoveryNoLongerNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { - if( ! isSilentReDiscovery ) + if( !isSilentReDiscovery ) log.success( "Periodic S-Chain re-discovery is not needed right from startup" ); return; // not needed right from very beginning } - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); let periodicDiscoveryInterval = imaState.joSChainDiscovery.periodicDiscoveryInterval; if( periodicDiscoveryInterval <= 0 ) periodicDiscoveryInterval = 5 * 60 * 1000; - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.debug( "Periodic S-Chain re-discovery will be done with {} interval...", periodicDiscoveryInterval ); } @@ -766,19 +766,19 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; if( checkPeriodicDiscoveryNoLongerNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { - if( ! isSilentReDiscovery ) + if( !isSilentReDiscovery ) log.information( "Final periodic S-Chain re-discovery done" ); if( fnAfterRediscover ) fnAfterRediscover( true ); return; // not needed anymore, all nodes completely discovered } - if( ! isSilentReDiscovery ) + if( !isSilentReDiscovery ) log.information( "Partial periodic S-Chain re-discovery done" ); if( fnAfterRediscover ) fnAfterRediscover( false ); } ).catch( function() {} ); }, periodicDiscoveryInterval ); - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.information( "Periodic S-Chain re-discovery was started with interval {}" + " millisecond(s)", periodicDiscoveryInterval ); } diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index 1d616798..93388bd9 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -62,7 +62,7 @@ export class EventDispatcher { return this._listeners.some( item => item.type === type && item.listener === listener ); } addEventListener( type: any, listener: any ) { - if( ! this.hasEventListener( type, listener ) ) { + if( !this.hasEventListener( type, listener ) ) { this._listeners.push( { type, listener, diff --git a/src/imaCore.ts b/src/imaCore.ts index 6c36edbb..6e7ff518 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -124,7 +124,7 @@ async function findOutReferenceLogRecord( details.debug( "{p}Got {} log record(s) ({}) with data: {}", strLogPrefix, cntLogRecord, strEventName, arrLogRecords ); } - for( let idxLogRecord = 0; idxLogRecord < cntLogRecord; ++ idxLogRecord ) { + for( let idxLogRecord = 0; idxLogRecord < cntLogRecord; ++idxLogRecord ) { const joEvent = arrLogRecords[idxLogRecord]; const ev = { currentMessage: joEvent.args[0], @@ -176,7 +176,7 @@ async function findOutAllReferenceLogRecords( } let nWalkMsgNumber = nOutMsgCnt - 1; let nWalkBlockId = bnBlockId; - for( ; nWalkMsgNumber >= nIncMsgCnt; -- nWalkMsgNumber ) { + for( ; nWalkMsgNumber >= nIncMsgCnt; --nWalkMsgNumber ) { const joReferenceLogRecord = await findOutReferenceLogRecord( details, strLogPrefix, ethersProvider, joMessageProxy, nWalkBlockId, nWalkMsgNumber, isVerbose ); if( joReferenceLogRecord == null ) @@ -312,7 +312,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer: TTransferOptions ) { const nBlockTo = "latest"; for( let nWalkMsgNumber = optsTransfer.nIncMsgCnt; nWalkMsgNumber < optsTransfer.nOutMsgCnt; - ++ nWalkMsgNumber + ++nWalkMsgNumber ) { const joFilter = optsTransfer.joMessageProxySrc.filters[strEventName]( owaspUtils.ethersMod.ethers.utils.id( optsTransfer.chainNameDst ), @@ -538,7 +538,7 @@ async function preCheckAllMessagesSign( optsTransfer.strTransferErrorCategoryName, optsTransfer.details.toString() ); return false; } - if( ! loop.checkTimeFraming( null, optsTransfer.strDirection, optsTransfer.joRuntimeOpts ) ) { + if( !loop.checkTimeFraming( null, optsTransfer.strDirection, optsTransfer.joRuntimeOpts ) ) { optsTransfer.details.warning( "{p}Time framing overflow (after signing messages)", optsTransfer.strLogPrefix ); imaTransferErrorHandling.saveTransferSuccessAll(); @@ -550,7 +550,7 @@ async function preCheckAllMessagesSign( async function callbackAllMessagesSign( optsTransfer: TTransferOptions, err: Error | string | null, jarrMessages: any[], joGlueResult: any ) { - if( ! await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) + if( !await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) return; const nBlockSize = optsTransfer.arrMessageCounters.length; optsTransfer.strActionName = "dst-chain.MessageProxy.postIncomingMessages()"; @@ -724,7 +724,7 @@ async function handleAllMessagesSigning( optsTransfer: TTransferOptions ) { async function checkOutgoingMessageEventInOneNode( optsTransfer: TTransferOptions, optsOutgoingMessageAnalysis: TOutgoingMessageAnalysisOptions ) { - if( ! optsOutgoingMessageAnalysis.joNode ) { + if( !optsOutgoingMessageAnalysis.joNode ) { optsTransfer.details.error( "{p}{bright} no S-Chain node provided", optsTransfer.strLogPrefix, optsTransfer.strDirection ); @@ -760,7 +760,7 @@ async function checkOutgoingMessageEventInOneNode( "{p}Got {} event(s) ({}) on node {} with data: {}", optsTransfer.strLogPrefix, cntEvents, strEventName, optsOutgoingMessageAnalysis.joNode.name, nodeRV ); - for( let idxEvent = 0; idxEvent < cntEvents; ++ idxEvent ) { + for( let idxEvent = 0; idxEvent < cntEvents; ++idxEvent ) { const joEvent = nodeRV[idxEvent]; const eventValuesByName: any = { dstChainHash: joEvent.args[0], @@ -779,7 +779,7 @@ async function checkOutgoingMessageEventInOneNode( } } } catch ( err ) { - ++ optsOutgoingMessageAnalysis.cntFailedNodes; + ++optsOutgoingMessageAnalysis.cntFailedNodes; optsTransfer.details.error( "{p}{bright} message analysis error: Failed to scan events on node {}, " + "detailed node description is: {}, error is: {err}, stack is: ", @@ -789,14 +789,14 @@ async function checkOutgoingMessageEventInOneNode( return true; // continue nodes analysis } if( bEventIsFound ) { - ++ optsOutgoingMessageAnalysis.cntPassedNodes; + ++optsOutgoingMessageAnalysis.cntPassedNodes; optsTransfer.details.success( "{p}{bright} message {} validation on node {} using URL {url} is passed", optsTransfer.strLogPrefix, optsTransfer.strDirection, optsOutgoingMessageAnalysis.idxMessage + 1, optsOutgoingMessageAnalysis.joNode.name, strUrlHttp ); } else { - ++ optsOutgoingMessageAnalysis.cntFailedNodes; + ++optsOutgoingMessageAnalysis.cntFailedNodes; optsTransfer.details.error( "{p}{bright} message {} validation on node {} using URL {url} is failed", optsTransfer.strLogPrefix, optsTransfer.strDirection, @@ -820,7 +820,7 @@ async function checkOutgoingMessageEvent( optsTransfer: TTransferOptions, joSChain: skaleObserver.TSChainInformation ) { const cntNodes = joSChain.nodes.length; const cntMessages = optsTransfer.jarrMessages.length; - for( let idxMessage = 0; idxMessage < cntMessages; ++ idxMessage ) { + for( let idxMessage = 0; idxMessage < cntMessages; ++idxMessage ) { const idxImaMessage = optsTransfer.arrMessageCounters[idxMessage]; const joMessage = optsTransfer.jarrMessages[idxMessage]; optsTransfer.details.trace( @@ -840,13 +840,13 @@ async function checkOutgoingMessageEvent( try { for( optsOutgoingMessageAnalysis.idxNode = 0; optsOutgoingMessageAnalysis.idxNode < cntNodes; - ++ optsOutgoingMessageAnalysis.idxNode + ++optsOutgoingMessageAnalysis.idxNode ) { optsOutgoingMessageAnalysis.joNode = joSChain.nodes[ optsOutgoingMessageAnalysis.idxNode]; const isContinueNodesAnalysis = await checkOutgoingMessageEventInOneNode( optsTransfer, optsOutgoingMessageAnalysis ); - if( ! isContinueNodesAnalysis ) + if( !isContinueNodesAnalysis ) break; } } catch ( err ) { @@ -877,7 +877,7 @@ async function checkOutgoingMessageEvent( optsTransfer.details.close(); return false; } - if( ! ( optsOutgoingMessageAnalysis.cntPassedNodes >= optsTransfer.cntNodesShouldPass ) ) { + if( !( optsOutgoingMessageAnalysis.cntPassedNodes >= optsTransfer.cntNodesShouldPass ) ) { optsTransfer.details.critical( "{p}Error validating {bright} messages, passed node count {} is less then " + "needed count {}", optsTransfer.strLogPrefix, optsTransfer.strDirection, @@ -911,7 +911,7 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { "transfer step(s)", optsTransfer.strLogPrefix, optsTransfer.nIdxCurrentMsg, optsTransfer.nStepsDone, optsTransfer.nMaxTransactionsCount, optsTransfer.nTransferSteps ); - if( ! loop.checkTimeFraming( + if( !loop.checkTimeFraming( null, optsTransfer.strDirection, optsTransfer.joRuntimeOpts ) ) { optsTransfer.details.warning( "{p}WARNING: Time framing overflow" + "(after entering block former iteration loop)", optsTransfer.strLogPrefix ); @@ -922,7 +922,7 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { await gatherMessages( optsTransfer ); if( optsTransfer.cntAccumulatedForBlock == 0 ) break; - if( ! loop.checkTimeFraming( + if( !loop.checkTimeFraming( null, optsTransfer.strDirection, optsTransfer.joRuntimeOpts ) ) { optsTransfer.details.warning( "{p}Time framing overflow" + "(after forming block of messages)", optsTransfer.strLogPrefix ); @@ -932,7 +932,7 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { } if( optsTransfer.strDirection == "S2S" ) { optsTransfer.strActionName = "S2S message analysis"; - if( ! optsTransfer.joExtraSignOpts ) { + if( !optsTransfer.joExtraSignOpts ) { throw new Error( "Could not validate S2S messages, " + "no extra options provided to transfer algorithm" ); } @@ -960,7 +960,7 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { "comparison, {} message(s) to check...", optsTransfer.strLogPrefix, optsTransfer.strDirection, optsTransfer.chainNameSrc, cntNodes, optsTransfer.cntNodesShouldPass, optsTransfer.cntNodesMayFail, cntMessages ); - if( ! ( await checkOutgoingMessageEvent( optsTransfer, joSChain ) ) ) + if( !( await checkOutgoingMessageEvent( optsTransfer, joSChain ) ) ) return false; } @@ -985,7 +985,7 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { `${optsTransfer.nTransferLoopCounter}-doTransfer-B-${optsTransfer.chainNameSrc}` + `-->${optsTransfer.chainNameDst}`; try { - if( ! ( await handleAllMessagesSigning( optsTransfer ) ) ) + if( !( await handleAllMessagesSigning( optsTransfer ) ) ) return false; } catch ( err ) { optsTransfer.details.critical( @@ -994,7 +994,7 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { } if( optsTransfer.bErrorInSigningMessages ) break; - ++ optsTransfer.nStepsDone; + ++optsTransfer.nStepsDone; } return true; } @@ -1064,7 +1064,7 @@ export async function doTransfer( cntNodesShouldPass: 0, cntNodesMayFail: 0 }; - ++ gTransferLoopCounter; + ++gTransferLoopCounter; optsTransfer.strGatheredDetailsName = `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter}-doTransfer-A-` + `${optsTransfer.chainNameSrc}-->${optsTransfer.chainNameDst}`; @@ -1089,7 +1089,7 @@ export async function doTransfer( optsTransfer.details.debug( "{p}Message signing is {oo}", optsTransfer.strLogPrefix, optsTransfer.imaState.bSignMessages ); if( optsTransfer.fnSignMessages == null || optsTransfer.fnSignMessages == undefined || - ( ! optsTransfer.imaState.bSignMessages ) + ( !optsTransfer.imaState.bSignMessages ) ) { optsTransfer.details.debug( "{p}Using internal signing stub function", optsTransfer.strLogPrefix ); @@ -1122,11 +1122,11 @@ export async function doTransfer( if( optsTransfer.nBlockAge < 0 ) optsTransfer.nBlockAge = 0; try { - if( ! ( await doQueryOutgoingMessageCounter( optsTransfer ) ) ) { + if( !( await doQueryOutgoingMessageCounter( optsTransfer ) ) ) { gIsOneTransferInProgressInThisThread = false; return false; } - if( ! ( await doMainTransferLoopActions( optsTransfer ) ) ) { + if( !( await doMainTransferLoopActions( optsTransfer ) ) ) { gIsOneTransferInProgressInThisThread = false; return false; } @@ -1151,7 +1151,7 @@ export async function doTransfer( } optsTransfer.details.close(); } - if( ! optsTransfer.bErrorInSigningMessages ) { + if( !optsTransfer.bErrorInSigningMessages ) { imaTransferErrorHandling.saveTransferSuccess( optsTransfer.strTransferErrorCategoryName ); } @@ -1196,7 +1196,7 @@ export async function doAllS2S( // s-chain --> s-chain const cntSChains = arrSChainsCached.length; log.information( "Have {} S-Chain(s) connected to this S-Chain for performing " + "S2S transfers in {}.", cntSChains, threadInfo.threadDescription() ); - for( let idxSChain = 0; idxSChain < cntSChains; ++ idxSChain ) { + for( let idxSChain = 0; idxSChain < cntSChains; ++idxSChain ) { const joSChain = arrSChainsCached[idxSChain]; const urlSrc = skaleObserver.pickRandomSChainUrl( joSChain ); const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = @@ -1209,7 +1209,7 @@ export async function doAllS2S( // s-chain --> s-chain let bOK = false; try { nIndexS2S = idxSChain; - if( ! await pwa.checkOnLoopStart( imaState, "s2s", nIndexS2S ) ) { + if( !await pwa.checkOnLoopStart( imaState, "s2s", nIndexS2S ) ) { imaState.loopState.s2s.wasInProgress = false; log.notice( "Skipped(s2s) due to cancel mode reported from PWA in {}", threadInfo.threadDescription() ); @@ -1283,9 +1283,9 @@ export async function doAllS2S( // s-chain --> s-chain await pwa.notifyOnLoopEnd( imaState, "s2s", nIndexS2S ); } if( bOK ) - ++ cntOK; + ++cntOK; else - ++ cntFail; + ++cntFail; } joRuntimeOpts.idxChainKnownForS2S = 0; // reset/clear joRuntimeOpts.cntChainsKnownForS2S = 0; // reset/clear diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index dc298b32..b75a5462 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -41,7 +41,7 @@ export async function getBalanceEth( ) { const strLogPrefix = "getBalanceEth() call "; try { - if( ! ( ethersProvider && joAccount ) ) + if( !( ethersProvider && joAccount ) ) return ""; const strAddress = joAccount.address(); if( ( !isMainNet ) && contractERC20 ) { @@ -323,7 +323,7 @@ export async function viewEthPaymentFromSchainOnMainNet( const strActionName = ""; const strLogPrefix = "S ETH View: "; try { - if( ! ( ethersProviderMainNet && joAccountMN && joDepositBoxETH ) ) + if( !( ethersProviderMainNet && joAccountMN && joDepositBoxETH ) ) return null; const addressFrom = joAccountMN.address(); const xWei = diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 606a36eb..fc61de78 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -73,7 +73,7 @@ export function createProgressiveEventsScanPlan( details: log.TLogger, nLatestBl if( arrProgressiveEventsScanPlan.length > 0 ) { const joLastPlan = arrProgressiveEventsScanPlan[arrProgressiveEventsScanPlan.length - 1]; - if( ! ( joLastPlan.nBlockFrom == 0 && joLastPlan.nBlockTo == "latest" ) ) { + if( !( joLastPlan.nBlockFrom == 0 && joLastPlan.nBlockTo == "latest" ) ) { arrProgressiveEventsScanPlan.push( { nBlockFrom: 0, nBlockTo: "latest", type: "entire block range" } ); } @@ -93,7 +93,7 @@ export async function safeGetPastEventsProgressive( const strURL = owaspUtils.ethersProviderToUrl( ethersProvider ); details.information( "{p}Will run progressive logs search for event {} via URL {url}, " + "from block {}, to block...", strLogPrefix, strEventName, strURL, nBlockFrom, nBlockTo ); - if( ! imaTransferErrorHandling.getEnabledProgressiveEventsScan() ) { + if( !imaTransferErrorHandling.getEnabledProgressiveEventsScan() ) { details.warning( "{p}IMPORTANT NOTICE: Will skip progressive events scan in block range from {} to {} " + "because it's {}", strLogPrefix, nBlockFrom, nBlockTo, log.fmtError( "DISABLED" ) ); @@ -117,7 +117,7 @@ export async function safeGetPastEventsProgressive( nBlockFrom = owaspUtils.toBN( nBlockFrom ); const nBlockZero = owaspUtils.toBN( 0 ); const isFirstZero = ( nBlockFrom.eq( nBlockZero ) ) ? true : false; - if( ! ( isFirstZero && isLastLatest ) ) { + if( !( isFirstZero && isLastLatest ) ) { details.trace( "{p}Will skip progressive event log records scan and use scan in block " + "range from {} to {}", strLogPrefix, nBlockFrom.toHexString(), nBlockTo.toHexString() ); return await safeGetPastEvents( @@ -212,11 +212,11 @@ export async function safeGetTransactionCount( retValOnFail = ""; let ret = retValOnFail; let idxAttempt = 1; - for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + for( ; idxAttempt <= cntAttempts; ++idxAttempt ) { const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); - if( ! isOnLine ) { + if( !isOnLine ) { ret = retValOnFail; - if( ! throwIfServerOffline ) + if( !throwIfServerOffline ) return ret; details.error( "Cannot call {} via {url} because server is off-line, attempt {} of {}", strFnName + "()", u, idxAttempt, cntAttempts ); @@ -257,11 +257,11 @@ export async function safeGetTransactionReceipt( retValOnFail = ""; let ret = retValOnFail; let idxAttempt = 1; - for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + for( ; idxAttempt <= cntAttempts; ++idxAttempt ) { const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); - if( ! isOnLine ) { + if( !isOnLine ) { ret = retValOnFail; - if( ! throwIfServerOffline ) + if( !throwIfServerOffline ) return ret; details.error( "Cannot call {} via {url} because server is off-line, attempt {} of {}", strFnName + "()", u, idxAttempt, cntAttempts ); @@ -313,11 +313,11 @@ export async function safeGetPastEvents( } else nBlockTo = owaspUtils.toBN( nBlockTo ); nBlockFrom = owaspUtils.toBN( nBlockFrom ); - for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + for( ; idxAttempt <= cntAttempts; ++idxAttempt ) { const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); - if( ! isOnLine ) { + if( !isOnLine ) { ret = retValOnFail; - if( ! throwIfServerOffline ) + if( !throwIfServerOffline ) return ret; details.error( "{p}Cannot do {} event filtering via {url} because server is off-line, " + diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 2fe640bd..c3ff53be 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -27,12 +27,12 @@ import * as log from "./log.js"; import * as owaspUtils from "./owaspUtils.js"; export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ): any { - if( ! ( strName && typeof strName == "string" && jarrReceipts ) ) + if( !( strName && typeof strName == "string" && jarrReceipts ) ) return { sumGasUsed: 0, strReport: "N/A" }; let i; let sumGasUsed = owaspUtils.toBN( "0" ); let s = "\n" + log.fmtInformation( "Gas usage report for " ) + log.fmtInformation( "{p}\n", strName ); - for( i = 0; i < jarrReceipts.length; ++ i ) { + for( i = 0; i < jarrReceipts.length; ++i ) { try { sumGasUsed = sumGasUsed.add( owaspUtils.toBN( jarrReceipts[i].receipt.gasUsed ) ); s += log.fmtInformation( " {p}", jarrReceipts[i].description ) + diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 14c0b6f4..776caa90 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -93,11 +93,11 @@ export async function safeGetBlockNumber( retValOnFail = ""; let ret = retValOnFail; let idxAttempt = 1; - for( ; idxAttempt <= cntAttempts; ++ idxAttempt ) { + for( ; idxAttempt <= cntAttempts; ++idxAttempt ) { const isOnLine = await rpcCall.checkUrl( u, nWaitStepMilliseconds ); - if( ! isOnLine ) { + if( !isOnLine ) { ret = retValOnFail; - if( ! throwIfServerOffline ) + if( !throwIfServerOffline ) return ret; details.error( "Cannot call {} via {url} because server is off-line", strFnName + "()", u ); @@ -128,7 +128,7 @@ export function getBlocksCountInInIterativeStepOfEventsScan(): number { return gCountOfBlocksInIterativeStep; } export function setBlocksCountInInIterativeStepOfEventsScan( n?: number ): void { - if( ! n ) + if( !n ) gCountOfBlocksInIterativeStep = 0; else { gCountOfBlocksInIterativeStep = owaspUtils.parseIntOrHex( n ); @@ -141,7 +141,7 @@ export function getMaxIterationsInAllRangeEventsScan(): number { return gCountOfBlocksInIterativeStep; } export function setMaxIterationsInAllRangeEventsScan( n?: number ): void { - if( ! n ) + if( !n ) gMaxBlockScanIterationsInAllRange = 0; else { gMaxBlockScanIterationsInAllRange = owaspUtils.parseIntOrHex( n ); diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index e78899c0..e93b0aaa 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -171,13 +171,13 @@ async function handleOracleSigned( } optsGasPriceSetup.strActionName = "doOracleGasPriceSetup.formatSignature"; let signature: owaspUtils.TXYSignature | null = joGlueResult ? joGlueResult.signature : null; - if( ! signature ) + if( !signature ) signature = { X: "0", Y: "0" }; let hashPoint = joGlueResult ? joGlueResult.hashPoint : null; - if( ! hashPoint ) + if( !hashPoint ) hashPoint = { X: "0", Y: "0" }; let hint = joGlueResult ? joGlueResult.hint : null; - if( ! hint ) + if( !hint ) hint = "0"; const sign: owaspUtils.TBLSSignature = { blsSignature: [ signature.X, signature.Y ], // BLS glue of signatures @@ -252,7 +252,7 @@ export async function doOracleGasPriceSetup( chainIdSChain: string, fnSignMsgOracle: TFunctionSignMsgOracle ) { - if( ! getEnabledOracle() ) + if( !getEnabledOracle() ) return true; const optsGasPriceSetup: TGasPriceSetupOptions = { ethersProviderMainNet, diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 7a194d99..034c7911 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -62,11 +62,11 @@ export async function waitForHasChain( cntWaitAttempts?: number, nSleepMilliseconds?: number ) { - if( ! cntWaitAttempts ) + if( !cntWaitAttempts ) cntWaitAttempts = 100; - if( ! nSleepMilliseconds ) + if( !nSleepMilliseconds ) nSleepMilliseconds = 5; - for( let idxWaitAttempts = 0; idxWaitAttempts < cntWaitAttempts; ++ idxWaitAttempts ) { + for( let idxWaitAttempts = 0; idxWaitAttempts < cntWaitAttempts; ++idxWaitAttempts ) { if( await invokeHasChain( details, ethersProvider, joLinker, joAccount, chainIdSChain ) ) return true; details.trace( "Sleeping {} milliseconds...", nSleepMilliseconds ); @@ -96,7 +96,7 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 try { strActionName = "checkIsRegisteredSChainInDepositBoxes(reg-step1)"; const addressFrom = joAccountMN.address(); - if( ! joLinker ) + if( !joLinker ) throw new Error( "No Linker contract" ); const bIsRegistered = await joLinker.callStatic.hasSchain( chainIdSChain, { from: addressFrom } ); @@ -148,21 +148,21 @@ export async function registerSChainInDepositBoxes( // step 1 try { strActionName = "Register S-chain in deposit boxes, step 1, connectSchain"; details.debug( "{p}Will register S-Chain in lock_and_data on Main-net", strLogPrefix ); - if( ! joTokenManagerLinker ) + if( !joTokenManagerLinker ) throw new Error( "No TokenManagerLinker contract" ) - if( ! joCommunityLocker ) + if( !joCommunityLocker ) throw new Error( "No CommunityLocker contract" ) - if( ! joTokenManagerETH ) + if( !joTokenManagerETH ) throw new Error( "No TokenManagerETH contract" ) - if( ! joTokenManagerERC20 ) + if( !joTokenManagerERC20 ) throw new Error( "No TokenManagerERC20 contract" ) - if( ! joTokenManagerERC721 ) + if( !joTokenManagerERC721 ) throw new Error( "No TokenManagerERC721 contract" ) - if( ! joTokenManagerERC1155 ) + if( !joTokenManagerERC1155 ) throw new Error( "No TokenManagerERC1155 contract" ) - if( ! joTokenManagerERC721WithMetadata ) + if( !joTokenManagerERC721WithMetadata ) throw new Error( "No TokenManagerERC721WithMetadata contract" ) - if( ! joLinker ) + if( !joLinker ) throw new Error( "No Linker contract" ) const arrArguments = [ chainNameSChain, [ @@ -205,7 +205,7 @@ export async function registerSChainInDepositBoxes( // step 1 details, ethersProviderMainNet, joLinker, joAccountMN, chainNameSChain, cntWaitAttempts, nSleepMilliseconds ); - if( ! isSChainStatusOKay ) + if( !isSChainStatusOKay ) throw new Error( "S-Chain ownership status check timeout" ); } catch ( err ) { details.critical( "{p}Error in registerSChainInDepositBoxes() during {bright}: {err}" + diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 26595c70..ef5dbd1a 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -10,15 +10,15 @@ log.addStdout(); process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; function finalizeOutput( jo: any ) { - if( ! jo ) + if( !jo ) return; process.stdout.write( log.fmtInformation( "{}", jo ) ); } function postConvertBN( jo: any, name: any ) { - if( ! jo ) + if( !jo ) return; - if( ! ( name in jo ) ) + if( !( name in jo ) ) return; if( typeof jo[name] != "object" ) return; @@ -93,7 +93,7 @@ async function run() { }; const joCall: rpcCall.TRPCCall = await rpcCall.create( strSgxWalletURL, rpcCallOpts ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${strSgxWalletURL}` ); const joIn: any = { method: "ecdsaSignMessageHash", diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 2d82c2ad..aa64b79d 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -42,7 +42,7 @@ export async function getBalanceErc20( ) { const strLogPrefix = "getBalanceErc20() call "; try { - if( ! ( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in + if( !( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in joABI && ( strCoinName + "_address" ) in joABI ) ) return ""; const strAddress = joAccount.address(); @@ -72,7 +72,7 @@ export async function getOwnerOfErc721( ) { const strLogPrefix = "getOwnerOfErc721() call "; try { - if( ! ( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in + if( !( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in joABI && ( strCoinName + "_address" ) in joABI ) ) return ""; const strAddress = joAccount.address(); @@ -101,7 +101,7 @@ export async function getBalanceErc1155( ) { const strLogPrefix = "getBalanceErc1155() call "; try { - if( ! ( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in + if( !( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in joABI && ( strCoinName + "_address" ) in joABI ) ) return ""; const strAddress = joAccount.address(); @@ -1277,21 +1277,21 @@ export async function doErc20PaymentS2S( const strLogPrefix = `S2S ERC20 Payment(${( isForward ? "forward" : "reverse" )}:): `; try { strActionName = `validateArgs/doErc20PaymentS2S/${( isForward ? "forward" : "reverse" )}`; - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No ethers provider specified for source of transfer" ); - if( ! strChainNameDst ) + if( !strChainNameDst ) throw new Error( "No destination chain name provided" ); - if( ! joAccountSrc ) + if( !joAccountSrc ) throw new Error( "No account or sign TX way provided" ); - if( ! strCoinNameErc20Src ) + if( !strCoinNameErc20Src ) throw new Error( "Need full source ERC20 information, like ABI" ); - if( ! joSrcErc20 ) + if( !joSrcErc20 ) throw new Error( "No source ERC20 ABI provided" ); if( isReverse ) { - if( ! ercDstAddress20 ) + if( !ercDstAddress20 ) throw new Error( "No destination ERC20 address provided" ); } - if( ! tc ) + if( !tc ) throw new Error( "No transaction customizer provided" ); const ercSrcAbi20 = joSrcErc20[strCoinNameErc20Src + "_abi"]; const ercSrcAddress20 = joSrcErc20[strCoinNameErc20Src + "_address"]; @@ -1417,21 +1417,21 @@ export async function doErc721PaymentS2S( const strLogPrefix = `S2S ERC721 Payment(${( isForward ? "forward" : "reverse" )}: `; try { strActionName = `validateArgs/doErc721PaymentS2S/${( isForward ? "forward" : "reverse" )}`; - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No provider for source of transfer" ); - if( ! strChainNameDst ) + if( !strChainNameDst ) throw new Error( "No destination chain name provided" ); - if( ! joAccountSrc ) + if( !joAccountSrc ) throw new Error( "No account or sign TX way provided" ); - if( ! strCoinNameErc721Src ) + if( !strCoinNameErc721Src ) throw new Error( "Need full source ERC721 information, like ABI" ); - if( ! joSrcErc721 ) + if( !joSrcErc721 ) throw new Error( "No source ERC721 ABI provided" ); if( isReverse ) { - if( ! ercDstAddress721 ) + if( !ercDstAddress721 ) throw new Error( "No destination ERC721 address provided" ); } - if( ! tc ) + if( !tc ) throw new Error( "No transaction customizer provided" ); const ercSrcAbi721 = joSrcErc721[strCoinNameErc721Src + "_abi"]; const ercSrcAddress721 = joSrcErc721[strCoinNameErc721Src + "_address"]; @@ -1562,21 +1562,21 @@ export async function doErc1155PaymentS2S( const strLogPrefix = `S2S ERC1155 Payment(${( isForward ? "forward" : "reverse" )}): `; try { strActionName = `validateArgs/doErc1155PaymentS2S/${( isForward ? "forward" : "reverse" )}`; - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No provider for source of transfer" ); - if( ! strChainNameDst ) + if( !strChainNameDst ) throw new Error( "No destination chain name provided" ); - if( ! joAccountSrc ) + if( !joAccountSrc ) throw new Error( "No account or sign TX way provided" ); - if( ! strCoinNameErc1155Src ) + if( !strCoinNameErc1155Src ) throw new Error( "Need full source ERC1155 information, like ABI" ); - if( ! joSrcErc1155 ) + if( !joSrcErc1155 ) throw new Error( "No source ERC1155 ABI provided" ); if( isReverse ) { - if( ! ercDstAddress1155 ) + if( !ercDstAddress1155 ) throw new Error( "No destination ERC1155 address provided" ); } - if( ! tc ) + if( !tc ) throw new Error( "No transaction customizer provided" ); const ercSrcAbi1155 = joSrcErc1155[strCoinNameErc1155Src + "_abi"]; const ercSrcAddress1155 = joSrcErc1155[strCoinNameErc1155Src + "_address"]; @@ -1708,21 +1708,21 @@ export async function doErc1155BatchPaymentS2S( try { strActionName = `validateArgs/doErc1155BatchPaymentS2S/${( isForward ? "forward" : "reverse" )}`; - if( ! ethersProviderSrc ) + if( !ethersProviderSrc ) throw new Error( "No provider for source of transfer" ); - if( ! strChainNameDst ) + if( !strChainNameDst ) throw new Error( "No destination chain name provided" ); - if( ! joAccountSrc ) + if( !joAccountSrc ) throw new Error( "No account or sign TX way provided" ); - if( ! strCoinNameErc1155Src ) + if( !strCoinNameErc1155Src ) throw new Error( "Need full source ERC1155 information, like ABI" ); - if( ! joSrcErc1155 ) + if( !joSrcErc1155 ) throw new Error( "No source ERC1155 ABI provided" ); if( isReverse ) { - if( ! ercDstAddress1155 ) + if( !ercDstAddress1155 ) throw new Error( "No destination ERC1155 address provided" ); } - if( ! tc ) + if( !tc ) throw new Error( "No transaction customizer provided" ); const ercSrcAbi1155 = joSrcErc1155[strCoinNameErc1155Src + "_abi"]; const ercSrcAddress1155 = joSrcErc1155[strCoinNameErc1155Src + "_address"]; @@ -1848,7 +1848,7 @@ export async function mintErc20( const details = log.createMemoryStream(); try { details.debug( "{p}Mint ERC20 token amount {}", strLogPrefix, nAmount ); - if( ! ( ethersProvider && joAccount && strAddressMintTo && + if( !( ethersProvider && joAccount && strAddressMintTo && typeof strAddressMintTo == "string" && strAddressMintTo.length > 0 && strTokenContractAddress && typeof strTokenContractAddress == "string" && strTokenContractAddress.length > 0 && joTokenContractABI @@ -1918,7 +1918,7 @@ export async function mintErc721( const details = log.createMemoryStream(); try { details.debug( "{p}Mint ERC721 token ID {}", strLogPrefix, idToken ); - if( ! ( ethersProvider && joAccount && strAddressMintTo && + if( !( ethersProvider && joAccount && strAddressMintTo && typeof strAddressMintTo == "string" && strAddressMintTo.length > 0 && strTokenContractAddress && typeof strTokenContractAddress == "string" && strTokenContractAddress.length > 0 && joTokenContractABI @@ -1990,7 +1990,7 @@ export async function mintErc1155( try { details.debug( "{p}Mint ERC1155 token ID {} token amount {}", strLogPrefix, idToken, nAmount ); - if( ! ( ethersProvider && joAccount && strAddressMintTo && + if( !( ethersProvider && joAccount && strAddressMintTo && typeof strAddressMintTo == "string" && strAddressMintTo.length > 0 && strTokenContractAddress && typeof strTokenContractAddress == "string" && strTokenContractAddress.length > 0 && joTokenContractABI @@ -2062,7 +2062,7 @@ export async function burnErc20( const details = log.createMemoryStream(); try { details.debug( "{p}Burn ERC20 token amount {}", strLogPrefix, nAmount ); - if( ! ( ethersProvider && joAccount && strAddressBurnFrom && + if( !( ethersProvider && joAccount && strAddressBurnFrom && typeof strAddressBurnFrom == "string" && strAddressBurnFrom.length > 0 && strTokenContractAddress && typeof strTokenContractAddress == "string" && strTokenContractAddress.length > 0 && joTokenContractABI @@ -2131,7 +2131,7 @@ export async function burnErc721( const details = log.createMemoryStream(); try { details.debug( "{p}Burn ERC721 token ID {}", strLogPrefix, idToken ); - if( ! ( ethersProvider && joAccount && + if( !( ethersProvider && joAccount && strTokenContractAddress && typeof strTokenContractAddress == "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) @@ -2201,7 +2201,7 @@ export async function burnErc1155( try { details.debug( "{p}Burn ERC1155 token ID {} token amount {}", strLogPrefix, idToken, nAmount ); - if( ! ( ethersProvider && joAccount && strAddressBurnFrom && + if( !( ethersProvider && joAccount && strAddressBurnFrom && typeof strAddressBurnFrom == "string" && strAddressBurnFrom.length > 0 && strTokenContractAddress && typeof strTokenContractAddress == "string" && strTokenContractAddress.length > 0 && joTokenContractABI diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 5bec39f2..5b749f00 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -72,8 +72,8 @@ export function getLastTransferErrors( isIncludeTextLog: boolean ): any[] { if( typeof isIncludeTextLog == "undefined" ) isIncludeTextLog = true; const jarr = JSON.parse( JSON.stringify( gArrLastTransferErrors ) ); - if( ! isIncludeTextLog ) { - for( let i = 0; i < jarr.length; ++ i ) { + if( !isIncludeTextLog ) { + for( let i = 0; i < jarr.length; ++i ) { const jo: any = jarr[i]; if( "textLog" in jo ) delete jo.textLog; diff --git a/src/imaTx.ts b/src/imaTx.ts index 1b6bc305..915483a9 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -104,7 +104,7 @@ export async function dryRunCall( gasPrice: any, gasValue: any, weiHowMuch: any, opts?: any ) { - if( ! dryRunIsEnabled() ) + if( !dryRunIsEnabled() ) return null; // success isDryRunResultIgnore = ( isDryRunResultIgnore != null && isDryRunResultIgnore != undefined ) ? ( !!isDryRunResultIgnore ) : false; @@ -113,7 +113,7 @@ export async function dryRunCall( let strArgumentsDescription = ""; if( arrArguments.length > 0 ) { strArgumentsDescription += log.fmtDebug( "( " ); - for( let i = 0; i < arrArguments.length; ++ i ) { + for( let i = 0; i < arrArguments.length; ++i ) { if( i > 0 ) strArgumentsDescription += log.fmtDebug( ", " ); strArgumentsDescription += log.fmtInformation( "{}", arrArguments[i] ); @@ -194,7 +194,7 @@ async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ) { const txAdjusted: any = optsPayedCall.unsignedTx; // JSON.parse( JSON.stringify( optsPayedCall.rawTx ) ); const arrNamesConvertToHex = [ "gas", "gasLimit", "optsPayedCall.gasPrice", "value" ]; - for( let idxName = 0; idxName < arrNamesConvertToHex.length; ++ idxName ) { + for( let idxName = 0; idxName < arrNamesConvertToHex.length; ++idxName ) { const strName = arrNamesConvertToHex[idxName]; if( strName in txAdjusted && typeof txAdjusted[strName] == "object" && typeof txAdjusted[strName].toHexString == "function" ) @@ -271,9 +271,9 @@ async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ) { } function postConvertBN( jo: any, name: any ) { - if( ! jo ) + if( !jo ) return; - if( ! ( name in jo ) ) + if( !( name in jo ) ) return; if( typeof jo[name] == "object" ) return; @@ -345,7 +345,7 @@ export async function payedCall( let strArgumentsDescription = ""; if( optsPayedCall.arrArguments.length > 0 ) { strArgumentsDescription += log.fmtDebug( "( " ); - for( let i = 0; i < optsPayedCall.arrArguments.length; ++ i ) { + for( let i = 0; i < optsPayedCall.arrArguments.length; ++i ) { if( i > 0 ) strArgumentsDescription += log.fmtDebug( ", " ); strArgumentsDescription += log.fmtInformation( "{}", optsPayedCall.arrArguments[i] ); @@ -438,7 +438,7 @@ export async function checkTransactionToSchain( powNumber = imaUtils.replaceAll( powNumber, "\t", "" ); powNumber = powNumber.trim(); details.trace( "{p}Trimmed PoW-mining number is {}", strLogPrefix, powNumber ); - if( ! powNumber ) + if( !powNumber ) throw new Error( "Failed to compute gas price with PoW-mining(1), got empty text" ); powNumber = owaspUtils.toBN( owaspUtils.ensureStartsWith0x( powNumber ) ); details.trace( "{p}BN PoW-mining number is {}", strLogPrefix, powNumber ); @@ -579,7 +579,7 @@ async function tmWait( details.debug( "{p}TM - will wait TX {} to complete for {} second(s) maximum", strLogPrefix, txId, nWaitSeconds ); const startTs = imaHelperAPIs.currentTimestamp(); - while( ! tmIsFinished( await tmGetRecord( txId ) ) && + while( !tmIsFinished( await tmGetRecord( txId ) ) && ( imaHelperAPIs.currentTimestamp() - startTs ) < nWaitSeconds ) await threadInfo.sleep( 500 ); const r = await tmGetRecord( txId ); @@ -686,7 +686,7 @@ export class TransactionCustomizer { let strArgumentsDescription = ""; if( arrArguments.length > 0 ) { strArgumentsDescription += log.fmtDebug( "( " ); - for( let i = 0; i < arrArguments.length; ++ i ) { + for( let i = 0; i < arrArguments.length; ++i ) { if( i > 0 ) strArgumentsDescription += log.fmtDebug( ", " ); strArgumentsDescription += log.fmtInformation( "{}", arrArguments[i] ); diff --git a/src/log.ts b/src/log.ts index d601a005..eb102eff 100644 --- a/src/log.ts +++ b/src/log.ts @@ -101,7 +101,7 @@ export function enableColorization( bIsEnable?: boolean ): void { cc.enable( !!bIsEnable ); } export function isEnabledColorization(): boolean { - return ( !! ( cc.isEnabled() ) ); + return ( !!( cc.isEnabled() ) ); } export function getPrintTimestamps(): boolean { @@ -180,7 +180,7 @@ export function getStreamWithFilePath( strFilePath: string ): TLogger | null { let gStreamGlobal: TLogger | null; export function globalStream(): TLogger { - if( ! gStreamGlobal ) { + if( !gStreamGlobal ) { gStreamGlobal = { id: 0, strPath: "global", @@ -219,7 +219,7 @@ export function globalStream(): TLogger { export function createStandardOutputStream(): TLogger | null { try { const objEntry: TLogger = { - id: gIdentifierAllocatorCounter ++, + id: gIdentifierAllocatorCounter++, strPath: "stdout", nMaxSizeBeforeRotation: -1, nMaxFilesCount: -1, @@ -330,7 +330,7 @@ export function insertStandardOutputStream(): boolean { export function createMemoryOutputStream(): TLogger { try { const objEntry: TLoggerMemory = { - id: gIdentifierAllocatorCounter ++, + id: gIdentifierAllocatorCounter++, strPath: "memory", nMaxSizeBeforeRotation: -1, nMaxFilesCount: -1, @@ -349,7 +349,7 @@ export function createMemoryOutputStream(): TLogger { return false; const s = this.arrAccumulatedLogTextLines[ this.arrAccumulatedLogTextLines.length - 1]; - if( ! s ) + if( !s ) return false; if( s[s.length - 1] == "\n" ) return true; @@ -358,7 +358,7 @@ export function createMemoryOutputStream(): TLogger { write: function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); - for( let i = 0; i < arr.length; ++ i ) { + for( let i = 0; i < arr.length; ++i ) { const strLine = arr[i]; let strHeader = ""; if( this.isLastLineEndsWithCarriageReturn() || @@ -373,7 +373,7 @@ export function createMemoryOutputStream(): TLogger { writeRaw: function( ...args: any[] ): void { const s = fmtArgumentsArray( args ); const arr = s.split( "\n" ); - for( let i = 0; i < arr.length; ++ i ) { + for( let i = 0; i < arr.length; ++i ) { const strLine = arr[i]; this.arrAccumulatedLogTextLines.push( strLine + "\n" ); } @@ -386,13 +386,13 @@ export function createMemoryOutputStream(): TLogger { function( nBytesToWrite: number ) { this.arrAccumulatedLogTextLines = []; }, toString: function(): string { let s = ""; - for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) + for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++i ) s += this.arrAccumulatedLogTextLines[i]; return s; }, exposeDetailsTo: function( otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { - if( ! ( this.arrAccumulatedLogTextLines && + if( !( this.arrAccumulatedLogTextLines && this.arrAccumulatedLogTextLines.length > 0 ) ) return; let werePausedTimeStamps = false; @@ -412,7 +412,7 @@ export function createMemoryOutputStream(): TLogger { cc.sunny( strTitle ) + cc.bright( " action (" ) + cc.sunny( "BEGIN" ) + cc.bright( ") --- --- ------ --- " ) ); otherStream.write( "\n" ); - for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++ i ) { + for( let i = 0; i < this.arrAccumulatedLogTextLines.length; ++i ) { try { otherStream.writeRaw( this.arrAccumulatedLogTextLines[i] ); } catch ( err ) { @@ -509,7 +509,7 @@ export function createFileOutput( ): TLogger | null { try { const objEntry: TLogger = { - id: gIdentifierAllocatorCounter ++, + id: gIdentifierAllocatorCounter++, strPath: "" + strFilePath, nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation || 0 ), nMaxFilesCount: 0 + ( nMaxFilesCount || 0 ), @@ -666,13 +666,13 @@ export function insertFileOutput( export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): string { strDefaultErrorText = strDefaultErrorText || "unknown error or error without a description"; - if( ! jo ) + if( !jo ) return strDefaultErrorText; try { const isError = function( err: Error | string ) { return err && err instanceof Error && err.stack && err.message; }; - if( ! isError( jo ) ) { + if( !isError( jo ) ) { if( "error" in jo ) { jo = jo.error; if( typeof jo == "string" ) @@ -695,7 +695,7 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): s function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[] | null { if( !( strFormat && typeof strFormat == "string" ) ) return null; - if( ! cntArgsMax ) + if( !cntArgsMax ) cntArgsMax = 0; const arrParts: any[] = []; let s = strFormat; let cntFoundArgs = 0; @@ -714,7 +714,7 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ if( strPart.length > 0 ) arrParts.push( { type: "text", text: strPart } ); arrParts.push( { type: "arg", text: strArgDesc } ); - ++ cntFoundArgs; + ++cntFoundArgs; if( s.length == 0 ) break; } @@ -731,14 +731,14 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; let s = ""; let isValueMode = false; const fnDefaultOneArgumentFormatter = function( arg?: any, fnCustomFormatter?: any ): string { - if( ! fnCustomFormatter ) + if( !fnCustomFormatter ) fnCustomFormatter = fnFormatter; const t = typeof arg; if( t == "string" ) { if( arg.length > 0 ) { if( arg == " " || arg == "\n" ) { // skip - } else if( ! cc.isStringAlreadyColorized( arg ) ) + } else if( !cc.isStringAlreadyColorized( arg ) ) return fnCustomFormatter( arg ); } } else @@ -746,11 +746,11 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { return arg; }; const fnFormatOneArgument = function( arg: any, fmt?: any ): string { - if( ! arg ) + if( !arg ) return arg; if( arg == " " || arg == "\n" ) return arg; - if( ! isValueMode ) + if( !isValueMode ) return fnDefaultOneArgumentFormatter( arg, null ); if( fmt && typeof "fmt" == "string" ) { if( fmt == "raw" ) @@ -788,11 +788,11 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { isValueMode = true; if( idxArgNextPrinted < arrArgs.length ) s += fnFormatOneArgument( arrArgs[idxArgNextPrinted], joPart.text ); - ++ idxArgNextPrinted; + ++idxArgNextPrinted; continue; } // assume joPart.type == "text" always here, at this point - if( ! cc.isStringAlreadyColorized( joPart.text ) ) + if( !cc.isStringAlreadyColorized( joPart.text ) ) s += fnFormatter( joPart.text ); else s += joPart.text; @@ -975,9 +975,9 @@ export function createMemoryStream(): TLogger { export function add( strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): boolean { - if( ! nMaxSizeBeforeRotation ) + if( !nMaxSizeBeforeRotation ) nMaxSizeBeforeRotation = 0; - if( ! nMaxFilesCount ) + if( !nMaxFilesCount ) nMaxFilesCount = 0; return insertFileOutput( strFilePath, @@ -1037,7 +1037,7 @@ let gMapReversedVerbose: Map < string, number > = new Map < string, number >(); export function verbose(): any { return gMapVerbose; } export function verboseReversed(): Map < string, number > { - if( ! gMapReversedVerbose ) + if( !gMapReversedVerbose ) gMapReversedVerbose = computeVerboseAlias(); return gMapReversedVerbose; } diff --git a/src/loop.ts b/src/loop.ts index 52443d3b..749994a5 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -173,7 +173,7 @@ async function singleTransferLoopPartOracle( optsLoop: TLoopOptions, strLogPrefi log.notice( "{p}Will invoke Oracle gas price setup in {}...", strLogPrefix, threadInfo.threadDescription() ); try { - if( ! await pwa.checkOnLoopStart( imaState, "oracle" ) ) { + if( !await pwa.checkOnLoopStart( imaState, "oracle" ) ) { imaState.loopState.oracle.wasInProgress = false; log.notice( "{p}Skipped(oracle) in {} due to cancel mode reported from PWA", strLogPrefix, threadInfo.threadDescription() ); @@ -181,11 +181,11 @@ async function singleTransferLoopPartOracle( optsLoop: TLoopOptions, strLogPrefi if( checkTimeFraming( null, "oracle", optsLoop.joRuntimeOpts ) ) { imaState.loopState.oracle.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "oracle" ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joCommunityLocker ) + if( !imaState.joCommunityLocker ) throw new Error( "No CommunityLocker contract" ); b0 = await imaOracleOperations.doOracleGasPriceSetup( imaState.chainProperties.mn.ethersProvider, @@ -224,7 +224,7 @@ async function singleTransferLoopPartM2S( optsLoop: TLoopOptions, strLogPrefix: log.notice( "{p}Will invoke M2S transfer in {}...", strLogPrefix, threadInfo.threadDescription() ); try { - if( ! await pwa.checkOnLoopStart( imaState, "m2s" ) ) { + if( !await pwa.checkOnLoopStart( imaState, "m2s" ) ) { imaState.loopState.m2s.wasInProgress = false; log.notice( "{p}Skipped(m2s) in {} due to cancel mode reported from PWA", strLogPrefix, threadInfo.threadDescription() ); @@ -232,13 +232,13 @@ async function singleTransferLoopPartM2S( optsLoop: TLoopOptions, strLogPrefix: if( checkTimeFraming( null, "m2s", optsLoop.joRuntimeOpts ) ) { imaState.loopState.m2s.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "m2s" ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain ) contract" ); b1 = await IMA.doTransfer( // main-net --> s-chain "M2S", @@ -293,7 +293,7 @@ async function singleTransferLoopPartS2M( optsLoop: TLoopOptions, strLogPrefix: log.notice( "{p}Will invoke S2M transfer in {}...", strLogPrefix, threadInfo.threadDescription() ); try { - if( ! await pwa.checkOnLoopStart( imaState, "s2m" ) ) { + if( !await pwa.checkOnLoopStart( imaState, "s2m" ) ) { imaState.loopState.s2m.wasInProgress = false; log.notice( "{p}Skipped(s2m) in {} due to cancel mode reported from PWA", strLogPrefix, threadInfo.threadDescription() ); @@ -301,13 +301,13 @@ async function singleTransferLoopPartS2M( optsLoop: TLoopOptions, strLogPrefix: if( checkTimeFraming( null, "s2m", optsLoop.joRuntimeOpts ) ) { imaState.loopState.s2m.isInProgress = true; await pwa.notifyOnLoopStart( imaState, "s2m" ); - if( ! imaState.chainProperties.mn.ethersProvider ) + if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxyMainNet ) + if( !imaState.joMessageProxyMainNet ) throw new Error( "No MessageProxyMainNet contract" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); b2 = await IMA.doTransfer( // s-chain --> main-net "S2M", @@ -366,11 +366,11 @@ async function singleTransferLoopPartS2S( optsLoop: TLoopOptions, strLogPrefix: if( optsLoop.enableStepS2S && imaState.optsS2S.isEnabled ) { log.notice( "{p}Will invoke all S2S transfers...", strLogPrefix ); try { - if( ! imaState.chainProperties.sc.ethersProvider ) + if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); - if( ! imaState.joMessageProxySChain ) + if( !imaState.joMessageProxySChain ) throw new Error( "No MessageProxySChain contract" ); - if( ! imaState.joTokenManagerETH ) + if( !imaState.joTokenManagerETH ) throw new Error( "No TokenManagerETH contract" ); b3 = await IMA.doAllS2S( // s-chain --> s-chain optsLoop.joRuntimeOpts, @@ -586,7 +586,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { const cntWorkers = 2; log.debug( "Loop module will create its ", cntWorkers, " worker(s) in ", threadInfo.threadDescription(), "..." ); - for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) { + for( let idxWorker = 0; idxWorker < cntWorkers; ++idxWorker ) { const workerData: TWorkerData = { url: "ima_loop_server" + idxWorker, colorization: { isEnabled: log.isEnabledColorization() } @@ -610,7 +610,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { const joMessage = eventData.message; switch ( joMessage.method ) { case "init": - if( ! joMessage.error ) { + if( !joMessage.error ) { aClient.logicalInitComplete = true; break } @@ -736,7 +736,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { colorization: { isEnabled: log.isEnabledColorization() } } }; - while( ! aClient.logicalInitComplete ) { + while( !aClient.logicalInitComplete ) { log.information( "LOOP server is not initialized yet..." ); await threadInfo.sleep( 1000 ); aClient.send( jo ); @@ -755,12 +755,12 @@ export async function runParallelLoops( opts: TParallelLoopRunOptions ) { } export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) { - if( ! ( joMessage && typeof joMessage == "object" && + if( !( joMessage && typeof joMessage == "object" && "method" in joMessage && joMessage.method == "skale_imaNotifyLoopWork" ) ) return; const cntWorkers = gArrWorkers.length; - for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) + for( let idxWorker = 0; idxWorker < cntWorkers; ++idxWorker ) gArrClients[idxWorker].send( joMessage ); } @@ -773,6 +773,6 @@ export async function spreadUpdatedSChainNetwork( isFinal: boolean ) { joSChainNetworkInfo: imaState.joSChainNetworkInfo }; const cntWorkers = gArrWorkers.length; - for( let idxWorker = 0; idxWorker < cntWorkers; ++ idxWorker ) + for( let idxWorker = 0; idxWorker < cntWorkers; ++idxWorker ) gArrClients[idxWorker].send( joMessage ); } diff --git a/src/main.ts b/src/main.ts index 235557d0..c8393ac2 100644 --- a/src/main.ts +++ b/src/main.ts @@ -175,10 +175,10 @@ function initMonitoringServer(): void { if( imaState.bLogMonitoringServer ) log.trace( "{p}<<< message from {}: {}", strLogPrefix, ip, joMessage ); - if( ! ( "method" in joMessage ) ) + if( !( "method" in joMessage ) ) throw new Error( "\"method\" field was not specified" ); joAnswer.method = joMessage.method; - if( ! ( "id" in joMessage ) ) + if( !( "id" in joMessage ) ) throw new Error( "\"id\" field was not specified" ); joAnswer.id = joMessage.id; switch ( joMessage.method ) { @@ -287,10 +287,10 @@ function initJsonRpcServer(): void { try { const joMessage: any = JSON.parse( message ); log.trace( "{p}<<< Peer message from {}: ", strLogPrefix, ip, joMessage ); - if( ! ( "method" in joMessage ) ) + if( !( "method" in joMessage ) ) throw new Error( "\"method\" field was not specified" ); joAnswer.method = joMessage.method; - if( ! ( "id" in joMessage ) ) + if( !( "id" in joMessage ) ) throw new Error( "\"id\" field was not specified" ); if( "id" in joMessage ) joAnswer.id = joMessage.id; @@ -339,7 +339,7 @@ function initJsonRpcServer(): void { log.error( "{p}Bad message from {}: {}, error is: {err}, stack is:\n{stack}", strLogPrefix, ip, message, err, err ); } - if( ! isSkipMode ) + if( !isSkipMode ) fnSendAnswer( joAnswer ); } ); gExpressJsonRpcAppIMA.listen( imaState.nJsonRpcPort ); @@ -378,7 +378,7 @@ async function doTheJob() { log.information( "{p}{}{}", strLogPrefix, cntFalse, log.fmtError( " task(s) failed" ) ); log.information( "{p}{p}", strLogPrefix, imaHelperAPIs.longSeparator ); process.exitCode = ( cntFalse > 0 ) ? cntFalse : 0; - if( ! state.isPreventExitAfterLastAction() ) + if( !state.isPreventExitAfterLastAction() ) process.exit( process.exitCode ); } @@ -442,9 +442,9 @@ async function main() { log.information( "S-Chain network was discovery uses {} mode", ( isSilentReDiscovery ? log.fmtWarning( "silent" ) : log.fmtSuccess( "exposed details" ) ) ); - if( ! imaState.bNoWaitSChainStarted ) { + if( !imaState.bNoWaitSChainStarted ) { await discoveryTools.waitUntilSChainStarted(); - if( ! isSilentReDiscovery ) { + if( !isSilentReDiscovery ) { log.information( "This S-Chain discovery will be done for command line task handler" ); } diff --git a/src/observer.ts b/src/observer.ts index 493c3a57..2ee9b163 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -88,7 +88,7 @@ export interface TSChainsInformation { export function findSChainIndexInArrayByName( arrSChains: TSChainInformation[], strSChainName: string ) { - for( let idxSChain = 0; idxSChain < arrSChains.length; ++ idxSChain ) { + for( let idxSChain = 0; idxSChain < arrSChains.length; ++idxSChain ) { const joSChain = arrSChains[idxSChain]; if( joSChain.name.toString() == strSChainName.toString() ) return idxSChain; @@ -100,11 +100,11 @@ let gConnectedChainsData: TSChainsInformation | null = null; export function autoUpdateLastCachedSChains(): boolean { const imaState: state.TIMAState = state.get(); - if( ! imaState.optsS2S.strNetworkBrowserPath ) + if( !imaState.optsS2S.strNetworkBrowserPath ) return false; const jo: TSChainsInformation = imaUtils.jsonFileLoad( imaState.optsS2S.strNetworkBrowserPath, null ); - if( ! ( jo && "schains" in jo && "updatedAt" in jo ) ) { + if( !( jo && "schains" in jo && "updatedAt" in jo ) ) { log.error( "Connected S-chains cache in thread {} was not updated from file {}, bad data format", threadInfo.threadDescription(), imaState.optsS2S.strNetworkBrowserPath ); @@ -122,7 +122,7 @@ export function autoUpdateLastCachedSChains(): boolean { export function getLastCachedSChains(): TSChainInformation[] { autoUpdateLastCachedSChains(); - if( ! gConnectedChainsData ) + if( !gConnectedChainsData ) return []; return JSON.parse( JSON.stringify( gConnectedChainsData.schains ) ); } diff --git a/src/oracle.ts b/src/oracle.ts index 85d05a29..b3a74a4e 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -54,7 +54,7 @@ export function findPowNumber( strRequestPart: string, details: log.TLogger, isV let i = 0; let n = 0; let s = ""; if( isVerbose ) details.debug( "source t={}, this is UTC timestamp", t ); - for( ; i < gConstMaxPowResultLimit; ++ i ) { + for( ; i < gConstMaxPowResultLimit; ++i ) { n = 0 + i; s = "{" + strRequestPart + ",\"time\":" + t + ",\"pow\":" + n + "}"; @@ -127,7 +127,7 @@ async function handleOracleSubmitRequestResult( } let gp = null; for( let idxAttempt = 0; idxAttempt < cntAttempts; ++idxAttempt ) { - const nMillisecondsToSleep = ( ! idxAttempt ) + const nMillisecondsToSleep = ( !idxAttempt ) ? nMillisecondsSleepBefore : nMillisecondsSleepPeriod; if( nMillisecondsToSleep > 0 ) await threadInfo.sleep( nMillisecondsToSleep ); @@ -166,11 +166,11 @@ export async function oracleGetGasPrice( oracleOpts: any, details: log.TLogger ) const isVerbose = "isVerbose" in oracleOpts ? oracleOpts.isVerbose : false; let isVerboseTraceDetails = "isVerboseTraceDetails" in oracleOpts ? oracleOpts.isVerboseTraceDetails : false; - if( ! ( log.verboseGet() >= log.verboseName2Number( "trace" ) ) ) + if( !( log.verboseGet() >= log.verboseName2Number( "trace" ) ) ) isVerboseTraceDetails = false; const callOpts = "callOpts" in oracleOpts ? oracleOpts.callOpts : { }; joCall = await rpcCall.create( url, callOpts || { } ); - if( ! joCall ) + if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${url}` ); const s = findPowNumber( "\"cid\":1000,\"uri\":\"geth://\",\"jsps\":[\"/result\"]," + diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 49454085..bcb5bcba 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -471,7 +471,7 @@ export function ipFromHex( hex?: any ): string { export function cloneObjectByRootKeys( joIn?: any ): any { const joOut: any = { }; const arrKeys = Object.keys( joIn ); - for( let i = 0; i < arrKeys.length; ++ i ) { + for( let i = 0; i < arrKeys.length; ++i ) { const key = arrKeys[i]; const value = joIn[key]; joOut[key] = value; @@ -750,7 +750,7 @@ export function toBN( arg: any ): any { multiplier = toBNbasic( -1, 10 ); } stringArg = stringArg === "" ? "0" : stringArg; - if( ( ! stringArg.match( /^-?[0-9]+$/ ) && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) || + if( ( !stringArg.match( /^-?[0-9]+$/ ) && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) || stringArg.match( /^[a-fA-F]+$/ ) || ( isHexPrefixed && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) ) return toBNbasic( stringArg, 16 ).mul( multiplier ) @@ -774,7 +774,7 @@ export function isNumeric( s?: any ): boolean { } export function toHexStringSafe( val?: any ): string { - if( ! val ) + if( !val ) return "0x0"; if( "toHexString" in val && typeof val.toHexString == "function" ) return val.toHexString(); @@ -803,11 +803,11 @@ export function setInterval2( fn: () => void, t: number, stepMilliSeconds?: numb } export function clearInterval2( iv: any ): void { - if( ! iv ) + if( !iv ) return; - if( ! ( "real_iv" in iv ) ) + if( !( "real_iv" in iv ) ) return; - if( ! iv.real_iv ) + if( !iv.real_iv ) return; clearInterval( iv.real_iv ); iv.real_iv = null; diff --git a/src/pwa.ts b/src/pwa.ts index feed6e46..68f45e31 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -43,7 +43,7 @@ function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): num if( i == nNodeNumber ) break; arrWalkNodeIndices.push( i ); - -- i; + --i; if( i < 0 ) i = nNodesCount - 1; } @@ -51,7 +51,7 @@ function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): num } export function checkLoopWorkTypeStringIsCorrect( strLoopWorkType: string ): boolean { - if( ! strLoopWorkType ) + if( !strLoopWorkType ) return false; switch ( strLoopWorkType.toString().toLowerCase() ) { case "oracle": @@ -74,16 +74,16 @@ function composeEmptyStateForPendingWorkAnalysis(): any { function getNodeProgressAndTimestamp( joNode: discoveryTools.TSChainNode, strLoopWorkType: string, nIndexS2S: number ) { - if( ! ( "pwaState" in joNode ) ) + if( !( "pwaState" in joNode ) ) joNode.pwaState = composeEmptyStateForPendingWorkAnalysis(); strLoopWorkType = strLoopWorkType.toLowerCase(); - if( ( !joNode.pwaState ) || ( ! ( strLoopWorkType in joNode.pwaState ) ) ) { + if( ( !joNode.pwaState ) || ( !( strLoopWorkType in joNode.pwaState ) ) ) { throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type, ` + "cannot access info" ); } if( strLoopWorkType != "s2s" ) return ( joNode.pwaState as any )[strLoopWorkType]; - if( ! ( nIndexS2S in joNode.pwaState[strLoopWorkType].mapS2S ) ) + if( !( nIndexS2S in joNode.pwaState[strLoopWorkType].mapS2S ) ) joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S] = { isInProgress: false, ts: 0 }; return joNode.pwaState[strLoopWorkType].mapS2S[nIndexS2S]; @@ -93,18 +93,18 @@ export async function checkOnLoopStart( imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined - if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) + if( !checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type` ); - if( ! imaState.isPWA ) + if( !imaState.isPWA ) return true; // PWA is N/A if( imaState.nNodesCount <= 1 ) return true; // PWA is N/A if( !( imaState.nNodeNumber >= 0 && imaState.nNodeNumber < imaState.nNodesCount ) ) return true; // PWA is N/A - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) return true; // PWA is N/A const jarrNodes = imaState.joSChainNetworkInfo.network; - if( ! jarrNodes ) + if( !jarrNodes ) throw new Error( "S-Chain network info is not available yet to PWA" ); const arrBusyNodeIndices: number[] = []; const arrWalkNodeIndices: number[] = @@ -163,18 +163,18 @@ export async function handleLoopStateArrived( let isSuccess = false; let joNode: any = null; try { - if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) + if( !checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type` ); - if( ! imaState.isPWA ) + if( !imaState.isPWA ) return true; if( imaState.nNodesCount <= 1 ) return true; // PWA is N/A if( !( imaState.nNodeNumber >= 0 && imaState.nNodeNumber < imaState.nNodesCount ) ) return true; // PWA is N/A - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) return true; // PWA is N/A const jarrNodes = imaState.joSChainNetworkInfo.network; - if( ! jarrNodes ) + if( !jarrNodes ) throw new Error( "S-Chain network info is not available yet to PWA" ); joNode = jarrNodes[nNodeNumber]; const joProps: any = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); @@ -186,7 +186,7 @@ export async function handleLoopStateArrived( nNodeNumber, strLoopWorkType, isStart, 0 + ts ); const isSignatureOK = await imaBLS.doVerifyReadyHash( strMessageHash, nNodeNumber, signature, imaState.isPrintPWA ); - if( ! isSignatureOK ) + if( !isSignatureOK ) throw new Error( "BLS verification failed" ); joProps.isInProgress = ( !!isStart ); joProps.ts = 0 + ts; @@ -212,18 +212,18 @@ async function notifyOnLoopImpl( const se = isStart ? "start" : "end"; try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined - if( ! checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) + if( !checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type` ); - if( ! imaState.isPWA ) + if( !imaState.isPWA ) return true; if( imaState.nNodesCount <= 1 ) return true; // PWA is N/A if( !( imaState.nNodeNumber >= 0 && imaState.nNodeNumber < imaState.nNodesCount ) ) return true; // PWA is N/A - if( ! imaState.joSChainNetworkInfo ) + if( !imaState.joSChainNetworkInfo ) return true; // PWA is N/A const jarrNodes = imaState.joSChainNetworkInfo.network; - if( ! jarrNodes ) + if( !jarrNodes ) throw new Error( "S-Chain network info is not available yet to PWA" ); const nUtcUnixTimeStamp = Math.floor( ( new Date() ).getTime() / 1000 ); @@ -252,7 +252,7 @@ async function notifyOnLoopImpl( if( joCall ) await joCall.disconnect(); } ); - if( ! joCall ) + if( !joCall ) return false; const joIn: any = { method: "skale_imaNotifyLoopWork", diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 86b1ce13..e0f06bb8 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -92,7 +92,7 @@ export async function waitWebSocketIsOpen( socket: ws.WebSocket, if( isInsideAsyncHandler ) return; isInsideAsyncHandler = true; - ++ nStep; + ++nStep; if( socket.readyState === 1 ) { // Notice, connection is made if we are here clearInterval( iv ); @@ -102,7 +102,7 @@ export async function waitWebSocketIsOpen( socket: ws.WebSocket, } else { if( fnStep ) { const isContinue = await fnStep( nStep ); - if( ! isContinue ) { + if( !isContinue ) { clearInterval( iv ); reject( new Error( "web socket wait timeout by callback " + `on step ${nStep}` ) ); @@ -236,7 +236,7 @@ export async function doConnectIfNeeded( async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: TFunctionConnectionResultHandler ) { - if( ! joCall.isAutoReconnect ) + if( !joCall.isAutoReconnect ) return; if( joCall.isDisconnectMode ) return; @@ -361,7 +361,7 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu } ); await promiseComplete.catch( function( err: Error | string ) { log.error( "{url} HTTP call error {err}", joCall.url, err ); - if( ! errCall ) + if( !errCall ) errCall = `HTTP(S)/RPC call(catch) error: ${err as any}`; } ); } else { @@ -492,7 +492,7 @@ export function enrichTopLevelFieldsInJSON( jo: any ) { } export function isValidUrl( s: any ) { - if( ! s ) + if( !s ) return false; try { const u = new URL( s.toString() ); @@ -504,7 +504,7 @@ export function isValidUrl( s: any ) { } export function getValidUrl( s: any ) { - if( ! s ) + if( !s ) return null; try { return new URL( s.toString() ); @@ -514,7 +514,7 @@ export function getValidUrl( s: any ) { } export function getDefaultPort( strProtocol: any ) { - if( ! strProtocol ) + if( !strProtocol ) return 80; switch ( strProtocol.toString().toLowerCase() ) { case "http:": @@ -529,7 +529,7 @@ export function getDefaultPort( strProtocol: any ) { export function getValidHostAndPort( s: any ) { const u = getValidUrl( s ); - if( ! u ) + if( !u ) return null; const jo = { strHost: u.hostname, @@ -634,14 +634,14 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec } export async function checkUrl( u: URL | string, nTimeoutMilliseconds: number, isLog?: boolean ) { - if( ! u ) + if( !u ) return false; const jo = getValidHostAndPort( u ); if( isLog ) { console.log( `${gStrTcpConnectionHeader}Extracted from URL ${u.toString()} data ` + `fields are: ${JSON.stringify( jo )}` ); } - if( ! ( jo?.strHost && "nPort" in jo ) ) { + if( !( jo?.strHost && "nPort" in jo ) ) { console.log( `${gStrTcpConnectionHeader}Extracted from URL ${u.toString()} data ` + "fields are bad, returning \"false\" as result of TCP connection check" ); return false; diff --git a/src/socket.ts b/src/socket.ts index 26e5b03f..32142e6d 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -78,7 +78,7 @@ export const updateSocketDataStatsForMessage = function( joMessage: any, joStats ) strMethod = "" + joMessage.method; if( strMethod in joStats ) - joStats[strMethod] ++; + joStats[strMethod]++; else joStats[strMethod] = 1; }; @@ -123,7 +123,7 @@ export class BasicServerAcceptor extends EventDispatcher { super.dispose(); } disposeNotifyClients() { - for( const [ /*keyWalk*/, entryWalk ] of Object.entries( this.mapClients ) ) { + for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapClients ) ) { const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { const pair: any = entry; @@ -154,7 +154,7 @@ export class BasicServerAcceptor extends EventDispatcher { flush() { if( this.isDisposing || this.isDisposed ) return; - for( const [ /*keyWalk*/, entryWalk ] of Object.entries( this.mapClients ) ) { + for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapClients ) ) { const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { const pair: any = entry; @@ -225,7 +225,7 @@ export class BasicSocketPipe extends EventDispatcher { super.dispose(); } disposeImpersonatedEntries() { // for external in-app usage only - for( const [ /*keyWalk*/, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { + for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { const entry: any = entryWalk; try { if( entry && "dispose" in entry && typeof entry.dispose == "function" ) @@ -326,7 +326,7 @@ export class BasicSocketPipe extends EventDispatcher { generateSocketDataStatsJSON( jo ) ); } - for( let i = 0; i < cnt; ++ i ) { + for( let i = 0; i < cnt; ++i ) { const joMessage = jo.arrPackedMessages[i]; if( settings.logging.net.socket.receive ) console.log( this.socketLoggingTextPrefix( "receive" ), joMessage ); @@ -390,15 +390,15 @@ export const gMapConnectedInWorkerClients: Record < string, any > = { }; export const outOfWorkerAPIs: any = { onMessage: function( worker: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); - if( ! ( "workerMessageType" in jo ) || + if( !( "workerMessageType" in jo ) || typeof jo.workerMessageType != "string" || jo.workerMessageType.length == 0 ) return false; // not a socket message - if( ! ( "workerEndPoint" in jo ) || + if( !( "workerEndPoint" in jo ) || typeof jo.workerEndPoint != "string" || jo.workerEndPoint.length == 0 ) return false; // TO-DO: send error answer and return true - if( ! ( "workerUUID" in jo ) || typeof jo.workerUUID != "string" || + if( !( "workerUUID" in jo ) || typeof jo.workerUUID != "string" || jo.workerUUID.length == 0 ) return false; // TO-DO: send error answer and return true switch ( jo.workerMessageType ) { @@ -434,26 +434,26 @@ export const outOfWorkerAPIs: any = { workerUUID, data: jo }; - //worker.postMessage( socketReceivedDataReverseMarshall( joSend ) ); + // worker.postMessage( socketReceivedDataReverseMarshall( joSend ) ); worker.postMessage( socketSentDataMarshall( joSend ) ); } }; export const inWorkerAPIs: any = { onMessage: function( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); - if( ! ( "workerMessageType" in jo ) || + if( !( "workerMessageType" in jo ) || typeof jo.workerMessageType != "string" || jo.workerMessageType.length == 0 ) return false; // not a socket message - if( ! ( "workerEndPoint" in jo ) || + if( !( "workerEndPoint" in jo ) || typeof jo.workerEndPoint != "string" || jo.workerEndPoint.length == 0 ) return false; // TO-DO: send error answer and return true - if( ! ( "workerUUID" in jo ) || + if( !( "workerUUID" in jo ) || typeof jo.workerUUID != "string" || jo.workerUUID.length == 0 ) return false; // TO-DO: send error answer and return true - if( ! ( jo.workerEndPoint in gMapLocalServers ) ) + if( !( jo.workerEndPoint in gMapLocalServers ) ) return false; // TO-DO: send error answer and return true const acceptor = gMapLocalServers[jo.workerEndPoint]; switch ( jo.workerMessageType ) { @@ -477,7 +477,7 @@ export const inWorkerAPIs: any = { workerUUID, data: jo }; - //postMessage( socketReceivedDataReverseMarshall( joSend ) ); + // postMessage( socketReceivedDataReverseMarshall( joSend ) ); postMessage( socketSentDataMarshall( joSend ) ); } }; @@ -518,7 +518,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.dispose(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.fnSend( "inWorkerDisconnect", this.acceptor.strEndPoint, this.clientPort, {} ); this.isConnected = false; @@ -591,14 +591,14 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { return true; } performDisconnect( jo: any ) { - if( ! ( jo.workerUUID in this.mapClients ) ) + if( !( jo.workerUUID in this.mapClients ) ) return false; // TO-DO: send error answer and return true const pipe = this.mapClients[jo.workerUUID]; pipe.performDisconnect(); return true; } receiveForClientPort( clientPort: any, jo: any ) { - if( ! ( clientPort in this.mapClients ) ) + if( !( clientPort in this.mapClients ) ) return false; // TO-DO: send error answer and return true const pipe = this.mapClients[clientPort]; pipe.receive( jo ); @@ -639,7 +639,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { super.dispose(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.isConnected = false; delete gMapConnectedInWorkerClients["" + this.clientPort]; @@ -701,7 +701,7 @@ export class OutOfWorkerRelay extends EventDispatcher { self.isAutoFlushOutgoing = ( isAutoFlushOutgoing == null || isAutoFlushOutgoing == undefined ) ? true : ( !!( isAutoFlushOutgoing ) ); - if( ! acceptor ) { + if( !acceptor ) { throw new Error( `OutOfWorkerRelay ${self.strRelayName} needs acceptor ` + "for normal functionality" ); } @@ -715,7 +715,7 @@ export class OutOfWorkerRelay extends EventDispatcher { self.onConnection_ = function( eventData: any ) { const pipeIncoming: any = eventData.socket; let pipeOutgoing: any = null; - if( ( ! ( "remoteAddress" in eventData ) ) || + if( ( !( "remoteAddress" in eventData ) ) || eventData.remoteAddress == null || eventData.remoteAddress == undefined ) pipeIncoming.strSavedRemoteAddress = pipeIncoming.constructor.name; else @@ -815,7 +815,7 @@ export class OutOfWorkerRelay extends EventDispatcher { console.log( "Relay \"" + self.strRelayName + "\" external-client socket \"" + pipeIncoming.strSavedRemoteAddress + "\" message ", joMessage ); } - if( ! pipeOutgoing ) { + if( !pipeOutgoing ) { throw new Error( `Relay ${self.strRelayName} is not completely initialized ` + "and cannot transfer messages" ); } @@ -841,7 +841,7 @@ export class OutOfWorkerRelay extends EventDispatcher { console.log( "Relay \"" + self.strRelayName + "\" relay-client socket \"" + pipeIncoming.strSavedRemoteAddress + "\" message ", joMessage ); } - if( ! pipeOutgoing ) { + if( !pipeOutgoing ) { throw new Error( `Relay ${self.strRelayName} is not completely initialized ` + "and cannot transfer messages" ); } @@ -894,7 +894,7 @@ export class OutOfWorkerRelay extends EventDispatcher { pipeIncoming.on( "message", _onExternalPipeMessage ); // 2) configure outgoing relay client pipe pipeOutgoing = pipeIncoming.relayClientSocket = self.fnCreateClient(); - if( ! pipeOutgoing ) { + if( !pipeOutgoing ) { pipeIncoming.dispose(); throw new Error( `Relay ${self.strRelayName} failed to initialize ` + "relay-client socket to target server" ); @@ -1056,7 +1056,7 @@ export class OneToOneRelay extends EventDispatcher { pipeIncoming.strSavedRemoteAddress + "\" message ", joMessage ); } - if( ! pipeOutgoing ) { + if( !pipeOutgoing ) { throw new Error( `Relay ${self.strRelayName} is not completely initialized ` + "and cannot transfer messages" ); } @@ -1089,7 +1089,7 @@ export class OneToOneRelay extends EventDispatcher { pipeIncoming.strSavedRemoteAddress + "\" message ", joMessage ); } - if( ! pipeOutgoing ) { + if( !pipeOutgoing ) { throw new Error( `Relay ${self.strRelayName} is not completely initialized ` + "and cannot transfer messages" ); } @@ -1216,7 +1216,7 @@ export class DirectPipe extends BasicSocketPipe { this.dispose(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.isConnected = false; if( this.acceptor ) @@ -1332,7 +1332,7 @@ export class LocalSocketClientPipe extends DirectPipe { } this.acceptor = gMapLocalServers[this.strEndPoint]; this.clientPort = 0 + this.acceptor.nextClientPort; - ++ this.acceptor.nextClientPort; + ++this.acceptor.nextClientPort; this.url = "local_client_pipe://" + this.strEndPoint + ":" + this.clientPort; this.isConnected = true; const serverPipe = new LocalSocketServerPipe( this, this.acceptor, 0 + this.clientPort ); @@ -1375,7 +1375,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.acceptor = acceptor; this.clientNumber = 0 + acceptor.nextClientNumber; this.clientPort = 0 + this.clientNumber; - ++ acceptor.nextClientNumber; + ++acceptor.nextClientNumber; this.wsConnection = wsConnection; this.remoteAddress = "" + remoteAddress; this.url = "ws_server_pipe(" + this.clientNumber + ")://" + remoteAddress; @@ -1432,7 +1432,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.dispose(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.isConnected = false; if( this._removeWsEventListeners ) { @@ -1566,7 +1566,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { super.disconnect(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.wsDisconnect(); } @@ -1668,7 +1668,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } catch ( err ) { anyError = err; } - if( ! bPass ) { + if( !bPass ) { try { this.wsConnection.terminate(); bPass = true; @@ -1676,7 +1676,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { anyError = err; } } - if( ! bPass ) + if( !bPass ) console.warn( "Web socket client pipe termination error", anyError ); this.wsConnection = null; } @@ -1742,7 +1742,7 @@ export class RTCConnection extends EventDispatcher { arrAdditionalProps != undefined && arrAdditionalProps.length > 0 ) { - for( let i = 0; i < arrAdditionalProps.length; ++ i ) + for( let i = 0; i < arrAdditionalProps.length; ++i ) arrProps.push( arrAdditionalProps[i] ); } if( arrProps.length > 0 ) @@ -1795,7 +1795,7 @@ export class RTCConnection extends EventDispatcher { } send( data: any ) { const s = socketSentDataMarshall( data ); - if( ! this.dc ) { + if( !this.dc ) { this.onError( `Attempt to send message to uninitialized RTC data channel: ${s}` ); return; } @@ -1876,7 +1876,7 @@ export class RTCConnection extends EventDispatcher { // in a same way as oniceconnectionstatechange, // see https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/onicegatheringstatechange - if( ! this.pc ) { + if( !this.pc ) { console.log( "WARNING: Participant \"" + this.idRtcParticipant + "\" ICE gathering state changed event with no pc\", event is:", event @@ -2225,7 +2225,7 @@ export class RTCServerPeer extends RTCConnection { super(); this.rtcCreator = rtcCreator; this.idSomebodyOtherSide = null; - this.idOffer = this.rtcCreator.idOfferNext ++; + this.idOffer = this.rtcCreator.idOfferNext++; this.tsOfferCreated = null; if( settings.logging.net.signaling.offerRegister ) console.log( "Register offer", this.idOffer, "(RTCServerPeer constructor)" ); @@ -2316,7 +2316,7 @@ export class RTCServerPeer extends RTCConnection { } } publishCancel() { - if( ! this.isPublishing ) + if( !this.isPublishing ) return; this.isOfferPublishedOnSignalingServer = false; this.isPublishing = false; @@ -2327,7 +2327,7 @@ export class RTCServerPeer extends RTCConnection { this.signalingNegotiationCancel(); // mutual cancel } signalingNegotiationCancel() { - if( ! this.isSignalingNegotiation ) + if( !this.isSignalingNegotiation ) return; this.isSignalingNegotiation = false; if( this.timerSignalingNegotiation ) { @@ -2472,7 +2472,7 @@ export class RTCServerPeer extends RTCConnection { console.log( " <<< " + self.describe() + " got candidate", event ); if( settings.logging.net.signaling.candidate ) console.log( " <<< " + self.describe() + " got candidate", event ); - if( ! self.rtcCreator.signalingPipe ) + if( !self.rtcCreator.signalingPipe ) throw new Error( "no connection to signaling server" ); const joPublishOfferMessage = { id: utils.randomCallID(), @@ -2529,7 +2529,7 @@ export class RTCServerPeer extends RTCConnection { if( event.candidate == null || settings.net.rtc.fastPublishMode.serverPeer ) { - if( ! self.isOfferPublishedOnSignalingServer ) { + if( !self.isOfferPublishedOnSignalingServer ) { self.isOfferPublishedOnSignalingServer = true; self.publishOfferOnSignalingServer(); } @@ -2575,7 +2575,7 @@ export class RTCCreator extends RTCActor { console.log( "Unregister offer", idOfferWalk, "(one of all, RTCCreator dispose)" ); rtcPeer.dispose(); } - for( const [ /*idSomebodyOtherSideWalk*/, rtcPeerWalk ] of + for( const [ /* idSomebodyOtherSideWalk */, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.dispose(); @@ -2598,7 +2598,7 @@ export class RTCCreator extends RTCActor { idSomebodyOtherSide + "\" via offer ID " + idOffer.toString() ); } - if( ! ( idOffer in this.mapServerOffers ) ) { + if( !( idOffer in this.mapServerOffers ) ) { const strError = "not a registered pending offer(onOtherSideIdentified)"; if( settings.logging.net.signaling.error ) { console.warn( @@ -2657,7 +2657,7 @@ export class RTCCreator extends RTCActor { if( joMessage.error == null ) { const idSomebodyOtherSide = "" + joMessage.idSomebody_joiner; const idOffer = 0 + joMessage.idOffer; - if( ! ( idOffer in this.mapServerOffers ) ) { + if( !( idOffer in this.mapServerOffers ) ) { const strError = "not a registered pending offer(signalingPublishAnswer)"; if( settings.logging.net.signaling.error ) { console.warn( @@ -2751,7 +2751,7 @@ export class RTCCreator extends RTCActor { send( data: any ) { // implementation in RTCCreator does send to all try { const s = socketSentDataMarshall( data ); - for( const [ /*idSomebodyOtherSideWalk*/, rtcPeerWalk ] + for( const [ /* idSomebodyOtherSideWalk */, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; try { @@ -2766,12 +2766,12 @@ export class RTCCreator extends RTCActor { } onImpersonationComplete() { super.onImpersonationComplete(); - for( const [ /*idOfferWalk*/, rtcPeerWalk ] + for( const [ /* idOfferWalk */, rtcPeerWalk ] of Object.entries( this.mapServerOffers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.onImpersonationCompleteForCreator(); } - for( const [ /*idSomebodyOtherSideWalk*/, rtcPeerWalk ] + for( const [ /* idSomebodyOtherSideWalk */, rtcPeerWalk ] of Object.entries( this.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.onImpersonationCompleteForCreator(); @@ -2874,12 +2874,12 @@ export class RTCJoiner extends RTCActor { self.iceComplete = true; self.onIceComplete( event ); try { - if( ! self.signalingPipe ) { + if( !self.signalingPipe ) { if( self.dc ) return; // already connected, ignore (Firefox fix) throw new Error( "no connection to signaling server" ); } - if( ! self.isAnswerPublishedOnSignalingServer ) { + if( !self.isAnswerPublishedOnSignalingServer ) { self.publishSignalingAnswer( event ); self.isAnswerPublishedOnSignalingServer = true; } @@ -2911,7 +2911,7 @@ export class RTCJoiner extends RTCActor { event ); } - if( ! self.signalingPipe ) + if( !self.signalingPipe ) throw new Error( "no connection to signaling server" ); const joPublishAnswerMessage = { id: utils.randomCallID(), @@ -3103,7 +3103,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.acceptor = acceptor; self.clientNumber = 0 + acceptor.nextClientNumber; self.clientPort = 0 + ( self.clientNumber || 0 ); - ++ acceptor.nextClientNumber; + ++acceptor.nextClientNumber; self.rtcPeer = rtcPeer; self.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); @@ -3153,11 +3153,11 @@ export class WebRTCServerPipe extends BasicSocketPipe { this.rtcPeer = null; this.url = ""; this.strSignalingServerURL = ""; - //super.handleServerDisposed(); + // super.handleServerDisposed(); this.dispose(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.isConnected = false; if( this.acceptor ) @@ -3368,14 +3368,14 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } } removeAllPendingOffers() { - for( const [ /*idOfferWalk*/, rtcPeerWalk ] + for( const [ /* idOfferWalk */, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; const serverPipe = rtcPeer.serverPipe; serverPipe.dispose(); } this.rtcCreator.mapServerPeers = { }; - for( const [ /*idOfferWalk*/, rtcPeerWalk ] + for( const [ /* idOfferWalk */, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapPendingOffers ) ) { const rtcPeer: any = rtcPeerWalk; rtcPeer.dispose(); @@ -3387,7 +3387,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { return; for( let n = Object.keys( this.mapPendingOffers ).length; n < this.maxActiveOfferCount; - ++ n ) + ++n ) this.addPendingOffer(); } }; @@ -3457,7 +3457,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { super.disconnect(); } performDisconnect() { - if( ! this.isConnected ) + if( !this.isConnected ) return; this.rtcDisconnect(); } diff --git a/src/socketServer.ts b/src/socketServer.ts index 42fc773c..34157b89 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -51,7 +51,7 @@ export class SocketServer extends EventDispatcher { self.isLogSocketTrafficRaw = false; acceptor.on( "connection", function( eventData: any ) { const socket = eventData.socket; - if( ( ! ( "remoteAddress" in eventData ) ) || + if( ( !( "remoteAddress" in eventData ) ) || eventData.remoteAddress == null || eventData.remoteAddress == undefined ) socket.strSavedRemoteAddress = socket.constructor.name; diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 18bbeb1a..17fcf188 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -206,7 +206,7 @@ export const formatDateTime = function( return "null-date-time"; if( dt === undefined ) return "undefined-date-time"; - if( ! ( dt instanceof Date ) ) + if( !( dt instanceof Date ) ) return "not-a-date-time"; isDate = ( isDate == null || isDate == undefined ) ? true : ( !!isDate ); isTime = ( isTime == null || isTime == undefined ) ? true : ( !!isTime ); diff --git a/src/utils.ts b/src/utils.ts index bde1ffc0..1d283ed5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -161,7 +161,7 @@ export async function waitForClonedTokenToAppear( sc.joABI["token_manager_" + strTokenSuffixLC + "_address"], sc.joABI["token_manager_" + strTokenSuffixLC + "_abi"], sc.ethersProvider ); - for( let idxAttempt = 0; idxAttempt < cntAttempts; ++ idxAttempt ) { + for( let idxAttempt = 0; idxAttempt < cntAttempts; ++idxAttempt ) { log.information( "Discovering {} step {}...", strTokenSuffixUC, idxAttempt ); if( gMillisecondsToSleepStepWaitForClonedTokenToAppear > 0 ) await threadInfo.sleep( gMillisecondsToSleepStepWaitForClonedTokenToAppear ); @@ -405,7 +405,7 @@ export function checkKeysExistInABI( const cnt = arrKeys.length; for( let i = 0; i < cnt; ++i ) { const strKey = arrKeys[i]; - if( ! checkKeyExistInABI( strName, strFile, joABI, strKey, isExitOnError ) ) + if( !checkKeyExistInABI( strName, strFile, joABI, strKey, isExitOnError ) ) return false; } return true; From 03ae31dae0abe7d9f8b5badc14db7cd4a31922e0 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:02:03 +0000 Subject: [PATCH 26/53] linting improvement, camelcase: off rule removed --- src/.eslintrc.cjs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 7f7eba87..1944e37c 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -22,7 +22,6 @@ module.exports = { "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "double" ], "semi": [ "error", "always" ], - "camelcase": "off", "eqeqeq": "off", "comma-dangle": [ "error", "never" ], "comma-style": [ "error", "last" ], From 2d32235025f1ce3a650039b2aceb05c257186da5 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:07:54 +0000 Subject: [PATCH 27/53] linting improvement, removed un-needed inplace disable for linter --- src/loopWorker.ts | 1 - src/owaspUtils.ts | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 29b442ca..69c27787 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -197,7 +197,6 @@ class ObserverServer extends SocketServer { log.posNeg( joMessage.isFinal, "final", "partial" ) ); imaState.joSChainNetworkInfo = joMessage.joSChainNetworkInfo; }; - // eslint-disable-next-line dot-notation self.mapApiHandlers.skale_imaNotifyLoopWork = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { self.initLogMethods(); diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index bcb5bcba..020fcf7b 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -739,12 +739,12 @@ export function toBNbasic( x?: any, optionalRadix?: number ): any { export function toBN( arg: any ): any { if( typeof arg === "string" || typeof arg === "number" ) { - let multiplier = toBNbasic( 1 ); // eslint-disable-line + let multiplier = toBNbasic( 1 ); const formattedString = String( arg ).toLowerCase().trim() const isHexPrefixed = formattedString.substr( 0, 2 ) === "0x" || formattedString.substr( 0, 3 ) === "-0x" - let stringArg = stripHexPrefix(formattedString); // eslint-disable-line + let stringArg = stripHexPrefix( formattedString ); if( stringArg.substr( 0, 1 ) === "-" ) { stringArg = stripHexPrefix( stringArg.slice( 1 ) ) multiplier = toBNbasic( -1, 10 ); From c1e189ec983d9a27903321a4190af41584d87034 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:12:00 +0000 Subject: [PATCH 28/53] linting improvement, removed no-tabs: off and no-mixed-spaces-and-tabs: off rules --- src/.eslintrc.cjs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 1944e37c..0643c439 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -34,8 +34,6 @@ module.exports = { "nonblock-statement-body-position": [ "error", "below" ], "no-unneeded-ternary": "off", "no-cond-assign": [ "error", "always" ], - "no-tabs": "off", - "no-mixed-spaces-and-tabs": "off", "no-useless-return": "off", "no-new": "off", "no-fallthrough": "off", From 4409ddba5f79624fb8dd1ad40a6f5edfbb79ba8a Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:17:53 +0000 Subject: [PATCH 29/53] linting improvement, removed no-useless-return: off and no-new: off rules --- src/.eslintrc.cjs | 2 -- src/loop.ts | 3 +-- src/loopWorker.ts | 3 +-- src/socket.ts | 6 +++++- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 0643c439..51db9c92 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -34,8 +34,6 @@ module.exports = { "nonblock-statement-body-position": [ "error", "below" ], "no-unneeded-ternary": "off", "no-cond-assign": [ "error", "always" ], - "no-useless-return": "off", - "no-new": "off", "no-fallthrough": "off", "padded-blocks": "off", "lines-between-class-members": [ "error", "never" ], diff --git a/src/loop.ts b/src/loop.ts index 749994a5..e12c8a8e 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -598,8 +598,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { } ) ); gArrWorkers[idxWorker].on( "message", function( jo: any ) { - if( networkLayer.outOfWorkerAPIs.onMessage( gArrWorkers[idxWorker], jo ) ) - return; + networkLayer.outOfWorkerAPIs.onMessage( gArrWorkers[idxWorker], jo ); } ); const aClient = new networkLayer.OutOfWorkerSocketClientPipe( workerData.url, gArrWorkers[idxWorker] ); diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 69c27787..0ff98ab8 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -40,8 +40,7 @@ let imaState: state.TIMAState = state.get(); if( parentPort ) { parentPort.on( "message", jo => { - if( networkLayer.inWorkerAPIs.onMessage( jo ) ) - return; + networkLayer.inWorkerAPIs.onMessage( jo ); } ); } diff --git a/src/socket.ts b/src/socket.ts index 32142e6d..2caa18cc 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -350,6 +350,8 @@ export class BasicSocketPipe extends EventDispatcher { } reconnect() { } + checkItself() { + } }; export class NullSocketPipe extends BasicSocketPipe { @@ -587,7 +589,9 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { performAccept( jo: any ) { if( jo.workerUUID in this.mapClients ) return false; // TO-DO: send error answer and return true - new InWorkerServerPipe( this, "" + jo.workerUUID, this.fnSend ); + const p: InWorkerServerPipe = + new InWorkerServerPipe( this, "" + jo.workerUUID, this.fnSend ); + p.checkItself(); return true; } performDisconnect( jo: any ) { From 390aa0b4afd19ca92d27477922693d37493c1050 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:25:12 +0000 Subject: [PATCH 30/53] linting improvement, removed comma-spacing: off rule --- src/.eslintrc.cjs | 1 - src/bls.ts | 49 ++++++++------- src/cc.ts | 8 +-- src/cli.ts | 30 ++++----- src/discoveryTools.ts | 26 ++++---- src/imaCore.ts | 2 +- src/imaEthOperations.ts | 6 +- src/imaGasUsageOperations.ts | 4 +- src/imaOracleOperations.ts | 2 +- src/imaRegistrationOperations.ts | 2 +- src/imaReimbursementOperations.ts | 6 +- src/imaSgxExternalSigner.ts | 2 +- src/imaTokenOperations.ts | 70 ++++++++++----------- src/imaTransferErrorHandling.ts | 2 +- src/imaTx.ts | 18 +++--- src/log.ts | 20 +++--- src/loop.ts | 4 +- src/loopWorker.ts | 8 +-- src/main.ts | 10 +-- src/oracle.ts | 4 +- src/owaspUtils.ts | 14 ++--- src/pwa.ts | 2 +- src/rpcCall.ts | 22 +++---- src/socket.ts | 100 +++++++++++++++--------------- src/socketServer.ts | 4 +- src/socketUtils.ts | 18 +++--- src/threadInfo.ts | 2 +- src/utils.ts | 20 +++--- 28 files changed, 228 insertions(+), 228 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 51db9c92..f51954d0 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -25,7 +25,6 @@ module.exports = { "eqeqeq": "off", "comma-dangle": [ "error", "never" ], "comma-style": [ "error", "last" ], - "comma-spacing": "off", "space-in-parens": [ "error", "always" ], "space-before-blocks": [ "error", "always" ], "array-bracket-spacing": [ "error", "always" ], diff --git a/src/bls.ts b/src/bls.ts index bc5ed3d4..a45528c2 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -435,7 +435,7 @@ function performBlsGlue( const cnt = arrSignResults.length; for( let i = 0; i < cnt; ++i ) { const jo: any = arrSignResults[i]; - if( ( !jo ) || typeof jo != "object" ) + if( ( !jo ) || typeof jo !== "object" ) throw new Error( `Failed to save BLS part ${i} because it's not JSON object` ); const strPath = strActionDir + "/sign-result" + jo.index + ".json"; details.trace( "{p}Saving {} file containing {}", strLogPrefix, strPath, jo ); @@ -525,7 +525,7 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an const cnt = arrSignResults.length; for( let i = 0; i < cnt; ++i ) { const jo: any = arrSignResults[i]; - if( ( !jo ) || typeof jo != "object" ) + if( ( !jo ) || typeof jo !== "object" ) throw new Error( `Failed to save BLS part ${i} because it's not JSON object` ); const strPath = strActionDir + "/sign-result" + jo.index + ".json"; details.trace( "{p}Saving {} file...", strLogPrefix, strPath ); @@ -962,9 +962,9 @@ async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions ( optsSignOperation.imaState.bSignMessages && "joSChainNetworkInfo" in optsSignOperation.imaState && optsSignOperation.imaState.joSChainNetworkInfo && - typeof optsSignOperation.imaState.joSChainNetworkInfo == "object" && + typeof optsSignOperation.imaState.joSChainNetworkInfo === "object" && "network" in optsSignOperation.imaState.joSChainNetworkInfo && - typeof optsSignOperation.imaState.joSChainNetworkInfo.network == "object" + typeof optsSignOperation.imaState.joSChainNetworkInfo.network === "object" ) ? optsSignOperation.imaState.joSChainNetworkInfo.network : []; @@ -1267,8 +1267,9 @@ async function doSignProcessHandleCall( optsSignOperation.strLogPrefix, log.generateTimestampString( null, true ), "skale_imaVerifyAndSign", i, strNodeURL, optsSignOperation.fromChainName, optsSignOperation.targetChainName, joParams, joOut, optsSignOperation.sequenceId ); - if( ( !joOut ) || typeof joOut != "object" || ( !( "result" in joOut ) ) || ( !joOut.result ) || - typeof joOut.result != "object" || ( "error" in joOut && joOut.error ) ) { + if( ( !joOut ) || typeof joOut !== "object" || ( !( "result" in joOut ) ) || + ( !joOut.result ) || typeof joOut.result !== "object" || + ( "error" in joOut && joOut.error ) ) { ++optsSignOperation.joGatheringTracker.nCountErrors; optsSignOperation.details.critical( "{p}S-Chain node {} reported wallet error: {err}, sequence ID is ", @@ -1599,9 +1600,9 @@ async function doSignU256OneImplHandleCallResult( ++optsSignU256.joGatheringTracker.nCountReceived; optsSignU256.details.trace( "{p}Did invoked {} for to sign value {}, answer is: {}", optsSignU256.strLogPrefix, "skale_imaBSU256", optsSignU256.u256.toString(), joOut ); - if( ( !joOut ) || typeof joOut != "object" || ( !( "result" in joOut ) ) || + if( ( !joOut ) || typeof joOut !== "object" || ( !( "result" in joOut ) ) || ( "error" in joOut && joOut.error ) || - ( !joOut.result ) || typeof joOut.result != "object" || + ( !joOut.result ) || typeof joOut.result !== "object" || ( !( "signature" in joOut.result ) ) || joOut.result.signature != "object" ) { ++optsSignU256.joGatheringTracker.nCountErrors; @@ -1975,10 +1976,10 @@ async function doSignReadyHashHandleCallResult( details.trace( "{p}Call to ", "SGX done, answer is: {}", strLogPrefix, joOut ); let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && - typeof joOut.result == "object" ) + typeof joOut.result === "object" ) joSignResult = joOut.result; if( joOut.signResult != null && joOut.signResult != undefined && - typeof joOut.signResult == "object" ) + typeof joOut.signResult === "object" ) joSignResult = joOut.signResult; if( !joSignResult ) { const strError = "No signature arrived"; @@ -1987,7 +1988,7 @@ async function doSignReadyHashHandleCallResult( throw new Error( strError ); } if( "errorMessage" in joSignResult && - typeof joSignResult.errorMessage == "string" && + typeof joSignResult.errorMessage === "string" && joSignResult.errorMessage.length > 0 ) { const strError = `BLS-sign finished with error: ${joSignResult.errorMessage};`; @@ -2029,9 +2030,9 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a throw new Error( "BLS keys name is unknown, cannot sign U256" ); } let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; - if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey == "string" && + if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey === "string" && joAccount.strPathSslKey.length > 0 && "strPathSslCert" in joAccount && - typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 + typeof joAccount.strPathSslCert === "string" && joAccount.strPathSslCert.length > 0 ) { rpcCallOpts = { cert: fs.readFileSync( joAccount.strPathSslCert, "utf8" ), @@ -2069,7 +2070,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a await joCall.disconnect(); } const isSuccess = ( - joSignResult && typeof joSignResult == "object" && ( !joSignResult.error ) ) + joSignResult && typeof joSignResult === "object" && ( !joSignResult.error ) ) ? true : false; if( isExposeOutput || ( !isSuccess ) ) details.exposeDetailsTo( log.globalStream(), "BLS-raw-signer", isSuccess ); @@ -2186,10 +2187,10 @@ async function handleBlsSignMessageHashResult( optsHandleVerifyAndSign.strDirection, joOut ); let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && - typeof joOut.result == "object" ) + typeof joOut.result === "object" ) joSignResult = joOut.result; if( joOut.signResult != null && joOut.signResult != undefined && - typeof joOut.signResult == "object" ) + typeof joOut.signResult === "object" ) joSignResult = joOut.signResult; if( "qa" in optsHandleVerifyAndSign.joCallData ) optsHandleVerifyAndSign.joRetVal.qa = optsHandleVerifyAndSign.joCallData.qa; @@ -2203,7 +2204,7 @@ async function handleBlsSignMessageHashResult( throw new Error( strError ); } if( "errorMessage" in joSignResult && - typeof joSignResult.errorMessage == "string" && + typeof joSignResult.errorMessage === "string" && joSignResult.errorMessage.length > 0 ) { optsHandleVerifyAndSign.isSuccess = false; @@ -2268,9 +2269,9 @@ export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndS throw new Error( "BLS keys name is unknown, cannot sign IMA message(s)" ); } let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; - if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey == "string" && + if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey === "string" && joAccount.strPathSslKey.length > 0 && "strPathSslCert" in joAccount && - typeof joAccount.strPathSslCert == "string" && joAccount.strPathSslCert.length > 0 + typeof joAccount.strPathSslCert === "string" && joAccount.strPathSslCert.length > 0 ) { rpcCallOpts = { cert: fs.readFileSync( joAccount.strPathSslCert, "utf8" ), @@ -2361,10 +2362,10 @@ async function handleBlsSignMessageHash256Result( optsBSU256.strLogPrefix, joOut ); let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && - typeof joOut.result == "object" ) + typeof joOut.result === "object" ) joSignResult = joOut.result; if( joOut.signResult != null && joOut.signResult != undefined && - typeof joOut.signResult == "object" ) + typeof joOut.signResult === "object" ) joSignResult = joOut.signResult; if( !joSignResult ) { const strError = "No signature arrived"; @@ -2375,7 +2376,7 @@ async function handleBlsSignMessageHash256Result( throw new Error( strError ); } if( "errorMessage" in joSignResult && - typeof joSignResult.errorMessage == "string" && + typeof joSignResult.errorMessage === "string" && joSignResult.errorMessage.length > 0 ) { optsBSU256.isSuccess = false; const strError = "BLS-sign finished with " + @@ -2416,10 +2417,10 @@ export async function handleSkaleImaBSU256( joCallData: TBSU256CallData ) { throw new Error( "No account to perform blsSignMessageHash for U256" ) let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; if( "strPathSslKey" in optsBSU256.joAccount && - typeof optsBSU256.joAccount.strPathSslKey == "string" && + typeof optsBSU256.joAccount.strPathSslKey === "string" && optsBSU256.joAccount.strPathSslKey.length > 0 && "strPathSslCert" in optsBSU256.joAccount && - typeof optsBSU256.joAccount.strPathSslCert == "string" && + typeof optsBSU256.joAccount.strPathSslCert === "string" && optsBSU256.joAccount.strPathSslCert.length > 0 ) { rpcCallOpts = { diff --git a/src/cc.ts b/src/cc.ts index 235070c9..c34ead85 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -37,7 +37,7 @@ export function enable( b?: boolean ): void { } export function isStringAlreadyColorized( s?: any ): boolean { - if( s && typeof s == "string" && s.length > 0 && s[0] == "\x1b" ) + if( s && typeof s === "string" && s.length > 0 && s[0] == "\x1b" ) return true; return false; } @@ -197,7 +197,7 @@ export function rainbowPart( s: string, i: number ) { } export function rainbow( s?: any ): string { - if( ( !gFlagIsEnabled ) || ( !s ) || ( typeof s != "string" ) || s.length == 0 ) + if( ( !gFlagIsEnabled ) || ( !s ) || ( typeof s !== "string" ) || s.length == 0 ) return s ? s.toString() : JSON.stringify( s ); let res = ""; const cnt = s.length; @@ -978,11 +978,11 @@ export function stack( err?: any ): string { return ""; if( err && "stack" in err ) { const st = err.stack - if( st && typeof st == "string" ) + if( st && typeof st === "string" ) err = st; } try { - const arr = ( typeof err == "string" ) ? err.split( "\n" ) : err; + const arr = ( typeof err === "string" ) ? err.split( "\n" ) : err; const cnt = arr.length; let i; for( i = 0; i < cnt; ++i ) { diff --git a/src/cli.ts b/src/cli.ts index d158374b..0eb473c7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -113,7 +113,7 @@ export function ensureHaveCredentials( isExitIfEmpty: boolean, isPrintValue: boolean ) { strFriendlyChainName = strFriendlyChainName || ""; - if( !( typeof joAccount == "object" ) ) { + if( !( typeof joAccount === "object" ) ) { log.error( "ARGUMENTS VALIDATION WARNING: bad account specified for {} chain", strFriendlyChainName ); if( isExitIfEmpty ) @@ -121,7 +121,7 @@ export function ensureHaveCredentials( } let cntAccountVariantsSpecified = 0; if( "strTransactionManagerURL" in joAccount && - typeof joAccount.strTransactionManagerURL == "string" && + typeof joAccount.strTransactionManagerURL === "string" && joAccount.strTransactionManagerURL.length > 0 ) { ++cntAccountVariantsSpecified; @@ -131,7 +131,7 @@ export function ensureHaveCredentials( ); } if( "strSgxURL" in joAccount && - typeof joAccount.strSgxURL == "string" && + typeof joAccount.strSgxURL === "string" && joAccount.strSgxURL.length > 0 ) { ++cntAccountVariantsSpecified; @@ -140,7 +140,7 @@ export function ensureHaveCredentials( joAccount.strSgxURL, isExitIfEmpty, isPrintValue ); if( "strPathSslKey" in joAccount && - typeof joAccount.strPathSslKey == "string" && + typeof joAccount.strPathSslKey === "string" && joAccount.strPathSslKey.length > 0 ) { ensureHaveValue( @@ -149,7 +149,7 @@ export function ensureHaveCredentials( ); } if( "strPathSslCert" in joAccount && - typeof joAccount.strPathSslCert == "string" && + typeof joAccount.strPathSslCert === "string" && joAccount.strPathSslCert.length > 0 ) { ensureHaveValue( @@ -159,7 +159,7 @@ export function ensureHaveCredentials( } } if( "strSgxKeyName" in joAccount && - typeof joAccount.strSgxKeyName == "string" && + typeof joAccount.strSgxKeyName === "string" && joAccount.strSgxKeyName.length > 0 ) { ++cntAccountVariantsSpecified; @@ -169,7 +169,7 @@ export function ensureHaveCredentials( ); } if( "privateKey" in joAccount && - typeof joAccount.privateKey == "string" && + typeof joAccount.privateKey === "string" && joAccount.privateKey.length > 0 ) { ++cntAccountVariantsSpecified; @@ -179,7 +179,7 @@ export function ensureHaveCredentials( ); } if( "address_" in joAccount && - typeof joAccount.address_ == "string" && + typeof joAccount.address_ === "string" && joAccount.address_.length > 0 ) { ++cntAccountVariantsSpecified; @@ -1363,7 +1363,7 @@ function commonInitPrintSysInfo() { function commonInitCheckAbiPaths() { const imaState: state.TIMAState = state.get(); if( imaState.strPathAbiJsonSkaleManager && - ( typeof imaState.strPathAbiJsonSkaleManager == "string" ) && + ( typeof imaState.strPathAbiJsonSkaleManager === "string" ) && imaState.strPathAbiJsonSkaleManager.length > 0 ) { imaState.joAbiSkaleManager = @@ -1376,7 +1376,7 @@ function commonInitCheckAbiPaths() { } if( imaState.chainProperties.mn.strPathAbiJson && - typeof imaState.chainProperties.mn.strPathAbiJson == "string" && + typeof imaState.chainProperties.mn.strPathAbiJson === "string" && imaState.chainProperties.mn.strPathAbiJson.length > 0 ) { imaState.chainProperties.mn.joAbiIMA = imaUtils.jsonFileLoad( imaState.chainProperties.mn.strPathAbiJson, null ); @@ -1388,7 +1388,7 @@ function commonInitCheckAbiPaths() { } if( imaState.chainProperties.sc.strPathAbiJson && - typeof imaState.chainProperties.sc.strPathAbiJson == "string" && + typeof imaState.chainProperties.sc.strPathAbiJson === "string" && imaState.chainProperties.sc.strPathAbiJson.length > 0 ) { imaState.chainProperties.sc.joAbiIMA = @@ -1401,7 +1401,7 @@ function commonInitCheckAbiPaths() { } if( imaState.chainProperties.tc.strPathAbiJson && - typeof imaState.chainProperties.tc.strPathAbiJson == "string" && + typeof imaState.chainProperties.tc.strPathAbiJson === "string" && imaState.chainProperties.tc.strPathAbiJson.length > 0 ) { imaState.chainProperties.tc.joAbiIMA = @@ -2654,7 +2654,7 @@ export function commonInit() { export function imaInitEthersProviders() { const imaState: state.TIMAState = state.get(); if( imaState.chainProperties.mn.strURL && - typeof imaState.chainProperties.mn.strURL == "string" && + typeof imaState.chainProperties.mn.strURL === "string" && imaState.chainProperties.mn.strURL.length > 0 ) { const u = imaState.chainProperties.mn.strURL; @@ -2666,7 +2666,7 @@ export function imaInitEthersProviders() { } if( imaState.chainProperties.sc.strURL && - typeof imaState.chainProperties.sc.strURL == "string" && + typeof imaState.chainProperties.sc.strURL === "string" && imaState.chainProperties.sc.strURL.length > 0 ) { const u = imaState.chainProperties.sc.strURL; @@ -2678,7 +2678,7 @@ export function imaInitEthersProviders() { } if( imaState.chainProperties.tc.strURL && - typeof imaState.chainProperties.tc.strURL == "string" && + typeof imaState.chainProperties.tc.strURL === "string" && imaState.chainProperties.tc.strURL.length > 0 ) { const u = imaState.chainProperties.tc.strURL; diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 19210248..eee4a799 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -134,7 +134,7 @@ export function formatBalanceInfo( bi: any, strAddress: string ): string { let s = ""; s += log.fmtInformation( "{p}", bi.assetName ); if( "assetAddress" in bi && - typeof bi.assetAddress == "string" && bi.assetAddress.length > 0 ) + typeof bi.assetAddress === "string" && bi.assetAddress.length > 0 ) s += log.fmtDebug( "/{}", bi.assetAddress ); if( "idToken" in bi ) s += log.fmtDebug( " token ID {}", bi.idToken ); @@ -169,34 +169,34 @@ function getSChainNodesCount( joSChainNetworkInfo: TSChainNetworkInfo ): number export function isSChainNodeFullyDiscovered( joNode: TSChainNode ): boolean { if( !joNode ) return false; - if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo == "object" && - "t" in joNode.imaInfo && typeof joNode.imaInfo.t == "number" && + if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo === "object" && + "t" in joNode.imaInfo && typeof joNode.imaInfo.t === "number" && joNode.imaInfo.t > 0 && - "n" in joNode.imaInfo && typeof joNode.imaInfo.n == "number" && + "n" in joNode.imaInfo && typeof joNode.imaInfo.n === "number" && joNode.imaInfo.n > 0 && "BLSPublicKey0" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey0 == "string" && + typeof joNode.imaInfo.BLSPublicKey0 === "string" && joNode.imaInfo.BLSPublicKey0.length > 0 && "BLSPublicKey1" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey1 == "string" && + typeof joNode.imaInfo.BLSPublicKey1 === "string" && joNode.imaInfo.BLSPublicKey1.length > 0 && "BLSPublicKey2" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey2 == "string" && + typeof joNode.imaInfo.BLSPublicKey2 === "string" && joNode.imaInfo.BLSPublicKey2.length > 0 && "BLSPublicKey3" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey3 == "string" && + typeof joNode.imaInfo.BLSPublicKey3 === "string" && joNode.imaInfo.BLSPublicKey3.length > 0 && "commonBLSPublicKey0" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey0 == "string" && + typeof joNode.imaInfo.commonBLSPublicKey0 === "string" && joNode.imaInfo.commonBLSPublicKey0.length > 0 && "commonBLSPublicKey1" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey1 == "string" && + typeof joNode.imaInfo.commonBLSPublicKey1 === "string" && joNode.imaInfo.commonBLSPublicKey1.length > 0 && "commonBLSPublicKey2" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey2 == "string" && + typeof joNode.imaInfo.commonBLSPublicKey2 === "string" && joNode.imaInfo.commonBLSPublicKey2.length > 0 && "commonBLSPublicKey3" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey3 == "string" && + typeof joNode.imaInfo.commonBLSPublicKey3 === "string" && joNode.imaInfo.commonBLSPublicKey3.length > 0 ) return true; @@ -253,7 +253,7 @@ export async function waitUntilSChainStarted() { log.critical( "S-Chain network discovery attempt failed: {err}", err ); isError = true; } ); - if( ( !isError ) && joSChainNetworkInfo && typeof joSChainNetworkInfo == "object" ) { + if( ( !isError ) && joSChainNetworkInfo && typeof joSChainNetworkInfo === "object" ) { imaState.joSChainNetworkInfo = joSChainNetworkInfo; bSuccess = true; } diff --git a/src/imaCore.ts b/src/imaCore.ts index 6e7ff518..9f354e26 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -629,7 +629,7 @@ async function callbackAllMessagesSign( optsTransfer.joAccountDst, optsTransfer.strActionName, gasPrice, estimatedGasPostIncomingMessages, weiHowMuchPostIncomingMessages, opts ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { optsTransfer.jarrReceipts.push( { description: "doTransfer/postIncomingMessages()", "optsTransfer.detailsString": diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index b75a5462..cbb89913 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -112,7 +112,7 @@ export async function doEthPaymentFromMainNet( "DepositBox", joDepositBox, "deposit", arrArguments, joAccountSrc, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "doEthPaymentFromMainNet", receipt: joReceipt @@ -209,7 +209,7 @@ export async function doEthPaymentFromSChain( "TokenManagerETH", joTokenManagerETH, "exitToMain", arrArguments, joAccountSrc, strActionName, gasPrice, estimatedGas, 0, opts ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "doEthPaymentFromSChain", receipt: joReceipt @@ -293,7 +293,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( "getMyEth", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "receiveEthPaymentFromSchainOnMainNet", receipt: joReceipt diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index c3ff53be..7f1e17d7 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -27,7 +27,7 @@ import * as log from "./log.js"; import * as owaspUtils from "./owaspUtils.js"; export function composeGasUsageReportFromArray( strName: string, jarrReceipts: any[] ): any { - if( !( strName && typeof strName == "string" && jarrReceipts ) ) + if( !( strName && typeof strName === "string" && jarrReceipts ) ) return { sumGasUsed: 0, strReport: "N/A" }; let i; let sumGasUsed = owaspUtils.toBN( "0" ); let s = "\n" + log.fmtInformation( "Gas usage report for " ) + @@ -49,7 +49,7 @@ export function printGasUsageReportFromArray( strName: string, jarrReceipts: any[], details?: any ) { details = details || log; const jo: any = composeGasUsageReportFromArray( strName, jarrReceipts ); - if( jo.strReport && typeof jo.strReport == "string" && jo.strReport.length > 0 && + if( jo.strReport && typeof jo.strReport === "string" && jo.strReport.length > 0 && jo.sumGasUsed?.gt( owaspUtils.toBN( "0" ) ) ) log.information( jo.strReport ); } diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index e93b0aaa..b1e60a05 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -230,7 +230,7 @@ async function handleOracleSigned( "setGasPrice", arrArgumentsSetGasPrice, optsGasPriceSetup.joAccountSC, optsGasPriceSetup.strActionName, gasPrice, estimatedGasSetGasPrice, weiHowMuch, opts ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { optsGasPriceSetup.jarrReceipts.push( { description: "doOracleGasPriceSetup/setGasPrice", receipt: joReceipt diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 034c7911..f67d16ad 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -195,7 +195,7 @@ export async function registerSChainInDepositBoxes( // step 1 "Linker", joLinker, "connectSchain", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "registerSChainInDepositBoxes", receipt: joReceipt diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index 736f77a2..25c7293d 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -194,7 +194,7 @@ export async function reimbursementWalletRecharge( details, ethersProviderMainNet, "CommunityPool", joCommunityPool, "rechargeUserWallet", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, nReimbursementRecharge, null ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "reimbursementWalletRecharge", receipt: joReceipt @@ -261,7 +261,7 @@ export async function reimbursementWalletWithdraw( "CommunityPool", joCommunityPool, "withdrawFunds", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "reimbursementWalletWithdraw", receipt: joReceipt @@ -326,7 +326,7 @@ export async function reimbursementSetRange( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, joAccountSC, strActionName, gasPrice, estimatedGas, weiHowMuch, opts ); - if( joReceipt && typeof joReceipt == "object" ) { + if( joReceipt && typeof joReceipt === "object" ) { jarrReceipts.push( { description: "reimbursementSetRange", receipt: joReceipt diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index ef5dbd1a..909ad745 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -20,7 +20,7 @@ function postConvertBN( jo: any, name: any ) { return; if( !( name in jo ) ) return; - if( typeof jo[name] != "object" ) + if( typeof jo[name] !== "object" ) return; jo[name] = owaspUtils.toHexStringSafe( jo[name] ); } diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index aa64b79d..36a13237 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -182,7 +182,7 @@ export async function doErc721PaymentFromMainNet( details, ethersProviderMainNet, "ERC721", contractERC721, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc721PaymentFromMainNet/approve", receipt: joReceiptApprove @@ -214,7 +214,7 @@ export async function doErc721PaymentFromMainNet( "DepositBoxERC721", joDepositBoxERC721, "depositERC721", arrArgumentsDepositERC721, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC721, null ); - if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { + if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { jarrReceipts.push( { description: "doErc721PaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -320,7 +320,7 @@ export async function doErc20PaymentFromMainNet( details, ethersProviderMainNet, "ERC20", contractERC20, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc20PaymentFromMainNet/approve", receipt: joReceiptApprove @@ -351,7 +351,7 @@ export async function doErc20PaymentFromMainNet( "DepositBoxERC20", joDepositBoxERC20, "depositERC20", arrArgumentsDepositERC20, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC20, null ); - if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { + if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { jarrReceipts.push( { description: "doErc20PaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -463,7 +463,7 @@ export async function doErc1155PaymentFromMainNet( "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc1155PaymentFromMainNet/approve", receipt: joReceiptApprove @@ -499,7 +499,7 @@ export async function doErc1155PaymentFromMainNet( "depositERC1155", arrArgumentsDepositERC1155, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC1155, null ); - if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { + if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { jarrReceipts.push( { description: "doErc1155PaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -596,7 +596,7 @@ export async function doErc1155BatchPaymentFromMainNet( details, ethersProviderMainNet, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromMainNet/approve", receipt: joReceiptApprove @@ -628,7 +628,7 @@ export async function doErc1155BatchPaymentFromMainNet( "depositERC1155Batch", arrArgumentsDepositERC1155Batch, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC1155Batch, null ); - if( joReceiptDeposit && typeof joReceiptDeposit == "object" ) { + if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -731,7 +731,7 @@ export async function doErc20PaymentFromSChain( details, ethersProviderSChain, "ERC20", contractERC20, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc20PaymentFromSChain/approve", receipt: joReceiptApprove @@ -772,7 +772,7 @@ export async function doErc20PaymentFromSChain( "exitToMainERC20", arrArgumentsExitToMainERC20, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC20, weiHowMuchExitToMainERC20, opts ); - if( joReceiptExitToMainERC20 && typeof joReceiptExitToMainERC20 == "object" ) { + if( joReceiptExitToMainERC20 && typeof joReceiptExitToMainERC20 === "object" ) { jarrReceipts.push( { description: "doErc20PaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC20 @@ -877,7 +877,7 @@ export async function doErc721PaymentFromSChain( details, ethersProviderSChain, "ERC721", contractERC721, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc721PaymentFromSChain/transfer-from", receipt: joReceiptApprove @@ -918,7 +918,7 @@ export async function doErc721PaymentFromSChain( "exitToMainERC721", arrArgumentsExitToMainERC721, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC721, weiHowMuchExitToMainERC721, opts ); - if( joReceiptExitToMainERC721 && typeof joReceiptExitToMainERC721 == "object" ) { + if( joReceiptExitToMainERC721 && typeof joReceiptExitToMainERC721 === "object" ) { jarrReceipts.push( { description: "doErc721PaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC721 @@ -1025,7 +1025,7 @@ export async function doErc1155PaymentFromSChain( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc1155PaymentFromSChain/transfer-from", receipt: joReceiptApprove @@ -1066,7 +1066,7 @@ export async function doErc1155PaymentFromSChain( "exitToMainERC1155", arrArgumentsExitToMainERC1155, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC1155, weiHowMuchExitToMainERC1155, opts ); - if( joReceiptExitToMainERC1155 && typeof joReceiptExitToMainERC1155 == "object" ) { + if( joReceiptExitToMainERC1155 && typeof joReceiptExitToMainERC1155 === "object" ) { jarrReceipts.push( { description: "doErc1155PaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC1155 @@ -1168,7 +1168,7 @@ export async function doErc1155BatchPaymentFromSChain( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromSChain/transfer-from", receipt: joReceiptApprove @@ -1211,7 +1211,7 @@ export async function doErc1155BatchPaymentFromSChain( joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC1155Batch, weiHowMuchExitToMainERC1155Batch, opts ); if( joReceiptExitToMainERC1155Batch && - typeof joReceiptExitToMainERC1155Batch == "object" + typeof joReceiptExitToMainERC1155Batch === "object" ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromSChain/exit-to-main", @@ -1341,7 +1341,7 @@ export async function doErc20PaymentS2S( details, ethersProviderSrc, "ERC20", contractERC20, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: `doErc20PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, receipt: joReceiptApprove @@ -1372,7 +1372,7 @@ export async function doErc20PaymentS2S( "transferToSchainERC20", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC20, null ); - if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { + if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { jarrReceipts.push( { description: "doErc20PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1481,7 +1481,7 @@ export async function doErc721PaymentS2S( details, ethersProviderSrc, "ERC721", contractERC721, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: `doErc721PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, @@ -1515,7 +1515,7 @@ export async function doErc721PaymentS2S( "transferToSchainERC721", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC721, null ); - if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { + if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { jarrReceipts.push( { description: "doErc721PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1627,7 +1627,7 @@ export async function doErc1155PaymentS2S( "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: `doErc1155PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, @@ -1660,7 +1660,7 @@ export async function doErc1155PaymentS2S( "transferToSchainERC1155", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC1155, null ); - if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { + if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { jarrReceipts.push( { description: "doErc1155PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1773,7 +1773,7 @@ export async function doErc1155BatchPaymentS2S( details, ethersProviderSrc, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove == "object" ) { + if( joReceiptApprove && typeof joReceiptApprove === "object" ) { jarrReceipts.push( { description: `doErc1155BatchPaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, @@ -1807,7 +1807,7 @@ export async function doErc1155BatchPaymentS2S( "transferToSchainERC1155Batch", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC1155, null ); - if( joReceiptTransfer && typeof joReceiptTransfer == "object" ) { + if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { jarrReceipts.push( { description: "doErc1155PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1849,8 +1849,8 @@ export async function mintErc20( try { details.debug( "{p}Mint ERC20 token amount {}", strLogPrefix, nAmount ); if( !( ethersProvider && joAccount && strAddressMintTo && - typeof strAddressMintTo == "string" && strAddressMintTo.length > 0 && - strTokenContractAddress && typeof strTokenContractAddress == "string" && + typeof strAddressMintTo === "string" && strAddressMintTo.length > 0 && + strTokenContractAddress && typeof strTokenContractAddress === "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); @@ -1919,8 +1919,8 @@ export async function mintErc721( try { details.debug( "{p}Mint ERC721 token ID {}", strLogPrefix, idToken ); if( !( ethersProvider && joAccount && strAddressMintTo && - typeof strAddressMintTo == "string" && strAddressMintTo.length > 0 && - strTokenContractAddress && typeof strTokenContractAddress == "string" && + typeof strAddressMintTo === "string" && strAddressMintTo.length > 0 && + strTokenContractAddress && typeof strTokenContractAddress === "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); @@ -1991,8 +1991,8 @@ export async function mintErc1155( details.debug( "{p}Mint ERC1155 token ID {} token amount {}", strLogPrefix, idToken, nAmount ); if( !( ethersProvider && joAccount && strAddressMintTo && - typeof strAddressMintTo == "string" && strAddressMintTo.length > 0 && - strTokenContractAddress && typeof strTokenContractAddress == "string" && + typeof strAddressMintTo === "string" && strAddressMintTo.length > 0 && + strTokenContractAddress && typeof strTokenContractAddress === "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); @@ -2063,8 +2063,8 @@ export async function burnErc20( try { details.debug( "{p}Burn ERC20 token amount {}", strLogPrefix, nAmount ); if( !( ethersProvider && joAccount && strAddressBurnFrom && - typeof strAddressBurnFrom == "string" && strAddressBurnFrom.length > 0 && - strTokenContractAddress && typeof strTokenContractAddress == "string" && + typeof strAddressBurnFrom === "string" && strAddressBurnFrom.length > 0 && + strTokenContractAddress && typeof strTokenContractAddress === "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); @@ -2132,7 +2132,7 @@ export async function burnErc721( try { details.debug( "{p}Burn ERC721 token ID {}", strLogPrefix, idToken ); if( !( ethersProvider && joAccount && - strTokenContractAddress && typeof strTokenContractAddress == "string" && + strTokenContractAddress && typeof strTokenContractAddress === "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); @@ -2202,8 +2202,8 @@ export async function burnErc1155( details.debug( "{p}Burn ERC1155 token ID {} token amount {}", strLogPrefix, idToken, nAmount ); if( !( ethersProvider && joAccount && strAddressBurnFrom && - typeof strAddressBurnFrom == "string" && strAddressBurnFrom.length > 0 && - strTokenContractAddress && typeof strTokenContractAddress == "string" && + typeof strAddressBurnFrom === "string" && strAddressBurnFrom.length > 0 && + strTokenContractAddress && typeof strTokenContractAddress === "string" && strTokenContractAddress.length > 0 && joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 5b749f00..d00ef22f 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -69,7 +69,7 @@ export function saveTransferSuccessAll(): void { } export function getLastTransferErrors( isIncludeTextLog: boolean ): any[] { - if( typeof isIncludeTextLog == "undefined" ) + if( typeof isIncludeTextLog === "undefined" ) isIncludeTextLog = true; const jarr = JSON.parse( JSON.stringify( gArrLastTransferErrors ) ); if( !isIncludeTextLog ) { diff --git a/src/imaTx.ts b/src/imaTx.ts index 915483a9..ecd5ff72 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -196,8 +196,8 @@ async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ) { const arrNamesConvertToHex = [ "gas", "gasLimit", "optsPayedCall.gasPrice", "value" ]; for( let idxName = 0; idxName < arrNamesConvertToHex.length; ++idxName ) { const strName = arrNamesConvertToHex[idxName]; - if( strName in txAdjusted && typeof txAdjusted[strName] == "object" && - typeof txAdjusted[strName].toHexString == "function" ) + if( strName in txAdjusted && typeof txAdjusted[strName] === "object" && + typeof txAdjusted[strName].toHexString === "function" ) txAdjusted[strName] = owaspUtils.toHexStringSafe( txAdjusted[strName] ); } if( "gasLimit" in txAdjusted ) @@ -233,7 +233,7 @@ async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ) { async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ) { const tx = optsPayedCall.unsignedTx; let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); - if( typeof chainId == "string" && chainId ) + if( typeof chainId === "string" && chainId ) chainId = owaspUtils.parseIntOrHex( chainId ); optsPayedCall.details.trace( "{p}Chain ID is: {}", optsPayedCall.strLogPrefix, chainId ); @@ -275,7 +275,7 @@ function postConvertBN( jo: any, name: any ) { return; if( !( name in jo ) ) return; - if( typeof jo[name] == "object" ) + if( typeof jo[name] === "object" ) return; jo[name] = owaspUtils.toBN( jo[name] ); } @@ -285,7 +285,7 @@ async function payedCallDirect( optsPayedCall: TRunTimePayedCallOptions ) { owaspUtils.ensureStartsWith0x( optsPayedCall.joAccount.privateKey ), optsPayedCall.ethersProvider ); let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); - if( typeof chainId == "string" && chainId ) + if( typeof chainId === "string" && chainId ) chainId = owaspUtils.parseIntOrHex( chainId ); optsPayedCall.details.trace( "{p}Chain ID is: {}", optsPayedCall.strLogPrefix, chainId ); if( ( !( chainId in optsPayedCall.unsignedTx ) ) || @@ -487,23 +487,23 @@ export function getAccountConnectivityInfo( joAccount: state.TAccount ) { isAutoSend: false }; if( "strTransactionManagerURL" in joAccount && - typeof joAccount.strTransactionManagerURL == "string" && + typeof joAccount.strTransactionManagerURL === "string" && joAccount.strTransactionManagerURL.length > 0 ) { joACI.isBad = false; joACI.strType = "tm"; joACI.isAutoSend = true; } else if( "strSgxURL" in joAccount && - typeof joAccount.strSgxURL == "string" && + typeof joAccount.strSgxURL === "string" && joAccount.strSgxURL.length > 0 && "strSgxKeyName" in joAccount && - typeof joAccount.strSgxKeyName == "string" && + typeof joAccount.strSgxKeyName === "string" && joAccount.strSgxKeyName.length > 0 ) { joACI.isBad = false; joACI.strType = "sgx"; } else if( "privateKey" in joAccount && - typeof joAccount.privateKey == "string" && + typeof joAccount.privateKey === "string" && joAccount.privateKey.length > 0 ) { joACI.isBad = false; diff --git a/src/log.ts b/src/log.ts index eb102eff..2e62eda8 100644 --- a/src/log.ts +++ b/src/log.ts @@ -121,7 +121,7 @@ export function n2s( n: any, sz: number ): string { export function generateTimestampString( ts?: any, isColorized?: boolean ): string { isColorized = - ( typeof isColorized == "undefined" ) + ( typeof isColorized === "undefined" ) ? true : ( !!isColorized ); ts = ( ts instanceof Date ) ? ts : new Date(); const ccDate = function( x?: any ): string { return isColorized ? cc.date( x ) : x; }; @@ -675,16 +675,16 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): s if( !isError( jo ) ) { if( "error" in jo ) { jo = jo.error; - if( typeof jo == "string" ) + if( typeof jo === "string" ) return jo; - if( typeof jo != "object" ) + if( typeof jo !== "object" ) return strDefaultErrorText + "(" + jo.toString() + ")"; } - if( typeof jo == "string" && jo ) + if( typeof jo === "string" && jo ) return strDefaultErrorText + "(" + jo.toString() + ")"; return strDefaultErrorText; } - if( typeof jo.message == "string" && jo.message.length > 0 ) + if( typeof jo.message === "string" && jo.message.length > 0 ) return jo.message; strDefaultErrorText += "(" + jo.toString() + ")"; } catch ( err ) { @@ -693,7 +693,7 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): s } function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[] | null { - if( !( strFormat && typeof strFormat == "string" ) ) + if( !( strFormat && typeof strFormat === "string" ) ) return null; if( !cntArgsMax ) cntArgsMax = 0; @@ -752,7 +752,7 @@ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { return arg; if( !isValueMode ) return fnDefaultOneArgumentFormatter( arg, null ); - if( fmt && typeof "fmt" == "string" ) { + if( fmt && typeof "fmt" === "string" ) { if( fmt == "raw" ) return arg; if( fmt == "p" ) @@ -816,7 +816,7 @@ export function outputStringToAllStreams( s: string ): void { for( let i = 0; i < gArrStreams.length; ++i ) { try { const objEntry = gArrStreams[i]; - if( objEntry && "write" in objEntry && typeof objEntry.write == "function" ) + if( objEntry && "write" in objEntry && typeof objEntry.write === "function" ) objEntry.write( s ); } catch ( err ) { } @@ -1042,7 +1042,7 @@ export function verboseReversed(): Map < string, number > { return gMapReversedVerbose; } export function verboseLevelAsTextForLog( vl: any ): string { - if( typeof vl == "undefined" ) + if( typeof vl === "undefined" ) vl = verboseGet(); if( vl in gMapVerbose ) { const tl = gMapVerbose.get( vl ) || 0; @@ -1053,7 +1053,7 @@ export function verboseLevelAsTextForLog( vl: any ): string { export function verboseName2Number( s: string ): number { const mapReversedVerbose: Map < string, number > = verboseReversed(); const n = mapReversedVerbose.get( s ) - if( typeof n == "undefined" ) + if( typeof n === "undefined" ) return 9; return n; } diff --git a/src/loop.ts b/src/loop.ts index e12c8a8e..7857dd02 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -134,7 +134,7 @@ export function checkTimeFraming( log.fmtInformation( "{}", joRuntimeOpts.cntChainsKnownForS2S ), "\n" ); if( "joExtraSignOpts" in joRuntimeOpts && - typeof joRuntimeOpts.joExtraSignOpts == "object" ) { + typeof joRuntimeOpts.joExtraSignOpts === "object" ) { strFrameInfo += log.fmtDebug( " S-Chain source", ".............", log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts.chainNameSrc ), "/", log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts.chainIdSrc ), @@ -754,7 +754,7 @@ export async function runParallelLoops( opts: TParallelLoopRunOptions ) { } export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) { - if( !( joMessage && typeof joMessage == "object" && + if( !( joMessage && typeof joMessage === "object" && "method" in joMessage && joMessage.method == "skale_imaNotifyLoopWork" ) ) return; diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 0ff98ab8..0d2985db 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -48,7 +48,7 @@ function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { const jo: any = networkLayer.socketReceivedDataReverseMarshall( data ); const joSend: any = { workerMessageType: - ( type && typeof type == "string" && type.length > 0 ) + ( type && typeof type === "string" && type.length > 0 ) ? type : "inWorkerMessage", workerEndPoint: endpoint, @@ -131,7 +131,7 @@ class ObserverServer extends SocketServer { self.opts.imaState.chainProperties.sc.joAccount.address = function() { return owaspUtils.fnAddressImpl_( this ); }; if( self.opts.imaState.chainProperties.mn.strURL && - typeof self.opts.imaState.chainProperties.mn.strURL == "string" && + typeof self.opts.imaState.chainProperties.mn.strURL === "string" && self.opts.imaState.chainProperties.mn.strURL.length > 0 ) { const u = self.opts.imaState.chainProperties.mn.strURL; @@ -144,7 +144,7 @@ class ObserverServer extends SocketServer { } if( self.opts.imaState.chainProperties.sc.strURL && - typeof self.opts.imaState.chainProperties.sc.strURL == "string" && + typeof self.opts.imaState.chainProperties.sc.strURL === "string" && self.opts.imaState.chainProperties.sc.strURL.length > 0 ) { const u = self.opts.imaState.chainProperties.sc.strURL; @@ -223,7 +223,7 @@ class ObserverServer extends SocketServer { } initLogMethods() { const self: any = this; - if( "fatal" in self && self.fatal && typeof self.fatal == "function" ) + if( "fatal" in self && self.fatal && typeof self.fatal === "function" ) return; self.fatal = function( ...args: any[] ) { if( log.verboseGet() >= log.verboseName2Number( "fatal" ) ) { diff --git a/src/main.ts b/src/main.ts index c8393ac2..4400472e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -155,7 +155,7 @@ function initMonitoringServer(): void { gServerMonitoringWS = new ws.WebSocketServer( { port: 0 + imaState.nMonitoringPort } ); gServerMonitoringWS.on( "connection", function( wsPeer: any, req: any ) { let ip = req.socket.remoteAddress; - if( "headers" in req && req.headers && typeof req.headers == "object" && + if( "headers" in req && req.headers && typeof req.headers === "object" && "x-forwarded-for" in req.headers && req.headers["x-forwarded-for"] ) ip = req.headers["x-forwarded-for"]; // better under NGINX if( ( !ip ) && "_socket" in req && req._socket && "remoteAddress" in req._socket ) @@ -331,7 +331,7 @@ function initJsonRpcServer(): void { joAnswer.error = `Unknown method name ${joMessage.method} was specified`; break } // switch( joMessage.method ) - if( ( !joAnswer ) || typeof joAnswer != "object" ) { + if( ( !joAnswer ) || typeof joAnswer !== "object" ) { joAnswer = {}; joAnswer.error = "internal error, null data returned"; } @@ -411,15 +411,15 @@ async function main() { const strTmpAddressFromEnvSChainTarget = owaspUtils.toEthPrivateKey( process.env.ACCOUNT_FOR_SCHAIN_TARGET ); if( strTmpAddressFromEnvMainNet && - typeof strTmpAddressFromEnvMainNet == "string" && + typeof strTmpAddressFromEnvMainNet === "string" && strTmpAddressFromEnvMainNet.length > 0 ) imaState.chainProperties.mn.joAccount.address_ = "" + strTmpAddressFromEnvMainNet; if( strTmpAddressFromEnvSChain && - typeof strTmpAddressFromEnvSChain == "string" && + typeof strTmpAddressFromEnvSChain === "string" && strTmpAddressFromEnvSChain.length > 0 ) imaState.chainProperties.sc.joAccount.address_ = "" + strTmpAddressFromEnvSChain; if( strTmpAddressFromEnvSChainTarget && - typeof strTmpAddressFromEnvSChainTarget == "string" && + typeof strTmpAddressFromEnvSChainTarget === "string" && strTmpAddressFromEnvSChainTarget.length > 0 ) imaState.chainProperties.tc.joAccount.address_ = "" + strTmpAddressFromEnvSChainTarget; parseCommandLine(); diff --git a/src/oracle.ts b/src/oracle.ts index b3a74a4e..1233a132 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -86,7 +86,7 @@ async function handleOracleCheckResultResult( ) { if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_checkResult) result is: {}", joOut ); - if( !( "result" in joOut && typeof joOut.result == "string" && + if( !( "result" in joOut && typeof joOut.result === "string" && joOut.result.length > 0 ) ) { if( isVerboseTraceDetails ) details.error( "Bad unexpected result in oracle_checkResult" ); @@ -118,7 +118,7 @@ async function handleOracleSubmitRequestResult( cntAttempts = 1; if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_submitRequest) result is: {}", joOut ); - if( !( "result" in joOut && typeof joOut.result == "string" && + if( !( "result" in joOut && typeof joOut.result === "string" && joOut.result.length > 0 ) ) { await joCall.disconnect(); details.error( "Bad unexpected result(oracle_submitRequest), malformed " + diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 020fcf7b..18b26c4e 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -80,7 +80,7 @@ export function rxIsFloat( val: any ): boolean { } export function parseIntOrHex( s: any ): number { - if( typeof s != "string" ) + if( typeof s !== "string" ) return parseInt( s ); s = s.trim(); if( s.length > 2 && s[0] == "0" && ( s[1] == "x" || s[1] == "X" ) ) @@ -703,8 +703,8 @@ export function ethersProviderToUrl( ): string { let strURL: string | null = null; if( ethersProvider && - "connection" in ethersProvider && typeof ethersProvider.connection == "object" && - "url" in ethersProvider.connection && typeof ethersProvider.connection.url == "string" + "connection" in ethersProvider && typeof ethersProvider.connection === "object" && + "url" in ethersProvider.connection && typeof ethersProvider.connection.url === "string" ) strURL = "" + ethersProvider.connection.url; return strURL || "N/A-URL"; @@ -727,7 +727,7 @@ export function stripHexPrefix( s: any ): string { export function toBNbasic( x?: any, optionalRadix?: number ): any { try { - if( optionalRadix && typeof optionalRadix == "number" && optionalRadix == 16 ) + if( optionalRadix && typeof optionalRadix === "number" && optionalRadix == 16 ) x = ensureStartsWith0x( x ); const bn = ethersMod.ethers.BigNumber.from( x ); return bn; @@ -776,11 +776,11 @@ export function isNumeric( s?: any ): boolean { export function toHexStringSafe( val?: any ): string { if( !val ) return "0x0"; - if( "toHexString" in val && typeof val.toHexString == "function" ) + if( "toHexString" in val && typeof val.toHexString === "function" ) return val.toHexString(); - if( typeof val == "number" || typeof val == "bigint" ) + if( typeof val === "number" || typeof val === "bigint" ) return ensureStartsWith0x( val.toString( 16 ) ); - if( "toString" in val && typeof val.toString == "function" ) + if( "toString" in val && typeof val.toString === "function" ) return val.toString(); return "" + val; } diff --git a/src/pwa.ts b/src/pwa.ts index 68f45e31..b58e55e4 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -118,7 +118,7 @@ export async function checkOnLoopStart( const walkNodeIndex = arrWalkNodeIndices[i]; const joNode = jarrNodes[walkNodeIndex]; const joProps: any = getNodeProgressAndTimestamp( joNode, strLoopWorkType, nIndexS2S ); - if( joProps && typeof joProps == "object" && + if( joProps && typeof joProps === "object" && "isInProgress" in joProps && joProps.isInProgress && joProps.ts != 0 && nUtcUnixTimeStamp >= joProps.ts ) { diff --git a/src/rpcCall.ts b/src/rpcCall.ts index e0f06bb8..b84c37fd 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -179,7 +179,7 @@ export async function doConnect( async function( nStep: number ) { // work done handler }, async function( nStep: number ) { // step handler - if( strWsError && typeof strWsError == "string" && strWsError.length > 0 ) { + if( strWsError && typeof strWsError === "string" && strWsError.length > 0 ) { log.error( "{url} web socket wait error detected: {err}", joCall.url, strWsError ); return false; @@ -197,7 +197,7 @@ export async function doConnect( } return true; // continue waiting } ); - if( strWsError && typeof strWsError == "string" && strWsError.length > 0 ) { + if( strWsError && typeof strWsError === "string" && strWsError.length > 0 ) { const err = new Error( strWsError ); if( fn ) await fn( joCall, err ); @@ -296,8 +296,8 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu } const strBody = JSON.stringify( joIn ); let errCall: string | null = null; let joOut: any | null = null; - if( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert == "string" && - joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key == "string" + if( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert === "string" && + joCall.joRpcOptions.key && typeof joCall.joRpcOptions.key === "string" ) { const u = new URL( joCall.url ); const options = { @@ -309,13 +309,13 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu "Content-Type": "application/json" }, ca: ( joCall.joRpcOptions?.ca && - typeof joCall.joRpcOptions.ca == "string" ) + typeof joCall.joRpcOptions.ca === "string" ) ? joCall.joRpcOptions.ca : null, cert: ( joCall.joRpcOptions?.cert && - typeof joCall.joRpcOptions.cert == "string" ) + typeof joCall.joRpcOptions.cert === "string" ) ? joCall.joRpcOptions.cert : null, key: ( joCall.joRpcOptions?.key && - typeof joCall.joRpcOptions.key == "string" ) + typeof joCall.joRpcOptions.key === "string" ) ? joCall.joRpcOptions.key : null }; let accumulatedBody = ""; @@ -378,13 +378,13 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu agent: false, httpsAgent: false, ca: ( joCall.joRpcOptions?.ca && - typeof joCall.joRpcOptions.ca == "string" ) + typeof joCall.joRpcOptions.ca === "string" ) ? joCall.joRpcOptions.ca : null, cert: ( joCall.joRpcOptions?.cert && - typeof joCall.joRpcOptions.cert == "string" ) + typeof joCall.joRpcOptions.cert === "string" ) ? joCall.joRpcOptions.cert : null, key: ( joCall.joRpcOptions?.key && - typeof joCall.joRpcOptions.key == "string" ) + typeof joCall.joRpcOptions.key === "string" ) ? joCall.joRpcOptions.key : null }; const response = @@ -412,7 +412,7 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) { if( !validateURL( strURL ) ) throw new Error( `JSON RPC CALLER cannot create a call object invalid URL: ${strURL}` ); - if( !( strURL && typeof strURL == "string" && strURL.length > 0 ) ) { + if( !( strURL && typeof strURL === "string" && strURL.length > 0 ) ) { throw new Error( "rpcCallCreate() was invoked with " + `bad parameters: ${JSON.stringify( arguments )}` ); } diff --git a/src/socket.ts b/src/socket.ts index 2caa18cc..4077cc47 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -45,9 +45,9 @@ export const gMapLocalServers: any = { }; // used both for local and in-worker s export const socketSentDataMarshall = function( data?: any ): any { const s = data - ? ( ( typeof data == "string" ) + ? ( ( typeof data === "string" ) ? data - : ( ( typeof data == "object" ) ? JSON.stringify( data ) : data.toString() ) + : ( ( typeof data === "object" ) ? JSON.stringify( data ) : data.toString() ) ) : ""; return s; @@ -55,9 +55,9 @@ export const socketSentDataMarshall = function( data?: any ): any { export const socketReceivedDataReverseMarshall = function( data?: any ): object { try { const jo: any = data - ? ( ( typeof data == "object" ) + ? ( ( typeof data === "object" ) ? data - : ( ( typeof data == "string" ) ? JSON.parse( data ) : data ) + : ( ( typeof data === "string" ) ? JSON.parse( data ) : data ) ) : { }; return jo; @@ -74,7 +74,7 @@ export const updateSocketDataStatsForMessage = function( joMessage: any, joStats let strMethod = "_N/A_"; if( "method" in joMessage && joMessage.method && - typeof joMessage.method == "string" + typeof joMessage.method === "string" ) strMethod = "" + joMessage.method; if( strMethod in joStats ) @@ -86,7 +86,7 @@ export const generateSocketDataStatsJSON = function( jo: any ) { const joStats: any = {}; if( "arrPackedMessages" in jo && jo.arrPackedMessages && - typeof jo.arrPackedMessages == "object" + typeof jo.arrPackedMessages === "object" ) { for( const joMessage of jo.arrPackedMessages ) updateSocketDataStatsForMessage( joMessage, joStats ); @@ -228,7 +228,7 @@ export class BasicSocketPipe extends EventDispatcher { for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { const entry: any = entryWalk; try { - if( entry && "dispose" in entry && typeof entry.dispose == "function" ) + if( entry && "dispose" in entry && typeof entry.dispose === "function" ) entry.dispose(); } catch ( err ) { } @@ -315,7 +315,7 @@ export class BasicSocketPipe extends EventDispatcher { const jo: any = socketReceivedDataReverseMarshall( data ); if( "arrPackedMessages" in jo && jo.arrPackedMessages && - typeof jo.arrPackedMessages == "object" + typeof jo.arrPackedMessages === "object" ) { const cnt = jo.arrPackedMessages.length; if( settings.logging.net.socket.receiveCount ) @@ -393,14 +393,14 @@ export const outOfWorkerAPIs: any = { onMessage: function( worker: any, data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); if( !( "workerMessageType" in jo ) || - typeof jo.workerMessageType != "string" || + typeof jo.workerMessageType !== "string" || jo.workerMessageType.length == 0 ) return false; // not a socket message if( !( "workerEndPoint" in jo ) || - typeof jo.workerEndPoint != "string" || + typeof jo.workerEndPoint !== "string" || jo.workerEndPoint.length == 0 ) return false; // TO-DO: send error answer and return true - if( !( "workerUUID" in jo ) || typeof jo.workerUUID != "string" || + if( !( "workerUUID" in jo ) || typeof jo.workerUUID !== "string" || jo.workerUUID.length == 0 ) return false; // TO-DO: send error answer and return true switch ( jo.workerMessageType ) { @@ -430,7 +430,7 @@ export const outOfWorkerAPIs: any = { const jo: any = socketReceivedDataReverseMarshall( data ); const joSend: any = { workerMessageType: - ( type && typeof type == "string" && type.length > 0 ) + ( type && typeof type === "string" && type.length > 0 ) ? type : "inWorkerMessage", workerEndPoint: endpoint, workerUUID, @@ -444,15 +444,15 @@ export const inWorkerAPIs: any = { onMessage: function( data: any ) { const jo: any = socketReceivedDataReverseMarshall( data ); if( !( "workerMessageType" in jo ) || - typeof jo.workerMessageType != "string" || + typeof jo.workerMessageType !== "string" || jo.workerMessageType.length == 0 ) return false; // not a socket message if( !( "workerEndPoint" in jo ) || - typeof jo.workerEndPoint != "string" || + typeof jo.workerEndPoint !== "string" || jo.workerEndPoint.length == 0 ) return false; // TO-DO: send error answer and return true if( !( "workerUUID" in jo ) || - typeof jo.workerUUID != "string" || + typeof jo.workerUUID !== "string" || jo.workerUUID.length == 0 ) return false; // TO-DO: send error answer and return true if( !( jo.workerEndPoint in gMapLocalServers ) ) @@ -473,7 +473,7 @@ export const inWorkerAPIs: any = { const jo: any = socketReceivedDataReverseMarshall( data ); const joSend: any = { workerMessageType: - ( type && typeof type == "string" && type.length > 0 ) + ( type && typeof type === "string" && type.length > 0 ) ? type : "inWorkerMessage", workerEndPoint: endpoint, workerUUID, @@ -532,7 +532,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.url = ""; } implSend( data: any ) { - if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend != "function" ) { + if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend !== "function" ) { const s = "Cannot send messages to disconnected in-worker server pipe"; this.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); @@ -553,7 +553,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { super(); this.socketType = "InWorker"; this.strEndPoint = - ( strEndPoint && typeof strEndPoint == "string" && strEndPoint.length > 0 ) + ( strEndPoint && typeof strEndPoint === "string" && strEndPoint.length > 0 ) ? strEndPoint : "default_local_endpoint"; if( this.strEndPoint in gMapLocalServers ) { const s = @@ -578,7 +578,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { this.isDisposing = true; this.disposeNotifyClients(); if( this.strEndPoint && - typeof this.strEndPoint == "string" && + typeof this.strEndPoint === "string" && this.strEndPoint.length > 0 ) { if( this.strEndPoint in gMapLocalServers ) @@ -623,7 +623,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.clientPort = utils.UUIDv4(); this.strEndPoint = ( strEndPoint && - typeof strEndPoint == "string" && + typeof strEndPoint === "string" && strEndPoint.length > 0 ) ? strEndPoint @@ -664,7 +664,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.worker ) || ( !this.fnSend ) || - typeof this.fnSend != "function" + typeof this.fnSend !== "function" ) { const s = "Cannot send messages to disconnected in-worker client pipe"; this.dispatchEvent( @@ -697,7 +697,7 @@ export class OutOfWorkerRelay extends EventDispatcher { super(); const self = this; self.strRelayName = ( strRelayName != null && strRelayName != undefined && - typeof strRelayName == "string" && strRelayName.length > 0 ) + typeof strRelayName === "string" && strRelayName.length > 0 ) ? ( "" + strRelayName ) : "unnamed"; self.isAutoFlushIncoming = ( isAutoFlushIncoming == null || isAutoFlushIncoming == undefined ) @@ -709,7 +709,7 @@ export class OutOfWorkerRelay extends EventDispatcher { throw new Error( `OutOfWorkerRelay ${self.strRelayName} needs acceptor ` + "for normal functionality" ); } - if( typeof fnCreateClient != "function" ) { + if( typeof fnCreateClient !== "function" ) { throw new Error( `OutOfWorkerRelay ${self.strRelayName} needs callback ` + "to create connections to target server" ); } @@ -937,7 +937,7 @@ export class OneToOneRelay extends EventDispatcher { const self = this; self.strRelayName = ( strRelayName != null && strRelayName != undefined && - typeof strRelayName == "string" && strRelayName.length > 0 ) + typeof strRelayName === "string" && strRelayName.length > 0 ) ? ( "" + strRelayName ) : "unnamed"; self.isAutoFlushIncoming = ( isAutoFlushIncoming == null || isAutoFlushIncoming == undefined ) @@ -1277,7 +1277,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { this.socketType = "Local"; this.nextClientPort = 1; this.strEndPoint = - ( strEndPoint && typeof strEndPoint == "string" && strEndPoint.length > 0 ) + ( strEndPoint && typeof strEndPoint === "string" && strEndPoint.length > 0 ) ? strEndPoint : "default_local_endpoint"; if( this.strEndPoint in gMapLocalServers ) { const s = @@ -1302,7 +1302,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { this.isDisposing = true; this.disposeNotifyClients(); if( this.strEndPoint && - typeof this.strEndPoint == "string" && + typeof this.strEndPoint === "string" && this.strEndPoint.length > 0 ) { if( this.strEndPoint in gMapLocalServers ) @@ -1322,7 +1322,7 @@ export class LocalSocketClientPipe extends DirectPipe { this.acceptor = null; this.counterPipe = null; this.strEndPoint = - ( strEndPoint && typeof strEndPoint == "string" && strEndPoint.length > 0 ) + ( strEndPoint && typeof strEndPoint === "string" && strEndPoint.length > 0 ) ? strEndPoint : "default_local_endpoint"; if( !( this.strEndPoint in gMapLocalServers ) ) { const s = @@ -1486,8 +1486,8 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { super(); this.socketType = "WS"; this.wsServer = null; - if( key != null && key != undefined && typeof key == "string" && key.length > 0 && - cert != null && cert != undefined && typeof cert == "string" && cert.length > 0 + if( key != null && key != undefined && typeof key === "string" && key.length > 0 && + cert != null && cert != undefined && typeof cert === "string" && cert.length > 0 ) { const server = httpsModule.createServer( { key: "" + key, @@ -1539,7 +1539,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this._onWsError = null; this._onWsMessage = null; this.urlWS = - "" + ( ( url != null && url != undefined && typeof url == "string" ) ? url : "" ); + "" + ( ( url != null && url != undefined && typeof url === "string" ) ? url : "" ); this.url = "ws_client_pipe-" + this.urlWS; this.reconnect(); } @@ -1706,7 +1706,7 @@ export class RTCConnection extends EventDispatcher { this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); this.idRtcParticipant = "" + ( ( idRtcParticipant != null && idRtcParticipant != undefined && - typeof idRtcParticipant == "string" && idRtcParticipant.length > 0 ) + typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) ? idRtcParticipant : utils.UUIDv4() ); this.wasIdentified = false; this.iceComplete = false; @@ -1728,10 +1728,10 @@ export class RTCConnection extends EventDispatcher { describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { let strInstanceDescription = ( strInstanceType == null || strInstanceType == undefined || - ( typeof strInstanceType != "string" ) || strInstanceType.length == 0 ) + ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) ? "participant" : ( "" + strInstanceType ); - if( typeof this.idRtcParticipant == "string" && this.idRtcParticipant.length > 0 ) + if( typeof this.idRtcParticipant === "string" && this.idRtcParticipant.length > 0 ) strInstanceDescription += " " + this.idRtcParticipant; const arrProps: any[] = []; if( this.isDisposed ) @@ -2003,12 +2003,12 @@ export class RTCActor extends RTCConnection { }; if( signalingOptions ) { if( "idCategory" in signalingOptions && - typeof signalingOptions.idCategory == "string" && + typeof signalingOptions.idCategory === "string" && signalingOptions.idCategory.length > 0 ) this.signalingOptions.idCategory = "" + signalingOptions.idCategory; if( "idSpace" in signalingOptions && - typeof signalingOptions.idSpace == "string" && + typeof signalingOptions.idSpace === "string" && signalingOptions.idSpace.length > 0 ) this.signalingOptions.idSpace = "" + signalingOptions.idSpace; @@ -2028,7 +2028,7 @@ export class RTCActor extends RTCConnection { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || - ( typeof strInstanceType != "string" ) || + ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) ? ( this.isCreator ? "creator" : ( this.isJoiner ? "joiner" : "actor" ) ) : strInstanceType; @@ -2247,14 +2247,14 @@ export class RTCServerPeer extends RTCConnection { ? timeToSignalingNegotiationMilliseconds : settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.peerConfiguration = - ( peerConfiguration && typeof peerConfiguration == "object" ) + ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = - ( peerAdditionalOptions && typeof peerAdditionalOptions == "object" ) + ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; this.localMediaStream = ( localMediaStream != null && localMediaStream != undefined && - typeof localMediaStream == "object" ) + typeof localMediaStream === "object" ) ? localMediaStream : null; this.isOfferPublishedOnSignalingServer = false; this.initPeer(); @@ -2288,7 +2288,7 @@ export class RTCServerPeer extends RTCConnection { describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || - ( typeof strInstanceType != "string" ) || strInstanceType.length == 0 ) + ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) ? "server-peer" : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); @@ -2590,7 +2590,7 @@ export class RTCCreator extends RTCActor { describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || - ( typeof strInstanceType != "string" ) || strInstanceType.length == 0 ) + ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) ? "rtc-creator" : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); @@ -2802,10 +2802,10 @@ export class RTCJoiner extends RTCActor { this.isAnswerPublishedOnSignalingServer = false; this.signalingPipeOpen(); this.peerConfiguration = - ( peerConfiguration && typeof peerConfiguration == "object" ) + ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = - ( peerAdditionalOptions && typeof peerAdditionalOptions == "object" ) + ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; } dispose() { @@ -2822,7 +2822,7 @@ export class RTCJoiner extends RTCActor { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || - ( typeof strInstanceType != "string" ) || + ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) ? "rtc-joiner" : strInstanceType; @@ -3220,15 +3220,15 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); this.idRtcParticipant = "" + ( ( idRtcParticipant != null && idRtcParticipant != undefined && - typeof idRtcParticipant == "string" && idRtcParticipant.length > 0 ) + typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) ? idRtcParticipant : utils.UUIDv4() ); this.offerOptions = offerOptions ? offerOptions : null; this.signalingOptions = signalingOptions ? signalingOptions : null; this.peerConfiguration = - ( peerConfiguration && typeof peerConfiguration == "object" ) + ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = - ( peerAdditionalOptions && typeof peerAdditionalOptions == "object" ) + ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; this.socketType = "WebRTC"; this.maxActiveOfferCount = @@ -3413,15 +3413,15 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); this.idRtcParticipant = "" + ( ( idRtcParticipant != null && idRtcParticipant != undefined && - typeof idRtcParticipant == "string" && idRtcParticipant.length > 0 ) + typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) ? idRtcParticipant : utils.UUIDv4() ); this.offerOptions = offerOptions ? offerOptions : null; this.signalingOptions = signalingOptions ? signalingOptions : null; this.peerConfiguration = - ( peerConfiguration && typeof peerConfiguration == "object" ) + ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = - ( peerAdditionalOptions && typeof peerAdditionalOptions == "object" ) + ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; this.socketType = "WebRTC"; this.socketSubtype = "client"; diff --git a/src/socketServer.ts b/src/socketServer.ts index 34157b89..445ae6e8 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -38,7 +38,7 @@ export class SocketServer extends EventDispatcher { isLogSocketTrafficRaw?: boolean; constructor ( acceptor: any ) { super(); - if( acceptor == null || acceptor == undefined || typeof acceptor != "object" ) + if( acceptor == null || acceptor == undefined || typeof acceptor !== "object" ) throw new Error( "Cannot create server on bad acceptor" ); const self = this; self.log = console.log; @@ -125,7 +125,7 @@ export class SocketServer extends EventDispatcher { } if( joAnswer != null && joAnswer != undefined ) { - if( typeof joAnswer.error == "string" && joAnswer.error.length > 0 ) { + if( typeof joAnswer.error === "string" && joAnswer.error.length > 0 ) { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Socket {url} will send {sunny} {err}", socket.strSavedRemoteAddress, "error-answer", joAnswer ) ); diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 17fcf188..67043add 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -90,7 +90,7 @@ export const replaceAll = function( str: string, find: string, replace: string ) }; export const simpleEscapeString = function( s?: any ): string { - if( s == null || s == undefined || typeof s != "string" ) + if( s == null || s == undefined || typeof s !== "string" ) return s; s = replaceAll( s, "&", "&" ); s = replaceAll( s, "<", "<" ); @@ -128,12 +128,12 @@ export const prepareAnswerJSON = function( joMessage: any ): any { id: "" + ( ( joMessage != null && joMessage != undefined && - typeof joMessage.id == "string" ) + typeof joMessage.id === "string" ) ? joMessage.id : randomCallID() ), method: "" + ( ( joMessage != null && joMessage != undefined && - typeof joMessage.method == "string" ) + typeof joMessage.method === "string" ) ? joMessage.method : "" ), error: null }; @@ -145,7 +145,7 @@ export const makeValidSignalingServerURL = function( strSignalingServerURL?: str return "" + ( ( strSignalingServerURL != null && strSignalingServerURL != undefined && - typeof strSignalingServerURL == "string" && + typeof strSignalingServerURL === "string" && strSignalingServerURL.length > 0 ) ? "" + strSignalingServerURL : "" + proto + "://" + settings.net.hostname + ":" + settings.net.ports.signaling @@ -172,7 +172,7 @@ export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ): st export const parseDateTime = function( ts?: any ): Date | null { if( ts === null || ts === undefined ) return ts; - if( typeof ts != "string" ) + if( typeof ts !== "string" ) return null; // example: // 0----|----1----|----2----|---- @@ -214,7 +214,7 @@ export const formatDateTime = function( return ""; let s = ""; if( isDate ) { - sepDate = ( sepDate == null || sepDate == undefined || ( typeof sepDate != "string" ) ) + sepDate = ( sepDate == null || sepDate == undefined || ( typeof sepDate !== "string" ) ) ? "/" : sepDate; const strDate = "" + zeroPaddingLeft( dt.getFullYear(), 4 ) + @@ -225,13 +225,13 @@ export const formatDateTime = function( s += strDate; } if( isTime ) { - sepTime = ( sepTime == null || sepTime == undefined || ( typeof sepTime != "string" ) ) + sepTime = ( sepTime == null || sepTime == undefined || ( typeof sepTime !== "string" ) ) ? ":" : sepTime; if( isDate ) { sepBetween = ( sepBetween == null || sepBetween == undefined || - ( typeof sepBetween != "string" ) ) + ( typeof sepBetween !== "string" ) ) ? "-" : sepBetween; s += sepBetween; } @@ -247,7 +247,7 @@ export const formatDateTime = function( sepMilliseconds = ( sepMilliseconds == null || sepMilliseconds == undefined || - ( typeof sepMilliseconds != "string" ) ) + ( typeof sepMilliseconds !== "string" ) ) ? "." : sepMilliseconds; strTime += sepMilliseconds + zeroPaddingRight( dt.getMilliseconds(), 3 ); } diff --git a/src/threadInfo.ts b/src/threadInfo.ts index e69d7310..7b6eed8a 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -45,7 +45,7 @@ export function isMainThread(): boolean { } export function threadDescription( isColorized?: boolean ): string { - if( typeof isColorized == "undefined" ) + if( typeof isColorized === "undefined" ) isColorized = true; const tid: number = getCurrentThreadID(); const st: string = isMainThread() ? "main" : "worker"; diff --git a/src/utils.ts b/src/utils.ts index 1d283ed5..da612cfd 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -190,8 +190,8 @@ export async function waitForClonedTokenAppearErc20( sc: any, tokenERC20SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string ) { - if( "abi" in tokenERC20SC && typeof tokenERC20SC.abi == "object" && - "address" in tokenERC20SC && typeof tokenERC20SC.address == "string" + if( "abi" in tokenERC20SC && typeof tokenERC20SC.abi === "object" && + "address" in tokenERC20SC && typeof tokenERC20SC.address === "string" ) { log.warning( "Skipping automatic ERC20 instantiation discovery, already done before" ); return; @@ -207,8 +207,8 @@ export async function waitForClonedTokenAppearErc721( sc: any, tokenERC721SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string ) { - if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && - "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" + if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi === "object" && + "address" in tokenERC721SC && typeof tokenERC721SC.address === "string" ) { log.warning( "Skipping automatic ERC721instantiation discovery, already done before" ); return; @@ -225,8 +225,8 @@ export async function waitForClonedTokenAppearErc721WithMetadata( sc: any, tokenERC721SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string ) { - if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi == "object" && - "address" in tokenERC721SC && typeof tokenERC721SC.address == "string" + if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi === "object" && + "address" in tokenERC721SC && typeof tokenERC721SC.address === "string" ) { log.warning( "Skipping automatic ERC721_with_metadata instantiation discovery, " + "already done before" ); @@ -244,8 +244,8 @@ export async function waitForClonedTokenAppearErc1155( sc: any, tokenERC1155SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string ) { - if( "abi" in tokenERC1155SC && typeof tokenERC1155SC.abi == "object" && - "address" in tokenERC1155SC && typeof tokenERC1155SC.address == "string" + if( "abi" in tokenERC1155SC && typeof tokenERC1155SC.abi === "object" && + "address" in tokenERC1155SC && typeof tokenERC1155SC.address === "string" ) { log.warning( "Skipping automatic ERC1155 instantiation discovery, already done before" ); return; @@ -324,9 +324,9 @@ export function bytesAlignRightWithZeroes( arrBytes: Uint8Array, cntMin: number export function concatUint8Arrays( a: Uint8Array, b: Uint8Array ): Uint8Array { // a, b TypedArray of same type - if( typeof a == "string" ) + if( typeof a === "string" ) a = hexToBytes( a ); - if( typeof b == "string" ) + if( typeof b === "string" ) b = hexToBytes( b ); const c = new Uint8Array( a.length + b.length ); c.set( a, 0 ); From 4873029cc13689426b3353573e15275f058ee0fc Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:27:38 +0000 Subject: [PATCH 31/53] linting improvement, removed no-unneeded-ternary: off rule --- src/.eslintrc.cjs | 1 - src/bls.ts | 13 +++++---- src/cc.ts | 3 +-- src/clpTools.ts | 26 +++++++++--------- src/discoveryTools.ts | 2 +- src/imaCore.ts | 4 +-- src/imaEventLogScan.ts | 4 +-- src/imaHelperAPIs.ts | 6 ++--- src/imaOracleOperations.ts | 6 ++--- src/imaTokenOperations.ts | 20 +++++++------- src/imaTransferErrorHandling.ts | 2 +- src/loop.ts | 10 +++---- src/main.ts | 4 +-- src/owaspUtils.ts | 2 +- src/pwa.ts | 2 +- src/rpcCall.ts | 4 +-- src/socket.ts | 47 ++++++++++++++------------------- 17 files changed, 73 insertions(+), 83 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index f51954d0..90d5ad61 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -31,7 +31,6 @@ module.exports = { "object-curly-spacing": [ "error", "always" ], "curly": [ "error", "multi-or-nest" ], "nonblock-statement-body-position": [ "error", "below" ], - "no-unneeded-ternary": "off", "no-cond-assign": [ "error", "always" ], "no-fallthrough": "off", "padded-blocks": "off", diff --git a/src/bls.ts b/src/bls.ts index a45528c2..7e586722 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -1252,7 +1252,7 @@ async function doSignProcessHandleCall( optsSignOperation: TSignOperationOptions, joParams: any, joCall: rpcCall.TRPCCall, joIn: any, joOut: any, i: number ) { const imaState: state.TIMAState = state.get(); - const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; + const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignOperation.jarrNodes[i]; const strNodeURL = optsSignOperation.imaState.isCrossImaBlsMode ? imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ) @@ -1365,7 +1365,7 @@ async function doSignProcessHandleCall( async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperationOptions ) { const imaState: state.TIMAState = state.get(); - const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; + const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignOperation.jarrNodes[i]; const strNodeURL = optsSignOperation.imaState.isCrossImaBlsMode ? imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ) @@ -1590,7 +1590,7 @@ async function prepareSignU256( optsSignU256: TSignU256Options ) { async function doSignU256OneImplHandleCallResult( i: number, optsSignU256: TSignU256Options, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { const imaState: state.TIMAState = state.get(); - const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; + const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignU256.jarrNodes[i]; const strNodeURL = optsSignU256.imaState.isCrossImaBlsMode ? imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ) @@ -1690,7 +1690,7 @@ async function doSignU256OneImplHandleCallResult( async function doSignU256OneImpl( i: number, optsSignU256: TSignU256Options ) { const imaState: state.TIMAState = state.get(); - const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; + const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignU256.jarrNodes[i]; const strNodeURL = optsSignU256.imaState.isCrossImaBlsMode ? imaUtils.composeImaAgentNodeUrl( joNode, isThisNode ) @@ -2069,9 +2069,8 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a if( joCall ) await joCall.disconnect(); } - const isSuccess = ( - joSignResult && typeof joSignResult === "object" && ( !joSignResult.error ) ) - ? true : false; + const isSuccess = !!( ( + joSignResult && typeof joSignResult === "object" && ( !joSignResult.error ) ) ); if( isExposeOutput || ( !isSuccess ) ) details.exposeDetailsTo( log.globalStream(), "BLS-raw-signer", isSuccess ); details.close(); diff --git a/src/cc.ts b/src/cc.ts index c34ead85..2c7ff3fc 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -27,8 +27,7 @@ let gFlagIsEnabled: boolean = false; export function autoEnableFromCommandLineArgs(): void { const b: boolean = - ( process.argv.includes( "--colors" ) || process.argv.includes( "-colors" ) ) - ? true : false; + !!( ( process.argv.includes( "--colors" ) || process.argv.includes( "-colors" ) ) ); enable( b ); } diff --git a/src/clpTools.ts b/src/clpTools.ts index 17b38b33..6341c492 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -98,7 +98,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) imaState.chainProperties.mn.chainId.toString(), imaState.chainProperties.mn.transactionCustomizer //, ); - bSuccess = ( jarrReceipts != null && jarrReceipts.length > 0 ) ? true : false; + bSuccess = !!( ( jarrReceipts != null && jarrReceipts.length > 0 ) ); log.information( "{p}Chain was {}", strLogPrefix, log.posNeg( bSuccess, "registered successfully", "not registered" ) ); if( bSuccess ) { @@ -208,7 +208,7 @@ export function commandLineTaskMintErc20() { if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bMintIsOK = - await imaToken.mintErc20( + !!await imaToken.mintErc20( imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, @@ -220,7 +220,7 @@ export function commandLineTaskMintErc20() { imaState.chainProperties.tc.joErc20[imaState.chainProperties .tc.strCoinNameErc20 + "_abi"], imaState.chainProperties.tc.transactionCustomizer - ) ? true : false; + ); } catch ( err ) { bMintIsOK = false; } @@ -251,7 +251,7 @@ export function commandLineTaskMintErc721() { if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bMintIsOK = - await imaToken.mintErc721( + !!await imaToken.mintErc721( imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, @@ -263,7 +263,7 @@ export function commandLineTaskMintErc721() { imaState.chainProperties.tc.joErc721[imaState .chainProperties.tc.strCoinNameErc721 + "_abi"], imaState.chainProperties.tc.transactionCustomizer - ) ? true : false; + ); } } } catch ( err ) { @@ -296,7 +296,7 @@ export function commandLineTaskMintErc1155() { if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bMintIsOK = - await imaToken.mintErc1155( + !!await imaToken.mintErc1155( imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, @@ -311,7 +311,7 @@ export function commandLineTaskMintErc1155() { .joErc1155[imaState.chainProperties.tc .strCoinNameErc1155 + "_abi"], imaState.chainProperties.tc.transactionCustomizer - ) ? true : false; + ); } } } catch ( err ) { @@ -336,7 +336,7 @@ export function commandLineTaskBurnErc20() { if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bBurnIsOK = - await imaToken.burnErc20( + !!await imaToken.burnErc20( imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, @@ -350,7 +350,7 @@ export function commandLineTaskBurnErc20() { .joErc20[imaState.chainProperties .tc.strCoinNameErc20 + "_abi"], imaState.chainProperties.tc.transactionCustomizer - ) ? true : false; + ); } catch ( err ) { bBurnIsOK = false; } @@ -379,7 +379,7 @@ export function commandLineTaskBurnErc721() { if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bBurnIsOK = - await imaToken.burnErc721( + !!await imaToken.burnErc721( imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, @@ -392,7 +392,7 @@ export function commandLineTaskBurnErc721() { .joErc721[imaState.chainProperties .tc.strCoinNameErc721 + "_abi"], imaState.chainProperties.tc.transactionCustomizer - ) ? true : false; + ); } } } catch ( err ) { @@ -425,7 +425,7 @@ export function commandLineTaskBurnErc1155() { if( !imaState.chainProperties.tc.ethersProvider ) throw new Error( "No provider for target chain" ); bBurnIsOK = - await imaToken.burnErc1155( + !!await imaToken.burnErc1155( imaState.chainProperties.tc.ethersProvider, imaState.chainProperties.tc.chainId.toString(), imaState.chainProperties.tc.strChainName, @@ -440,7 +440,7 @@ export function commandLineTaskBurnErc1155() { .joErc1155[imaState.chainProperties .tc.strCoinNameErc1155 + "_abi"], imaState.chainProperties.tc.transactionCustomizer - ) ? true : false; + ); } } } catch ( err ) { diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index eee4a799..fc55175b 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -138,7 +138,7 @@ export function formatBalanceInfo( bi: any, strAddress: string ): string { s += log.fmtDebug( "/{}", bi.assetAddress ); if( "idToken" in bi ) s += log.fmtDebug( " token ID {}", bi.idToken ); - s += log.posNeg( ( bi.assetName == "ERC721" ) ? true : false, " owner is ", " balance is " ); + s += log.posNeg( ( bi.assetName == "ERC721" ), " owner is ", " balance is " ); s += ( bi.assetName == "ERC721" ) ? log.fmtInformation( "{p}", bi.owner ) : log.fmtInformation( "{p}", bi.balance ); if( bi.assetName == "ERC721" ) { diff --git a/src/imaCore.ts b/src/imaCore.ts index 9f354e26..99de7b5e 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -620,7 +620,7 @@ async function callbackAllMessagesSign( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = { isCheckTransactionToSchain: - ( optsTransfer.chainNameDst !== "Mainnet" ) ? true : false + ( optsTransfer.chainNameDst !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( optsTransfer.details, optsTransfer.ethersProviderDst, @@ -1303,5 +1303,5 @@ export async function doAllS2S( // s-chain --> s-chain } log.debug( s ); } - return ( cntFail == 0 ) ? true : false; + return ( cntFail == 0 ); } diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index fc61de78..751ff4d5 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -116,7 +116,7 @@ export async function safeGetPastEventsProgressive( } nBlockFrom = owaspUtils.toBN( nBlockFrom ); const nBlockZero = owaspUtils.toBN( 0 ); - const isFirstZero = ( nBlockFrom.eq( nBlockZero ) ) ? true : false; + const isFirstZero = !!( nBlockFrom.eq( nBlockZero ) ); if( !( isFirstZero && isLastLatest ) ) { details.trace( "{p}Will skip progressive event log records scan and use scan in block " + "range from {} to {}", strLogPrefix, nBlockFrom.toHexString(), nBlockTo.toHexString() ); @@ -395,7 +395,7 @@ export async function safeGetPastEventsIterative( } nBlockFrom = owaspUtils.toBN( nBlockFrom ); const nBlockZero = owaspUtils.toBN( 0 ); - const isFirstZero = ( nBlockFrom.eq( nBlockZero ) ) ? true : false; + const isFirstZero = !!( nBlockFrom.eq( nBlockZero ) ); if( isFirstZero && isLastLatest ) { if( nLatestBlockNumber.div( owaspUtils.toBN( imaHelperAPIs.getBlocksCountInInIterativeStepOfEventsScan() ) diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 776caa90..3234cd92 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -40,14 +40,14 @@ export function getMillisecondsSleepBeforeFetchOutgoingMessageEvent(): number { return gMillisecondsSleepBeforeFetchOutgoingMessageEvent; } export function setMillisecondsSleepBeforeFetchOutgoingMessageEvent( val?: number ): void { - gMillisecondsSleepBeforeFetchOutgoingMessageEvent = val ? val : 0; + gMillisecondsSleepBeforeFetchOutgoingMessageEvent = val || 0; } export function getSleepBetweenTransactionsOnSChainMilliseconds(): number { return gMillisecondsSleepBetweenTransactionsOnSChain; } export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ): void { - gMillisecondsSleepBetweenTransactionsOnSChain = val ? val : 0; + gMillisecondsSleepBetweenTransactionsOnSChain = val || 0; } export function getWaitForNextBlockOnSChain(): boolean { @@ -178,5 +178,5 @@ export function setForwardS2S( b?: boolean ): void { export function setReverseS2S( b?: boolean ): void { if( b == null || b == undefined ) b = true; - gFlagIsForwardS2S = b ? false : true; + gFlagIsForwardS2S = !b; } diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index b1e60a05..0424e672 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -112,9 +112,9 @@ async function prepareOracleGasPriceSetup( optsGasPriceSetup: TGasPriceSetupOpti nMillisecondsSleepPeriod: 3000, cntAttempts: 40, isVerbose: - ( log.verboseGet() >= log.verboseName2Number( "information" ) ) ? true : false, + ( log.verboseGet() >= log.verboseName2Number( "information" ) ), isVerboseTraceDetails: - ( log.verboseGet() >= log.verboseName2Number( "debug" ) ) ? true : false + ( log.verboseGet() >= log.verboseName2Number( "debug" ) ) }; optsGasPriceSetup.details.debug( "Will fetch Main Net gas price via call to Oracle with options {}...", oracleOpts ); @@ -222,7 +222,7 @@ async function handleOracleSigned( if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = { - isCheckTransactionToSchain: ( optsGasPriceSetup.chainIdSChain !== "Mainnet" ) ? true : false + isCheckTransactionToSchain: ( optsGasPriceSetup.chainIdSChain !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( optsGasPriceSetup.details, optsGasPriceSetup.ethersProviderSChain, diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 36a13237..c9bb83ce 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -1270,7 +1270,7 @@ export async function doErc20PaymentS2S( ercDstAddress20: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer ) { - const isReverse = isForward ? false : true; + const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -1410,7 +1410,7 @@ export async function doErc721PaymentS2S( ercDstAddress721: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer ) { - const isReverse = isForward ? false : true; + const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -1555,7 +1555,7 @@ export async function doErc1155PaymentS2S( ercDstAddress1155: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer ) { - const isReverse = isForward ? false : true; + const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -1700,7 +1700,7 @@ export async function doErc1155BatchPaymentS2S( ercDstAddress1155: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer ) { - const isReverse = isForward ? false : true; + const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -1880,7 +1880,7 @@ export async function mintErc20( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = - { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC20", contract, "mint", arrArgumentsMint, @@ -1950,7 +1950,7 @@ export async function mintErc721( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = - { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC721", contract, "mint", arrArgumentsMint, @@ -2024,7 +2024,7 @@ export async function mintErc1155( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = - { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC1155", contract, "mint", arrArgumentsMint, @@ -2094,7 +2094,7 @@ export async function burnErc20( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = - { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC20", contract, "burnFrom", arrArgumentsBurn, @@ -2161,7 +2161,7 @@ export async function burnErc721( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = - { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC721", contract, "burn", arrArgumentsBurn, @@ -2234,7 +2234,7 @@ export async function burnErc1155( throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = - { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) ? true : false }; + { isCheckTransactionToSchain: ( chainName !== "Mainnet" ) }; const joReceipt = await imaTx.payedCall( details, ethersProvider, "ERC1155", contract, "burn", arrArgumentsBurn, diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index d00ef22f..b0526bee 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -27,7 +27,7 @@ import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher.js"; export function verifyTransferErrorCategoryName( strCategory: string ) { - return "" + ( strCategory ? strCategory : "default" ); + return "" + ( strCategory || "default" ); } const gMaxLastTransferErrors: number = 20; diff --git a/src/loop.ts b/src/loop.ts index 7857dd02..4babca59 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -99,7 +99,7 @@ export function checkTimeFraming( nActiveNodeFrameIndex += nFrameShift; nActiveNodeFrameIndex %= imaState.nNodesCount; // for safety only } - let bSkip = ( nActiveNodeFrameIndex != imaState.nNodeNumber ) ? true : false; + let bSkip = ( nActiveNodeFrameIndex != imaState.nNodeNumber ); let bInsideGap = false; const nRangeStart = @@ -565,10 +565,10 @@ function getDefaultOptsLoop( idxWorker: number ): TLoopOptions { isInsideWorker: true, idxChainKnownForS2S: 0, cntChainsKnownForS2S: 0 }, isDelayFirstRun: false, - enableStepOracle: ( idxWorker == 0 ) ? true : false, - enableStepM2S: ( idxWorker == 0 ) ? true : false, - enableStepS2M: ( idxWorker == 1 ) ? true : false, - enableStepS2S: ( idxWorker == 0 ) ? true : false + enableStepOracle: ( idxWorker == 0 ), + enableStepM2S: ( idxWorker == 0 ), + enableStepS2M: ( idxWorker == 1 ), + enableStepS2S: ( idxWorker == 0 ) }; return optsLoop; } diff --git a/src/main.ts b/src/main.ts index 4400472e..d5027ef1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -231,8 +231,8 @@ function initMonitoringServer(): void { } break; case "get_last_transfer_errors": joAnswer.last_transfer_errors = imaTransferErrorHandling.getLastTransferErrors( - ( ( "isIncludeTextLog" in joMessage ) && joMessage.isIncludeTextLog ) - ? true : false ); + !!( ( ( "isIncludeTextLog" in joMessage ) && + joMessage.isIncludeTextLog ) ) ); joAnswer.last_error_categories = imaTransferErrorHandling.getLastErrorCategories(); break diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 18b26c4e..97763ffa 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -716,7 +716,7 @@ export function isHexPrefixed( s: any ): boolean { "Parameter value of owaspUtils.isHexPrefixed() must be type 'string' but it's " + `type ${typeof s}, while checking isHexPrefixed.` ); } - return ( s.slice( 0, 2 ) === "0x" ) ? true : false; + return ( s.slice( 0, 2 ) === "0x" ); } export function stripHexPrefix( s: any ): string { diff --git a/src/pwa.ts b/src/pwa.ts index b58e55e4..d498b111 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -236,7 +236,7 @@ async function notifyOnLoopImpl( nIndexS2S, isStart, nUtcUnixTimeStamp, signature ); // save own started for( let i = 0; i < jarrNodes.length; ++i ) { - const isThisNode = ( i == imaState.nNodeNumber ) ? true : false; + const isThisNode = ( i == imaState.nNodeNumber ); if( isThisNode ) continue; // skip this node const joNode = jarrNodes[i]; diff --git a/src/rpcCall.ts b/src/rpcCall.ts index b84c37fd..cac356fd 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -418,11 +418,11 @@ export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) } const joCall: TRPCCall = { url: "" + strURL, - joRpcOptions: opts ? opts : null, + joRpcOptions: opts || null, mapPendingByCallID: new Map < TCallID, TCallHandlerEntry >(), wsConn: null, isAutoReconnect: - ( opts && "isAutoReconnect" in opts && opts.isAutoReconnect ) ? true : false, + !!( ( opts && "isAutoReconnect" in opts && opts.isAutoReconnect ) ), isDisconnectMode: false, reconnect: async function( fnAfter: TFunctionConnectionResultHandler ) { await doConnect( joCall, opts, fnAfter ); diff --git a/src/socket.ts b/src/socket.ts index 4077cc47..67606264 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -32,13 +32,13 @@ export let wsModule: any = null; // server side only export let webRtcModule: any = null; // server side only export function setHttpsModule( mod: any ): void { - httpsModule = mod ? mod : null; + httpsModule = mod || null; } export function setWsModule( mod: any ): void { - wsModule = mod ? mod : null; + wsModule = mod || null; } export function setWebRtcModule( mod: any ): void { - webRtcModule = mod ? mod : null; + webRtcModule = mod || null; } export const gMapLocalServers: any = { }; // used both for local and in-worker servers @@ -1984,17 +1984,14 @@ export class RTCActor extends RTCConnection { }; if( offerOptions ) { this.offerOptions.offerToReceiveAudio = - ( "offerToReceiveAudio" in offerOptions && offerOptions.offerToReceiveAudio ) - ? true : false; + !!( ( "offerToReceiveAudio" in offerOptions && offerOptions.offerToReceiveAudio ) ); this.offerOptions.offerToReceiveVideo = - ( "offerToReceiveVideo" in offerOptions && offerOptions.offerToReceiveVideo ) - ? true : false; + !!( ( "offerToReceiveVideo" in offerOptions && offerOptions.offerToReceiveVideo ) ); this.offerOptions.voiceActivityDetection = - ( "voiceActivityDetection" in offerOptions && offerOptions.voiceActivityDetection ) - ? true : false; + !!( ( "voiceActivityDetection" in offerOptions && + offerOptions.voiceActivityDetection ) ); this.offerOptions.iceRestart = - ( "iceRestart" in offerOptions && offerOptions.iceRestart ) - ? true : false; + !!( ( "iceRestart" in offerOptions && offerOptions.iceRestart ) ); } this.signalingOptions = { @@ -2240,12 +2237,10 @@ export class RTCServerPeer extends RTCConnection { this.isSignalingNegotiationTimeout = false; this.timerPublishing = null; this.timerSignalingNegotiation = null; - this.timeToPublishMilliseconds = timeToPublishMilliseconds - ? timeToPublishMilliseconds - : settings.net.rtc.timeToPublishMilliseconds; - this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds - ? timeToSignalingNegotiationMilliseconds - : settings.net.rtc.timeToSignalingNegotiationMilliseconds; + this.timeToPublishMilliseconds = timeToPublishMilliseconds || + settings.net.rtc.timeToPublishMilliseconds; + this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds || + settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; @@ -3222,8 +3217,8 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { ( ( idRtcParticipant != null && idRtcParticipant != undefined && typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) ? idRtcParticipant : utils.UUIDv4() ); - this.offerOptions = offerOptions ? offerOptions : null; - this.signalingOptions = signalingOptions ? signalingOptions : null; + this.offerOptions = offerOptions || null; + this.signalingOptions = signalingOptions || null; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; @@ -3237,12 +3232,10 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { if( this.maxActiveOfferCount < 1 ) this.maxActiveOfferCount = 1; this.mapPendingOffers = { }; // idOffer -> RTCServerPeer - this.timeToPublishMilliseconds = timeToPublishMilliseconds - ? timeToPublishMilliseconds - : settings.net.rtc.timeToPublishMilliseconds; - this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds - ? timeToSignalingNegotiationMilliseconds - : settings.net.rtc.timeToSignalingNegotiationMilliseconds; + this.timeToPublishMilliseconds = timeToPublishMilliseconds || + settings.net.rtc.timeToPublishMilliseconds; + this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds || + settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.rtcCreator = new RTCCreator( "" + this.strSignalingServerURL, @@ -3415,8 +3408,8 @@ export class WebRTCClientPipe extends BasicSocketPipe { ( ( idRtcParticipant != null && idRtcParticipant != undefined && typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) ? idRtcParticipant : utils.UUIDv4() ); - this.offerOptions = offerOptions ? offerOptions : null; - this.signalingOptions = signalingOptions ? signalingOptions : null; + this.offerOptions = offerOptions || null; + this.signalingOptions = signalingOptions || null; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) ? peerConfiguration : settings.net.rtc.peerConfiguration; From d96e0a042e8a39904ee3847da8b32c6f1ff34712 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:28:58 +0000 Subject: [PATCH 32/53] linting improvement, removed no-fallthrough: off rule --- src/.eslintrc.cjs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 90d5ad61..3c350a65 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -32,7 +32,6 @@ module.exports = { "curly": [ "error", "multi-or-nest" ], "nonblock-statement-body-position": [ "error", "below" ], "no-cond-assign": [ "error", "always" ], - "no-fallthrough": "off", "padded-blocks": "off", "lines-between-class-members": [ "error", "never" ], "multiline-ternary": "off", From b79b3ddab0d4fc65bcece7f3078a3a63f48926b0 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:30:08 +0000 Subject: [PATCH 33/53] linting improvement, removed padded-blocks: off rule --- src/.eslintrc.cjs | 1 - src/bls.ts | 1 - src/cli.ts | 1 - src/imaEventLogScan.ts | 1 - src/imaTokenOperations.ts | 1 - src/loop.ts | 2 -- src/main.ts | 2 -- src/socket.ts | 1 - 8 files changed, 10 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 3c350a65..789ed000 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -32,7 +32,6 @@ module.exports = { "curly": [ "error", "multi-or-nest" ], "nonblock-statement-body-position": [ "error", "below" ], "no-cond-assign": [ "error", "always" ], - "padded-blocks": "off", "lines-between-class-members": [ "error", "never" ], "multiline-ternary": "off", "max-len": [ "error", { "code": 100, "tabWidth": 4 } ], diff --git a/src/bls.ts b/src/bls.ts index 7e586722..009ae9b6 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -949,7 +949,6 @@ async function checkCorrectnessOfMessagesToSign( strLogPrefix, cntBadMessages, cnt ); } else details.success( "{p}Correctness validation passed for {} message(s)", strLogPrefix, cnt ); - } async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions ) { diff --git a/src/cli.ts b/src/cli.ts index 0eb473c7..79849c95 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2689,7 +2689,6 @@ export function imaInitEthersProviders() { log.warning( "No S<->S Target S-Chain URL specified in command line arguments" + "(needed for particular operations only)" ); } - } // imaInitEthersProviders function initContractsIMA() { diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 751ff4d5..9823f455 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -336,7 +336,6 @@ export async function safeGetPastEvents( ret = await joContract.queryFilter( joFilter, nBlockFrom.toHexString(), nBlockTo.toHexString() ); return ret; - } catch ( err ) { ret = retValOnFail; details.error( diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index c9bb83ce..8caaf2fa 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -946,7 +946,6 @@ export async function doErc721PaymentFromSChain( throw new Error( "Verification failed for the OutgoingMessage event of the " + `MessageProxy${joMessageProxySChain.address} contract, no events found` ); } - } } catch ( err ) { details.critical( "{p}Payment error in {bright}: {err}, stack is:\n{stack}", diff --git a/src/loop.ts b/src/loop.ts index 4babca59..08301b23 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -397,7 +397,6 @@ async function singleTransferLoopPartS2S( optsLoop: TLoopOptions, strLogPrefix: } log.information( "{p}All S2S transfers done in {}: {}", strLogPrefix, threadInfo.threadDescription(), b3 ); - } else log.debug( "{p}Skipped S2S transfer in {}.", strLogPrefix, threadInfo.threadDescription() ); @@ -761,7 +760,6 @@ export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) const cntWorkers = gArrWorkers.length; for( let idxWorker = 0; idxWorker < cntWorkers; ++idxWorker ) gArrClients[idxWorker].send( joMessage ); - } export async function spreadUpdatedSChainNetwork( isFinal: boolean ) { diff --git a/src/main.ts b/src/main.ts index d5027ef1..452009d2 100644 --- a/src/main.ts +++ b/src/main.ts @@ -226,7 +226,6 @@ function initMonitoringServer(): void { for( const paramName of arrRuntimeParamNames ) { if( paramName in imaState ) joAnswer.runtime_params[paramName] = ( imaState as any )[paramName]; - } } break; case "get_last_transfer_errors": @@ -476,7 +475,6 @@ async function main() { // everything else is in async calls executed later, // skip exit here to avoid early termination while tasks ase still running } - } main().then( function() {} ).catch( function() {} ); diff --git a/src/socket.ts b/src/socket.ts index 67606264..456cb503 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -90,7 +90,6 @@ export const generateSocketDataStatsJSON = function( jo: any ) { ) { for( const joMessage of jo.arrPackedMessages ) updateSocketDataStatsForMessage( joMessage, joStats ); - } else updateSocketDataStatsForMessage( jo, joStats ); return joStats; From ccef74cdd0a60a9cc21ae5efe133b03c09ff4e48 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:31:23 +0000 Subject: [PATCH 34/53] linting improvement, removed multiline-ternary: off rule --- src/.eslintrc.cjs | 1 - src/bls.ts | 6 ++-- src/cc.ts | 6 ++-- src/cli.ts | 12 ++++--- src/clpTools.ts | 30 ++++++++++------ src/discoveryTools.ts | 3 +- src/imaCore.ts | 9 +++-- src/imaEventLogScan.ts | 9 +++-- src/imaHelperAPIs.ts | 3 +- src/imaTx.ts | 15 +++++--- src/log.ts | 18 ++++++---- src/loop.ts | 6 ++-- src/main.ts | 6 ++-- src/oracle.ts | 12 ++++--- src/owaspUtils.ts | 3 +- src/rpcCall.ts | 18 ++++++---- src/socket.ts | 78 ++++++++++++++++++++++++++++-------------- src/socketUtils.ts | 33 ++++++++++++------ 18 files changed, 178 insertions(+), 90 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 789ed000..08bb5c32 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -33,7 +33,6 @@ module.exports = { "nonblock-statement-body-position": [ "error", "below" ], "no-cond-assign": [ "error", "always" ], "lines-between-class-members": [ "error", "never" ], - "multiline-ternary": "off", "max-len": [ "error", { "code": 100, "tabWidth": 4 } ], "max-lines-per-function": [ "error", { "max": 200, "skipBlankLines": false } ], "@typescript-eslint/indent": [ "error", 4, { "ignoredNodes": [ "SwitchCase" ] } ], diff --git a/src/bls.ts b/src/bls.ts index 009ae9b6..939b05ab 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -878,7 +878,8 @@ async function checkCorrectnessOfMessagesToSign( const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = ( joExtraSignOpts && "ethersProviderSrc" in joExtraSignOpts && joExtraSignOpts.ethersProviderSrc ) - ? joExtraSignOpts.ethersProviderSrc : null; + ? joExtraSignOpts.ethersProviderSrc + : null; if( !ethersProvider ) { throw new Error( "CRITICAL ERROR: No provider specified in extra signing options " + `for checking messages of direction ${strDirection}` ); @@ -1467,7 +1468,8 @@ async function doSignMessagesImpl( }; optsSignOperation.details = optsSignOperation.imaState.isDynamicLogInBlsSigner - ? log.globalStream() : log.createMemoryStream(); + ? log.globalStream() + : log.createMemoryStream(); optsSignOperation.strGatheredDetailsName = optsSignOperation.strDirection + "-" + "doSignMessagesImpl-#" + optsSignOperation.nTransferLoopCounter + "-" + optsSignOperation.strFromChainName + "-msg#" + diff --git a/src/cc.ts b/src/cc.ts index 2c7ff3fc..77e0b2d0 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -54,7 +54,8 @@ export function validateRadix( value?: any, radix?: any ) { value = value.trim(); radix = ( radix == null || radix == undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) - ? 16 : 10 ) + ? 16 + : 10 ) : parseInt( radix, 10 ); return radix; } @@ -463,7 +464,8 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ const s = JSON.stringify( obj, ( jsonColorizer.cntCensoredMax > 0 ) - ? jsonColorizer.censor( obj ) : null, 4 + ? jsonColorizer.censor( obj ) + : null, 4 ) .replace( /&/g, "&" ).replace( /\\"/g, """ ) .replace( //g, ">" ) diff --git a/src/cli.ts b/src/cli.ts index 79849c95..0b0cfeb0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2565,11 +2565,13 @@ function commonInitGasMultipliersAndTransactionArgs() { log.debug( log.fmtInformation( "Oracle based gas reimbursement is" ), "...................." + ( imaOracleOperations.getEnabledOracle() - ? log.fmtSuccess( "enabled" ) : log.fmtError( "disabled" ) ) ); + ? log.fmtSuccess( "enabled" ) + : log.fmtError( "disabled" ) ) ); log.debug( log.fmtInformation( "S-Chain to S-Chain transferring is" ) + "..................." + ( imaState.optsS2S.isEnabled - ? log.fmtSuccess( "enabled" ) : log.fmtError( "disabled" ) ) ); + ? log.fmtSuccess( "enabled" ) + : log.fmtError( "disabled" ) ) ); log.debug( log.fmtInformation( "SKALE network browser file path is" ), "................." + ( imaState.optsS2S.strNetworkBrowserPath @@ -2581,11 +2583,13 @@ function commonInitGasMultipliersAndTransactionArgs() { log.debug( log.fmtInformation( "IMA JSON RPC server port is" ), ".........................." + ( ( imaState.nJsonRpcPort > 0 ) - ? log.fmtInformation( imaState.nJsonRpcPort ) : log.fmtError( "disabled" ) ) ); + ? log.fmtInformation( imaState.nJsonRpcPort ) + : log.fmtError( "disabled" ) ) ); log.debug( log.fmtInformation( "Cross-IMA mode is" ), "...................................." + ( imaState.isCrossImaBlsMode - ? log.fmtSuccess( "enabled" ) : log.fmtError( "disabled" ) ) ); + ? log.fmtSuccess( "enabled" ) + : log.fmtError( "disabled" ) ) ); log.debug( log.fmtInformation( "Dry-run is enabled" ), "..................................." + log.yn( imaTx.dryRunIsEnabled() ) ); diff --git a/src/clpTools.ts b/src/clpTools.ts index 6341c492..c2551e7d 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -242,7 +242,8 @@ export function commandLineTaskMintErc721() { imaState.chainProperties.tc.joAccount.address(); const idTokens: any[] = ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) - ? imaState.idTokens : []; + ? imaState.idTokens + : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { @@ -287,7 +288,8 @@ export function commandLineTaskMintErc1155() { imaState.chainProperties.tc.joAccount.address(); const idTokens: any[] = ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) - ? imaState.idTokens : []; + ? imaState.idTokens + : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { @@ -370,7 +372,8 @@ export function commandLineTaskBurnErc721() { try { const idTokens: any[] = ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) - ? imaState.idTokens : []; + ? imaState.idTokens + : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { @@ -416,7 +419,8 @@ export function commandLineTaskBurnErc1155() { imaState.chainProperties.tc.joAccount.address(); const idTokens: any[] = ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) - ? imaState.idTokens : []; + ? imaState.idTokens + : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { @@ -735,7 +739,8 @@ export function commandLineTaskShowBalance() { arrBalancesMN, arrBalancesSC, arrBalancesTC ); const idTokens: any[] = ( imaState.haveArrayOfTokenIdentifiers && imaState.idTokens ) - ? imaState.idTokens : []; + ? imaState.idTokens + : []; if( imaState.haveOneTokenIdentifier ) idTokens.push( imaState.idToken ); if( idTokens.length > 0 ) { @@ -1182,7 +1187,8 @@ export function commandLineTaskPaymentS2S() { const chainIdSrc = isForward ? sc.chainId : tc.chainId; const joAccountSrc = isForward ? sc.joAccount : tc.joAccount; const joTokenManagerERC20Src: owaspUtils.ethersMod.ethers.Contract | null = isForward - ? imaState.joTokenManagerERC20 : imaState.joTokenManagerERC20Target; + ? imaState.joTokenManagerERC20 + : imaState.joTokenManagerERC20Target; const joTokenManagerERC721Src: owaspUtils.ethersMod.ethers.Contract | null = isForward ? ( imaState.isWithMetadata721 ? imaState.joTokenManagerERC721WithMetadata @@ -1192,7 +1198,8 @@ export function commandLineTaskPaymentS2S() { : imaState.joTokenManagerERC721Target ); const joTokenManagerERC1155Src: owaspUtils.ethersMod.ethers.Contract | null = isForward - ? imaState.joTokenManagerERC1155 : imaState.joTokenManagerERC1155Target; + ? imaState.joTokenManagerERC1155 + : imaState.joTokenManagerERC1155Target; const strChainNameDst = isForward ? tc.strChainName : sc.strChainName; const strCoinNameErc20Src = isForward ? sc.strCoinNameErc20 : tc.strCoinNameErc20; const strCoinNameErc721Src = isForward ? sc.strCoinNameErc721 : tc.strCoinNameErc721; @@ -1220,11 +1227,14 @@ export function commandLineTaskPaymentS2S() { if( ( !strAddrErc1155ExplicitTarget ) && tc.joErc1155 && tc.strCoinNameErc1155 ) strAddrErc1155ExplicitTarget = tc.joErc1155[tc.strCoinNameErc1155 + "_address"]; const strAddrErc20Dst = isForward - ? strAddrErc20ExplicitTarget : strAddrErc20Explicit; + ? strAddrErc20ExplicitTarget + : strAddrErc20Explicit; const strAddrErc721Dst = isForward - ? strAddrErc721ExplicitTarget : strAddrErc721Explicit; + ? strAddrErc721ExplicitTarget + : strAddrErc721Explicit; const strAddrErc1155Dst = isForward - ? strAddrErc1155ExplicitTarget : strAddrErc1155Explicit; + ? strAddrErc1155ExplicitTarget + : strAddrErc1155Explicit; const txCustomizer: imaTx.TransactionCustomizer = isForward ? sc.transactionCustomizer : tc.transactionCustomizer; if( strCoinNameErc721Src.length > 0 ) { diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index fc55175b..633a148f 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -140,7 +140,8 @@ export function formatBalanceInfo( bi: any, strAddress: string ): string { s += log.fmtDebug( " token ID {}", bi.idToken ); s += log.posNeg( ( bi.assetName == "ERC721" ), " owner is ", " balance is " ); s += ( bi.assetName == "ERC721" ) - ? log.fmtInformation( "{p}", bi.owner ) : log.fmtInformation( "{p}", bi.balance ); + ? log.fmtInformation( "{p}", bi.owner ) + : log.fmtInformation( "{p}", bi.balance ); if( bi.assetName == "ERC721" ) { const isSame = ( bi.owner.trim().toLowerCase() == strAddress.trim().toLowerCase() ); diff --git a/src/imaCore.ts b/src/imaCore.ts index 99de7b5e..f4019ac5 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -851,7 +851,8 @@ async function checkOutgoingMessageEvent( } } catch ( err ) { const strUrlHttp = optsOutgoingMessageAnalysis.joNode - ? optsOutgoingMessageAnalysis.joNode.endpoints.ip.http : ""; + ? optsOutgoingMessageAnalysis.joNode.endpoints.ip.http + : ""; const strNodeName = optsOutgoingMessageAnalysis.joNode ? log.fmtInformation( optsOutgoingMessageAnalysis.joNode.name ) : log.fmtError( "<>" ); @@ -980,7 +981,8 @@ async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { optsTransfer.details.close(); optsTransfer.details = optsTransfer.imaState.isDynamicLogInDoTransfer - ? log.globalStream() : log.createMemoryStream(); + ? log.globalStream() + : log.createMemoryStream(); optsTransfer.strGatheredDetailsName = `${optsTransfer.strDirection}/#` + `${optsTransfer.nTransferLoopCounter}-doTransfer-B-${optsTransfer.chainNameSrc}` + `-->${optsTransfer.chainNameDst}`; @@ -1069,7 +1071,8 @@ export async function doTransfer( `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter}-doTransfer-A-` + `${optsTransfer.chainNameSrc}-->${optsTransfer.chainNameDst}`; optsTransfer.details = optsTransfer.imaState.isDynamicLogInDoTransfer - ? log.globalStream() : log.createMemoryStream(); + ? log.globalStream() + : log.createMemoryStream(); optsTransfer.strLogPrefixShort = `${optsTransfer.strDirection}/#${optsTransfer.nTransferLoopCounter} `; optsTransfer.strLogPrefix = `${optsTransfer.strLogPrefixShort}transfer loop from ` + diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 9823f455..74ac16d9 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -207,7 +207,8 @@ export async function safeGetTransactionCount( if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) - ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); + ? 1 + : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; @@ -252,7 +253,8 @@ export async function safeGetTransactionReceipt( if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) - ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); + ? 1 + : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; @@ -298,7 +300,8 @@ export async function safeGetPastEvents( if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) - ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); + ? 1 + : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index 3234cd92..a6ef5e17 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -88,7 +88,8 @@ export async function safeGetBlockNumber( if( throwIfServerOffline == null || throwIfServerOffline == undefined ) throwIfServerOffline = true; cntAttempts = ( owaspUtils.parseIntOrHex( cntAttempts ) < 1 ) - ? 1 : owaspUtils.parseIntOrHex( cntAttempts ); + ? 1 + : owaspUtils.parseIntOrHex( cntAttempts ); if( retValOnFail == null || retValOnFail == undefined ) retValOnFail = ""; let ret = retValOnFail; diff --git a/src/imaTx.ts b/src/imaTx.ts index ecd5ff72..0013a2f7 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -79,7 +79,8 @@ export function dryRunIsEnabled(): boolean { } export function dryRunEnable( isEnable: any ): boolean { gFlagDryRunIsEnabled = ( isEnable != null && isEnable != undefined ) - ? ( !!isEnable ) : true; + ? ( !!isEnable ) + : true; return ( !!gFlagDryRunIsEnabled ); } @@ -91,7 +92,8 @@ export function dryRunIsIgnored(): boolean { export function dryRunIgnore( isIgnored: boolean ): boolean { gFlagDryRunIsIgnored = ( isIgnored != null && isIgnored != undefined ) - ? ( !!isIgnored ) : true; + ? ( !!isIgnored ) + : true; return ( !!gFlagDryRunIsIgnored ); } @@ -107,7 +109,8 @@ export async function dryRunCall( if( !dryRunIsEnabled() ) return null; // success isDryRunResultIgnore = ( isDryRunResultIgnore != null && isDryRunResultIgnore != undefined ) - ? ( !!isDryRunResultIgnore ) : false; + ? ( !!isDryRunResultIgnore ) + : false; const strContractMethodDescription = log.fmtDebug( "{p}({}).{sunny}", strContractName, joContract.address, strMethodName ); let strArgumentsDescription = ""; @@ -250,9 +253,11 @@ async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ) { "\"" + owaspUtils.toHexStringSafe( tx.gasLimit ) + "\" " + "\"" + owaspUtils.toHexStringSafe( tx.nonce ) + "\" " + "\"" + ( optsPayedCall.joAccount.strPathSslCert - ? optsPayedCall.joAccount.strPathSslCert : "" ) + "\" " + + ? optsPayedCall.joAccount.strPathSslCert + : "" ) + "\" " + "\"" + ( optsPayedCall.joAccount.strPathSslKey - ? optsPayedCall.joAccount.strPathSslKey : "" ) + "\" " + + ? optsPayedCall.joAccount.strPathSslKey + : "" ) + "\" " + ""; const joSpawnOptions: any = { shell: true, diff --git a/src/log.ts b/src/log.ts index 2e62eda8..c55fb25f 100644 --- a/src/log.ts +++ b/src/log.ts @@ -122,7 +122,8 @@ export function n2s( n: any, sz: number ): string { export function generateTimestampString( ts?: any, isColorized?: boolean ): string { isColorized = ( typeof isColorized === "undefined" ) - ? true : ( !!isColorized ); + ? true + : ( !!isColorized ); ts = ( ts instanceof Date ) ? ts : new Date(); const ccDate = function( x?: any ): string { return isColorized ? cc.date( x ) : x; }; const ccTime = function( x?: any ): string { return isColorized ? cc.time( x ) : x; }; @@ -230,7 +231,8 @@ export function createStandardOutputStream(): TLogger | null { write: function( ...args: any[] ): void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) - ? generateTimestampPrefix( null, true ) : "" ); + ? generateTimestampPrefix( null, true ) + : "" ); s += fmtArgumentsArray( args ); try { if( this.objStream && s.length > 0 ) @@ -403,9 +405,11 @@ export function createMemoryOutputStream(): TLogger { } try { strTitle = strTitle - ? ( cc.bright( " (" ) + cc.attention( strTitle ) + cc.bright( ")" ) ) : ""; + ? ( cc.bright( " (" ) + cc.attention( strTitle ) + cc.bright( ")" ) ) + : ""; const strSuccessPrefix = isSuccess - ? cc.success( "SUCCESS" ) : cc.error( "ERROR" ); + ? cc.success( "SUCCESS" ) + : cc.error( "ERROR" ); otherStream.write( "\n" ); otherStream.write( cc.bright( "--- --- --- --- --- GATHERED " ) + strSuccessPrefix + cc.bright( " DETAILS FOR LATEST(" ) + @@ -520,7 +524,8 @@ export function createFileOutput( write: function( ...args: any[] ): void { let s = ( this.strOwnIndent ? this.strOwnIndent : "" ) + ( ( this.haveOwnTimestamps && ( !this.isPausedTimeStamps ) ) - ? generateTimestampPrefix( null, true ) : "" ); + ? generateTimestampPrefix( null, true ) + : "" ); s += fmtArgumentsArray( args ); try { if( s.length > 0 ) { @@ -728,7 +733,8 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { fnFormatter = fnFormatter || function( arg: any ) { return arg; }; const arrParts = ( arrArgs && arrArgs.length > 0 ) - ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; + ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) + : null; let s = ""; let isValueMode = false; const fnDefaultOneArgumentFormatter = function( arg?: any, fnCustomFormatter?: any ): string { if( !fnCustomFormatter ) diff --git a/src/loop.ts b/src/loop.ts index 08301b23..e95d4754 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -142,10 +142,12 @@ export function checkTimeFraming( } else { const s1: string = log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts - ? joRuntimeOpts.joExtraSignOpts.chainNameDst : "N/A" ) + ? joRuntimeOpts.joExtraSignOpts.chainNameDst + : "N/A" ) const s2: string = log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts - ? joRuntimeOpts.joExtraSignOpts.chainIdDst : "N/A" ) + ? joRuntimeOpts.joExtraSignOpts.chainIdDst + : "N/A" ) strFrameInfo += log.fmtDebug( " S-Chain destination", "........", s1, "/", s2, "\n" ); } diff --git a/src/main.ts b/src/main.ts index 452009d2..5fd9157f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -425,7 +425,8 @@ async function main() { initMonitoringServer(); initJsonRpcServer(); const isSilentReDiscovery = imaState.isPrintSecurityValues - ? false : imaState.joSChainDiscovery.isSilentReDiscovery; + ? false + : imaState.joSChainDiscovery.isSilentReDiscovery; const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ) { loop.spreadUpdatedSChainNetwork( isFinal ).then( function() {} ).catch( function() {} ); }; @@ -440,7 +441,8 @@ async function main() { } log.information( "S-Chain network was discovery uses {} mode", ( isSilentReDiscovery - ? log.fmtWarning( "silent" ) : log.fmtSuccess( "exposed details" ) ) ); + ? log.fmtWarning( "silent" ) + : log.fmtSuccess( "exposed details" ) ) ); if( !imaState.bNoWaitSChainStarted ) { await discoveryTools.waitUntilSChainStarted(); if( !isSilentReDiscovery ) { diff --git a/src/oracle.ts b/src/oracle.ts index 1233a132..cf1848bb 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -110,9 +110,11 @@ async function handleOracleSubmitRequestResult( joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { const nMillisecondsSleepBefore = "nMillisecondsSleepBefore" in oracleOpts - ? oracleOpts.nMillisecondsSleepBefore : 1000; + ? oracleOpts.nMillisecondsSleepBefore + : 1000; const nMillisecondsSleepPeriod = "nMillisecondsSleepPeriod" in oracleOpts - ? oracleOpts.nMillisecondsSleepPeriod : 3000; + ? oracleOpts.nMillisecondsSleepPeriod + : 3000; let cntAttempts = "cntAttempts" in oracleOpts ? oracleOpts.cntAttempts : 40; if( cntAttempts < 1 ) cntAttempts = 1; @@ -128,7 +130,8 @@ async function handleOracleSubmitRequestResult( let gp = null; for( let idxAttempt = 0; idxAttempt < cntAttempts; ++idxAttempt ) { const nMillisecondsToSleep = ( !idxAttempt ) - ? nMillisecondsSleepBefore : nMillisecondsSleepPeriod; + ? nMillisecondsSleepBefore + : nMillisecondsSleepPeriod; if( nMillisecondsToSleep > 0 ) await threadInfo.sleep( nMillisecondsToSleep ); try { @@ -165,7 +168,8 @@ export async function oracleGetGasPrice( oracleOpts: any, details: log.TLogger ) try { const isVerbose = "isVerbose" in oracleOpts ? oracleOpts.isVerbose : false; let isVerboseTraceDetails = "isVerboseTraceDetails" in oracleOpts - ? oracleOpts.isVerboseTraceDetails : false; + ? oracleOpts.isVerboseTraceDetails + : false; if( !( log.verboseGet() >= log.verboseName2Number( "trace" ) ) ) isVerboseTraceDetails = false; const callOpts = "callOpts" in oracleOpts ? oracleOpts.callOpts : { }; diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 97763ffa..9d652460 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -93,7 +93,8 @@ export function validateRadix( value: any, radix?: any ): boolean { value = value.trim(); radix = ( radix == null || radix == undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) - ? 16 : 10 ) + ? 16 + : 10 ) : parseInt( radix, 10 ); return radix; } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index cac356fd..473d216d 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -310,13 +310,16 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu }, ca: ( joCall.joRpcOptions?.ca && typeof joCall.joRpcOptions.ca === "string" ) - ? joCall.joRpcOptions.ca : null, + ? joCall.joRpcOptions.ca + : null, cert: ( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert === "string" ) - ? joCall.joRpcOptions.cert : null, + ? joCall.joRpcOptions.cert + : null, key: ( joCall.joRpcOptions?.key && typeof joCall.joRpcOptions.key === "string" ) - ? joCall.joRpcOptions.key : null + ? joCall.joRpcOptions.key + : null }; let accumulatedBody = ""; const promiseComplete = new Promise( ( resolve, reject ) => { @@ -379,13 +382,16 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu httpsAgent: false, ca: ( joCall.joRpcOptions?.ca && typeof joCall.joRpcOptions.ca === "string" ) - ? joCall.joRpcOptions.ca : null, + ? joCall.joRpcOptions.ca + : null, cert: ( joCall.joRpcOptions?.cert && typeof joCall.joRpcOptions.cert === "string" ) - ? joCall.joRpcOptions.cert : null, + ? joCall.joRpcOptions.cert + : null, key: ( joCall.joRpcOptions?.key && typeof joCall.joRpcOptions.key === "string" ) - ? joCall.joRpcOptions.key : null + ? joCall.joRpcOptions.key + : null }; const response = await urllib.request( joCall.url, requestOpts as urllib.RequestOptions ); diff --git a/src/socket.ts b/src/socket.ts index 456cb503..64755c0f 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -430,7 +430,8 @@ export const outOfWorkerAPIs: any = { const joSend: any = { workerMessageType: ( type && typeof type === "string" && type.length > 0 ) - ? type : "inWorkerMessage", + ? type + : "inWorkerMessage", workerEndPoint: endpoint, workerUUID, data: jo @@ -473,7 +474,8 @@ export const inWorkerAPIs: any = { const joSend: any = { workerMessageType: ( type && typeof type === "string" && type.length > 0 ) - ? type : "inWorkerMessage", + ? type + : "inWorkerMessage", workerEndPoint: endpoint, workerUUID, data: jo @@ -553,7 +555,8 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { this.socketType = "InWorker"; this.strEndPoint = ( strEndPoint && typeof strEndPoint === "string" && strEndPoint.length > 0 ) - ? strEndPoint : "default_local_endpoint"; + ? strEndPoint + : "default_local_endpoint"; if( this.strEndPoint in gMapLocalServers ) { const s = "Cannot start in-worker socket server on already listening \"" + @@ -697,13 +700,16 @@ export class OutOfWorkerRelay extends EventDispatcher { const self = this; self.strRelayName = ( strRelayName != null && strRelayName != undefined && typeof strRelayName === "string" && strRelayName.length > 0 ) - ? ( "" + strRelayName ) : "unnamed"; + ? ( "" + strRelayName ) + : "unnamed"; self.isAutoFlushIncoming = ( isAutoFlushIncoming == null || isAutoFlushIncoming == undefined ) - ? true : ( !!isAutoFlushIncoming ); + ? true + : ( !!isAutoFlushIncoming ); self.isAutoFlushOutgoing = ( isAutoFlushOutgoing == null || isAutoFlushOutgoing == undefined ) - ? true : ( !!( isAutoFlushOutgoing ) ); + ? true + : ( !!( isAutoFlushOutgoing ) ); if( !acceptor ) { throw new Error( `OutOfWorkerRelay ${self.strRelayName} needs acceptor ` + "for normal functionality" ); @@ -937,13 +943,16 @@ export class OneToOneRelay extends EventDispatcher { self.strRelayName = ( strRelayName != null && strRelayName != undefined && typeof strRelayName === "string" && strRelayName.length > 0 ) - ? ( "" + strRelayName ) : "unnamed"; + ? ( "" + strRelayName ) + : "unnamed"; self.isAutoFlushIncoming = ( isAutoFlushIncoming == null || isAutoFlushIncoming == undefined ) - ? true : ( !!isAutoFlushIncoming ); + ? true + : ( !!isAutoFlushIncoming ); self.isAutoFlushOutgoing = ( isAutoFlushOutgoing == null || isAutoFlushOutgoing == undefined ) - ? true : ( !!isAutoFlushIncoming ); + ? true + : ( !!isAutoFlushIncoming ); self.pipeIncoming = pipeIncoming; self.pipeOutgoing = pipeOutgoing; if( ( !( "strSavedRemoteAddress" in pipeIncoming ) ) || @@ -1181,9 +1190,11 @@ export class DirectPipe extends BasicSocketPipe { this.isConnected = false; this.acceptor = null; this.counterPipe = ( counterPipe != null && counterPipe != undefined ) - ? counterPipe : null; // set outside after this constructor call + ? counterPipe + : null; // set outside after this constructor call this.strEndPoint = this.counterPipe - ? ( "2-" + this.counterPipe.strEndPoint ) : ( "1-" + utils.randomDirectPipeID() ); + ? ( "2-" + this.counterPipe.strEndPoint ) + : ( "1-" + utils.randomDirectPipeID() ); this.clientPort = this.counterPipe ? 2 : 1; this.socketSubtype = "direct." + this.clientPort; this.url = "direct_pipe://" + this.strEndPoint + ":" + this.clientPort; @@ -1277,7 +1288,8 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { this.nextClientPort = 1; this.strEndPoint = ( strEndPoint && typeof strEndPoint === "string" && strEndPoint.length > 0 ) - ? strEndPoint : "default_local_endpoint"; + ? strEndPoint + : "default_local_endpoint"; if( this.strEndPoint in gMapLocalServers ) { const s = "Cannot start local socket server on already listening \"" + @@ -1322,7 +1334,8 @@ export class LocalSocketClientPipe extends DirectPipe { this.counterPipe = null; this.strEndPoint = ( strEndPoint && typeof strEndPoint === "string" && strEndPoint.length > 0 ) - ? strEndPoint : "default_local_endpoint"; + ? strEndPoint + : "default_local_endpoint"; if( !( this.strEndPoint in gMapLocalServers ) ) { const s = "Cannot connect to local socket server \"" + this.strEndPoint + @@ -1706,7 +1719,8 @@ export class RTCConnection extends EventDispatcher { this.idRtcParticipant = "" + ( ( idRtcParticipant != null && idRtcParticipant != undefined && typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) - ? idRtcParticipant : utils.UUIDv4() ); + ? idRtcParticipant + : utils.UUIDv4() ); this.wasIdentified = false; this.iceComplete = false; this.pc = null; @@ -2242,14 +2256,17 @@ export class RTCServerPeer extends RTCConnection { settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) - ? peerConfiguration : settings.net.rtc.peerConfiguration; + ? peerConfiguration + : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) - ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; + ? peerAdditionalOptions + : settings.net.rtc.peerAdditionalOptions; this.localMediaStream = ( localMediaStream != null && localMediaStream != undefined && typeof localMediaStream === "object" ) - ? localMediaStream : null; + ? localMediaStream + : null; this.isOfferPublishedOnSignalingServer = false; this.initPeer(); this.publish(); @@ -2797,10 +2814,12 @@ export class RTCJoiner extends RTCActor { this.signalingPipeOpen(); this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) - ? peerConfiguration : settings.net.rtc.peerConfiguration; + ? peerConfiguration + : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) - ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; + ? peerAdditionalOptions + : settings.net.rtc.peerAdditionalOptions; } dispose() { if( this.isDisposed ) @@ -3215,19 +3234,23 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.idRtcParticipant = "" + ( ( idRtcParticipant != null && idRtcParticipant != undefined && typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) - ? idRtcParticipant : utils.UUIDv4() ); + ? idRtcParticipant + : utils.UUIDv4() ); this.offerOptions = offerOptions || null; this.signalingOptions = signalingOptions || null; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) - ? peerConfiguration : settings.net.rtc.peerConfiguration; + ? peerConfiguration + : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) - ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; + ? peerAdditionalOptions + : settings.net.rtc.peerAdditionalOptions; this.socketType = "WebRTC"; this.maxActiveOfferCount = ( maxActiveOfferCount != null && maxActiveOfferCount != undefined ) - ? maxActiveOfferCount : settings.net.rtc.maxActiveOfferCount; + ? maxActiveOfferCount + : settings.net.rtc.maxActiveOfferCount; if( this.maxActiveOfferCount < 1 ) this.maxActiveOfferCount = 1; this.mapPendingOffers = { }; // idOffer -> RTCServerPeer @@ -3406,15 +3429,18 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.idRtcParticipant = "" + ( ( idRtcParticipant != null && idRtcParticipant != undefined && typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) - ? idRtcParticipant : utils.UUIDv4() ); + ? idRtcParticipant + : utils.UUIDv4() ); this.offerOptions = offerOptions || null; this.signalingOptions = signalingOptions || null; this.peerConfiguration = ( peerConfiguration && typeof peerConfiguration === "object" ) - ? peerConfiguration : settings.net.rtc.peerConfiguration; + ? peerConfiguration + : settings.net.rtc.peerConfiguration; this.peerAdditionalOptions = ( peerAdditionalOptions && typeof peerAdditionalOptions === "object" ) - ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; + ? peerAdditionalOptions + : settings.net.rtc.peerAdditionalOptions; this.socketType = "WebRTC"; this.socketSubtype = "client"; this.isConnected = false; diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 67043add..06e46809 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -58,13 +58,17 @@ export const randomString = function( if( length <= 0 ) return ""; isABC = ( isABC == null || isABC == undefined ) - ? true : ( !!isABC ); + ? true + : ( !!isABC ); isDigits = ( isDigits == null || isDigits == undefined ) - ? false : ( !!isDigits ); + ? false + : ( !!isDigits ); isSpecChr = ( isSpecChr == null || isSpecChr == undefined ) - ? false : ( !!isSpecChr ); + ? false + : ( !!isSpecChr ); isPunctuation = ( isPunctuation == null || isPunctuation == undefined ) - ? false : ( !!isPunctuation ); + ? false + : ( !!isPunctuation ); let arrCharacters = ""; if( isABC ) arrCharacters += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; @@ -129,12 +133,14 @@ export const prepareAnswerJSON = function( joMessage: any ): any { ( ( joMessage != null && joMessage != undefined && typeof joMessage.id === "string" ) - ? joMessage.id : randomCallID() ), + ? joMessage.id + : randomCallID() ), method: "" + ( ( joMessage != null && joMessage != undefined && typeof joMessage.method === "string" ) - ? joMessage.method : "" ), + ? joMessage.method + : "" ), error: null }; return joAnswer; @@ -215,7 +221,8 @@ export const formatDateTime = function( let s = ""; if( isDate ) { sepDate = ( sepDate == null || sepDate == undefined || ( typeof sepDate !== "string" ) ) - ? "/" : sepDate; + ? "/" + : sepDate; const strDate = "" + zeroPaddingLeft( dt.getFullYear(), 4 ) + sepDate + @@ -226,13 +233,15 @@ export const formatDateTime = function( } if( isTime ) { sepTime = ( sepTime == null || sepTime == undefined || ( typeof sepTime !== "string" ) ) - ? ":" : sepTime; + ? ":" + : sepTime; if( isDate ) { sepBetween = ( sepBetween == null || sepBetween == undefined || ( typeof sepBetween !== "string" ) ) - ? "-" : sepBetween; + ? "-" + : sepBetween; s += sepBetween; } let strTime = "" + @@ -242,13 +251,15 @@ export const formatDateTime = function( sepDate + zeroPaddingLeft( dt.getSeconds(), 2 ); isMilliseconds = ( isMilliseconds == null || isMilliseconds == undefined ) - ? true : ( !!isMilliseconds ); + ? true + : ( !!isMilliseconds ); if( isMilliseconds ) { sepMilliseconds = ( sepMilliseconds == null || sepMilliseconds == undefined || ( typeof sepMilliseconds !== "string" ) ) - ? "." : sepMilliseconds; + ? "." + : sepMilliseconds; strTime += sepMilliseconds + zeroPaddingRight( dt.getMilliseconds(), 3 ); } s += strTime; From c1d0fdf411f2a89f0b977cbec9952dcb5dd1a871 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 29 Dec 2023 19:43:01 +0000 Subject: [PATCH 35/53] linting improvement, removed handle-callback-err rule --- src/.eslintrc.cjs | 2 -- src/bls.ts | 1 + src/socket.ts | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 08bb5c32..c426edd6 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -57,8 +57,6 @@ module.exports = { "@typescript-eslint/no-dynamic-delete": "off", "@typescript-eslint/no-this-alias": "off", "@typescript-eslint/lines-between-class-members": "off", - "handle-callback-err": "off", - "n/handle-callback-err": "off", "@typescript-eslint/prefer-optional-chain": "off" } }; diff --git a/src/bls.ts b/src/bls.ts index 939b05ab..96a627c9 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -1427,6 +1427,7 @@ async function doSignMessagesImpl( nIdxCurrentMsgBlockStart, strFromChainName, joExtraSignOpts, + // eslint-disable-next-line n/handle-callback-err fn: fn || async function( err: Error | string | null, jarrMessages: any[], joGlueResult: any | null ) {}, bHaveResultReportCalled: false, diff --git a/src/socket.ts b/src/socket.ts index 64755c0f..f23009a2 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -3197,6 +3197,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); } + // eslint-disable-next-line n/handle-callback-err onError( err: any ) { } disconnect() { From b9722683a04d324a38e4d7a7d74e1d495685d58a Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 11:23:41 +0000 Subject: [PATCH 36/53] ESLint rules simplifications --- src/.eslintrc.cjs | 1 - src/imaTransferErrorHandling.ts | 1 + src/socket.ts | 14 +++++++++++++- src/socketServer.ts | 2 ++ 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index c426edd6..9e7a8114 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -54,7 +54,6 @@ module.exports = { "@typescript-eslint/no-non-null-asserted-nullish-coalescing": "off", "@typescript-eslint/prefer-nullish-coalescing": "off", "@typescript-eslint/strict-boolean-expressions": "off", - "@typescript-eslint/no-dynamic-delete": "off", "@typescript-eslint/no-this-alias": "off", "@typescript-eslint/lines-between-class-members": "off", "@typescript-eslint/prefer-optional-chain": "off" diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index b0526bee..4a62b9fd 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -56,6 +56,7 @@ export function saveTransferError( strCategory: string, textLog: any, ts?: any ) export function saveTransferSuccess( strCategory: string ): void { const c = verifyTransferErrorCategoryName( strCategory ); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete try { delete gMapTransferErrorCategories["" + c]; } catch ( err ) { } saveTransferEvents.dispatchEvent( new UniversalDispatcherEvent( diff --git a/src/socket.ts b/src/socket.ts index f23009a2..a6bde653 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -146,6 +146,7 @@ export class BasicServerAcceptor extends EventDispatcher { pair.serverPipe = null; pair.clientPipe = null; } + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapClients[key]; } } @@ -584,6 +585,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { this.strEndPoint.length > 0 ) { if( this.strEndPoint in gMapLocalServers ) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapLocalServers[this.strEndPoint]; } super.dispose(); @@ -641,6 +643,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.isDisposing = true; this.performDisconnect(); if( this.clientPort in gMapAwaitingInWorkerClients ) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapAwaitingInWorkerClients[this.clientPort]; super.dispose(); } @@ -648,6 +651,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { if( !this.isConnected ) return; this.isConnected = false; + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapConnectedInWorkerClients["" + this.clientPort]; this.fnSend( this.worker, "inWorkerDisconnect", this.strEndPoint, this.clientPort, {} ); this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); @@ -657,6 +661,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.url = ""; } performSuccessfulConnection() { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapAwaitingInWorkerClients[this.clientPort]; gMapConnectedInWorkerClients["" + this.clientPort] = this; this.isConnected = true; @@ -1317,6 +1322,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { this.strEndPoint.length > 0 ) { if( this.strEndPoint in gMapLocalServers ) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapLocalServers[this.strEndPoint]; } super.dispose(); @@ -2281,6 +2287,7 @@ export class RTCServerPeer extends RTCConnection { if( this.idOffer && this.idOffer in this.rtcCreator.mapServerOffers ) { if( settings.logging.net.signaling.offerUnregister ) console.log( "Unregister offer", this.idOffer, "(RTCServerPeer dispose)" ); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.rtcCreator.mapServerOffers[this.idOffer]; } this.idOffer = 0; @@ -2288,8 +2295,8 @@ export class RTCServerPeer extends RTCConnection { this.idOffer = 0; if( this.idSomebodyOtherSide != null ) { if( this.idSomebodyOtherSide in this.rtcCreator.mapServerPeers ) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.rtcCreator.mapServerPeers[this.idSomebodyOtherSide]; - this.idSomebodyOtherSide = null; } this.rtcCreator = null; @@ -2464,12 +2471,14 @@ export class RTCServerPeer extends RTCConnection { console.log( "Unregister offer", this.idOffer, "due to RTCServerPeer error:", err ); } + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.rtcCreator.mapServerOffers[this.idOffer]; } this.idOffer = 0; } if( this.idSomebodyOtherSide != null ) { if( this.idSomebodyOtherSide in this.rtcCreator.mapServerPeers ) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.rtcCreator.mapServerPeers[this.idSomebodyOtherSide]; this.idSomebodyOtherSide = null; } @@ -2630,6 +2639,7 @@ export class RTCCreator extends RTCActor { "Unregister offer", idOffer, "(onOtherSideIdentified in RTCCreator)" ); } + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapServerOffers[idOffer]; this.mapServerPeers["" + idSomebodyOtherSide] = rtcPeer; rtcPeer.onOtherSideIdentified( "" + idSomebodyOtherSide ); @@ -3378,12 +3388,14 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } detachPendingOffer( idOffer: any ) { if( idOffer in this.mapPendingOffers ) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapPendingOffers[idOffer]; } disposePendingOffer( idOffer: any ) { if( idOffer in this.mapPendingOffers ) { const rtcPeer = this.mapPendingOffers[idOffer]; rtcPeer.dispose(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapPendingOffers[idOffer]; } } diff --git a/src/socketServer.ts b/src/socketServer.ts index 445ae6e8..fd5c37f6 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -72,6 +72,7 @@ export class SocketServer extends EventDispatcher { _offAllPipeEventListeners(); _offAllPipeEventListeners = null; } + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete self.mapAcceptedPipes[socket]; }; let _onPipeError: any = function( eventData: any ) { @@ -83,6 +84,7 @@ export class SocketServer extends EventDispatcher { _offAllPipeEventListeners(); _offAllPipeEventListeners = null; } + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete self.mapAcceptedPipes[socket]; }; let _onPipeMessage: any = function( eventData: any ) { From c18c9747a50dc765c0093ed78b1c0ffe51bc55cb Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 13:41:31 +0000 Subject: [PATCH 37/53] ESLint rules simplifications --- src/.eslintrc.cjs | 1 - src/bls.ts | 106 +++++---- src/cc.ts | 6 +- src/cli.ts | 118 +++++----- src/clpTools.ts | 135 +++++------ src/discoveryTools.ts | 44 ++-- src/eventDispatcher.ts | 18 +- src/imaCore.ts | 29 +-- src/imaEthOperations.ts | 16 +- src/imaEventLogScan.ts | 16 +- src/imaGasUsageOperations.ts | 2 +- src/imaHelperAPIs.ts | 7 +- src/imaOracleOperations.ts | 10 +- src/imaRegistrationOperations.ts | 10 +- src/imaReimbursementOperations.ts | 16 +- src/imaSgxExternalSigner.ts | 8 +- src/imaTokenOperations.ts | 42 ++-- src/imaTransferErrorHandling.ts | 2 +- src/imaTx.ts | 41 ++-- src/log.ts | 38 ++-- src/loop.ts | 42 ++-- src/loopWorker.ts | 18 +- src/main.ts | 31 +-- src/observer.ts | 2 +- src/oracle.ts | 10 +- src/pwa.ts | 16 +- src/rpcCall.ts | 91 ++++---- src/socket.ts | 359 +++++++++++++++--------------- src/socketServer.ts | 4 +- src/state.ts | 12 +- src/utils.ts | 10 +- 31 files changed, 664 insertions(+), 596 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 9e7a8114..8155efc7 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -50,7 +50,6 @@ module.exports = { "while": { "before": false, "after": false } } } ], - "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/no-non-null-asserted-nullish-coalescing": "off", "@typescript-eslint/prefer-nullish-coalescing": "off", "@typescript-eslint/strict-boolean-expressions": "off", diff --git a/src/bls.ts b/src/bls.ts index 96a627c9..08a04e85 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -426,7 +426,7 @@ function performBlsGlue( const strActionDir = allocBlsTmpActionDir(); details.trace( "{p}{sunny} will work in {} director with {} sign results...", strLogPrefix, "performBlsGlue", strActionDir, arrSignResults.length ); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; const strOutput = "" @@ -516,7 +516,7 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an const strActionDir = allocBlsTmpActionDir(); details.trace( "{p}performBlsGlueU256 will work in {} director with {} sign results...", strLogPrefix, strActionDir, arrSignResults.length ); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; @@ -608,7 +608,7 @@ function performBlsVerifyI( nThreshold, nParticipants, "BLS verify-I", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; @@ -676,7 +676,7 @@ function performBlsVerifyIU256( nThreshold, nParticipants, "BLS verify-I-U256", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; @@ -733,7 +733,7 @@ function performBlsVerify( nThreshold, nParticipants, "BLS verify", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; @@ -805,7 +805,7 @@ function performBlsVerifyU256( nThreshold, nParticipants, "BLS verify-U256", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; @@ -857,7 +857,7 @@ async function checkCorrectnessOfMessagesToSign( details: log.TLogger, strLogPrefix: string, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, joExtraSignOpts?: loop.TExtraSignOpts | null -) { +): Promise < void > { const imaState: state.TIMAState = state.get(); let joMessageProxy: owaspUtils.ethersMod.ethers.Contract | null = null; let joAccount: state.TAccount | null = null; @@ -952,8 +952,15 @@ async function checkCorrectnessOfMessagesToSign( details.success( "{p}Correctness validation passed for {} message(s)", strLogPrefix, cnt ); } -async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions ) { - optsSignOperation.fn = optsSignOperation.fn || function() {}; +async function prepareSignMessagesImpl( + optsSignOperation: TSignOperationOptions ): Promise < boolean > { + optsSignOperation.fn = optsSignOperation.fn || + // eslint-disable-next-line n/handle-callback-err + async function( + err: Error | string | null, + jarrMessages: any[], + joGlueResult: any | null + ): Promise < void > {}; optsSignOperation.sequenceId = owaspUtils.removeStarting0x( owaspUtils.ethersMod.ethers.utils.id( log.generateTimestampString( null, false ) ) @@ -1035,7 +1042,8 @@ async function prepareSignMessagesImpl( optsSignOperation: TSignOperationOptions return true; } -async function gatherSigningCheckFinish( optsSignOperation: TSignOperationOptions ) { +async function gatherSigningCheckFinish( + optsSignOperation: TSignOperationOptions ): Promise < boolean > { const cntSuccess = optsSignOperation.arrSignResults.length; if( optsSignOperation.joGatheringTracker.nCountReceivedPrevious != optsSignOperation.joGatheringTracker.nCountReceived ) { @@ -1108,7 +1116,8 @@ async function gatherSigningCheckFinish( optsSignOperation: TSignOperationOption return true; } -async function gatherSigningCheckOverflow( optsSignOperation: TSignOperationOptions ) { +async function gatherSigningCheckOverflow( + optsSignOperation: TSignOperationOptions ): Promise < boolean > { if( optsSignOperation.joGatheringTracker.nCountReceived < optsSignOperation.jarrNodes.length ) return false; optsSignOperation.fn( @@ -1128,7 +1137,8 @@ async function gatherSigningCheckOverflow( optsSignOperation: TSignOperationOpti return true; } -async function gatherSigningStartImpl( optsSignOperation: TSignOperationOptions ) { +async function gatherSigningStartImpl( + optsSignOperation: TSignOperationOptions ): Promise < void > { optsSignOperation.details.debug( "{p}Waiting for BLS glue result...", optsSignOperation.strLogPrefix ); optsSignOperation.errGathering = null; @@ -1158,7 +1168,8 @@ async function gatherSigningStartImpl( optsSignOperation: TSignOperationOptions optsSignOperation.bHaveResultReportCalled = true; } -async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions ) { +async function gatherSigningFinishImpl( + optsSignOperation: TSignOperationOptions ): Promise < void > { optsSignOperation.details.trace( "{p}Will await for message BLS verification and sending...", optsSignOperation.strLogPrefix ); if( optsSignOperation.errGathering ) { @@ -1207,7 +1218,8 @@ async function gatherSigningFinishImpl( optsSignOperation: TSignOperationOptions } } -async function doSignConfigureChainAccessParams( optsSignOperation: TSignOperationOptions ) { +async function doSignConfigureChainAccessParams( + optsSignOperation: TSignOperationOptions ): Promise < void > { optsSignOperation.targetChainName = ""; optsSignOperation.fromChainName = ""; optsSignOperation.targetChainID = -4; @@ -1250,7 +1262,7 @@ async function doSignConfigureChainAccessParams( optsSignOperation: TSignOperati async function doSignProcessHandleCall( optsSignOperation: TSignOperationOptions, joParams: any, joCall: rpcCall.TRPCCall, - joIn: any, joOut: any, i: number ) { + joIn: any, joOut: any, i: number ): Promise < void > { const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignOperation.jarrNodes[i]; @@ -1363,7 +1375,8 @@ async function doSignProcessHandleCall( await joCall.disconnect(); } -async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperationOptions ) { +async function doSignProcessOneImpl( + i: number, optsSignOperation: TSignOperationOptions ): Promise < void > { const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignOperation.jarrNodes[i]; @@ -1384,7 +1397,7 @@ async function doSignProcessOneImpl( i: number, optsSignOperation: TSignOperatio optsSignOperation.strLogPrefix, strNodeDescColorized, err, optsSignOperation.sequenceId ); if( joCall ) - joCall.disconnect().then( function() {} ).catch( function() {} ); + joCall.disconnect().then( function(): void {} ).catch( function(): void {} ); } ); if( !joCall ) return; @@ -1418,7 +1431,7 @@ async function doSignMessagesImpl( nTransferLoopCounter: number, strDirection: string, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages -) { +): Promise < void > { const optsSignOperation: TSignOperationOptions = { imaState: state.get(), nTransferLoopCounter, @@ -1489,7 +1502,7 @@ async function doSignMessagesImpl( break; } doSignProcessOneImpl( i, optsSignOperation ) - .then( function() {} ).catch( function( err ) { + .then( function(): void {} ).catch( function( err ): void { log.error( "Failed single BLS sign processing, reported error is: {err}", err ); } ); @@ -1530,7 +1543,8 @@ async function doSignMessagesImpl( export async function doSignMessagesM2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages +): Promise < void > { await doSignMessagesImpl( nTransferLoopCounter, "M2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1540,7 +1554,8 @@ export async function doSignMessagesM2S( export async function doSignMessagesS2M( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages +): Promise < void > { await doSignMessagesImpl( nTransferLoopCounter, "S2M", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, @@ -1550,14 +1565,15 @@ export async function doSignMessagesS2M( export async function doSignMessagesS2S( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, strFromChainName: string, - joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages ) { + joExtraSignOpts?: loop.TExtraSignOpts | null, fn?: IMA.TFunctionAfterSigningMessages +): Promise < void > { await doSignMessagesImpl( nTransferLoopCounter, "S2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, joExtraSignOpts, fn ) } -async function prepareSignU256( optsSignU256: TSignU256Options ) { +async function prepareSignU256( optsSignU256: TSignU256Options ): Promise < boolean > { optsSignU256.details.debug( "{p}Will sign {} value...", optsSignU256.strLogPrefix, optsSignU256.u256 ); optsSignU256.details.trace( "{p}Will query to sign {} skaled node(s)...", @@ -1590,7 +1606,8 @@ async function prepareSignU256( optsSignU256: TSignU256Options ) { } async function doSignU256OneImplHandleCallResult( - i: number, optsSignU256: TSignU256Options, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + i: number, optsSignU256: TSignU256Options, joCall: rpcCall.TRPCCall, joIn: any, joOut: any +): Promise < void > { const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignU256.jarrNodes[i]; @@ -1690,7 +1707,8 @@ async function doSignU256OneImplHandleCallResult( await joCall.disconnect(); } -async function doSignU256OneImpl( i: number, optsSignU256: TSignU256Options ) { +async function doSignU256OneImpl( + i: number, optsSignU256: TSignU256Options ): Promise < boolean> { const imaState: state.TIMAState = state.get(); const isThisNode = ( i == imaState.nNodeNumber ); const joNode = optsSignU256.jarrNodes[i]; @@ -1715,6 +1733,7 @@ async function doSignU256OneImpl( i: number, optsSignU256: TSignU256Options ) { }; const joOut = await joCall.call( joIn ); await doSignU256OneImplHandleCallResult( i, optsSignU256, joCall, joIn, joOut ); + return true; } catch ( err ) { ++optsSignU256.joGatheringTracker.nCountReceived; ++optsSignU256.joGatheringTracker.nCountErrors; @@ -1728,7 +1747,8 @@ async function doSignU256OneImpl( i: number, optsSignU256: TSignU256Options ) { } } -async function gatherSigningCheckFinish256( optsSignU256: TSignU256Options ) { +async function gatherSigningCheckFinish256( + optsSignU256: TSignU256Options ): Promise < boolean > { const cntSuccess = optsSignU256.arrSignResults.length; if( optsSignU256.joGatheringTracker.nCountReceivedPrevious != optsSignU256.joGatheringTracker.nCountReceived ) { @@ -1792,7 +1812,8 @@ async function gatherSigningCheckFinish256( optsSignU256: TSignU256Options ) { return true; } -async function gatherSigningCheckOverflow256( optsSignU256: TSignU256Options ) { +async function gatherSigningCheckOverflow256( + optsSignU256: TSignU256Options ): Promise < boolean > { if( optsSignU256.joGatheringTracker.nCountReceived < optsSignU256.jarrNodes.length ) return false; optsSignU256.fn( @@ -1812,7 +1833,7 @@ async function gatherSigningCheckOverflow256( optsSignU256: TSignU256Options ) { return true; } -async function doSignU256Gathering( optsSignU256: TSignU256Options ) { +async function doSignU256Gathering( optsSignU256: TSignU256Options ): Promise < void > { optsSignU256.details.debug( "{p}Waiting for BLS glue result ", optsSignU256.strLogPrefix ); optsSignU256.errGathering = null; for( let idxStep = 0; idxStep < optsSignU256.joGatheringTracker.nWaitIntervalMaxSteps; @@ -1843,7 +1864,7 @@ async function doSignU256Gathering( optsSignU256: TSignU256Options ) { } export async function doSignU256( u256: any, details: log.TLogger, - fn: IMA.TFunctionAfterSigningMessages ) { + fn: IMA.TFunctionAfterSigningMessages ): Promise < void > { const optsSignU256: TSignU256Options = { u256, fn, @@ -1870,7 +1891,7 @@ export async function doSignU256( u256: any, details: log.TLogger, optsSignU256.jarrNodes = optsSignU256.imaState.joSChainNetworkInfo.network; optsSignU256.details.trace( "{p}Invoking signing u256 procedure...", optsSignU256.strLogPrefix ); - optsSignU256.fn = optsSignU256.fn || function() {}; + optsSignU256.fn = optsSignU256.fn || function(): void {}; if( !( optsSignU256.imaState.strPathBlsGlue.length > 0 && optsSignU256.imaState.joSChainNetworkInfo @@ -1898,7 +1919,7 @@ export async function doSignU256( u256: any, details: log.TLogger, export async function doVerifyReadyHash( strMessageHash: string, nZeroBasedNodeIndex: number, signature: any, isExposeOutput: boolean -) { +): Promise < boolean > { const imaState: state.TIMAState = state.get(); const strDirection = "RAW"; const strLogPrefix = `${strDirection}/BLS/#${nZeroBasedNodeIndex}: `; @@ -1920,7 +1941,7 @@ export async function doVerifyReadyHash( nThreshold, nParticipants, "verify ready hash", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function() { + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; @@ -1974,7 +1995,7 @@ async function doSignReadyHashHandleCallResult( strLogPrefix: string, details: log.TLogger, strMessageHash: string, isExposeOutput: boolean, joCall: rpcCall.TRPCCall, joIn: any, joOut: any -) { +): Promise < object > { details.trace( "{p}Call to ", "SGX done, answer is: {}", strLogPrefix, joOut ); let joSignResult: TSignResult = joOut; if( joOut.result != null && joOut.result != undefined && @@ -2004,7 +2025,8 @@ async function doSignReadyHashHandleCallResult( return joSignResult; } -export async function doSignReadyHash( strMessageHash: string, isExposeOutput: any ) { +export async function doSignReadyHash( + strMessageHash: string, isExposeOutput: any ): Promise < boolean > { const imaState: state.TIMAState = state.get(); const strLogPrefix = ""; const details: log.TLogger = log.createMemoryStream(); @@ -2080,7 +2102,7 @@ export async function doSignReadyHash( strMessageHash: string, isExposeOutput: a } async function prepareHandlingOfSkaleImaVerifyAndSign( - optsHandleVerifyAndSign: THandleVerifyAndSignOptions ) { + optsHandleVerifyAndSign: THandleVerifyAndSignOptions ): Promise < boolean > { optsHandleVerifyAndSign.details.debug( "{p}Will verify and sign {}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.joCallData ); optsHandleVerifyAndSign.nIdxCurrentMsgBlockStart = @@ -2137,7 +2159,7 @@ async function prepareHandlingOfSkaleImaVerifyAndSign( } async function prepareS2sOfSkaleImaVerifyAndSign( - optsHandleVerifyAndSign: THandleVerifyAndSignOptions ) { + optsHandleVerifyAndSign: THandleVerifyAndSignOptions ): Promise < void > { const strSChainNameSrc = optsHandleVerifyAndSign.joCallData.params.srcChainName; const strSChainNameDst = optsHandleVerifyAndSign.joCallData.params.dstChainName; optsHandleVerifyAndSign.details.trace( @@ -2182,7 +2204,7 @@ async function prepareS2sOfSkaleImaVerifyAndSign( async function handleBlsSignMessageHashResult( optsHandleVerifyAndSign: THandleVerifyAndSignOptions, joCallData: THandleVerifyAndSignCallData, joAccount: state.TAccount, joCall: rpcCall.TRPCCall, joIn: any, joOut: any -) { +): Promise < void > { optsHandleVerifyAndSign.details.trace( "{p}{bright} Call to SGX done, " + "answer is: {}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.strDirection, joOut ); @@ -2225,7 +2247,8 @@ async function handleBlsSignMessageHashResult( return joSignResult; } -export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndSignCallData ) { +export async function handleSkaleImaVerifyAndSign( + joCallData: THandleVerifyAndSignCallData ): Promise < object | null > { const optsHandleVerifyAndSign: THandleVerifyAndSignOptions = { joCallData, imaState: state.get(), @@ -2318,7 +2341,7 @@ export async function handleSkaleImaVerifyAndSign( joCallData: THandleVerifyAndS return optsHandleVerifyAndSign.joRetVal; } -async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { +async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ): Promise < boolean > { optsBSU256.details.debug( "{p}Will U256-BLS-sign {}", optsBSU256.strLogPrefix, optsBSU256.joCallData ); if( !optsBSU256.imaState.joSChainNetworkInfo ) @@ -2358,7 +2381,7 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ) { async function handleBlsSignMessageHash256Result( optsBSU256: TBSU256Options, joCallData: TBSU256CallData, joCall: rpcCall.TRPCCall, joIn: any, joOut: any -) { +): Promise < object > { optsBSU256.details.trace( "{p}Call to SGX done, answer is: {}", optsBSU256.strLogPrefix, joOut ); let joSignResult: TSignResult = joOut; @@ -2396,7 +2419,8 @@ async function handleBlsSignMessageHash256Result( return joSignResult; } -export async function handleSkaleImaBSU256( joCallData: TBSU256CallData ) { +export async function handleSkaleImaBSU256( + joCallData: TBSU256CallData ): Promise < object | null > { const optsBSU256: TBSU256Options = { joCallData, imaState: state.get(), diff --git a/src/cc.ts b/src/cc.ts index 77e0b2d0..15c0e481 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -49,7 +49,7 @@ export function replaceAll( str: string, find: string, replace: string ): string return str.replace( new RegExp( find, "g" ), replace ); } -export function validateRadix( value?: any, radix?: any ) { +export function validateRadix( value?: any, radix?: any ): number { value = "" + ( value ? value.toString() : "10" ); value = value.trim(); radix = ( radix == null || radix == undefined ) @@ -189,7 +189,7 @@ const gArrRainbowParts: any[] = [ gMapColorDefinitions.fgMagenta ]; -export function rainbowPart( s: string, i: number ) { +export function rainbowPart( s: string, i: number ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); const j = i % gArrRainbowParts.length; @@ -861,7 +861,7 @@ export function strval( s?: any ): string { return "" + fgYellow + s + reset; } -export function n2s( n: any, sz: number ) { +export function n2s( n: any, sz: number ): string { let s = "" + n; while( s.length < sz ) s = "0" + s; diff --git a/src/cli.ts b/src/cli.ts index 0b0cfeb0..4a5254eb 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -45,7 +45,7 @@ const gStrVersion = function att( ...args: any[] ): string { return log.fmtAttention( ...args ); }; -export function printAbout( isLog?: boolean ) { +export function printAbout( isLog?: boolean ): boolean { isLog = isLog || false; const strMsg = log.fmtTrace( att( gStrAppName ), " version ", log.fmtNotice( gStrVersion ) ); if( isLog ) @@ -55,7 +55,7 @@ export function printAbout( isLog?: boolean ) { return true; } -export function parseCommandLineArgument( s: string ) { +export function parseCommandLineArgument( s: string ): any { const joArg = { name: "", value: "" @@ -81,7 +81,7 @@ export function parseCommandLineArgument( s: string ) { export function ensureHaveValue( name: string, value: any, isExitIfEmpty: boolean, isPrintValue: boolean, fnNameColorizer?: any, fnValueColorizer?: any -) { +): boolean { isExitIfEmpty = isExitIfEmpty || false; isPrintValue = isPrintValue || false; fnNameColorizer = fnNameColorizer || ( ( x: any ) => { @@ -111,7 +111,7 @@ export function ensureHaveValue( export function ensureHaveCredentials( strFriendlyChainName: string, joAccount: state.TAccount, isExitIfEmpty: boolean, isPrintValue: boolean -) { +): boolean { strFriendlyChainName = strFriendlyChainName || ""; if( !( typeof joAccount === "object" ) ) { log.error( "ARGUMENTS VALIDATION WARNING: bad account specified for {} chain", @@ -198,7 +198,7 @@ export function ensureHaveCredentials( return true; } -export function findNodeIndex( joSChainNodeConfiguration: any ) { +export function findNodeIndex( joSChainNodeConfiguration: any ): number { try { const searchID = joSChainNodeConfiguration.skaleConfig.nodeInfo.nodeID; const cnt = joSChainNodeConfiguration.skaleConfig.sChain.nodes.length; @@ -211,7 +211,7 @@ export function findNodeIndex( joSChainNodeConfiguration: any ) { return 0; } -function parseHelp( imaState: state.TIMAState, joArg: any ) { // exits process on "--help" +function parseHelp( imaState: state.TIMAState, joArg: any ): boolean { // exits process on "--help" if( joArg.name != "help" ) return false; printAbout(); @@ -222,14 +222,15 @@ function parseHelp( imaState: state.TIMAState, joArg: any ) { // exits process o process.exit( 0 ); } -function parseVersion( imaState: state.TIMAState, joArg: any ) { // exits process on "--version" +function parseVersion( imaState: state.TIMAState, joArg: any ): boolean { + // exits process on "--version" if( joArg.name != "version" ) return false; printAbout(); process.exit( 0 ); } -function parseBasicArgs( imaState: state.TIMAState, joArg: any ) { +function parseBasicArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "colors" ) { log.enableColorization( true ); return true; @@ -257,7 +258,7 @@ function parseBasicArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseChainAccessArgs( imaState: state.TIMAState, joArg: any ) { +function parseChainAccessArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); imaState.chainProperties.mn.strURL = joArg.value; @@ -311,7 +312,7 @@ function parseChainAccessArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseTransactionManagerArgs( imaState: state.TIMAState, joArg: any ) { +function parseTransactionManagerArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "tm-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); const strURL = "" + joArg.value; @@ -351,7 +352,7 @@ function parseTransactionManagerArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseSgxArgs( imaState: state.TIMAState, joArg: any ) { +function parseSgxArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "sgx-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); imaState.chainProperties.mn.joAccount.strSgxURL = joArg.value; @@ -476,7 +477,7 @@ function parseSgxArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseCredentialsArgs( imaState: state.TIMAState, joArg: any ) { +function parseCredentialsArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "address-main-net" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.chainProperties.mn.joAccount.address_ = joArg.value; @@ -515,7 +516,7 @@ function parseCredentialsArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseAbiArgs( imaState: state.TIMAState, joArg: any ) { +function parseAbiArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "abi-skale-manager" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); imaState.strPathAbiJsonSkaleManager = imaUtils.normalizePath( joArg.value ); @@ -539,7 +540,7 @@ function parseAbiArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseErcArgs( imaState: state.TIMAState, joArg: any ) { +function parseErcArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "erc20-main-net" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); imaState.chainProperties.mn.strPathJsonErc20 = imaUtils.normalizePath( joArg.value ); @@ -624,7 +625,7 @@ function parseErcArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseTransactionArgs( imaState: state.TIMAState, joArg: any ) { +function parseTransactionArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "sleep-between-tx" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaHelperAPIs.setSleepBetweenTransactionsOnSChainMilliseconds( joArg.value ); @@ -722,7 +723,7 @@ function parseTransactionArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parsePaymentAmountArgs( imaState: state.TIMAState, joArg: any ) { +function parsePaymentAmountArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "value" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = owaspUtils.parseMoneySpecToWei( "" + joArg.value, true ); @@ -793,7 +794,7 @@ function parsePaymentAmountArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseTransferArgs( imaState: state.TIMAState, joArg: any ) { +function parseTransferArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "s2s-forward" ) { imaHelperAPIs.setForwardS2S(); return true; @@ -961,7 +962,7 @@ function parseTransferArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseMulticallArgs( imaState: state.TIMAState, joArg: any ) { +function parseMulticallArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "enable-multicall" ) { imaState.isEnabledMultiCall = true; return true; @@ -973,7 +974,7 @@ function parseMulticallArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parsePendingWorkAnalysisArgs( imaState: state.TIMAState, joArg: any ) { +function parsePendingWorkAnalysisArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "pwa" ) { imaState.isPWA = true; return true; @@ -998,7 +999,7 @@ function parsePendingWorkAnalysisArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseLoggingArgs( imaState: state.TIMAState, joArg: any ) { +function parseLoggingArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "gathered" ) { imaState.isPrintGathered = true; return true; @@ -1049,7 +1050,7 @@ function parseLoggingArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseBlsArgs( imaState: state.TIMAState, joArg: any ) { +function parseBlsArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "sign-messages" ) { imaState.bSignMessages = true; return true; @@ -1072,7 +1073,7 @@ function parseBlsArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseMonitoringArgs( imaState: state.TIMAState, joArg: any ) { +function parseMonitoringArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "monitoring-port" ) { owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nMonitoringPort = owaspUtils.toInteger( joArg.value ); @@ -1086,7 +1087,7 @@ function parseMonitoringArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseReimbursementArgs( imaState: state.TIMAState, joArg: any ) { +function parseReimbursementArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "reimbursement-chain" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.strReimbursementChain = joArg.value.trim(); @@ -1120,7 +1121,7 @@ function parseReimbursementArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseOracleArgs( imaState: state.TIMAState, joArg: any ) { +function parseOracleArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "enable-oracle" ) { imaOracleOperations.setEnabledOracle( true ); return true; @@ -1132,7 +1133,7 @@ function parseOracleArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseNetworkDiscoveryArgs( imaState: state.TIMAState, joArg: any ) { +function parseNetworkDiscoveryArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "network-browser-path" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.optsS2S.strNetworkBrowserPath = "" + joArg.value; @@ -1141,7 +1142,7 @@ function parseNetworkDiscoveryArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseBlockScannerArgs( imaState: state.TIMAState, joArg: any ) { +function parseBlockScannerArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "bs-step-size" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaHelperAPIs.setBlocksCountInInIterativeStepOfEventsScan( @@ -1164,7 +1165,7 @@ function parseBlockScannerArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseJsonRpcServerArgs( imaState: state.TIMAState, joArg: any ) { +function parseJsonRpcServerArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "json-rpc-port" ) { owaspUtils.verifyArgumentIsIntegerIpPortNumber( joArg ); imaState.nJsonRpcPort = owaspUtils.toInteger( joArg.value ); @@ -1173,7 +1174,7 @@ function parseJsonRpcServerArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseCrossImaCommunicationArgs( imaState: state.TIMAState, joArg: any ) { +function parseCrossImaCommunicationArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "cross-ima" ) { imaState.isCrossImaBlsMode = true; return true; @@ -1185,7 +1186,7 @@ function parseCrossImaCommunicationArgs( imaState: state.TIMAState, joArg: any ) return false; } -function parseShowConfigArgs( imaState: state.TIMAState, joArg: any ) { +function parseShowConfigArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "show-config" ) { imaState.bShowConfigMode = true; return true; @@ -1193,7 +1194,7 @@ function parseShowConfigArgs( imaState: state.TIMAState, joArg: any ) { return false; } -function parseOtherArgs( imaState: state.TIMAState, joArg: any ) { +function parseOtherArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "auto-exit" ) { owaspUtils.verifyArgumentIsInteger( joArg ); imaState.nAutoExitAfterSeconds = owaspUtils.toInteger( joArg.value ); @@ -1202,7 +1203,7 @@ function parseOtherArgs( imaState: state.TIMAState, joArg: any ) { return false; } -export function parse( joExternalHandlers: any, argv?: any[] ) { +export function parse( joExternalHandlers: any, argv?: any[] ): number { const imaState: state.TIMAState = state.get(); argv = argv || process.argv; const cntArgs = argv.length; @@ -1293,7 +1294,7 @@ export function parse( joExternalHandlers: any, argv?: any[] ) { return 0; } -async function asyncCheckUrlAtStartup( u: URL | string, name: string ) { +async function asyncCheckUrlAtStartup( u: URL | string, name: string ): Promise < boolean > { const details = log.createMemoryStream(); const nTimeoutMilliseconds = 10 * 1000; try { @@ -1315,7 +1316,7 @@ async function asyncCheckUrlAtStartup( u: URL | string, name: string ) { return false; } -function commonInitPrintSysInfo() { +function commonInitPrintSysInfo(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( isPrintGathered ) { @@ -1360,7 +1361,7 @@ function commonInitPrintSysInfo() { } } -function commonInitCheckAbiPaths() { +function commonInitCheckAbiPaths(): void { const imaState: state.TIMAState = state.get(); if( imaState.strPathAbiJsonSkaleManager && ( typeof imaState.strPathAbiJsonSkaleManager === "string" ) && @@ -1414,7 +1415,7 @@ function commonInitCheckAbiPaths() { } } -function commonInitCheckContractPresences() { +function commonInitCheckContractPresences(): void { const imaState: state.TIMAState = state.get(); if( imaState.bHaveSkaleManagerABI ) { imaUtils.checkKeysExistInABI( "skale-manager", @@ -1513,7 +1514,7 @@ function commonInitCheckContractPresences() { } } -function commonInitPrintFoundContracts() { +function commonInitPrintFoundContracts(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); // deposit_box_eth_address --> deposit_box_eth_abi @@ -1532,7 +1533,8 @@ function commonInitPrintFoundContracts() { // message_proxy_chain_address --> message_proxy_chain_abi const oct = function( - joContract?: owaspUtils.ethersMod.ethers.Contract | null ) { // optional contract address + joContract?: owaspUtils.ethersMod.ethers.Contract | null ): string { + // optional contract address if( joContract && "address" in joContract && joContract.address ) return log.fmtInformation( "{}", joContract.address ); return log.fmtError( "contract is not available" ); @@ -1617,7 +1619,7 @@ function commonInitPrintFoundContracts() { } } -function commonInitCheckErc20() { +function commonInitCheckErc20(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); let n1 = 0; @@ -1773,7 +1775,7 @@ function commonInitCheckErc20() { } } -function commonInitCheckErc721() { +function commonInitCheckErc721(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); let n1 = 0; @@ -1931,7 +1933,7 @@ function commonInitCheckErc721() { } } -function commonInitCheckErc1155() { +function commonInitCheckErc1155(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); let n1 = 0; @@ -2090,7 +2092,7 @@ function commonInitCheckErc1155() { } } -function commonInitCheckGeneralArgs() { +function commonInitCheckGeneralArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); const isPrintSecurityValues = ( !!( imaState.isPrintSecurityValues ) ); @@ -2209,7 +2211,7 @@ function commonInitCheckGeneralArgs() { } catch ( err ) {} } -function commonInitCheckCredentialsArgs() { +function commonInitCheckCredentialsArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); const isPrintSecurityValues = ( !!( imaState.isPrintSecurityValues ) ); @@ -2260,7 +2262,7 @@ function commonInitCheckCredentialsArgs() { } } -function commonInitCheckTransferAmountArgs() { +function commonInitCheckTransferAmountArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( @@ -2270,7 +2272,7 @@ function commonInitCheckTransferAmountArgs() { } ); } -function commonInitTransferringArgs() { +function commonInitTransferringArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( @@ -2378,7 +2380,7 @@ function commonInitTransferringArgs() { } } -function commonInitCheckAccessArgs() { +function commonInitCheckAccessArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); ensureHaveValue( @@ -2393,7 +2395,7 @@ function commonInitCheckAccessArgs() { } ); } -function commonInitErcTokensArgs() { +function commonInitErcTokensArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { @@ -2516,7 +2518,7 @@ function commonInitErcTokensArgs() { } } -function commonInitGasMultipliersAndTransactionArgs() { +function commonInitGasMultipliersAndTransactionArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( isPrintGathered ) { @@ -2599,7 +2601,7 @@ function commonInitGasMultipliersAndTransactionArgs() { } } -function commonInitLoggingArgs() { +function commonInitLoggingArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); if( imaState.strLogFilePath.length > 0 ) { @@ -2624,7 +2626,7 @@ function commonInitLoggingArgs() { } } -function commonInitAutomaticExitArgs() { +function commonInitAutomaticExitArgs(): void { const imaState: state.TIMAState = state.get(); const isPrintGathered = ( !!( imaState.isPrintGathered ) ); const isPrintSecurityValues = ( !!( imaState.isPrintSecurityValues ) ); @@ -2634,7 +2636,7 @@ function commonInitAutomaticExitArgs() { isPrintGathered && isPrintSecurityValues ); } -export function commonInit() { +export function commonInit(): void { const imaState: state.TIMAState = state.get(); commonInitPrintSysInfo(); commonInitCheckAbiPaths(); @@ -2655,14 +2657,15 @@ export function commonInit() { } } // commonInit -export function imaInitEthersProviders() { +export function imaInitEthersProviders(): void { const imaState: state.TIMAState = state.get(); if( imaState.chainProperties.mn.strURL && typeof imaState.chainProperties.mn.strURL === "string" && imaState.chainProperties.mn.strURL.length > 0 ) { const u = imaState.chainProperties.mn.strURL; - asyncCheckUrlAtStartup( u, "Main-net" ).then( function() {} ).catch( function() {} ); + asyncCheckUrlAtStartup( u, "Main-net" ) + .then( function(): void {} ).catch( function(): void {} ); imaState.chainProperties.mn.ethersProvider = owaspUtils.getEthersProviderFromURL( u ); } else { log.warning( "No Main-net URL specified in command line arguments" + @@ -2674,7 +2677,8 @@ export function imaInitEthersProviders() { imaState.chainProperties.sc.strURL.length > 0 ) { const u = imaState.chainProperties.sc.strURL; - asyncCheckUrlAtStartup( u, "S-Chain" ).then( function() {} ).catch( function() {} ); + asyncCheckUrlAtStartup( u, "S-Chain" ) + .then( function(): void {} ).catch( function(): void {} ); imaState.chainProperties.sc.ethersProvider = owaspUtils.getEthersProviderFromURL( u ); } else { log.warning( "No S-Chain URL specified in command line arguments" + @@ -2687,7 +2691,7 @@ export function imaInitEthersProviders() { ) { const u = imaState.chainProperties.tc.strURL; asyncCheckUrlAtStartup( u, "S<->S Target S-Chain" ) - .then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); imaState.chainProperties.tc.ethersProvider = owaspUtils.getEthersProviderFromURL( u ); } else { log.warning( "No S<->S Target S-Chain URL specified in command line arguments" + @@ -2695,7 +2699,7 @@ export function imaInitEthersProviders() { } } // imaInitEthersProviders -function initContractsIMA() { +function initContractsIMA(): void { const imaState: state.TIMAState = state.get(); if( imaState.chainProperties.mn.bHaveAbiIMA ) { const cp = imaState.chainProperties.mn; @@ -2853,7 +2857,7 @@ function initContractsIMA() { } } -function initContractsSkaleManager() { +function initContractsSkaleManager(): void { const imaState: state.TIMAState = state.get(); if( imaState.bHaveSkaleManagerABI ) { const cp = imaState.chainProperties.mn; @@ -2914,7 +2918,7 @@ function initContractsSkaleManager() { } } -export function initContracts() { +export function initContracts(): void { imaInitEthersProviders(); initContractsIMA(); initContractsSkaleManager(); diff --git a/src/clpTools.ts b/src/clpTools.ts index c2551e7d..e970b0ce 100644 --- a/src/clpTools.ts +++ b/src/clpTools.ts @@ -42,7 +42,7 @@ import * as imaUtils from "./utils.js"; import * as imaBLS from "./bls.js"; import type * as imaTx from "./imaTx.js"; -export async function registerAll( isPrintSummaryRegistrationCosts: boolean ) { +export async function registerAll( isPrintSummaryRegistrationCosts: boolean ): Promise < boolean > { if( !await registerStep1( false ) ) return false; if( isPrintSummaryRegistrationCosts ) @@ -50,7 +50,7 @@ export async function registerAll( isPrintSummaryRegistrationCosts: boolean ) { return true; } -export async function checkRegistrationAll() { +export async function checkRegistrationAll(): Promise { const b1 = await checkRegistrationStep1(); return b1; } @@ -65,7 +65,7 @@ const gInfoRegistrationCost: TRegistrationCostInformation = { sc: [] }; -export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) { +export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ): Promise { const imaState: state.TIMAState = state.get(); imaCLI.initContracts(); const strLogPrefix = "Reg 1: "; @@ -116,7 +116,7 @@ export async function registerStep1( isPrintSummaryRegistrationCosts: boolean ) return true; } -export async function checkRegistrationStep1() { +export async function checkRegistrationStep1(): Promise { const imaState: state.TIMAState = state.get(); imaCLI.initContracts(); if( !imaState.chainProperties.mn.ethersProvider ) @@ -130,7 +130,7 @@ export async function checkRegistrationStep1() { return bRetVal; } -export function printSummaryRegistrationCosts( details?: any ) { +export function printSummaryRegistrationCosts( details?: any ): void { if( !details ) details = log; imaGasUsage.printGasUsageReportFromArray( @@ -139,11 +139,11 @@ export function printSummaryRegistrationCosts( details?: any ) { "S-Chain REGISTRATION", gInfoRegistrationCost.sc, details ); } -export function commandLineTaskRegister() { +export function commandLineTaskRegister(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Full registration(all steps)", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // registerAll return await registerAll( true ); @@ -151,11 +151,11 @@ export function commandLineTaskRegister() { } ); } -export function commandLineTaskRegister1() { +export function commandLineTaskRegister1(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Registration step 1, register S-Chain in deposit box", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // registerStep1 return await registerStep1( true ); @@ -163,11 +163,11 @@ export function commandLineTaskRegister1() { } ); } -export function commandLineTaskCheckRegistration() { +export function commandLineTaskCheckRegistration(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Full registration status check(all steps)", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // checkRegistrationAll const b = await checkRegistrationAll(); @@ -179,11 +179,11 @@ export function commandLineTaskCheckRegistration() { } ); } -export function commandLineTaskCheckRegistration1() { +export function commandLineTaskCheckRegistration1(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Registration status check step 1, register S-Chain in deposit box", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // checkRegistrationStep1 const b = await checkRegistrationStep1(); @@ -195,11 +195,11 @@ export function commandLineTaskCheckRegistration1() { } ); } -export function commandLineTaskMintErc20() { +export function commandLineTaskMintErc20(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "mint ERC20", - fn: async function() { + fn: async function(): Promise < boolean > { let bMintIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { try { @@ -230,11 +230,11 @@ export function commandLineTaskMintErc20() { } ); } -export function commandLineTaskMintErc721() { +export function commandLineTaskMintErc721(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "mint ERC721", - fn: async function() { + fn: async function(): Promise < boolean > { let bMintIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc721.length > 0 ) { try { @@ -276,11 +276,11 @@ export function commandLineTaskMintErc721() { } ); } -export function commandLineTaskMintErc1155() { +export function commandLineTaskMintErc1155(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "mint ERC1155", - fn: async function() { + fn: async function(): Promise < boolean > { let bMintIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc1155.length > 0 ) { try { @@ -325,11 +325,11 @@ export function commandLineTaskMintErc1155() { } ); } -export function commandLineTaskBurnErc20() { +export function commandLineTaskBurnErc20(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "burn ERC20", - fn: async function() { + fn: async function(): Promise < boolean > { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc20.length > 0 ) { try { @@ -362,11 +362,11 @@ export function commandLineTaskBurnErc20() { } ); } -export function commandLineTaskBurnErc721() { +export function commandLineTaskBurnErc721(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "burn ERC721", - fn: async function() { + fn: async function(): Promise < boolean > { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc721.length > 0 ) { try { @@ -407,11 +407,11 @@ export function commandLineTaskBurnErc721() { } ); } -export function commandLineTaskBurnErc1155() { +export function commandLineTaskBurnErc1155(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "burn ERC1155", - fn: async function() { + fn: async function(): Promise < boolean > { let bBurnIsOK = false; if( imaState.chainProperties.tc.strCoinNameErc1155.length > 0 ) { try { @@ -458,7 +458,7 @@ export function commandLineTaskBurnErc1155() { export async function commandLineTaskShowBalanceEth( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[] -) { +): Promise { const imaState: state.TIMAState = state.get(); let assetAddress: string | null = null; if( imaState.chainProperties.mn.ethersProvider ) { @@ -521,7 +521,7 @@ export async function commandLineTaskShowBalanceEth( export async function commandLineTaskShowBalanceErc20( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[] -) { +): Promise { const imaState: state.TIMAState = state.get(); let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider && @@ -582,7 +582,7 @@ export async function commandLineTaskShowBalanceErc20( export async function commandLineTaskShowBalanceErc721( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[], idTokens: any[] -) { +): Promise { const imaState: state.TIMAState = state.get(); let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider && @@ -655,7 +655,7 @@ export async function commandLineTaskShowBalanceErc721( export async function commandLineTaskShowBalanceErc1155( arrBalancesMN: any[], arrBalancesSC: any[], arrBalancesTC: any[], idTokens: any[] -) { +): Promise { const imaState: state.TIMAState = state.get(); let assetAddress = null; if( imaState.chainProperties.mn.ethersProvider && @@ -726,11 +726,11 @@ export async function commandLineTaskShowBalanceErc1155( } } -export function commandLineTaskShowBalance() { +export function commandLineTaskShowBalance(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "show balance", - fn: async function() { + fn: async function(): Promise < boolean > { const arrBalancesMN: any = []; const arrBalancesSC: any = []; const arrBalancesTC: any = []; await commandLineTaskShowBalanceEth( @@ -787,11 +787,11 @@ export function commandLineTaskShowBalance() { } ); } -export function commandLineTaskPaymentM2S() { +export function commandLineTaskPaymentM2S(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "one M->S single payment", - fn: async function() { + fn: async function(): Promise < boolean > { if( imaState.chainProperties.mn.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one M->S single ERC721 payment: {}", imaState.idToken ); @@ -980,11 +980,11 @@ export function commandLineTaskPaymentM2S() { } ); } -export function commandLineTaskPaymentS2M() { +export function commandLineTaskPaymentS2M(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "one S->M single payment", - fn: async function() { + fn: async function(): Promise < boolean > { if( imaState.chainProperties.sc.strCoinNameErc721.length > 0 ) { // ERC721 payment log.information( "one S->M single ERC721 payment: {}", imaState.idToken ); @@ -1175,11 +1175,11 @@ export function commandLineTaskPaymentS2M() { } ); } -export function commandLineTaskPaymentS2S() { +export function commandLineTaskPaymentS2S(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "one S->S single payment", - fn: async function() { + fn: async function(): Promise < boolean > { const isForward = imaHelperAPIs.isForwardS2S(); const sc = imaState.chainProperties.sc; const tc = imaState.chainProperties.tc; const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = @@ -1365,11 +1365,11 @@ export function commandLineTaskPaymentS2S() { } ); } -export function commandLineTaskReceiveS2M() { +export function commandLineTaskReceiveS2M(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "receive one S->M single ETH payment", - fn: async function() { + fn: async function(): Promise < boolean > { log.information( "receive one S->M single ETH payment:" ); if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); @@ -1386,11 +1386,11 @@ export function commandLineTaskReceiveS2M() { } ); } -export function commandLineTaskViewS2M() { +export function commandLineTaskViewS2M(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "view one S->M single ETH payment", - fn: async function() { + fn: async function(): Promise < boolean > { log.information( "view one S->M single ETH payment:" ); log.information( "receive one S->M single ETH payment:" ); if( !imaState.chainProperties.mn.ethersProvider ) @@ -1412,11 +1412,11 @@ export function commandLineTaskViewS2M() { } ); } -export function commandLineTaskTransferM2S() { +export function commandLineTaskTransferM2S(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "single M->S transfer loop", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // main-net --> s-chain transfer const joRuntimeOpts: loop.TRuntimeOpts = { @@ -1460,11 +1460,11 @@ export function commandLineTaskTransferM2S() { } ); } -export function commandLineTaskTransferS2M() { +export function commandLineTaskTransferS2M(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "single S->M transfer loop", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // s-chain --> main-net transfer const joRuntimeOpts: loop.TRuntimeOpts = { @@ -1508,11 +1508,11 @@ export function commandLineTaskTransferS2M() { } ); } -export function commandLineTaskTransferS2S() { +export function commandLineTaskTransferS2S(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "single S->S transfer loop", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.optsS2S.isEnabled ) return true; if( !imaState.bNoWaitSChainStarted ) @@ -1550,11 +1550,11 @@ export function commandLineTaskTransferS2S() { } ); } -export function commandLineTaskTransfer() { +export function commandLineTaskTransfer(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Single M<->S transfer loop iteration", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); const joRuntimeOpts: loop.TRuntimeOpts = { @@ -1575,11 +1575,11 @@ export function commandLineTaskTransfer() { } ); } -export function commandLineTaskLoop() { +export function commandLineTaskLoop(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "M<->S and S->S transfer loop, startup in parallel mode", - fn: async function() { + fn: async function(): Promise < boolean > { state.setPreventExitAfterLastAction( true ); if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // M<->S transfer loop @@ -1600,11 +1600,11 @@ export function commandLineTaskLoop() { } ); } -export function commandLineTaskLoopSimple() { +export function commandLineTaskLoopSimple(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "M<->S and S->S transfer loop, startup simple mode", - fn: async function() { + fn: async function(): Promise < boolean > { state.setPreventExitAfterLastAction( true ); if( !imaState.bNoWaitSChainStarted ) await discoveryTools.waitUntilSChainStarted(); // M<->S transfer loop @@ -1635,7 +1635,8 @@ export function commandLineTaskLoopSimple() { } async function handleBrowseSkaleModesRpcInfoResult( - strLogPrefix: string, joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + strLogPrefix: string, joCall: rpcCall.TRPCCall, joIn: any, joOut: any +): Promise { const imaState: state.TIMAState = state.get(); log.information( "{p}S-Chain network information: {}", strLogPrefix, joOut.result ); @@ -1670,7 +1671,7 @@ async function handleBrowseSkaleModesRpcInfoResult( process.exit( 159 ); } } - const iv = setInterval( function() { + const iv = setInterval( function(): void { if( nCountReceivedImaDescriptions == jarrNodes.length ) { clearInterval( iv ); process.exit( 0 ); @@ -1679,12 +1680,12 @@ async function handleBrowseSkaleModesRpcInfoResult( await joCall.disconnect(); } -export function commandLineTaskBrowseSChain() { +export function commandLineTaskBrowseSChain(): void { const imaState: state.TIMAState = state.get(); imaState.bIsNeededCommonInit = false; imaState.arrActions.push( { name: "Browse S-Chain network", - fn: async function() { + fn: async function(): Promise < boolean > { const strLogPrefix = "S-Chain Browse: "; if( imaState.chainProperties.sc.strURL.length === 0 ) { log.fatal( "Missing S-Chain URL, please specify {}", "--url-s-chain" ); @@ -1715,11 +1716,11 @@ export function commandLineTaskBrowseSChain() { } ); } -export function commandLineTaskReimbursementShowBalance() { +export function commandLineTaskReimbursementShowBalance(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Show Balance", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); if( !imaState.joCommunityPool ) @@ -1739,11 +1740,11 @@ export function commandLineTaskReimbursementShowBalance() { } ); } -export function commandLineTaskReimbursementEstimateAmount() { +export function commandLineTaskReimbursementEstimateAmount(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Estimate Amount", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); if( !imaState.joCommunityPool ) @@ -1763,11 +1764,11 @@ export function commandLineTaskReimbursementEstimateAmount() { } ); } -export function commandLineTaskReimbursementRecharge() { +export function commandLineTaskReimbursementRecharge(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Recharge User Wallet", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); if( !imaState.joCommunityPool ) @@ -1787,11 +1788,11 @@ export function commandLineTaskReimbursementRecharge() { } ); } -export function commandLineTaskReimbursementWithdraw() { +export function commandLineTaskReimbursementWithdraw(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Withdraw User Wallet", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.chainProperties.mn.ethersProvider ) throw new Error( "No provider for MN" ); if( !imaState.joCommunityPool ) @@ -1811,11 +1812,11 @@ export function commandLineTaskReimbursementWithdraw() { } ); } -export function commandLineTaskReimbursementSetRange() { +export function commandLineTaskReimbursementSetRange(): void { const imaState: state.TIMAState = state.get(); imaState.arrActions.push( { name: "Gas Reimbursement - Set Minimal time interval from S2M and S2S transfers", - fn: async function() { + fn: async function(): Promise < boolean > { if( !imaState.chainProperties.sc.ethersProvider ) throw new Error( "No provider for SC" ); if( !imaState.joCommunityLocker ) diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 633a148f..6f3c4056 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -231,7 +231,7 @@ export function getSChainDiscoveredNodesCount( } } -export async function waitUntilSChainStarted() { +export async function waitUntilSChainStarted(): Promise { const imaState: state.TIMAState = state.get(); log.debug( "Checking S-Chain is accessible and sane..." ); if( ( !imaState.chainProperties.sc.strURL ) || @@ -307,7 +307,8 @@ function composeStillUnknownNodesMessage( } async function handlePeriodicDiscoveryAttemptActions( - isSilentReDiscovery: boolean, fnAfter: TFunctionAfterDiscovery | null ) { + isSilentReDiscovery: boolean, fnAfter: TFunctionAfterDiscovery | null +): Promise { if( gFlagIsInSChainDiscovery ) { log.information( "Notice: long this S-Chain re-discovery is in progress now..." ); return; @@ -315,7 +316,7 @@ async function handlePeriodicDiscoveryAttemptActions( const imaState: state.TIMAState = state.get(); if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); - fnAfter = fnAfter || function() {}; + fnAfter = fnAfter || function(): void {}; gFlagIsInSChainDiscovery = true; const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); try { @@ -378,7 +379,7 @@ async function handlePeriodicDiscoveryAttemptActions( } fnAfter(); continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, null ) - .then( function() {} ).catch( function( err ) { + .then( function(): void {} ).catch( function( err ): void { log.error( "Failed to continue S-chain discovery, reported error is: {err}", err ); } ) @@ -386,17 +387,18 @@ async function handlePeriodicDiscoveryAttemptActions( gFlagIsInSChainDiscovery = false; // fnAfter() will be called here inside async call at beginning continueSChainDiscoveryInBackgroundIfNeeded( isSilentReDiscovery, fnAfter ) - .then( function() {} ).catch( function( err ) { + .then( function(): void {} ).catch( function( err ): void { log.error( "Failed to continue S-chain discovery, reported error is: {err}", err ); } ); } export async function continueSChainDiscoveryInBackgroundIfNeeded( - isSilentReDiscovery: boolean, fnAfter: TFunctionAfterDiscovery | null ) { + isSilentReDiscovery: boolean, fnAfter: TFunctionAfterDiscovery | null +): Promise { if( gTimerSChainDiscovery != null ) return; - fnAfter = fnAfter || function() {}; + fnAfter = fnAfter || function(): void {}; const imaState: state.TIMAState = state.get(); if( imaState.joSChainDiscovery.repeatIntervalMilliseconds <= 0 ) { if( !isSilentReDiscovery ) @@ -434,9 +436,9 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( "continuing re-discovery.", cntUnDiscoveredYet, cntNodesOnChain ); } } - gTimerSChainDiscovery = setInterval( function() { + gTimerSChainDiscovery = setInterval( function(): void { handlePeriodicDiscoveryAttemptActions( isSilentReDiscovery, fnAfter ) - .then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); }, imaState.joSChainDiscovery.periodicDiscoveryInterval ); } @@ -454,7 +456,7 @@ function handleDiscoverSkaleImaInfoResult( } } -async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { +async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ): Promise { optsDiscover.cntFailed = 0; for( let i = 0; i < optsDiscover.cntNodes; ++i ) { const nCurrentNodeIdx = 0 + i; @@ -507,7 +509,7 @@ async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ) { } } -async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { +async function discoverSChainWait( optsDiscover: TDiscoveryOptions ): Promise { if( !optsDiscover.isSilentReDiscovery ) { log.debug( "{p}Waiting for response from at least {} node(s)...", optsDiscover.strLogPrefix, optsDiscover.nCountToWait ); @@ -519,7 +521,7 @@ async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { nWaitStepMilliseconds ) - 3; if( cntWaitAttempts < 1 ) cntWaitAttempts = 1; - const iv = setInterval( function() { + const iv = setInterval( function(): void { optsDiscover.nCountAvailable = optsDiscover.cntNodes - optsDiscover.cntFailed; // notice, below provided up-to-date count of available and fully discovered nodes: @@ -577,7 +579,7 @@ async function discoverSChainWait( optsDiscover: TDiscoveryOptions ) { async function handleDiscoverSkaleNodesRpcInfoResult( optsDiscover: TDiscoveryOptions, scURL: string, - joCall: rpcCall.TRPCCall, joIn: any, joOut: any ) { + joCall: rpcCall.TRPCCall, joIn: any, joOut: any ): Promise { if( !optsDiscover.isSilentReDiscovery ) { log.trace( "{p}OK, got (own) S-Chain network information: {}", optsDiscover.strLogPrefix, joOut.result ); @@ -633,7 +635,7 @@ async function handleDiscoverSkaleNodesRpcInfoResult( throw err; } let rv = false; - await discoverSChainWait( optsDiscover ).then( function() { + await discoverSChainWait( optsDiscover ).then( function(): void { if( optsDiscover.fnAfter ) optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); rv = true; @@ -648,7 +650,8 @@ async function handleDiscoverSkaleNodesRpcInfoResult( export async function discoverSChainNetwork( fnAfter: TFunctionAfterDiscovery | null, isSilentReDiscovery: boolean, - joPrevSChainNetworkInfo: any, nCountToWait: number ) { + joPrevSChainNetworkInfo: any, nCountToWait: number +): Promise { const optsDiscover: TDiscoveryOptions = { fnAfter, isSilentReDiscovery: ( !!isSilentReDiscovery ), @@ -707,7 +710,8 @@ export async function discoverSChainNetwork( let gIntervalPeriodicDiscovery: any = null; function checkPeriodicDiscoveryNoLongerNeeded( - joSChainNetworkInfo: TSChainNetworkInfo | null, isSilentReDiscovery: boolean ) { + joSChainNetworkInfo: TSChainNetworkInfo | null, isSilentReDiscovery: boolean +): boolean { if( !joSChainNetworkInfo ) return false; const imaState: state.TIMAState = state.get(); @@ -731,7 +735,7 @@ function checkPeriodicDiscoveryNoLongerNeeded( export async function doPeriodicSChainNetworkDiscoveryIfNeeded( isSilentReDiscovery: boolean, fnAfterRediscover?: TFunctionAfterRediscovery -) { +): Promise { if( gIntervalPeriodicDiscovery ) return; // already started const imaState: state.TIMAState = state.get(); @@ -753,7 +757,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( periodicDiscoveryInterval ); } fnAfterRediscover = fnAfterRediscover || function( status: boolean ) { }; - gIntervalPeriodicDiscovery = setInterval( function() { + gIntervalPeriodicDiscovery = setInterval( function(): void { let nCountToWait = ( cntNodesOnChain > 2 ) ? Math.ceil( cntNodesOnChain * 2 / 3 ) : cntNodesOnChain; @@ -763,7 +767,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( log.information( "This S-Chain discovery will be done for periodic discovery update" ); discoverSChainNetwork( null, isSilentReDiscovery, joPrevSChainNetworkInfo, nCountToWait ) - .then( function() { + .then( function(): void { joPrevSChainNetworkInfo = imaState.joSChainNetworkInfo; if( checkPeriodicDiscoveryNoLongerNeeded( joPrevSChainNetworkInfo, isSilentReDiscovery ) ) { @@ -777,7 +781,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( log.information( "Partial periodic S-Chain re-discovery done" ); if( fnAfterRediscover ) fnAfterRediscover( false ); - } ).catch( function() {} ); + } ).catch( function(): void {} ); }, periodicDiscoveryInterval ); if( !isSilentReDiscovery ) { log.information( "Periodic S-Chain re-discovery was started with interval {}" + diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index 93388bd9..72aa71dc 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -48,7 +48,7 @@ export class EventDispatcher { this.isDisposed = false; this.isDisposing = false; } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -58,10 +58,10 @@ export class EventDispatcher { ); this.removeAllEventListeners(); } - hasEventListener( type: any, listener: any ) { + hasEventListener( type: any, listener: any ): boolean { return this._listeners.some( item => item.type === type && item.listener === listener ); } - addEventListener( type: any, listener: any ) { + addEventListener( type: any, listener: any ): EventDispatcher { if( !this.hasEventListener( type, listener ) ) { this._listeners.push( { type, @@ -71,7 +71,7 @@ export class EventDispatcher { } return this; } - removeEventListener( type: any, listener: any ) { + removeEventListener( type: any, listener: any ): EventDispatcher { while( true ) { const index = ( listener != undefined ) ? this._listeners.findIndex( @@ -86,20 +86,20 @@ export class EventDispatcher { } return this; } - removeAllEventListeners() { + removeAllEventListeners(): EventDispatcher { this._listeners = []; return this; } - on( type: any, listener: any ) { + on( type: any, listener: any ): EventDispatcher { return this.addEventListener( type, listener ); } - off( type: any, listener: any ) { + off( type: any, listener: any ): EventDispatcher { return this.removeEventListener( type, listener ); } - offAll() { + offAll(): EventDispatcher { return this.removeAllEventListeners(); } - dispatchEvent( evt: any ) { + dispatchEvent( evt: any ): EventDispatcher { const a = this._listeners.filter( item => item.type === evt.type ); for( const item of a ) { const { diff --git a/src/imaCore.ts b/src/imaCore.ts index f4019ac5..e3986839 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -113,7 +113,7 @@ async function findOutReferenceLogRecord( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joMessageProxy: owaspUtils.ethersMod.ethers.Contract, bnBlockId: any, nMessageNumberToFind: number, isVerbose?: boolean -) { +): Promise { const bnMessageNumberToFind = owaspUtils.toBN( nMessageNumberToFind.toString() ); const strEventName = "PreviousMessageReference"; const arrLogRecords = await imaEventLogScan.safeGetPastEventsProgressive( @@ -157,7 +157,7 @@ async function findOutAllReferenceLogRecords( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joMessageProxy: owaspUtils.ethersMod.ethers.Contract, bnBlockId: any, nIncMsgCnt: number, nOutMsgCnt: number, isVerbose?: boolean -) { +): Promise { if( isVerbose ) { details.debug( "{p}Optimized IMA message search algorithm will start at block {}" + @@ -220,7 +220,7 @@ let gTransferLoopCounter = 0; // [to] // address[] memory to // [amount] // uint256[] memory amount / *uint256[2] memory blsSignature* / // ) -async function doQueryOutgoingMessageCounter( optsTransfer: TTransferOptions ) { +async function doQueryOutgoingMessageCounter( optsTransfer: TTransferOptions ): Promise { let nPossibleIntegerValue = 0; optsTransfer.details.debug( "{p}SRC MessageProxy address is.....{}", optsTransfer.strLogPrefixShort, optsTransfer.joMessageProxySrc.address ); @@ -328,7 +328,7 @@ async function doQueryOutgoingMessageCounter( optsTransfer: TTransferOptions ) { return true; } -async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ) { +async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ): Promise { let joValues: any = null; const strChainHashWeAreLookingFor = owaspUtils.ethersMod.ethers.utils.id( optsTransfer.chainNameDst ); @@ -373,7 +373,7 @@ async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ) return joValues; } -async function gatherMessages( optsTransfer: TTransferOptions ) { +async function gatherMessages( optsTransfer: TTransferOptions ): Promise { optsTransfer.arrMessageCounters = []; optsTransfer.jarrMessages = []; optsTransfer.nIdxCurrentMsgBlockStart = 0 + optsTransfer.nIdxCurrentMsg; @@ -523,7 +523,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ) { async function preCheckAllMessagesSign( optsTransfer: TTransferOptions, err: Error | string | null, - jarrMessages: any[], joGlueResult: any ) { + jarrMessages: any[], joGlueResult: any ): Promise { const strDidInvokedSigningCallbackMessage = log.fmtDebug( "{p}Did invoked message signing callback, first real message index is: {}, have {} " + "message(s) to process {}", optsTransfer.strLogPrefix, @@ -549,7 +549,7 @@ async function preCheckAllMessagesSign( async function callbackAllMessagesSign( optsTransfer: TTransferOptions, err: Error | string | null, - jarrMessages: any[], joGlueResult: any ) { + jarrMessages: any[], joGlueResult: any ): Promise { if( !await preCheckAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ) ) return; const nBlockSize = optsTransfer.arrMessageCounters.length; @@ -629,7 +629,7 @@ async function callbackAllMessagesSign( optsTransfer.joAccountDst, optsTransfer.strActionName, gasPrice, estimatedGasPostIncomingMessages, weiHowMuchPostIncomingMessages, opts ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { optsTransfer.jarrReceipts.push( { description: "doTransfer/postIncomingMessages()", "optsTransfer.detailsString": @@ -692,7 +692,7 @@ async function callbackAllMessagesSign( } } -async function handleAllMessagesSigning( optsTransfer: TTransferOptions ) { +async function handleAllMessagesSigning( optsTransfer: TTransferOptions ): Promise { try { let strErrFinal: string = ""; await optsTransfer.fnSignMessages( optsTransfer.nTransferLoopCounter, @@ -723,7 +723,8 @@ async function handleAllMessagesSigning( optsTransfer: TTransferOptions ) { async function checkOutgoingMessageEventInOneNode( optsTransfer: TTransferOptions, - optsOutgoingMessageAnalysis: TOutgoingMessageAnalysisOptions ) { + optsOutgoingMessageAnalysis: TOutgoingMessageAnalysisOptions +): Promise { if( !optsOutgoingMessageAnalysis.joNode ) { optsTransfer.details.error( "{p}{bright} no S-Chain node provided", @@ -817,7 +818,7 @@ async function checkOutgoingMessageEventInOneNode( } async function checkOutgoingMessageEvent( - optsTransfer: TTransferOptions, joSChain: skaleObserver.TSChainInformation ) { + optsTransfer: TTransferOptions, joSChain: skaleObserver.TSChainInformation ): Promise { const cntNodes = joSChain.nodes.length; const cntMessages = optsTransfer.jarrMessages.length; for( let idxMessage = 0; idxMessage < cntMessages; ++idxMessage ) { @@ -894,7 +895,7 @@ async function checkOutgoingMessageEvent( return true; } -async function doMainTransferLoopActions( optsTransfer: TTransferOptions ) { +async function doMainTransferLoopActions( optsTransfer: TTransferOptions ): Promise { // classic scanner with optional usage of optimized IMA messages search algorithm // outer loop is block former/creator, then transfer optsTransfer.nIdxCurrentMsg = optsTransfer.nIncMsgCnt; @@ -1019,7 +1020,7 @@ export async function doTransfer( nBlockAwaitDepth: number, nBlockAge: number, fnSignMessages: TFunctionDoSignMessages, joExtraSignOpts: loop.TExtraSignOpts | null, transactionCustomizerDst: imaTx.TransactionCustomizer -) { +): Promise { const optsTransfer: TTransferOptions = { strDirection, joRuntimeOpts, @@ -1191,7 +1192,7 @@ export async function doAllS2S( // s-chain --> s-chain nBlockAge: number, fnSignMessages: TFunctionDoSignMessages, transactionCustomizerDst: imaTx.TransactionCustomizer -) { +): Promise { let cntOK = 0; let cntFail = 0; let nIndexS2S = 0; const sc = imaState.chainProperties.sc; const strDirection = "S2S"; diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index cbb89913..1b367255 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -38,7 +38,7 @@ export async function getBalanceEth( chainId: string, joAccount: state.TAccount | null, contractERC20: owaspUtils.ethersMod.Contract | null -) { +): Promise { const strLogPrefix = "getBalanceEth() call "; try { if( !( ethersProvider && joAccount ) ) @@ -77,7 +77,7 @@ export async function doEthPaymentFromMainNet( chainIdSChain: string, weiHowMuch: any, // how much WEI money to send transactionCustomizerMainNet: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any[] = []; let strActionName = ""; @@ -112,7 +112,7 @@ export async function doEthPaymentFromMainNet( "DepositBox", joDepositBox, "deposit", arrArguments, joAccountSrc, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "doEthPaymentFromMainNet", receipt: joReceipt @@ -173,7 +173,7 @@ export async function doEthPaymentFromSChain( joMessageProxySChain: owaspUtils.ethersMod.ethers.Contract, // for checking logs weiHowMuch: any, // how much WEI money to send transactionCustomizerSChain: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -209,7 +209,7 @@ export async function doEthPaymentFromSChain( "TokenManagerETH", joTokenManagerETH, "exitToMain", arrArguments, joAccountSrc, strActionName, gasPrice, estimatedGas, 0, opts ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "doEthPaymentFromSChain", receipt: joReceipt @@ -259,7 +259,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( joAccountMN: state.TAccount, joDepositBoxETH: owaspUtils.ethersMod.ethers.Contract, transactionCustomizerMainNet: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -293,7 +293,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( "getMyEth", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "receiveEthPaymentFromSchainOnMainNet", receipt: joReceipt @@ -318,7 +318,7 @@ export async function viewEthPaymentFromSchainOnMainNet( ethersProviderMainNet: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joAccountMN: state.TAccount, joDepositBoxETH: owaspUtils.ethersMod.ethers.Contract -) { +): Promise { const details = log.createMemoryStream(); const strActionName = ""; const strLogPrefix = "S ETH View: "; diff --git a/src/imaEventLogScan.ts b/src/imaEventLogScan.ts index 74ac16d9..4bce7eab 100644 --- a/src/imaEventLogScan.ts +++ b/src/imaEventLogScan.ts @@ -29,7 +29,9 @@ import * as rpcCall from "./rpcCall.js"; import * as imaHelperAPIs from "./imaHelperAPIs.js"; import * as imaTransferErrorHandling from "./imaTransferErrorHandling.js"; -export function createProgressiveEventsScanPlan( details: log.TLogger, nLatestBlockNumber: any ) { +export function createProgressiveEventsScanPlan( + details: log.TLogger, nLatestBlockNumber: any +): any[] { // assume Main Net mines 6 blocks per minute const blocksInOneMinute = 6; const blocksInOneHour = blocksInOneMinute * 60; @@ -89,7 +91,7 @@ export async function safeGetPastEventsProgressive( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, attempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any -) { +): Promise { const strURL = owaspUtils.ethersProviderToUrl( ethersProvider ); details.information( "{p}Will run progressive logs search for event {} via URL {url}, " + "from block {}, to block...", strLogPrefix, strEventName, strURL, nBlockFrom, nBlockTo ); @@ -169,7 +171,7 @@ export async function getContractCallEvents( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockNumber: any, strTxHash: string, joFilter: any -) { +): Promise { joFilter = joFilter || {}; nBlockNumber = owaspUtils.toBN( nBlockNumber ); const n10 = owaspUtils.toBN( 10 ); @@ -200,7 +202,7 @@ export async function safeGetTransactionCount( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, address: string, param: any, retValOnFail: any, throwIfServerOffline: boolean -) { +): Promise { const strFnName = "getTransactionCount"; const u = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; @@ -246,7 +248,7 @@ export async function safeGetTransactionReceipt( details: log.TLogger, cntAttempts: number, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, txHash: string, retValOnFail?: any, throwIfServerOffline?: boolean -) { +): Promise { const strFnName = "getTransactionReceipt"; const u = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; @@ -294,7 +296,7 @@ export async function safeGetPastEvents( cntAttempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any, retValOnFail?: any, throwIfServerOffline?: boolean -) { +): Promise { const u = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; if( throwIfServerOffline == null || throwIfServerOffline == undefined ) @@ -372,7 +374,7 @@ export async function safeGetPastEventsIterative( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, attempts: number, joContract: owaspUtils.ethersMod.ethers.Contract, strEventName: string, nBlockFrom: any, nBlockTo: any, joFilter: any -) { +): Promise { if( imaHelperAPIs.getBlocksCountInInIterativeStepOfEventsScan() <= 0 || imaHelperAPIs.getMaxIterationsInAllRangeEventsScan() <= 0 ) { details.warning( diff --git a/src/imaGasUsageOperations.ts b/src/imaGasUsageOperations.ts index 7f1e17d7..10e49ccd 100644 --- a/src/imaGasUsageOperations.ts +++ b/src/imaGasUsageOperations.ts @@ -46,7 +46,7 @@ export function composeGasUsageReportFromArray( strName: string, jarrReceipts: a } export function printGasUsageReportFromArray( - strName: string, jarrReceipts: any[], details?: any ) { + strName: string, jarrReceipts: any[], details?: any ): void { details = details || log; const jo: any = composeGasUsageReportFromArray( strName, jarrReceipts ); if( jo.strReport && typeof jo.strReport === "string" && jo.strReport.length > 0 && diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index a6ef5e17..ac2fe602 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -53,7 +53,7 @@ export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ): export function getWaitForNextBlockOnSChain(): boolean { return ( !!gFlagWaitForNextBlockOnSChain ); } -export function setWaitForNextBlockOnSChain( val: any ) { +export function setWaitForNextBlockOnSChain( val: any ): void { gFlagWaitForNextBlockOnSChain = ( !!val ); } @@ -62,7 +62,8 @@ export const currentTimestamp = (): number => { }; export async function safeWaitForNextBlockToAppear( - details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider ) { + details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider +): Promise { const nBlockNumber: any = owaspUtils.toBN( await safeGetBlockNumber( details, 10, ethersProvider ) ); details.trace( "Waiting for next block to appear..." ); @@ -81,7 +82,7 @@ export async function safeGetBlockNumber( details: log.TLogger, cntAttempts: number, ethersProvider: owaspUtils.ethersMod.providers.JsonRpcProvider, retValOnFail?: any, throwIfServerOffline?: boolean -) { +): Promise { const strFnName: string = "getBlockNumber"; const u: string = owaspUtils.ethersProviderToUrl( ethersProvider ); const nWaitStepMilliseconds = 10 * 1000; diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 0424e672..52f629eb 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -65,7 +65,9 @@ export function setEnabledOracle( isEnabled: boolean ): void { gFlagIsEnabledOracle = ( !!isEnabled ); } -async function prepareOracleGasPriceSetup( optsGasPriceSetup: TGasPriceSetupOptions ) { +async function prepareOracleGasPriceSetup( + optsGasPriceSetup: TGasPriceSetupOptions +): Promise { optsGasPriceSetup.strActionName = "prepareOracleGasPriceSetup.optsGasPriceSetup.latestBlockNumber()"; optsGasPriceSetup.latestBlockNumber = @@ -157,7 +159,7 @@ async function prepareOracleGasPriceSetup( optsGasPriceSetup: TGasPriceSetupOpti async function handleOracleSigned( optsGasPriceSetup: TGasPriceSetupOptions, strError: Error | string | null, - u256: any, joGlueResult: any | null ) { + u256: any, joGlueResult: any | null ): Promise { if( strError ) { optsGasPriceSetup.details.critical( "{p}Error in doOracleGasPriceSetup() during {bright}: {err}", @@ -230,7 +232,7 @@ async function handleOracleSigned( "setGasPrice", arrArgumentsSetGasPrice, optsGasPriceSetup.joAccountSC, optsGasPriceSetup.strActionName, gasPrice, estimatedGasSetGasPrice, weiHowMuch, opts ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { optsGasPriceSetup.jarrReceipts.push( { description: "doOracleGasPriceSetup/setGasPrice", receipt: joReceipt @@ -251,7 +253,7 @@ export async function doOracleGasPriceSetup( chainIdMainNet: string, chainIdSChain: string, fnSignMsgOracle: TFunctionSignMsgOracle -) { +): Promise { if( !getEnabledOracle() ) return true; const optsGasPriceSetup: TGasPriceSetupOptions = { diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index f67d16ad..7d623325 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -36,7 +36,7 @@ export async function invokeHasChain( joLinker: owaspUtils.ethersMod.Contract, // Main-Net or S-Chin joAccount: state.TAccount, // Main-Net or S-Chin chainIdSChain: string -) { +): Promise { const strLogPrefix = "Wait for added chain status: "; const strActionName = "invokeHasChain(hasSchain): joLinker.hasSchain"; try { @@ -61,7 +61,7 @@ export async function waitForHasChain( chainIdSChain: string, cntWaitAttempts?: number, nSleepMilliseconds?: number -) { +): Promise { if( !cntWaitAttempts ) cntWaitAttempts = 100; if( !nSleepMilliseconds ) @@ -84,7 +84,7 @@ export async function checkIsRegisteredSChainInDepositBoxes( // step 1 joLinker: owaspUtils.ethersMod.Contract | null, joAccountMN: state.TAccount, chainIdSChain: string -) { +): Promise { const details = log.createMemoryStream(); details.debug( "Main-net Linker address is...........{}", joLinker ? joLinker.address : "N/A" ); details.debug( "S-Chain ID is.......................{}", chainIdSChain ); @@ -135,7 +135,7 @@ export async function registerSChainInDepositBoxes( // step 1 transactionCustomizerMainNet: imaTx.TransactionCustomizer, cntWaitAttempts?: number, nSleepMilliseconds?: number -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any[] = []; details.debug( "Main-net Linker address is..........{}", joLinker ? joLinker.address : "N/A" ); @@ -195,7 +195,7 @@ export async function registerSChainInDepositBoxes( // step 1 "Linker", joLinker, "connectSchain", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "registerSChainInDepositBoxes", receipt: joReceipt diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index 25c7293d..309a9ce0 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -38,7 +38,7 @@ export async function reimbursementShowBalance( transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, isForcePrintOut: boolean -) { +): Promise { const details = log.createMemoryStream(); let s = ""; const strLogPrefix = "Gas Reimbursement - Show Balance "; @@ -79,7 +79,7 @@ export async function reimbursementEstimateAmount( transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, isForcePrintOut: boolean -) { +): Promise { const details = log.createMemoryStream(); let s = ""; const strLogPrefix = "Gas Reimbursement - Estimate Amount To Recharge "; @@ -162,7 +162,7 @@ export async function reimbursementWalletRecharge( transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, nReimbursementRecharge: string | number | null -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -194,7 +194,7 @@ export async function reimbursementWalletRecharge( details, ethersProviderMainNet, "CommunityPool", joCommunityPool, "rechargeUserWallet", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, nReimbursementRecharge, null ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "reimbursementWalletRecharge", receipt: joReceipt @@ -224,7 +224,7 @@ export async function reimbursementWalletWithdraw( transactionCustomizerMainNet: imaTx.TransactionCustomizer, strReimbursementChain: string, nReimbursementWithdraw: string | number | null -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -261,7 +261,7 @@ export async function reimbursementWalletWithdraw( "CommunityPool", joCommunityPool, "withdrawFunds", arrArguments, joAccountMN, strActionName, gasPrice, estimatedGas, weiHowMuch ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "reimbursementWalletWithdraw", receipt: joReceipt @@ -291,7 +291,7 @@ export async function reimbursementSetRange( transactionCustomizerSChain: imaTx.TransactionCustomizer, strChainNameOriginChain: string, nReimbursementRange: any -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -326,7 +326,7 @@ export async function reimbursementSetRange( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, joAccountSC, strActionName, gasPrice, estimatedGas, weiHowMuch, opts ); - if( joReceipt && typeof joReceipt === "object" ) { + if( joReceipt ) { jarrReceipts.push( { description: "reimbursementSetRange", receipt: joReceipt diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 909ad745..1415d648 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -9,13 +9,13 @@ log.addStdout(); // allow self-signed wss and https process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; -function finalizeOutput( jo: any ) { +function finalizeOutput( jo: any ): void { if( !jo ) return; process.stdout.write( log.fmtInformation( "{}", jo ) ); } -function postConvertBN( jo: any, name: any ) { +function postConvertBN( jo: any, name: any ): void { if( !jo ) return; if( !( name in jo ) ) @@ -25,7 +25,7 @@ function postConvertBN( jo: any, name: any ) { jo[name] = owaspUtils.toHexStringSafe( jo[name] ); } -async function run() { +async function run(): Promise { try { if( gIsDebugLogging ) log.debug( "Process startup arguments array is {}", process.argv ); @@ -155,4 +155,4 @@ async function run() { process.exit( 1 ); } } -run().then( function() {} ).catch( function() {} ); +run().then( function(): void {} ).catch( function(): void {} ); diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 8caaf2fa..409de82b 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -39,7 +39,7 @@ export async function getBalanceErc20( joAccount: state.TAccount, strCoinName: string, joABI: any -) { +): Promise { const strLogPrefix = "getBalanceErc20() call "; try { if( !( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in @@ -69,7 +69,7 @@ export async function getOwnerOfErc721( strCoinName: string, joABI: any, idToken: any -) { +): Promise { const strLogPrefix = "getOwnerOfErc721() call "; try { if( !( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in @@ -98,7 +98,7 @@ export async function getBalanceErc1155( strCoinName: string, joABI: any, idToken: any -) { +): Promise { const strLogPrefix = "getBalanceErc1155() call "; try { if( !( ethersProvider && joAccount && strCoinName && joABI && ( strCoinName + "_abi" ) in @@ -138,7 +138,7 @@ export async function doErc721PaymentFromMainNet( strCoinNameErc721SChain: string, erc721PrivateTestnetJsonSChain: any, transactionCustomizerMainNet: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -276,7 +276,7 @@ export async function doErc20PaymentFromMainNet( strCoinNameErc20SChain: string, erc20SChain: any, transactionCustomizerMainNet: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -414,7 +414,7 @@ export async function doErc1155PaymentFromMainNet( strCoinNameErc1155SChain: string, erc1155PrivateTestnetJsonSChain: any, transactionCustomizerMainNet: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -558,7 +558,7 @@ export async function doErc1155BatchPaymentFromMainNet( erc1155PrivateTestnetJsonMainNet: any, strCoinNameErc1155SChain: string, erc1155PrivateTestnetJsonSChain: any, transactionCustomizerMainNet: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -688,7 +688,7 @@ export async function doErc20PaymentFromSChain( strCoinNameErc20SChain: string, joErc20SChain: any, transactionCustomizerSChain: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -832,7 +832,7 @@ export async function doErc721PaymentFromSChain( strCoinNameErc721SChain: string, joErc721SChain: any, transactionCustomizerSChain: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -980,7 +980,7 @@ export async function doErc1155PaymentFromSChain( strCoinNameErc1155SChain: string, joErc1155Chain: any, transactionCustomizerSChain: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -1127,7 +1127,7 @@ export async function doErc1155BatchPaymentFromSChain( strCoinNameErc1155SChain: string, joErc1155Chain: any, transactionCustomizerSChain: imaTx.TransactionCustomizer -) { +): Promise { const details = log.createMemoryStream(); const jarrReceipts: any = []; let strActionName = ""; @@ -1268,7 +1268,7 @@ export async function doErc20PaymentS2S( joSrcErc20: any, ercDstAddress20: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer -) { +): Promise { const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; @@ -1408,7 +1408,7 @@ export async function doErc721PaymentS2S( joSrcErc721: any, ercDstAddress721: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer -) { +): Promise { const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; @@ -1553,7 +1553,7 @@ export async function doErc1155PaymentS2S( joSrcErc1155: any, ercDstAddress1155: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer -) { +): Promise { const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; @@ -1698,7 +1698,7 @@ export async function doErc1155BatchPaymentS2S( joSrcErc1155: any, ercDstAddress1155: any, // only reverse payment needs it tc: imaTx.TransactionCustomizer -) { +): Promise { const isReverse = !isForward; const details = log.createMemoryStream(); const jarrReceipts: any = []; @@ -1841,7 +1841,7 @@ export async function mintErc20( strTokenContractAddress: string, joTokenContractABI: any, tc: imaTx.TransactionCustomizer -) { +): Promise { let strActionName = "mintErc20() init"; const strLogPrefix = "mintErc20() call "; const details = log.createMemoryStream(); @@ -1911,7 +1911,7 @@ export async function mintErc721( strTokenContractAddress: string, joTokenContractABI: any, tc: imaTx.TransactionCustomizer -) { +): Promise { let strActionName = "mintErc721() init"; const strLogPrefix = "mintErc721() call "; const details = log.createMemoryStream(); @@ -1982,7 +1982,7 @@ export async function mintErc1155( strTokenContractAddress: string, joTokenContractABI: any, tc: imaTx.TransactionCustomizer -) { +): Promise { let strActionName = "mintErc1155() init"; const strLogPrefix = "mintErc1155() call "; const details = log.createMemoryStream(); @@ -2055,7 +2055,7 @@ export async function burnErc20( strTokenContractAddress: string, joTokenContractABI: any, tc: imaTx.TransactionCustomizer -) { +): Promise { let strActionName = "burnErc20() init"; const strLogPrefix = "burnErc20() call "; const details = log.createMemoryStream(); @@ -2124,7 +2124,7 @@ export async function burnErc721( strTokenContractAddress: string, joTokenContractABI: any, tc: imaTx.TransactionCustomizer -) { +): Promise { let strActionName = "burnErc721() init"; const strLogPrefix = "burnErc721() call "; const details = log.createMemoryStream(); @@ -2193,7 +2193,7 @@ export async function burnErc1155( strTokenContractAddress: string, joTokenContractABI: any, tc: imaTx.TransactionCustomizer -) { +): Promise { let strActionName = "burnErc1155() init"; const strLogPrefix = "burnErc1155() call "; const details = log.createMemoryStream(); diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 4a62b9fd..7eec71c5 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -26,7 +26,7 @@ import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher.js"; -export function verifyTransferErrorCategoryName( strCategory: string ) { +export function verifyTransferErrorCategoryName( strCategory: string ): string { return "" + ( strCategory || "default" ); } diff --git a/src/imaTx.ts b/src/imaTx.ts index 0013a2f7..b6a22745 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -105,7 +105,7 @@ export async function dryRunCall( joAccount: state.TAccount, strActionName: string, isDryRunResultIgnore: boolean, gasPrice: any, gasValue: any, weiHowMuch: any, opts?: any -) { +): Promise { if( !dryRunIsEnabled() ) return null; // success isDryRunResultIgnore = ( isDryRunResultIgnore != null && isDryRunResultIgnore != undefined ) @@ -152,7 +152,7 @@ export async function dryRunCall( } } -async function payedCallPrepare( optsPayedCall: TRunTimePayedCallOptions ) { +async function payedCallPrepare( optsPayedCall: TRunTimePayedCallOptions ): Promise { optsPayedCall.joACI = getAccountConnectivityInfo( optsPayedCall.joAccount ); if( optsPayedCall.gasPrice ) { optsPayedCall.callOpts.gasPrice = @@ -193,7 +193,7 @@ async function payedCallPrepare( optsPayedCall: TRunTimePayedCallOptions ) { optsPayedCall.txHash ); } -async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ) { +async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ): Promise { const txAdjusted: any = optsPayedCall.unsignedTx; // JSON.parse( JSON.stringify( optsPayedCall.rawTx ) ); const arrNamesConvertToHex = [ "gas", "gasLimit", "optsPayedCall.gasPrice", "value" ]; @@ -233,7 +233,7 @@ async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ) { } } -async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ) { +async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ): Promise { const tx = optsPayedCall.unsignedTx; let { chainId } = await optsPayedCall.ethersProvider.getNetwork(); if( typeof chainId === "string" && chainId ) @@ -275,7 +275,7 @@ async function payedCallSGX( optsPayedCall: TRunTimePayedCallOptions ) { postConvertBN( optsPayedCall.joReceipt, "effectiveGasPrice" ); } -function postConvertBN( jo: any, name: any ) { +function postConvertBN( jo: any, name: any ): void { if( !jo ) return; if( !( name in jo ) ) @@ -285,7 +285,7 @@ function postConvertBN( jo: any, name: any ) { jo[name] = owaspUtils.toBN( jo[name] ); } -async function payedCallDirect( optsPayedCall: TRunTimePayedCallOptions ) { +async function payedCallDirect( optsPayedCall: TRunTimePayedCallOptions ): Promise { const ethersWallet = new owaspUtils.ethersMod.ethers.Wallet( owaspUtils.ensureStartsWith0x( optsPayedCall.joAccount.privateKey ), optsPayedCall.ethersProvider ); @@ -320,7 +320,7 @@ export async function payedCall( joAccount: state.TAccount, strActionName: string, gasPrice: any, estimatedGas: any, weiHowMuch: any, opts?: any -) { +): Promise { const optsPayedCall: TRunTimePayedCallOptions = { details, ethersProvider, @@ -417,7 +417,7 @@ export async function checkTransactionToSchain( details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, joAccount: state.TAccount -) { +): Promise { const strLogPrefix = "PoW-mining: "; try { const strFromAddress = joAccount.address(); // unsignedTx.from; @@ -465,7 +465,8 @@ export async function checkTransactionToSchain( } export async function calculatePowNumber( - address: string, nonce: any, gas: any, details: log.TLogger, strLogPrefix: string ) { + address: string, nonce: any, gas: any, details: log.TLogger, strLogPrefix: string +): Promise { try { let _address = owaspUtils.ensureStartsWith0x( address ); _address = ethereumJsUtilModule.toChecksumAddress( _address ); @@ -485,7 +486,7 @@ export async function calculatePowNumber( } } -export function getAccountConnectivityInfo( joAccount: state.TAccount ) { +export function getAccountConnectivityInfo( joAccount: state.TAccount ): object { const joACI: any = { isBad: true, strType: "bad", @@ -526,7 +527,7 @@ function tmGenerateRandomHex( size: number ): string { .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ) } -function tmMakeId( details: log.TLogger ) { +function tmMakeId( details: log.TLogger ): string { const prefix = "tx-"; const unique = tmGenerateRandomHex( 16 ); const id = prefix + unique + "js"; @@ -534,7 +535,7 @@ function tmMakeId( details: log.TLogger ) { return id; } -function tmMakeRecord( tx: any = {}, score: any ) { +function tmMakeRecord( tx: any = {}, score: any ): any { const status = "PROPOSED"; return JSON.stringify( { score, @@ -543,12 +544,12 @@ function tmMakeRecord( tx: any = {}, score: any ) { } ); } -function tmMakeScore( priority: number ) { +function tmMakeScore( priority: number ): number { const ts = imaHelperAPIs.currentTimestamp(); return priority * Math.pow( 10, ts.toString().length ) + ts; } -async function tmSend( details: log.TLogger, tx: any, priority: number = 5 ) { +async function tmSend( details: log.TLogger, tx: any, priority: number = 5 ): Promise { details.trace( "TM - sending tx {} ts: {}", tx, imaHelperAPIs.currentTimestamp() ); const id = tmMakeId( details ); const score = tmMakeScore( priority ); @@ -562,13 +563,13 @@ async function tmSend( details: log.TLogger, tx: any, priority: number = 5 ) { return id; } -function tmIsFinished( record: any ) { +function tmIsFinished( record: any ): boolean { if( record == null ) return null; return [ "SUCCESS", "FAILED", "DROPPED" ].includes( record.status ); } -async function tmGetRecord( txId: any ) { +async function tmGetRecord( txId: any ): Promise { const r = await redis.get( txId ); if( r != null ) return JSON.parse( r ); @@ -579,7 +580,7 @@ async function tmWait( details: log.TLogger, txId: any, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - nWaitSeconds: number = 36000 ) { + nWaitSeconds: number = 36000 ): Promise { const strLogPrefix = log.fmtDebug( "(gathered details)" ) + " "; details.debug( "{p}TM - will wait TX {} to complete for {} second(s) maximum", strLogPrefix, txId, nWaitSeconds ); @@ -614,7 +615,7 @@ async function tmEnsureTransaction( details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, priority: any, txAdjusted: any, cntAttempts?: number, sleepMilliseconds?: number -) { +): Promise { cntAttempts = cntAttempts || 1; sleepMilliseconds = sleepMilliseconds || ( 30 * 1000 ); let txId = ""; @@ -651,7 +652,7 @@ export class TransactionCustomizer { } async computeGasPrice( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, - maxGasPrice: any ) { + maxGasPrice: any ): Promise { const gasPrice = owaspUtils.parseIntOrHex( owaspUtils.toBN( @@ -684,7 +685,7 @@ export class TransactionCustomizer { joAccount: state.TAccount, strActionName: string, gasPrice: any, gasValueRecommended: any, weiHowMuch: any, opts?: any - ) { + ): Promise { let estimatedGas: any = 0; const strContractMethodDescription = log.fmtDebug( "{p}({}).{sunny}", strContractName, joContract.address, strMethodName ); diff --git a/src/log.ts b/src/log.ts index c55fb25f..b5550c5d 100644 --- a/src/log.ts +++ b/src/log.ts @@ -193,9 +193,9 @@ export function globalStream(): TLogger { strOwnIndent: "", write, writeRaw, - close: function() { }, - open: function() { }, - size: function() { return 0; }, + close: function(): void { }, + open: function(): void { }, + size: function(): number { return 0; }, rotate: function( nBytesToWrite: number ) { }, toString: function(): string { return ""; }, exposeDetailsTo, @@ -246,9 +246,9 @@ export function createStandardOutputStream(): TLogger | null { this.objStream.write( s ); } catch ( err ) { } }, - close: function() { this.objStream = null; }, - open: function() { try { this.objStream = process.stdout; } catch ( err ) { } }, - size: function() { return 0; }, + close: function(): void { this.objStream = null; }, + open: function(): void { try { this.objStream = process.stdout; } catch ( err ) { } }, + size: function(): number { return 0; }, rotate: function( nBytesToWrite: number ) { }, toString: function(): string { return "" + this.strPath; }, exposeDetailsTo: @@ -341,12 +341,12 @@ export function createMemoryOutputStream(): TLogger { haveOwnTimestamps: true, isPausedTimeStamps: false, strOwnIndent: " ", - isBeginningOfAccumulatedLog: function() { + isBeginningOfAccumulatedLog: function(): boolean { if( this.arrAccumulatedLogTextLines.length == 0 ) return true; return false; }, - isLastLineEndsWithCarriageReturn: function() { + isLastLineEndsWithCarriageReturn: function(): boolean { if( this.arrAccumulatedLogTextLines.length == 0 ) return false; const s = this.arrAccumulatedLogTextLines[ @@ -380,10 +380,10 @@ export function createMemoryOutputStream(): TLogger { this.arrAccumulatedLogTextLines.push( strLine + "\n" ); } }, - clear: function() { this.arrAccumulatedLogTextLines = []; }, - close: function() { this.clear(); }, - open: function() { this.clear(); }, - size: function() { return 0; }, + clear: function(): void { this.arrAccumulatedLogTextLines = []; }, + close: function(): void { this.clear(); }, + open: function(): void { this.clear(); }, + size: function(): number { return 0; }, rotate: function( nBytesToWrite: number ) { this.arrAccumulatedLogTextLines = []; }, toString: function(): string { @@ -543,17 +543,17 @@ export function createFileOutput( } } catch ( err ) { } }, - close: function() { + close: function(): void { if( !this.objStream ) return; fs.closeSync( this.objStream ); this.objStream = null; }, - open: function() { + open: function(): void { this.objStream = fs.openSync( this.strPath, "a", fs.constants.O_NONBLOCK | fs.constants.O_RDWR ); }, - size: function() { + size: function(): number { try { return fs.lstatSync( this.strPath ).size; } catch ( err ) { return 0; } }, rotate: function( nBytesToWrite: number ) { @@ -674,7 +674,7 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): s if( !jo ) return strDefaultErrorText; try { - const isError = function( err: Error | string ) { + const isError = function( err: Error | string ): boolean { return err && err instanceof Error && err.stack && err.message; }; if( !isError( jo ) ) { @@ -1018,7 +1018,7 @@ gMapVerbose.set( 7, "notice" ); gMapVerbose.set( 8, "debug" ); gMapVerbose.set( 9, "trace" ); -function computeVerboseAlias() { +function computeVerboseAlias(): Map < string, number > { const m: Map < string, number > = new Map < string, number >(); for( const [ key, val ] of gMapVerbose ) { const name = val; @@ -1067,10 +1067,10 @@ export function verboseName2Number( s: string ): number { let gFlagIsExposeDetails = false; let gVerboseLevel = 0 + verboseName2Number( "information" ); -export function exposeDetailsGet() { +export function exposeDetailsGet(): boolean { return ( !!gFlagIsExposeDetails ); } -export function exposeDetailsSet( isExpose: any ) { +export function exposeDetailsSet( isExpose: any ): void { gFlagIsExposeDetails = ( !!isExpose ); } diff --git a/src/loop.ts b/src/loop.ts index e95d4754..005cc983 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -168,7 +168,8 @@ export function checkTimeFraming( return true; }; -async function singleTransferLoopPartOracle( optsLoop: TLoopOptions, strLogPrefix: string ) { +async function singleTransferLoopPartOracle( + optsLoop: TLoopOptions, strLogPrefix: string ): Promise { const imaState: state.TIMAState = state.get(); let b0 = true; if( optsLoop.enableStepOracle && imaOracleOperations.getEnabledOracle() ) { @@ -219,7 +220,8 @@ async function singleTransferLoopPartOracle( optsLoop: TLoopOptions, strLogPrefi return b0; } -async function singleTransferLoopPartM2S( optsLoop: TLoopOptions, strLogPrefix: string ) { +async function singleTransferLoopPartM2S( + optsLoop: TLoopOptions, strLogPrefix: string ): Promise { const imaState: state.TIMAState = state.get(); let b1 = true; if( optsLoop.enableStepM2S ) { @@ -288,7 +290,8 @@ async function singleTransferLoopPartM2S( optsLoop: TLoopOptions, strLogPrefix: return b1; } -async function singleTransferLoopPartS2M( optsLoop: TLoopOptions, strLogPrefix: string ) { +async function singleTransferLoopPartS2M( + optsLoop: TLoopOptions, strLogPrefix: string ): Promise { const imaState: state.TIMAState = state.get(); let b2 = true; if( optsLoop.enableStepS2M ) { @@ -362,7 +365,8 @@ async function singleTransferLoopPartS2M( optsLoop: TLoopOptions, strLogPrefix: return b2; } -async function singleTransferLoopPartS2S( optsLoop: TLoopOptions, strLogPrefix: string ) { +async function singleTransferLoopPartS2S( + optsLoop: TLoopOptions, strLogPrefix: string ): Promise { const imaState: state.TIMAState = state.get(); let b3 = true; if( optsLoop.enableStepS2S && imaState.optsS2S.isEnabled ) { @@ -405,12 +409,13 @@ async function singleTransferLoopPartS2S( optsLoop: TLoopOptions, strLogPrefix: return b3; } -function printLoopPartSkippedWarning( strLoopPartName: string ) { +function printLoopPartSkippedWarning( strLoopPartName: string ): void { log.warning( "Skipped {} transfer loop part due to other single transfer loop is in " + "progress right now", strLoopPartName ); } -export async function singleTransferLoop( optsLoop: TLoopOptions ) { +export async function singleTransferLoop( + optsLoop: TLoopOptions ): Promise { const imaState: state.TIMAState = state.get(); const strLogPrefix = `Single Loop in ${threadInfo.threadDescription( false )} `; try { @@ -471,19 +476,22 @@ export async function singleTransferLoop( optsLoop: TLoopOptions ) { imaState.loopState.s2s.isInProgress = false; return false; } -export async function singleTransferLoopWithRepeat( optsLoop: TLoopOptions ) { +export async function singleTransferLoopWithRepeat( + optsLoop: TLoopOptions ): Promise { const imaState: state.TIMAState = state.get(); await singleTransferLoop( optsLoop ); - setTimeout( function() { - singleTransferLoopWithRepeat( optsLoop ).then( function() {} ).catch( function() {} ); + setTimeout( function(): void { + singleTransferLoopWithRepeat( optsLoop ) + .then( function(): void {} ).catch( function(): void {} ); }, imaState.nLoopPeriodSeconds * 1000 ); }; -export async function runTransferLoop( optsLoop: TLoopOptions ) { +export async function runTransferLoop( optsLoop: TLoopOptions ): Promise { const imaState: state.TIMAState = state.get(); const isDelayFirstRun = owaspUtils.toBoolean( optsLoop.isDelayFirstRun ); if( isDelayFirstRun ) { - setTimeout( function() { - singleTransferLoopWithRepeat( optsLoop ).then( function() {} ).catch( function() {} ); + setTimeout( function(): void { + singleTransferLoopWithRepeat( optsLoop ) + .then( function(): void {} ).catch( function(): void {} ); }, imaState.nLoopPeriodSeconds * 1000 ); } else await singleTransferLoopWithRepeat( optsLoop ); @@ -495,7 +503,7 @@ export async function runTransferLoop( optsLoop: TLoopOptions ) { const gArrWorkers: worker_threads.Worker[] = []; const gArrClients: networkLayer.OutOfWorkerSocketClientPipe[] = []; -function constructChainProperties( opts: TParallelLoopRunOptions ) { +function constructChainProperties( opts: TParallelLoopRunOptions ): any { return { mn: { joAccount: { @@ -581,7 +589,7 @@ interface TWorkerData { } } -export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { +export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ): Promise { if( gArrWorkers.length > 0 ) return gArrWorkers; const cntWorkers = 2; @@ -746,7 +754,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ) { gArrWorkers.length, " worker(s) in ", threadInfo.threadDescription() ); } -export async function runParallelLoops( opts: TParallelLoopRunOptions ) { +export async function runParallelLoops( opts: TParallelLoopRunOptions ): Promise { log.notice( "Will start parallel IMA transfer loops in {}...", threadInfo.threadDescription() ); await ensureHaveWorkers( opts ); log.success( "Done, did started parallel IMA transfer loops in {}, have {} worker(s) and {} " + @@ -754,7 +762,7 @@ export async function runParallelLoops( opts: TParallelLoopRunOptions ) { return true; } -export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) { +export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ): Promise { if( !( joMessage && typeof joMessage === "object" && "method" in joMessage && joMessage.method == "skale_imaNotifyLoopWork" ) ) @@ -764,7 +772,7 @@ export async function spreadArrivedStateOfPendingWorkAnalysis( joMessage: any ) gArrClients[idxWorker].send( joMessage ); } -export async function spreadUpdatedSChainNetwork( isFinal: boolean ) { +export async function spreadUpdatedSChainNetwork( isFinal: boolean ): Promise { const imaState: state.TIMAState = state.get(); const joMessage: any = { method: "spreadUpdatedSChainNetwork", diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 0d2985db..6e3efd23 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -44,7 +44,7 @@ if( parentPort ) { } ); } -function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ) { +function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ): void { const jo: any = networkLayer.socketReceivedDataReverseMarshall( data ); const joSend: any = { workerMessageType: @@ -80,7 +80,7 @@ class ObserverServer extends SocketServer { }; if( self.initComplete ) return joAnswer; - self.log = function() { + self.log = function(): void { const args = Array.prototype.slice.call( arguments ); const jo: any = { method: "log", @@ -127,9 +127,9 @@ class ObserverServer extends SocketServer { socket.send( jo, isFlush ); } ); self.opts.imaState.chainProperties.mn.joAccount.address = - function() { return owaspUtils.fnAddressImpl_( this ); }; + function(): string { return owaspUtils.fnAddressImpl_( this ); }; self.opts.imaState.chainProperties.sc.joAccount.address = - function() { return owaspUtils.fnAddressImpl_( this ); }; + function(): string { return owaspUtils.fnAddressImpl_( this ); }; if( self.opts.imaState.chainProperties.mn.strURL && typeof self.opts.imaState.chainProperties.mn.strURL === "string" && self.opts.imaState.chainProperties.mn.strURL.length > 0 @@ -181,7 +181,7 @@ class ObserverServer extends SocketServer { log.yn( self.opts.imaState.optsLoop.enableStepS2S ) ); /* await */ loop.runTransferLoop( self.opts.imaState.optsLoop ) - .then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); self.information( "Full init compete for in-worker IMA loop {} in {}", workerData.url, threadInfo.threadDescription() ); return joAnswer; @@ -207,12 +207,12 @@ class ObserverServer extends SocketServer { ( !!( joMessage.params.isStart ) ), owaspUtils.toInteger( joMessage.params.ts ), joMessage.params.signature - ).then( function() {} ).catch( function() {} ); + ).then( function(): void {} ).catch( function(): void {} ); } console.log( "Initialized in-worker IMA loop {} server in {}", workerData.url, threadInfo.threadDescription() ); } - dispose() { + dispose(): void { const self: any = this; self.isDisposing = true; if( self.intervalPeriodicSchainsCaching ) { @@ -221,7 +221,7 @@ class ObserverServer extends SocketServer { } super.dispose(); } - initLogMethods() { + initLogMethods(): void { const self: any = this; if( "fatal" in self && self.fatal && typeof self.fatal === "function" ) return; @@ -302,7 +302,7 @@ class ObserverServer extends SocketServer { const acceptor = new networkLayer.InWorkerSocketServerAcceptor( workerData.url, doSendMessage ); const server = new ObserverServer( acceptor ); -server.on( "dispose", function() { +server.on( "dispose", function(): void { const self: any = server; self.debug( "Disposed in-worker in {} IMA loop {}", threadInfo.threadDescription(), workerData.url ); diff --git a/src/main.ts b/src/main.ts index 5fd9157f..1b5ffd63 100644 --- a/src/main.ts +++ b/src/main.ts @@ -43,7 +43,7 @@ import * as state from "./state.js"; // allow self-signed wss and https process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; -process.on( "unhandledRejection", function( reason: any, p: any ) { +process.on( "unhandledRejection", function( reason: any, p: any ): void { log.fatal( "CRITICAL ERROR: unhandled rejection with reason {} and promise {}", reason, p ); @@ -54,7 +54,7 @@ process.on( "unhandledRejection", function( reason: any, p: any ) { process.exit( 1 ); } ); -function parseCommandLine() { +function parseCommandLine(): void { const imaState: state.TIMAState = state.get(); log.autoEnableColorizationFromCommandLineArgs(); const strPrintedArguments = process.argv.join( " " ); @@ -116,7 +116,7 @@ function parseCommandLine() { if( imaState.nAutoExitAfterSeconds > 0 ) { log.warning( "Automatic exit after {} second(s) is requested.", imaState.nAutoExitAfterSeconds ); - const iv = owaspUtils.setInterval2( function() { + const iv = owaspUtils.setInterval2( function(): void { log.warning( "Performing automatic exit after {} second(s)...", imaState.nAutoExitAfterSeconds ); owaspUtils.clearInterval2( iv ); @@ -344,7 +344,7 @@ function initJsonRpcServer(): void { gExpressJsonRpcAppIMA.listen( imaState.nJsonRpcPort ); } -async function doTheJob() { +async function doTheJob(): Promise { const imaState: state.TIMAState = state.get(); const strLogPrefix = "Job 1: "; let idxAction = 0; @@ -392,15 +392,15 @@ function handleFirstSChainDiscoveryAttemptDone( const imaState: state.TIMAState = state.get(); imaState.joSChainNetworkInfo = joSChainNetworkInfo; discoveryTools.continueSChainDiscoveryInBackgroundIfNeeded( - isSilentReDiscovery, function() { + isSilentReDiscovery, function(): void { discoveryTools.doPeriodicSChainNetworkDiscoveryIfNeeded( isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ) - .then( function() {} ).catch( function() {} ); - } ).then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); + } ).then( function(): void {} ).catch( function(): void {} ); imaState.joSChainNetworkInfo = joSChainNetworkInfo; } -async function main() { +async function main(): Promise { log.autoEnableColorizationFromCommandLineArgs(); const imaState: state.TIMAState = state.get(); const strTmpAddressFromEnvMainNet = @@ -427,8 +427,9 @@ async function main() { const isSilentReDiscovery = imaState.isPrintSecurityValues ? false : imaState.joSChainDiscovery.isSilentReDiscovery; - const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ) { - loop.spreadUpdatedSChainNetwork( isFinal ).then( function() {} ).catch( function() {} ); + const fnOnPeriodicDiscoveryResultAvailable = function( isFinal: boolean ): void { + loop.spreadUpdatedSChainNetwork( isFinal ) + .then( function(): void {} ).catch( function(): void {} ); }; if( imaState.bSignMessages ) { if( imaState.strPathBlsGlue.length == 0 ) { @@ -458,25 +459,25 @@ async function main() { err, joSChainNetworkInfo, isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ); } - doTheJob().then( function() {} ).catch( function() {} ); + doTheJob().then( function(): void {} ).catch( function(): void {} ); // Finish of IMA Agent startup, // everything else is in async calls executed later }, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait ).catch( function( err: Error | string ) { const strError = owaspUtils.extractErrorMessage( err ); log.critical( "S-Chain network discovery failed: {err}", strError ); - doTheJob().then( function() {} ).catch( function() {} ); + doTheJob().then( function(): void {} ).catch( function(): void {} ); } ); } } else { discoveryTools.doPeriodicSChainNetworkDiscoveryIfNeeded( isSilentReDiscovery, fnOnPeriodicDiscoveryResultAvailable ) - .then( function() {} ).catch( function() {} ); - doTheJob().then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); + doTheJob().then( function(): void {} ).catch( function(): void {} ); // Finish of IMA Agent startup, // everything else is in async calls executed later, // skip exit here to avoid early termination while tasks ase still running } } -main().then( function() {} ).catch( function() {} ); +main().then( function(): void {} ).catch( function(): void {} ); diff --git a/src/observer.ts b/src/observer.ts index 2ee9b163..9b111a3b 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -87,7 +87,7 @@ export interface TSChainsInformation { } export function findSChainIndexInArrayByName( - arrSChains: TSChainInformation[], strSChainName: string ) { + arrSChains: TSChainInformation[], strSChainName: string ): number { for( let idxSChain = 0; idxSChain < arrSChains.length; ++idxSChain ) { const joSChain = arrSChains[idxSChain]; if( joSChain.name.toString() == strSChainName.toString() ) diff --git a/src/oracle.ts b/src/oracle.ts index cf1848bb..1ecb3692 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -45,7 +45,8 @@ function getUtcTimestampString( d?: Date ): string { return t; } -export function findPowNumber( strRequestPart: string, details: log.TLogger, isVerbose?: boolean ) { +export function findPowNumber( + strRequestPart: string, details: log.TLogger, isVerbose?: boolean ): any { details = details || log; if( isVerbose ) details.debug( "source part of request to find PoW number is {}", strRequestPart ); @@ -83,7 +84,7 @@ export function findPowNumber( strRequestPart: string, details: log.TLogger, isV async function handleOracleCheckResultResult( oracleOpts: any, details: log.TLogger, isVerboseTraceDetails: boolean, joCall: rpcCall.TRPCCall, joIn: any, joOut: any -) { +): Promise { if( isVerboseTraceDetails ) details.debug( "RPC call(oracle_checkResult) result is: {}", joOut ); if( !( "result" in joOut && typeof joOut.result === "string" && @@ -108,7 +109,7 @@ async function handleOracleCheckResultResult( async function handleOracleSubmitRequestResult( oracleOpts: any, details: log.TLogger, isVerboseTraceDetails: boolean, joCall: rpcCall.TRPCCall, joIn: any, joOut: any -) { +): Promise { const nMillisecondsSleepBefore = "nMillisecondsSleepBefore" in oracleOpts ? oracleOpts.nMillisecondsSleepBefore : 1000; @@ -160,7 +161,8 @@ async function handleOracleSubmitRequestResult( throw new Error( "RPC call(oracle_checkResult) all attempts timed out" ); } -export async function oracleGetGasPrice( oracleOpts: any, details: log.TLogger ) { +export async function oracleGetGasPrice( + oracleOpts: any, details: log.TLogger ): Promise { details = details || log; const url: string = oracleOpts.url; let gp: any = null; diff --git a/src/pwa.ts b/src/pwa.ts index d498b111..8e433a42 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -73,7 +73,7 @@ function composeEmptyStateForPendingWorkAnalysis(): any { } function getNodeProgressAndTimestamp( - joNode: discoveryTools.TSChainNode, strLoopWorkType: string, nIndexS2S: number ) { + joNode: discoveryTools.TSChainNode, strLoopWorkType: string, nIndexS2S: number ): any { if( !( "pwaState" in joNode ) ) joNode.pwaState = composeEmptyStateForPendingWorkAnalysis(); strLoopWorkType = strLoopWorkType.toLowerCase(); @@ -90,7 +90,8 @@ function getNodeProgressAndTimestamp( } export async function checkOnLoopStart( - imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number +): Promise { try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined if( !checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) @@ -158,7 +159,7 @@ export async function checkOnLoopStart( export async function handleLoopStateArrived( imaState: state.TIMAState, nNodeNumber: number, strLoopWorkType: string, nIndexS2S: number, isStart: boolean, ts: any, signature: any -) { +): Promise { const se = isStart ? "start" : "end"; let isSuccess = false; let joNode: any = null; @@ -208,7 +209,8 @@ export async function handleLoopStateArrived( } async function notifyOnLoopImpl( - imaState: state.TIMAState, strLoopWorkType: string, isStart: boolean, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, isStart: boolean, nIndexS2S?: number +): Promise { const se = isStart ? "start" : "end"; try { nIndexS2S = nIndexS2S || 0; // convert to number if undefined @@ -280,11 +282,13 @@ async function notifyOnLoopImpl( } export async function notifyOnLoopStart( - imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number +): Promise { return await notifyOnLoopImpl( imaState, strLoopWorkType, true, nIndexS2S ); } export async function notifyOnLoopEnd( - imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ) { + imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number +): Promise { return await notifyOnLoopImpl( imaState, strLoopWorkType, false, nIndexS2S ); } diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 473d216d..9b6d6c51 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -81,14 +81,15 @@ const gSecondsConnectionTimeout = 60; export type TFunctionWsStep = ( nStep: number ) => Promise < boolean >; export type TFunctionWsDone = ( nStep: number ) => Promise < void >; -export async function waitWebSocketIsOpen( socket: ws.WebSocket, - fnDone?: TFunctionWsDone, fnStep?: TFunctionWsStep ) { +export async function waitWebSocketIsOpen( + socket: ws.WebSocket, fnDone?: TFunctionWsDone, fnStep?: TFunctionWsStep +): Promise { fnDone = fnDone || async function( nStep: number ) { }; fnStep = fnStep || async function( nStep: number ) { return true; }; let nStep = 0; const promiseComplete = new Promise( function( resolve, reject ) { let isInsideAsyncHandler = false; - const fnAsyncHandler = async function() { + const fnAsyncHandler = async function(): Promise < void > { if( isInsideAsyncHandler ) return; isInsideAsyncHandler = true; @@ -111,7 +112,7 @@ export async function waitWebSocketIsOpen( socket: ws.WebSocket, } isInsideAsyncHandler = false; }; - const iv = setInterval( function() { + const iv = setInterval( function(): void { if( isInsideAsyncHandler ) return; fnAsyncHandler().then( () => { } ).catch( () => { } ); @@ -121,7 +122,8 @@ export async function waitWebSocketIsOpen( socket: ws.WebSocket, } export async function doConnect( - joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: TFunctionConnectionResultHandler ) { + joCall: TRPCCall, opts: TRPCCallOpts | null, fn?: TFunctionConnectionResultHandler +): Promise { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -130,11 +132,11 @@ export async function doConnect( if( isUrlWS( joCall.url ) ) { let strWsError: string = ""; joCall.wsConn = new ws.WebSocket( joCall.url ); - joCall.wsConn.on( "open", function() { + joCall.wsConn.on( "open", function(): void { if( fn ) - fn( joCall, null ).then( function() {} ).catch( function() {} ); + fn( joCall, null ).then( function(): void {} ).catch( function(): void {} ); } ); - joCall.wsConn.on( "close", function() { + joCall.wsConn.on( "close", function(): void { strWsError = "web socket was closed, please check provided URL is valid and accessible"; joCall.wsConn = null; @@ -146,7 +148,8 @@ export async function doConnect( joCall.wsConn = null; if( wsConn ) wsConn.close(); - doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); + doReconnectWsStep( joCall, opts ) + .then( function(): void {} ).catch( function(): void {} ); } ); joCall.wsConn.on( "fail", function( err: Error | string ) { strWsError = err.toString() || "internal web socket failure"; @@ -155,7 +158,8 @@ export async function doConnect( joCall.wsConn = null; if( wsConn ) wsConn.close(); - doReconnectWsStep( joCall, opts ).then( function() {} ).catch( function() {} ); + doReconnectWsStep( joCall, opts ) + .then( function(): void {} ).catch( function(): void {} ); } ); joCall.wsConn.on( "message", function incoming( data: any ) { const joOut = JSON.parse( data ); @@ -170,7 +174,7 @@ export async function doConnect( clearTimeout( entry.out ); if( entry.fn ) { entry.fn( entry.joIn, joOut, null ) - .then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); } } } @@ -192,7 +196,7 @@ export async function doConnect( if( wsConn ) wsConn.close(); doReconnectWsStep( joCall, opts ) - .then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); return false; // stop waiting } return true; // continue waiting @@ -201,7 +205,7 @@ export async function doConnect( const err = new Error( strWsError ); if( fn ) await fn( joCall, err ); - return; + return joCall; } } if( fn ) @@ -215,7 +219,8 @@ export async function doConnect( } export async function doConnectIfNeeded( - joCall: TRPCCall, opts: TRPCCallOpts | null, fn: TFunctionConnectionResultHandler ) { + joCall: TRPCCall, opts: TRPCCallOpts | null, fn: TFunctionConnectionResultHandler +): Promise { try { if( !validateURL( joCall.url ) ) { throw new Error( "JSON RPC CALLER cannot connect web socket " + @@ -223,7 +228,7 @@ export async function doConnectIfNeeded( } if( isUrlWS( joCall.url ) && ( !joCall.wsConn ) ) { await joCall.reconnect( fn ); - return; + return joCall; } if( fn ) await fn( joCall, null ); @@ -235,7 +240,7 @@ export async function doConnectIfNeeded( } async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, - fn?: TFunctionConnectionResultHandler ) { + fn?: TFunctionConnectionResultHandler ): Promise { if( !joCall.isAutoReconnect ) return; if( joCall.isDisconnectMode ) @@ -243,15 +248,16 @@ async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, doConnect( joCall, opts, async function( joCall: TRPCCall, err: Error | string | null ) { if( err ) { doReconnectWsStep( joCall, opts ) - .then( function() {} ).catch( function() {} ); + .then( function(): void {} ).catch( function(): void {} ); return; } if( fn ) await fn( joCall, null ); - } ).then( function() {} ).catch( function() {} ); + } ).then( function(): void {} ).catch( function(): void {} ); } -async function doDisconnect( joCall: TRPCCall, fn?: TFunctionConnectionResultHandler ) { +async function doDisconnect( + joCall: TRPCCall, fn?: TFunctionConnectionResultHandler ): Promise { try { joCall.isDisconnectMode = true; const wsConn = joCall.wsConn ? joCall.wsConn : null; @@ -270,7 +276,8 @@ async function doDisconnect( joCall: TRPCCall, fn?: TFunctionConnectionResultHan } } -export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResultHandler ) { +export async function doCall( + joCall: TRPCCall, joIn: any, fn: TFunctionCallResultHandler ): Promise { joIn = enrichTopLevelFieldsInJSON( joIn ); if( joCall.wsConn ) { const entry: TCallHandlerEntry = { @@ -279,7 +286,7 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu out: null }; joCall.mapPendingByCallID.set( joIn.id, entry ); - entry.iv = setTimeout( function() { + entry.iv = setTimeout( function(): void { if( entry.iv ) clearTimeout( entry.iv ); entry.iv = null; @@ -329,7 +336,7 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu res.on( "data", function( body: any ) { accumulatedBody += body; } ); - res.on( "end", function() { + res.on( "end", function(): void { if( res.statusCode !== 200 ) { joOut = null; errCall = "Response ends with bad status code: " + @@ -415,7 +422,8 @@ export async function doCall( joCall: TRPCCall, joIn: any, fn: TFunctionCallResu } } -export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) { +export async function rpcCallCreate( + strURL: string, opts: TRPCCallOpts | null ): Promise { if( !validateURL( strURL ) ) throw new Error( `JSON RPC CALLER cannot create a call object invalid URL: ${strURL}` ); if( !( strURL && typeof strURL === "string" && strURL.length > 0 ) ) { @@ -459,7 +467,7 @@ export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) log.error( "{url} JSON RPC call(performer) error: {err}", strURL, err ); } ); - } ).then( function() {} ).catch( function() {} ); ; + } ).then( function(): void {} ).catch( function(): void {} ); ; } ); return await promiseComplete.catch( function( err: Error | string ) { log.error( @@ -476,17 +484,17 @@ export async function rpcCallCreate( strURL: string, opts: TRPCCallOpts | null ) export { rpcCallCreate as create }; -export function generateRandomIntegerInRange( min: any, max: any ) { +export function generateRandomIntegerInRange( min: any, max: any ): number { min = Math.ceil( min ); max = Math.floor( max ); return Math.floor( Math.random() * ( max - min + 1 ) ) + min; } -export function generateRandomRpcCallId() { +export function generateRandomRpcCallId(): number { return generateRandomIntegerInRange( 1, Number.MAX_SAFE_INTEGER ); } -export function enrichTopLevelFieldsInJSON( jo: any ) { +export function enrichTopLevelFieldsInJSON( jo: any ): any { if( ( !( "jsonrpc" in jo ) ) || ( typeof jo.jsonrpc !== "string" ) || jo.jsonrpc.length === 0 @@ -497,7 +505,7 @@ export function enrichTopLevelFieldsInJSON( jo: any ) { return jo; } -export function isValidUrl( s: any ) { +export function isValidUrl( s: any ): boolean { if( !s ) return false; try { @@ -509,7 +517,7 @@ export function isValidUrl( s: any ) { return false; } -export function getValidUrl( s: any ) { +export function getValidUrl( s: any ): URL | null { if( !s ) return null; try { @@ -519,7 +527,7 @@ export function getValidUrl( s: any ) { return null; } -export function getDefaultPort( strProtocol: any ) { +export function getDefaultPort( strProtocol: any ): number { if( !strProtocol ) return 80; switch ( strProtocol.toString().toLowerCase() ) { @@ -533,7 +541,7 @@ export function getDefaultPort( strProtocol: any ) { return 80; } -export function getValidHostAndPort( s: any ) { +export function getValidHostAndPort( s: any ): any { const u = getValidUrl( s ); if( !u ) return null; @@ -546,9 +554,10 @@ export function getValidHostAndPort( s: any ) { const gStrTcpConnectionHeader: string = "TCP connection checker: "; -export async function checkTcpPromise( strHost: string, nPort: number, nTimeoutMilliseconds: number, - isLog?: boolean ) { - return await new Promise( ( resolve, reject ) => { +export async function checkTcpPromise( + strHost: string, nPort: number, nTimeoutMilliseconds: number, isLog?: boolean +): Promise { + return await new Promise( ( resolve, reject ) => { if( isLog ) { console.log( `${gStrTcpConnectionHeader}Will establish ` + @@ -610,21 +619,22 @@ export async function checkTcpPromise( strHost: string, nPort: number, nTimeoutM } ); } -export async function checkTcp( strHost: string, nPort: number, nTimeoutMilliseconds: number, - isLog?: boolean ) { +export async function checkTcp( + strHost: string, nPort: number, nTimeoutMilliseconds: number, isLog?: boolean +): Promise { let isOnline = false; try { const promiseCompleteTcpCheck = checkTcpPromise( strHost, nPort, nTimeoutMilliseconds, isLog ) - .then( function() { isOnline = true; } ) - .catch( function() { isOnline = false; } ); + .then( function(): void { isOnline = true; } ) + .catch( function(): void { isOnline = false; } ); if( isLog ) { console.log( `${gStrTcpConnectionHeader}Waiting for ` + `TCP connection to ${strHost}:${nPort} check done...` ); } - await promiseCompleteTcpCheck.catch( function() { isOnline = false; } ); + await promiseCompleteTcpCheck.catch( function(): void { isOnline = false; } ); if( isLog ) { console.log( `${gStrTcpConnectionHeader}TCP connection ` + @@ -639,7 +649,8 @@ export async function checkTcp( strHost: string, nPort: number, nTimeoutMillisec return isOnline; } -export async function checkUrl( u: URL | string, nTimeoutMilliseconds: number, isLog?: boolean ) { +export async function checkUrl( + u: URL | string, nTimeoutMilliseconds: number, isLog?: boolean ): Promise { if( !u ) return false; const jo = getValidHostAndPort( u ); diff --git a/src/socket.ts b/src/socket.ts index a6bde653..eff10af0 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -52,7 +52,7 @@ export const socketSentDataMarshall = function( data?: any ): any { : ""; return s; }; -export const socketReceivedDataReverseMarshall = function( data?: any ): object { +export const socketReceivedDataReverseMarshall = function( data?: any ): any { try { const jo: any = data ? ( ( typeof data === "object" ) @@ -70,7 +70,7 @@ export const socketReceivedDataReverseMarshall = function( data?: any ): object } }; -export const updateSocketDataStatsForMessage = function( joMessage: any, joStats: any ) { +export const updateSocketDataStatsForMessage = function( joMessage: any, joStats: any ): void { let strMethod = "_N/A_"; if( "method" in joMessage && joMessage.method && @@ -82,7 +82,7 @@ export const updateSocketDataStatsForMessage = function( joMessage: any, joStats else joStats[strMethod] = 1; }; -export const generateSocketDataStatsJSON = function( jo: any ) { +export const generateSocketDataStatsJSON = function( jo: any ): any { const joStats: any = {}; if( "arrPackedMessages" in jo && jo.arrPackedMessages && @@ -121,7 +121,7 @@ export class BasicServerAcceptor extends EventDispatcher { this.disposeNotifyClients(); super.dispose(); } - disposeNotifyClients() { + disposeNotifyClients(): void { for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapClients ) ) { const entry: any = entryWalk; if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { @@ -137,7 +137,7 @@ export class BasicServerAcceptor extends EventDispatcher { } this.mapClients = { }; } - unregisterClientByKey( key: any ) { + unregisterClientByKey( key: any ): void { if( key in this.mapClients ) { const entry = this.mapClients[key]; if( entry ) { @@ -151,7 +151,7 @@ export class BasicServerAcceptor extends EventDispatcher { } } } - flush() { + flush(): void { if( this.isDisposing || this.isDisposed ) return; for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapClients ) ) { @@ -165,7 +165,7 @@ export class BasicServerAcceptor extends EventDispatcher { } } } - newDirectConnection() { + newDirectConnection(): DirectPipe | null { if( this.isDisposing || this.isDisposed ) return null; if( !this.isListening ) @@ -175,7 +175,7 @@ export class BasicServerAcceptor extends EventDispatcher { serverPipe.acceptor = this; this.mapClients["" + serverPipe.clientPort] = serverPipe; const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); serverPipe.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: serverPipe } ) ); @@ -214,7 +214,7 @@ export class BasicSocketPipe extends EventDispatcher { this.relayClientSocket = null; // for relay only this.mapImpersonatedEntries = { }; // for external in-app usage only } - dispose() { + dispose(): void { if( this.relayClientSocket ) { this.relayClientSocket.dispose(); this.relayClientSocket = null; @@ -224,7 +224,7 @@ export class BasicSocketPipe extends EventDispatcher { this.arrAccumulatedMessages = []; super.dispose(); } - disposeImpersonatedEntries() { // for external in-app usage only + disposeImpersonatedEntries(): void { // for external in-app usage only for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { const entry: any = entryWalk; try { @@ -235,11 +235,11 @@ export class BasicSocketPipe extends EventDispatcher { } this.mapImpersonatedEntries = { }; // for app usage } - implSend( data: any ) { + implSend( data: any ): void { throw new Error( "BasicSocketPipe.implSend() must be overridden but calling it was attempted" ); } - isAutoFlush() { + isAutoFlush(): boolean { if( this.maxAccumulatedMessagesCount <= 1 ) return true; const cnt = this.arrAccumulatedMessages.length; @@ -247,7 +247,7 @@ export class BasicSocketPipe extends EventDispatcher { return false; return true; } - socketDescription() { + socketDescription(): string { return "" + // + this.socketType // + " " @@ -255,10 +255,10 @@ export class BasicSocketPipe extends EventDispatcher { // + " " this.url; } - socketLoggingTextPrefix( strLogEventName: string ) { + socketLoggingTextPrefix( strLogEventName: string ): string { return "" + strLogEventName + " " + this.socketDescription() + " -"; } - send( data: any, isFlush?: boolean ) { + send( data: any, isFlush?: boolean ): void { if( this.isDisposed || ( !this.isConnected ) ) return; if( this.isAutoFlush() ) { @@ -275,7 +275,7 @@ export class BasicSocketPipe extends EventDispatcher { if( isFlush ) this.flush(); } - flush() { + flush(): void { if( this.isDisposed || ( !this.isConnected ) ) return; const cnt = this.arrAccumulatedMessages.length; @@ -304,12 +304,12 @@ export class BasicSocketPipe extends EventDispatcher { if( this.relayClientSocket ) this.relayClientSocket.flush(); } - implReceive( data: any ) { + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); } - receive( data: any ) { + receive( data: any ): void { if( settings.logging.net.socket.receiveBlock ) console.log( this.socketLoggingTextPrefix( "receive-block" ), data ); const jo: any = socketReceivedDataReverseMarshall( data ); @@ -345,12 +345,12 @@ export class BasicSocketPipe extends EventDispatcher { console.log( this.socketLoggingTextPrefix( "receive" ), jo ); this.implReceive( jo ); } - disconnect() { + disconnect(): void { this.isConnected = false; } - reconnect() { + reconnect(): void { } - checkItself() { + checkItself(): void { } }; @@ -362,23 +362,23 @@ export class NullSocketPipe extends BasicSocketPipe { this.url = "NullUrl"; this.isConnected = true; } - dispose() { + dispose(): void { this.isConnected = false; super.dispose(); } - implSend( data: any ) { + implSend( data: any ): void { } - implReceive( data: any ) { + implReceive( data: any ): void { } - send( data: any ) { + send( data: any ): void { } - receive( data: any ) { + receive( data: any ): void { } - flush() { + flush(): void { } }; -export const isRunningInWorker = function() { +export const isRunningInWorker = function(): boolean { if( self.document === undefined ) return true; return false; @@ -390,7 +390,7 @@ export const gMapAwaitingInWorkerClients: Record < string, any > = { }; export const gMapConnectedInWorkerClients: Record < string, any > = { }; export const outOfWorkerAPIs: any = { - onMessage: function( worker: any, data: any ) { + onMessage: function( worker: any, data: any ): boolean { const jo: any = socketReceivedDataReverseMarshall( data ); if( !( "workerMessageType" in jo ) || typeof jo.workerMessageType !== "string" || @@ -426,7 +426,8 @@ export const outOfWorkerAPIs: any = { return false; // TO-DO: send error answer and return true } // switch( jo.workerMessageType ) }, - onSendMessage: function( worker: any, type: any, endpoint: any, workerUUID: any, data: any ) { + onSendMessage: function( + worker: any, type: any, endpoint: any, workerUUID: any, data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); const joSend: any = { workerMessageType: @@ -500,7 +501,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.acceptor.mapClients[this.clientPort] = this; this.fnSend( "inWorkerConnect", this.acceptor.strEndPoint, this.clientPort, {} ); const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( @@ -508,11 +509,11 @@ export class InWorkerServerPipe extends BasicSocketPipe { "connection", { socket: self, remoteAddress: "" + self.url } ) ); }, 0 ); } - dispose() { + dispose(): void { this.performDisconnect(); super.dispose(); } - handleServerDisposed() { + handleServerDisposed(): void { this.performDisconnect(); this.isConnected = false; this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); @@ -521,7 +522,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.url = ""; this.dispose(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.fnSend( "inWorkerDisconnect", this.acceptor.strEndPoint, this.clientPort, {} ); @@ -533,7 +534,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.fnSend = null; this.url = ""; } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend !== "function" ) { const s = "Cannot send messages to disconnected in-worker server pipe"; this.dispatchEvent( @@ -543,7 +544,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { const jo: any = socketReceivedDataReverseMarshall( data ); this.fnSend( "inWorkerMessage", this.acceptor.strEndPoint, this.clientPort, jo ); } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } @@ -570,12 +571,12 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { this.fnSend = fnSend || inWorkerAPIs.onSendMessage; this.isListening = true; const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -590,7 +591,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { } super.dispose(); } - performAccept( jo: any ) { + performAccept( jo: any ): boolean { if( jo.workerUUID in this.mapClients ) return false; // TO-DO: send error answer and return true const p: InWorkerServerPipe = @@ -598,14 +599,14 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { p.checkItself(); return true; } - performDisconnect( jo: any ) { + performDisconnect( jo: any ): boolean { if( !( jo.workerUUID in this.mapClients ) ) return false; // TO-DO: send error answer and return true const pipe = this.mapClients[jo.workerUUID]; pipe.performDisconnect(); return true; } - receiveForClientPort( clientPort: any, jo: any ) { + receiveForClientPort( clientPort: any, jo: any ): boolean { if( !( clientPort in this.mapClients ) ) return false; // TO-DO: send error answer and return true const pipe = this.mapClients[clientPort]; @@ -637,7 +638,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.fnSend( this.worker, "inWorkerConnect", this.strEndPoint, this.clientPort, {} ); gMapAwaitingInWorkerClients["" + this.clientPort] = this; } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -647,7 +648,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { delete gMapAwaitingInWorkerClients[this.clientPort]; super.dispose(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.isConnected = false; @@ -660,14 +661,14 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.strEndPoint = ""; this.url = ""; } - performSuccessfulConnection() { + performSuccessfulConnection(): void { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapAwaitingInWorkerClients[this.clientPort]; gMapConnectedInWorkerClients["" + this.clientPort] = this; this.isConnected = true; this.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: this } ) ); } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.worker ) || ( !this.fnSend ) || @@ -684,7 +685,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { const jo: any = socketReceivedDataReverseMarshall( data ); this.fnSend( this.worker, "inWorkerMessage", this.strEndPoint, this.clientPort, jo ); } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } @@ -747,7 +748,7 @@ export class OutOfWorkerRelay extends EventDispatcher { } ) ); // 1) configure incoming pipe let _offAllPipeEventListeners: any = null; - let _onExternalPipeClose: any = function() { + let _onExternalPipeClose: any = function(): void { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" external-client socket closed \"" + @@ -765,7 +766,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onRelayPipeClose: any = function() { + let _onRelayPipeClose: any = function(): void { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" relay-client socket closed \"" + @@ -871,7 +872,7 @@ export class OutOfWorkerRelay extends EventDispatcher { if( self.isAutoFlushOutgoing ) pipeOutgoing.flush(); }; - _offAllPipeEventListeners = function() { + _offAllPipeEventListeners = function(): void { if( _onExternalPipeClose ) { pipeIncoming.off( "close", _onExternalPipeClose ); _onExternalPipeClose = null; @@ -919,14 +920,14 @@ export class OutOfWorkerRelay extends EventDispatcher { }; self.acceptor.on( "connection", self.onConnection_ ); } - dispose() { + dispose(): void { this.isDisposing = true; if( this.acceptor ) this.acceptor.off( "connection", this.onConnection_ ); this.onConnection_ = null; super.dispose(); } - flush() { + flush(): void { if( this.acceptor ) this.acceptor.flush(); } @@ -971,7 +972,7 @@ export class OneToOneRelay extends EventDispatcher { // 1) configure incoming pipe let _offAllPipeEventListeners: any = null; - let _onIncomingPipeClose: any = function() { + let _onIncomingPipeClose: any = function(): void { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" incoming-client socket closed \"" + @@ -992,7 +993,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onOutgoingPipeClose: any = function() { + let _onOutgoingPipeClose: any = function(): void { if( settings.logging.net.relay.disconnect ) { console.warn( "Relay \"" + self.strRelayName + "\" outgoing-client socket closed \"" + @@ -1125,7 +1126,7 @@ export class OneToOneRelay extends EventDispatcher { if( self.isAutoFlushOutgoing ) pipeIncoming.flush(); }; - _offAllPipeEventListeners = function() { + _offAllPipeEventListeners = function(): void { if( _onIncomingPipeClose ) { pipeIncoming.off( "close", _onIncomingPipeClose ); _onIncomingPipeClose = null; @@ -1166,11 +1167,11 @@ export class OneToOneRelay extends EventDispatcher { pipeOutgoing.on( "error", _onOutgoingPipeError ); pipeOutgoing.on( "message", _onOutgoingPipeMessage ); } - dispose() { + dispose(): void { this.isDisposing = true; super.dispose(); } - flush() { + flush(): void { if( this.pipeIncoming ) this.pipeIncoming.flush(); if( this.pipeOutgoing ) @@ -1209,7 +1210,7 @@ export class DirectPipe extends BasicSocketPipe { this.counterPipe.isConnected = true; if( isBroadcastOpenEvents ) { const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); @@ -1220,11 +1221,11 @@ export class DirectPipe extends BasicSocketPipe { } } } - dispose() { + dispose(): void { this.performDisconnect(); super.dispose(); } - handleServerDisposed() { // this method is for using in local client/server pipe pairs + handleServerDisposed(): void { // this method is for using in local client/server pipe pairs this.performDisconnect(); this.isConnected = false; this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); @@ -1234,7 +1235,7 @@ export class DirectPipe extends BasicSocketPipe { this.url = ""; this.dispose(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.isConnected = false; @@ -1247,7 +1248,7 @@ export class DirectPipe extends BasicSocketPipe { this.clientPort = 0; this.url = ""; } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.counterPipe?.isConnected ) ) { const s = "Cannot send messages to disconnected local server pipe"; this.dispatchEvent( @@ -1258,7 +1259,7 @@ export class DirectPipe extends BasicSocketPipe { const jo: any = socketReceivedDataReverseMarshall( s ); this.counterPipe.receive( jo ); } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } @@ -1275,12 +1276,12 @@ export class LocalSocketServerPipe extends DirectPipe { this.url = "local_server_pipe://" + acceptor.strEndPoint + ":" + clientPort; this.acceptor.mapClients["" + clientPort] = this; const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } - dispose() { + dispose(): void { super.dispose(); } }; @@ -1306,13 +1307,13 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { gMapLocalServers[this.strEndPoint] = this; this.isListening = true; const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -1365,7 +1366,7 @@ export class LocalSocketClientPipe extends DirectPipe { clientPipe: this }; const self = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( @@ -1375,7 +1376,7 @@ export class LocalSocketClientPipe extends DirectPipe { ); }, 0 ); } - dispose() { + dispose(): void { super.dispose(); } }; @@ -1401,18 +1402,18 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.wsConnection = wsConnection; this.remoteAddress = "" + remoteAddress; this.url = "ws_server_pipe(" + this.clientNumber + ")://" + remoteAddress; - this._onWsClose = function() { + this._onWsClose = function(): void { self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self } ) ); }; - this._onWsError = function( event: any ) { + this._onWsError = function( event: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: self, message: event } ) ); }; - this._onWsMessage = function( event: any ) { + this._onWsMessage = function( event: any ): void { self.receive( event.data ); }; - this._removeWsEventListeners = function() { + this._removeWsEventListeners = function(): void { if( self._onWsClose ) { wsConnection.removeEventListener( "close", self._onWsClose ); self._onWsClose = null; @@ -1430,7 +1431,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { wsConnection.addEventListener( "error", this._onWsError ); wsConnection.addEventListener( "message", this._onWsMessage ); this.acceptor.mapClients["" + this.clientPort] = this; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( @@ -1440,11 +1441,11 @@ export class WebSocketServerPipe extends BasicSocketPipe { ); }, 0 ); } - dispose() { + dispose(): void { this.performDisconnect(); super.dispose(); } - handleServerDisposed() { + handleServerDisposed(): void { this.isConnected = false; this.clientNumber = 0; this.acceptor = null; @@ -1453,7 +1454,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.remoteAddress = ""; this.dispose(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.isConnected = false; @@ -1476,7 +1477,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.url = ""; this.remoteAddress = ""; } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket server pipe"; this.dispatchEvent( @@ -1486,11 +1487,11 @@ export class WebSocketServerPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.wsConnection.send( s ); } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } - implReceive( data: any ) { + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); @@ -1524,12 +1525,12 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { new WebSocketServerPipe( self, wsConnection, req.connection.remoteAddress ); } ); this.isListening = true; - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -1561,7 +1562,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.url = "ws_client_pipe-" + this.urlWS; this.reconnect(); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -1569,7 +1570,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.urlWS = null; super.dispose(); } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket client pipe"; this.dispatchEvent( @@ -1579,20 +1580,20 @@ export class WebSocketClientPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.wsConnection.send( s ); } - reconnect() { + reconnect(): void { this.performDisconnect(); this.wsConnect( "" + this.urlWS ); } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.wsDisconnect(); } - wsConnectAttempt( url: string, reconnectAfterMilliseconds?: number, iv?: any ) { + wsConnectAttempt( url: string, reconnectAfterMilliseconds?: number, iv?: any ): boolean { const self = this; try { if( this.isConnected || this.wsConnection ) @@ -1604,7 +1605,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { ) // server side : new WebSocket( url ); // client side this.url = "" + url; - this._onWsOpen = function() { + this._onWsOpen = function(): void { self.isConnected = true; self.dispatchEvent( new UniversalDispatcherEvent( @@ -1627,7 +1628,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this._onWsMessage = function( event: any ) { self.receive( event.data ); }; - this._removeWsEventListeners = function() { + this._removeWsEventListeners = function(): void { if( self._onWsOpen ) { self.wsConnection.removeEventListener( "open", self._onWsOpen ); self._onWsOpen = null; @@ -1657,7 +1658,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } if( reconnectAfterMilliseconds != null && reconnectAfterMilliseconds != undefined ) { if( reconnectAfterMilliseconds > 0 && ( !iv ) ) { - const iv = setTimeout( function() { + const iv = setTimeout( function(): void { try { if( self.wsConnectAttempt( url, reconnectAfterMilliseconds, iv ) ) clearTimeout( iv ); @@ -1668,7 +1669,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } return false; } - wsConnect( url: string ) { + wsConnect( url: string ): void { if( url.length == 0 ) { const s = "Cannot connect web socket server \"" + url + "\", bad url"; this.dispatchEvent( @@ -1677,7 +1678,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } this.wsConnectAttempt( url, settings.net.ws.client.reconnectAfterMilliseconds, null ); } - wsDisconnect() { + wsDisconnect(): void { if( this._removeWsEventListeners ) { this._removeWsEventListeners(); this._removeWsEventListeners = null; @@ -1705,7 +1706,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.isConnected = false; this.url = ""; } - implReceive( data: any ) { + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); @@ -1732,7 +1733,7 @@ export class RTCConnection extends EventDispatcher { this.pc = null; this.dc = null; } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -1744,7 +1745,7 @@ export class RTCConnection extends EventDispatcher { this.idRtcParticipant = null; super.dispose(); } - describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { let strInstanceDescription = ( strInstanceType == null || strInstanceType == undefined || ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) @@ -1772,7 +1773,7 @@ export class RTCConnection extends EventDispatcher { strInstanceDescription += "(" + arrProps.join( ", " ) + ")"; return strInstanceDescription; } - closeDataChannel() { + closeDataChannel(): void { if( this.dc ) { try { this.dc.ondatachannel = null; @@ -1789,7 +1790,7 @@ export class RTCConnection extends EventDispatcher { "dataChannelClose", { detail: { actor: this } } ) ); } } - closePeer() { + closePeer(): void { if( this.pc ) { try { this.pc.onicecandidate = null; @@ -1807,7 +1808,7 @@ export class RTCConnection extends EventDispatcher { this.pc = null; } } - onError( err: any ) { + onError( err: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "rtcParticipantError", { detail: { actor: this, error: err } } ) ); @@ -1816,7 +1817,7 @@ export class RTCConnection extends EventDispatcher { this.closeDataChannel(); this.closePeer(); } - send( data: any ) { + send( data: any ): void { const s = socketSentDataMarshall( data ); if( !this.dc ) { this.onError( `Attempt to send message to uninitialized RTC data channel: ${s}` ); @@ -1828,23 +1829,23 @@ export class RTCConnection extends EventDispatcher { this.onError( `Failed to send message to RTC data channel: ${err}` ); } } - onDataChannelOpen( event: any ) { + onDataChannelOpen( event: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelOpen", { detail: { actor: this } } ) ); } - onDataChannelClose( even: any ) { + onDataChannelClose( even: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelClose", { detail: { actor: this } } ) ); } - onDataChannelError( event: any ) { + onDataChannelError( event: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelError", { detail: { actor: this } } ) ); this.onError( "Data channel error " + event.toString() ); } - onDataChannelMessage( event: any ) { + onDataChannelMessage( event: any ): void { if( event.data.size ) { if( settings.logging.net.rtc.error ) { console.warn( @@ -1865,9 +1866,9 @@ export class RTCConnection extends EventDispatcher { } } } - onIceComplete( event: any ) { + onIceComplete( event: any ): void { } - onIceConnectionStateChange( event: any ) { + onIceConnectionStateChange( event: any ): void { // handler for self.pc.oniceconnectionstatechange, // see https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/oniceconnectionstatechange @@ -1894,7 +1895,7 @@ export class RTCConnection extends EventDispatcher { ); } } - onIceGatheringStateChange( event: any ) { + onIceGatheringStateChange( event: any ): void { // handler for self.pc.onicegatheringstatechange - this is recommended to handle // in a same way as oniceconnectionstatechange, // see https://developer.mozilla.org/en-US/docs/ @@ -1930,7 +1931,7 @@ export class RTCConnection extends EventDispatcher { ); } } - onIceIdentifyResult( event: any ) { + onIceIdentifyResult( event: any ): void { // handler for self.pc.onidentityresult, // see https://developer.mozilla.org/en-US/docs/Web/API/RTCIdentityEvent if( settings.logging.net.rtc.iceIceIdentifyResult ) { @@ -1948,7 +1949,7 @@ export class RTCConnection extends EventDispatcher { } } } - onIceSignalingStateChange( event: any ) { + onIceSignalingStateChange( event: any ): void { // handler for self.pc.onsignalingstatechange, see // https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/onsignalingstatechange @@ -1960,7 +1961,7 @@ export class RTCConnection extends EventDispatcher { "\", event is:", event ); } } - onIceNegotiationNeeded( event: any ) { + onIceNegotiationNeeded( event: any ): void { // handler for self.pc.onnegotiationneeded, // see https://developer.mozilla.org/en-US/docs/ // Web/API/RTCPeerConnection/onnegotiationneeded @@ -2030,7 +2031,7 @@ export class RTCActor extends RTCConnection { this.signalingOptions.idSpace = "" + signalingOptions.idSpace; } } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -2040,7 +2041,7 @@ export class RTCActor extends RTCConnection { this.bWasImpersonated = false; super.dispose(); } - describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || @@ -2050,10 +2051,10 @@ export class RTCActor extends RTCConnection { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } - onError( err: any ) { + onError( err: any ): void { super.onError( err ); } - signalingPipeOpen() { + signalingPipeOpen(): void { try { const self = this; self.signalingPipeClose(); @@ -2080,7 +2081,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } - signalingPipeClose() { + signalingPipeClose(): void { if( this.signalingPipe ) { try { if( settings.logging.net.signaling.disconnect ) @@ -2099,7 +2100,7 @@ export class RTCActor extends RTCConnection { "signalingClosed", { detail: { actor: this } } ) ); } } - signalingPipeOnOpen( eventData: any ) { + signalingPipeOnOpen( eventData: any ): void { try { this.dispatchEvent( new UniversalDispatcherEvent( @@ -2129,7 +2130,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } - signalingPipeOnClose( eventData: any ) { + signalingPipeOnClose( eventData: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "signalingPipeClose", { detail: { actor: this } } ) ); @@ -2141,7 +2142,7 @@ export class RTCActor extends RTCConnection { } this.signalingPipeClose(); } - signalingPipeOnError( eventData: any ) { + signalingPipeOnError( eventData: any ): void { // alert( JSON.stringify( eventData ) ); this.dispatchEvent( new UniversalDispatcherEvent( @@ -2155,7 +2156,7 @@ export class RTCActor extends RTCConnection { this.onError( eventData ); this.signalingPipeClose(); } - signalingPipeOnRawMessage( eventData: any ) { + signalingPipeOnRawMessage( eventData: any ): void { try { if( settings.logging.net.signaling.rawMessage ) { console.log( @@ -2173,7 +2174,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } - signalingPipeOnMessage( joMessage: any ) { + signalingPipeOnMessage( joMessage: any ): void { switch ( joMessage.method ) { case "signalingImpersonate": if( joMessage.error == null ) { @@ -2213,9 +2214,9 @@ export class RTCActor extends RTCConnection { break; } // switch( joMessage.method ) } - onImpersonationComplete() { } + onImpersonationComplete(): void { } // generic implementation should never be called - onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ) { } + onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ): void { } }; export class RTCServerPeer extends RTCConnection { @@ -2277,7 +2278,7 @@ export class RTCServerPeer extends RTCConnection { this.initPeer(); this.publish(); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -2303,7 +2304,7 @@ export class RTCServerPeer extends RTCConnection { this.tsOfferCreated = null; super.dispose(); } - describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) @@ -2311,7 +2312,7 @@ export class RTCServerPeer extends RTCConnection { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } - initPeer() { + initPeer(): void { if( this.isDisposed ) return; const self = this; @@ -2337,7 +2338,7 @@ export class RTCServerPeer extends RTCConnection { "message", function( event: any ) { self.onDataChannelMessage( event ); } ); } } - publishCancel() { + publishCancel(): void { if( !this.isPublishing ) return; this.isOfferPublishedOnSignalingServer = false; @@ -2348,7 +2349,7 @@ export class RTCServerPeer extends RTCConnection { } this.signalingNegotiationCancel(); // mutual cancel } - signalingNegotiationCancel() { + signalingNegotiationCancel(): void { if( !this.isSignalingNegotiation ) return; this.isSignalingNegotiation = false; @@ -2358,7 +2359,7 @@ export class RTCServerPeer extends RTCConnection { } this.publishCancel(); // mutual cancel } - publish() { + publish(): void { if( this.isDisposed || this.isPublishing || this.isSignalingNegotiation || ( !this.rtcCreator?.signalingPipe ) ) return; @@ -2366,7 +2367,7 @@ export class RTCServerPeer extends RTCConnection { self.isPublishing = true; if( self.timeToPublishMilliseconds > 0 ) { self.isSignalingNegotiation = false; - self.timerPublishing = setTimeout( function() { + self.timerPublishing = setTimeout( function(): void { self.publishCancel(); self.signalingNegotiationCancel(); self.isPublishTimeout = true; @@ -2417,7 +2418,7 @@ export class RTCServerPeer extends RTCConnection { new UniversalDispatcherEvent( "offerCreated", { detail: { participant: self } } ) ); self.pc.setLocalDescription( offerDescription ).then( - function() { + function(): void { // success if( settings.logging.net.signaling.localDescription ) { console.log( @@ -2447,7 +2448,7 @@ export class RTCServerPeer extends RTCConnection { self.onError( "Failed to create offer:" + err ); } ); } - onOtherSideIdentified( idSomebodyOtherSide: any ) { + onOtherSideIdentified( idSomebodyOtherSide: any ): void { this.publishCancel(); this.signalingNegotiationCancel(); this.idSomebodyOtherSide = "" + idSomebodyOtherSide; @@ -2463,7 +2464,7 @@ export class RTCServerPeer extends RTCConnection { } ) ); } - onError( err: any ) { + onError( err: any ): void { if( this.rtcCreator ) { this.rtcCreator.onRtcPeerError( this, err ); if( this.idOffer && this.idOffer in this.rtcCreator.mapServerOffers ) { @@ -2484,11 +2485,11 @@ export class RTCServerPeer extends RTCConnection { } super.onError( err ); } - onImpersonationCompleteForCreator() { // specific for server peer + onImpersonationCompleteForCreator(): void { // specific for server peer if( settings.logging.net.signaling.creatorImpersonationComplete ) console.log( "Creator impersonation complete" ); } - publishOfferOnSignalingServer() { + publishOfferOnSignalingServer(): void { const self = this; // eslint-disable-next-line no-useless-catch try { @@ -2518,7 +2519,7 @@ export class RTCServerPeer extends RTCConnection { "signalingNegotiationStart", { detail: { participant: self } } ) ); if( self.timeToSignalingNegotiationMilliseconds > 0 ) { self.isSignalingNegotiation = true; - self.timerSignalingNegotiation = setTimeout( function() { + self.timerSignalingNegotiation = setTimeout( function(): void { self.publishCancel(); self.signalingNegotiationCancel(); self.isSignalingNegotiationTimeout = true; @@ -2546,7 +2547,7 @@ export class RTCServerPeer extends RTCConnection { throw err; } } - onIceComplete( event: any ) { + onIceComplete( event: any ): void { super.onIceComplete( event ); const self = this; try { @@ -2589,7 +2590,7 @@ export class RTCCreator extends RTCActor { self.mapServerPeers = { }; // idSomebodyOtherSide -> RTCServerPeer self.signalingPipeOpen(); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -2607,7 +2608,7 @@ export class RTCCreator extends RTCActor { this.mapServerOffers = { }; super.dispose(); } - describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) @@ -2615,7 +2616,8 @@ export class RTCCreator extends RTCActor { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } - onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ) { // server peer got result + onOtherSideIdentified( + idSomebodyOtherSide: any, idOffer: any ): void { // server peer got result if( settings.logging.net.signaling.impersonate ) { console.log( this.describe() + " did identified other side RTC joiner \"" + @@ -2644,7 +2646,7 @@ export class RTCCreator extends RTCActor { this.mapServerPeers["" + idSomebodyOtherSide] = rtcPeer; rtcPeer.onOtherSideIdentified( "" + idSomebodyOtherSide ); } - onRtcPeerError( rtcPeer: any, err: any ) { + onRtcPeerError( rtcPeer: any, err: any ): void { if( settings.logging.net.rtc.error ) console.warn( " !!! " + this.describe() + " rtc peer error", err ); this.dispatchEvent( @@ -2653,7 +2655,7 @@ export class RTCCreator extends RTCActor { { detail: { actor: this, peer: rtcPeer, error: err } } ) ); } - signalingPipeOnMessage( joMessage: any ) { + signalingPipeOnMessage( joMessage: any ): void { const self = this; switch ( joMessage.method ) { case "signalingPublishOffer": @@ -2734,7 +2736,7 @@ export class RTCCreator extends RTCActor { return; } rtcPeer.pc.setRemoteDescription( answerDescription ).then( - function() { + function(): void { // success if( settings.logging.net.signaling.remoteDescription ) { console.log( @@ -2773,7 +2775,7 @@ export class RTCCreator extends RTCActor { break } // switch( joMessage.method ) } - send( data: any ) { // implementation in RTCCreator does send to all + send( data: any ): void { // implementation in RTCCreator does send to all try { const s = socketSentDataMarshall( data ); for( const [ /* idSomebodyOtherSideWalk */, rtcPeerWalk ] @@ -2789,7 +2791,7 @@ export class RTCCreator extends RTCActor { this.onError( err ); } } - onImpersonationComplete() { + onImpersonationComplete(): void { super.onImpersonationComplete(); for( const [ /* idOfferWalk */, rtcPeerWalk ] of Object.entries( this.mapServerOffers ) ) { @@ -2831,7 +2833,7 @@ export class RTCJoiner extends RTCActor { ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -2841,7 +2843,7 @@ export class RTCJoiner extends RTCActor { this.isAnswerPublishedOnSignalingServer = false; super.dispose(); } - describe( strInstanceType?: string, arrAdditionalProps?: any[] ) { + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || @@ -2851,7 +2853,7 @@ export class RTCJoiner extends RTCActor { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } - initPeer() { + initPeer(): void { if( this.isDisposed ) return; const self = this; @@ -2925,7 +2927,7 @@ export class RTCJoiner extends RTCActor { } }; // onicecandidate } - publishSignalingAnswer( event: any ) { + publishSignalingAnswer( event: any ): void { const self = this; // eslint-disable-next-line no-useless-catch try { @@ -2961,11 +2963,11 @@ export class RTCJoiner extends RTCActor { throw err; } } - delayedInitPeer() { + delayedInitPeer(): void { if( this.bWasImpersonated ) this.initPeer(); } - onImpersonationComplete() { + onImpersonationComplete(): void { super.onImpersonationComplete(); const joFetchOfferMessage = { id: utils.randomCallID(), @@ -2979,10 +2981,11 @@ export class RTCJoiner extends RTCActor { } this.signalingPipe.send( joFetchOfferMessage ); } - onIceComplete( event: any ) { + onIceComplete( event: any ): void { super.onIceComplete( event ); } - onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ) { // client peer got result + onOtherSideIdentified( + idSomebodyOtherSide: any, idOffer: any ): void { // client peer got result if( settings.logging.net.signaling.impersonate ) { console.log( this.describe() + " did identified other side RTC creator \"" + @@ -3002,7 +3005,7 @@ export class RTCJoiner extends RTCActor { } } ) ); } - signalingPipeOnMessage( joMessage: any ) { + signalingPipeOnMessage( joMessage: any ): void { const self = this; switch ( joMessage.method ) { case "signalingFetchOffer": @@ -3037,7 +3040,7 @@ export class RTCJoiner extends RTCActor { ); } this.pc.setRemoteDescription( offerDescription ).then( - function() { + function(): void { // success if( settings.logging.net.signaling.remoteDescription ) { console.log( @@ -3063,7 +3066,7 @@ export class RTCJoiner extends RTCActor { "answerCreated", { detail: { participant: self } } ) ); self.pc.setLocalDescription( answerDescription ).then( - function() { + function(): void { // success if( settings.logging.net.signaling.localDescription ) { console.log( @@ -3168,11 +3171,11 @@ export class WebRTCServerPipe extends BasicSocketPipe { new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); } ); } - dispose() { + dispose(): void { this.performDisconnect(); super.dispose(); } - handleServerDisposed() { + handleServerDisposed(): void { this.performDisconnect(); this.isConnected = false; this.clientNumber = 0; @@ -3183,7 +3186,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { // super.handleServerDisposed(); this.dispose(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.isConnected = false; @@ -3198,7 +3201,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { this.url = ""; this.strSignalingServerURL = ""; } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const err = "Cannot send messages to disconnected WebRTC socket server pipe"; this.onError( err ); @@ -3208,13 +3211,13 @@ export class WebRTCServerPipe extends BasicSocketPipe { this.rtcPeer.send( s ); } // eslint-disable-next-line n/handle-callback-err - onError( err: any ) { + onError( err: any ): void { } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } - implReceive( data: any ) { + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); @@ -3316,7 +3319,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { { socket: self, message: jo, errorType: "signalingPipeError" } ) ); } ); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -3328,7 +3331,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.disposeNotifyClients(); super.dispose(); } - addPendingOffer() { + addPendingOffer(): void { if( this.isDisposed ) return; const rtcPeer = @@ -3358,17 +3361,17 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { "peerLocalDescriptionSet", { detail: { acceptor: self, peerEvent: event } } ) ); } ); - const onTimeoutHandler = function() { + const onTimeoutHandler = function(): void { self.disposePendingOffer( rtcPeer.idOffer ); self.updateAllPendingOffers(); }; rtcPeer.on( "publishTimeout", onTimeoutHandler ); rtcPeer.on( "signalingNegotiationTimeout", onTimeoutHandler ); - rtcPeer.on( "signalingNegotiationStart", function() { + rtcPeer.on( "signalingNegotiationStart", function(): void { self.updateAllPendingOffers(); } ); - const retranslateError = function( eventData: any ) { + const retranslateError = function( eventData: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3386,12 +3389,12 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.mapPendingOffers[rtcPeer.idOffer] = rtcPeer; } - detachPendingOffer( idOffer: any ) { + detachPendingOffer( idOffer: any ): void { if( idOffer in this.mapPendingOffers ) // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapPendingOffers[idOffer]; } - disposePendingOffer( idOffer: any ) { + disposePendingOffer( idOffer: any ): void { if( idOffer in this.mapPendingOffers ) { const rtcPeer = this.mapPendingOffers[idOffer]; rtcPeer.dispose(); @@ -3399,7 +3402,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { delete this.mapPendingOffers[idOffer]; } } - removeAllPendingOffers() { + removeAllPendingOffers(): void { for( const [ /* idOfferWalk */, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapServerPeers ) ) { const rtcPeer: any = rtcPeerWalk; @@ -3414,7 +3417,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } this.mapPendingOffers = { }; } - updateAllPendingOffers() { + updateAllPendingOffers(): void { if( this.isDisposed ) return; for( let n = Object.keys( this.mapPendingOffers ).length; @@ -3463,7 +3466,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.url = "rtc_client_pipe-" + this.strSignalingServerURL; this.reconnect(); } - dispose() { + dispose(): void { if( this.isDisposed ) return; this.isDisposing = true; @@ -3471,7 +3474,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.strSignalingServerURL = null; super.dispose(); } - implSend( data: any ) { + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const s = "Cannot send messages to disconnected WebRTC socket client pipe"; this.dispatchEvent( @@ -3483,20 +3486,20 @@ export class WebRTCClientPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); } - reconnect() { + reconnect(): void { this.performDisconnect(); this.rtcConnect( "" + this.strSignalingServerURL ); } - disconnect() { + disconnect(): void { this.performDisconnect(); super.disconnect(); } - performDisconnect() { + performDisconnect(): void { if( !this.isConnected ) return; this.rtcDisconnect(); } - rtcConnect( strSignalingServerURL: string ) { + rtcConnect( strSignalingServerURL: string ): void { if( strSignalingServerURL.length == 0 ) { const s = "Cannot connect signaling server \"" + strSignalingServerURL + "\", bad url"; this.dispatchEvent( @@ -3591,7 +3594,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { } } } - rtcDisconnect() { + rtcDisconnect(): void { if( this.rtcPeer ) { this.rtcPeer.offAll(); this.rtcPeer.dispose(); @@ -3600,7 +3603,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.isConnected = false; this.url = ""; } - implReceive( data: any ) { + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( diff --git a/src/socketServer.ts b/src/socketServer.ts index fd5c37f6..2b21ac1b 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -63,7 +63,7 @@ export class SocketServer extends EventDispatcher { } self.mapAcceptedPipes[socket] = { }; let _offAllPipeEventListeners: any = null; - let _onPipeClose: any = function() { + let _onPipeClose: any = function(): void { if( self.isLogAcceptedSocket ) { self.log( log.fmtInformation( "Socket {url} was {bright}", socket.strSavedRemoteAddress, "closed" ) ); @@ -141,7 +141,7 @@ export class SocketServer extends EventDispatcher { socket.send( joAnswer, isFlush ); } }; - _offAllPipeEventListeners = function() { + _offAllPipeEventListeners = function(): void { if( _onPipeClose ) { socket.off( "close", _onPipeClose ); _onPipeClose = null; diff --git a/src/state.ts b/src/state.ts index e5412270..8dbae8da 100644 --- a/src/state.ts +++ b/src/state.ts @@ -85,7 +85,7 @@ function constructChainProperties(): TPropertiesOfChains { privateKey: owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_ETHEREUM ), address: - function() { return owaspUtils.fnAddressImpl_( this ); }, + function(): string { return owaspUtils.fnAddressImpl_( this ); }, strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_ETHEREUM ), @@ -124,7 +124,7 @@ function constructChainProperties(): TPropertiesOfChains { privateKey: owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN ), address: - function() { return owaspUtils.fnAddressImpl_( this ); }, + function(): string { return owaspUtils.fnAddressImpl_( this ); }, strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN ), nTmPriority: @@ -162,7 +162,7 @@ function constructChainProperties(): TPropertiesOfChains { privateKey: owaspUtils.toEthPrivateKey( process.env.PRIVATE_KEY_FOR_SCHAIN_TARGET ), address: - function() { return owaspUtils.fnAddressImpl_( this ); }, + function(): string { return owaspUtils.fnAddressImpl_( this ); }, strTransactionManagerURL: owaspUtils.toStringURL( process.env.TRANSACTION_MANAGER_URL_S_CHAIN_TARGET ), @@ -516,17 +516,17 @@ export function get(): TIMAState { return imaState; } -export function set( imaStateNew: TIMAState ) { +export function set( imaStateNew: TIMAState ): void { imaState = imaStateNew; return imaState; } let gFlagIsPreventExitAfterLastAction = false; -export function isPreventExitAfterLastAction() { +export function isPreventExitAfterLastAction(): boolean { return gFlagIsPreventExitAfterLastAction; } -export function setPreventExitAfterLastAction( isPrevent: any ) { +export function setPreventExitAfterLastAction( isPrevent: any ): void { gFlagIsPreventExitAfterLastAction = ( !!isPrevent ) } diff --git a/src/utils.ts b/src/utils.ts index da612cfd..984b96b7 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -145,7 +145,7 @@ export async function waitForClonedTokenToAppear( cntAttempts: number, tokensMN: TTokesABIHolder, strMainnetName: string -) { +): Promise { const strTokenSuffixLC = strTokenSuffix.toLowerCase(); const strTokenSuffixUC = owaspUtils.replaceAll( strTokenSuffix.toUpperCase(), "_WITH_METADATA", "_with_metadata" ); @@ -189,7 +189,7 @@ export async function waitForClonedTokenToAppear( export async function waitForClonedTokenAppearErc20( sc: any, tokenERC20SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string -) { +): Promise { if( "abi" in tokenERC20SC && typeof tokenERC20SC.abi === "object" && "address" in tokenERC20SC && typeof tokenERC20SC.address === "string" ) { @@ -206,7 +206,7 @@ export async function waitForClonedTokenAppearErc20( export async function waitForClonedTokenAppearErc721( sc: any, tokenERC721SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string -) { +): Promise { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi === "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address === "string" ) { @@ -224,7 +224,7 @@ export async function waitForClonedTokenAppearErc721( export async function waitForClonedTokenAppearErc721WithMetadata( sc: any, tokenERC721SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string -) { +): Promise { if( "abi" in tokenERC721SC && typeof tokenERC721SC.abi === "object" && "address" in tokenERC721SC && typeof tokenERC721SC.address === "string" ) { @@ -243,7 +243,7 @@ export async function waitForClonedTokenAppearErc721WithMetadata( export async function waitForClonedTokenAppearErc1155( sc: any, tokenERC1155SC: state.TTokeInformation, joAccountSC: state.TAccount, tokensMN: TTokesABIHolder, strMainnetName: string -) { +): Promise { if( "abi" in tokenERC1155SC && typeof tokenERC1155SC.abi === "object" && "address" in tokenERC1155SC && typeof tokenERC1155SC.address === "string" ) { From 5e5894321f5ce03d859c48150ee342a568e022bc Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 13:47:29 +0000 Subject: [PATCH 38/53] ESLint rules simplifications --- src/.eslintrc.cjs | 15 ++------------- src/bls.ts | 14 +++++++------- src/cc.ts | 6 +++--- src/discoveryTools.ts | 2 +- src/eventDispatcher.ts | 2 +- src/imaRegistrationOperations.ts | 16 ++++++++-------- src/imaTx.ts | 10 +++++----- src/log.ts | 4 ++-- src/loop.ts | 14 +++++++------- src/loopWorker.ts | 4 ++-- src/main.ts | 18 +++++++++--------- src/owaspUtils.ts | 10 +++++----- src/socket.ts | 24 ++++++++++++------------ src/state.ts | 2 +- src/threadInfo.ts | 2 +- 15 files changed, 66 insertions(+), 77 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 8155efc7..da90d293 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -14,14 +14,7 @@ module.exports = { "sourceType": "module" }, "rules": { - "indent": [ "error", 4, { - "CallExpression": { - "arguments": 1 - } - } ], "linebreak-style": [ "error", "unix" ], - "quotes": [ "error", "double" ], - "semi": [ "error", "always" ], "eqeqeq": "off", "comma-dangle": [ "error", "never" ], "comma-style": [ "error", "last" ], @@ -32,16 +25,12 @@ module.exports = { "curly": [ "error", "multi-or-nest" ], "nonblock-statement-body-position": [ "error", "below" ], "no-cond-assign": [ "error", "always" ], - "lines-between-class-members": [ "error", "never" ], "max-len": [ "error", { "code": 100, "tabWidth": 4 } ], "max-lines-per-function": [ "error", { "max": 200, "skipBlankLines": false } ], "@typescript-eslint/indent": [ "error", 4, { "ignoredNodes": [ "SwitchCase" ] } ], "@typescript-eslint/quotes": [ "error", "double" ], - "semi": "off", - "@typescript-eslint/semi": "off", - "space-before-function-paren": "off", + "@typescript-eslint/semi": [ "error", "always" ], "@typescript-eslint/space-before-function-paren": "off", - "keyword-spacing": "off", "@typescript-eslint/keyword-spacing": [ "error", { "overrides": { "if": { "before": false, "after": false }, @@ -54,7 +43,7 @@ module.exports = { "@typescript-eslint/prefer-nullish-coalescing": "off", "@typescript-eslint/strict-boolean-expressions": "off", "@typescript-eslint/no-this-alias": "off", - "@typescript-eslint/lines-between-class-members": "off", + "@typescript-eslint/lines-between-class-members": [ "error", "never" ], "@typescript-eslint/prefer-optional-chain": "off" } }; diff --git a/src/bls.ts b/src/bls.ts index 08a04e85..5adbf3d6 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -170,7 +170,7 @@ export interface TSignU256Options { } const anyShellMod: any = shellMod as any; -const shell = anyShellMod.default +const shell = anyShellMod.default; const Keccak = sha3Module.Keccak; @@ -429,7 +429,7 @@ function performBlsGlue( const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; - const strOutput = "" + const strOutput = ""; try { let strInput = ""; const cnt = arrSignResults.length; @@ -1548,7 +1548,7 @@ export async function doSignMessagesM2S( await doSignMessagesImpl( nTransferLoopCounter, "M2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn ) + joExtraSignOpts, fn ); } export async function doSignMessagesS2M( @@ -1559,7 +1559,7 @@ export async function doSignMessagesS2M( await doSignMessagesImpl( nTransferLoopCounter, "S2M", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn ) + joExtraSignOpts, fn ); } export async function doSignMessagesS2S( @@ -1570,7 +1570,7 @@ export async function doSignMessagesS2S( await doSignMessagesImpl( nTransferLoopCounter, "S2S", jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName, - joExtraSignOpts, fn ) + joExtraSignOpts, fn ); } async function prepareSignU256( optsSignU256: TSignU256Options ): Promise < boolean > { @@ -2366,7 +2366,7 @@ async function handleSkaleImaBSU256Prepare( optsBSU256: TBSU256Options ): Promis optsBSU256.strLogPrefix, optsBSU256.strMessageHash ); optsBSU256.details.trace( "{p}Will BLS-sign U256.", optsBSU256.strLogPrefix ); if( !optsBSU256.joAccount ) - throw new Error( "No account to perform blsSignMessageHash for U256" ) + throw new Error( "No account to perform blsSignMessageHash for U256" ); optsBSU256.joAccount = optsBSU256.imaState.chainProperties.sc.joAccount; if( !optsBSU256.joAccount.strSgxURL ) { optsBSU256.joAccount = optsBSU256.imaState.chainProperties.mn.joAccount; @@ -2439,7 +2439,7 @@ export async function handleSkaleImaBSU256( if( !( await handleSkaleImaBSU256Prepare( optsBSU256 ) ) ) return null; if( !optsBSU256.joAccount ) - throw new Error( "No account to perform blsSignMessageHash for U256" ) + throw new Error( "No account to perform blsSignMessageHash for U256" ); let rpcCallOpts: rpcCall.TRPCCallOpts | null = null; if( "strPathSslKey" in optsBSU256.joAccount && typeof optsBSU256.joAccount.strPathSslKey === "string" && diff --git a/src/cc.ts b/src/cc.ts index 15c0e481..f5563e36 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -427,7 +427,7 @@ export const getCircularReplacerForJsonStringify = (): any => { } return value; }; -} +}; export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ cntCensoredMax: 30000, // zero to disable censoring @@ -442,7 +442,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ if( i >= jsonColorizer.cntCensoredMax ) return "[Unknown]"; - ++i // so we know we aren't using the original object anymore + ++i; // so we know we aren't using the original object anymore return value; }; }, @@ -978,7 +978,7 @@ export function stack( err?: any ): string { if( !err ) return ""; if( err && "stack" in err ) { - const st = err.stack + const st = err.stack; if( st && typeof st === "string" ) err = st; } diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 6f3c4056..50cc03f2 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -382,7 +382,7 @@ async function handlePeriodicDiscoveryAttemptActions( .then( function(): void {} ).catch( function( err ): void { log.error( "Failed to continue S-chain discovery, reported error is: {err}", err ); - } ) + } ); } catch ( err ) { } gFlagIsInSChainDiscovery = false; // fnAfter() will be called here inside async call at beginning diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index 72aa71dc..cc578f71 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -32,7 +32,7 @@ export class UniversalDispatcherEvent { console.warn( "UniversalDispatcherEvent will skip", key, "data field" ); continue; } - const anyThis: any = this + const anyThis: any = this; anyThis[key] = value; } } diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index 7d623325..a6a6e585 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -149,21 +149,21 @@ export async function registerSChainInDepositBoxes( // step 1 strActionName = "Register S-chain in deposit boxes, step 1, connectSchain"; details.debug( "{p}Will register S-Chain in lock_and_data on Main-net", strLogPrefix ); if( !joTokenManagerLinker ) - throw new Error( "No TokenManagerLinker contract" ) + throw new Error( "No TokenManagerLinker contract" ); if( !joCommunityLocker ) - throw new Error( "No CommunityLocker contract" ) + throw new Error( "No CommunityLocker contract" ); if( !joTokenManagerETH ) - throw new Error( "No TokenManagerETH contract" ) + throw new Error( "No TokenManagerETH contract" ); if( !joTokenManagerERC20 ) - throw new Error( "No TokenManagerERC20 contract" ) + throw new Error( "No TokenManagerERC20 contract" ); if( !joTokenManagerERC721 ) - throw new Error( "No TokenManagerERC721 contract" ) + throw new Error( "No TokenManagerERC721 contract" ); if( !joTokenManagerERC1155 ) - throw new Error( "No TokenManagerERC1155 contract" ) + throw new Error( "No TokenManagerERC1155 contract" ); if( !joTokenManagerERC721WithMetadata ) - throw new Error( "No TokenManagerERC721WithMetadata contract" ) + throw new Error( "No TokenManagerERC721WithMetadata contract" ); if( !joLinker ) - throw new Error( "No Linker contract" ) + throw new Error( "No Linker contract" ); const arrArguments = [ chainNameSChain, [ joTokenManagerLinker.address, // call params diff --git a/src/imaTx.ts b/src/imaTx.ts index b6a22745..c7f389c7 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -366,13 +366,13 @@ export async function payedCall( switch ( optsPayedCall.joACI.strType ) { case "tm": await payedCallTM( optsPayedCall ); - break + break; case "sgx": await payedCallSGX( optsPayedCall ); - break + break; case "direct": await payedCallDirect( optsPayedCall ); - break + break; default: { const strErrorPrefix = "Transaction sign and send error(INNER FLOW): "; optsPayedCall.details.critical( @@ -435,7 +435,7 @@ export async function checkTransactionToSchain( strLogPrefix, strFromAddress, owaspUtils.toHexStringSafe( unsignedTx.gasLimit ) ); const powNumberBuffer = await calculatePowNumber( strFromAddress, owaspUtils.toBN( unsignedTx.nonce ).toHexString(), - owaspUtils.toHexStringSafe( unsignedTx.gasLimit ), details, strLogPrefix ) + owaspUtils.toHexStringSafe( unsignedTx.gasLimit ), details, strLogPrefix ); details.debug( "{p}Returned PoW-mining number {}", strLogPrefix, powNumberBuffer ); let powNumber: string = powNumberBuffer.toString( "utf8" ).trim(); powNumber = imaUtils.replaceAll( powNumber, "\r", "" ); @@ -524,7 +524,7 @@ const gTransactionManagerPool = "transactions"; function tmGenerateRandomHex( size: number ): string { return [ ...Array( size ) ] - .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ) + .map( () => Math.floor( Math.random() * 16 ).toString( 16 ) ).join( "" ); } function tmMakeId( details: log.TLogger ): string { diff --git a/src/log.ts b/src/log.ts index b5550c5d..7244e9c6 100644 --- a/src/log.ts +++ b/src/log.ts @@ -95,7 +95,7 @@ const getDurationString = cc.getDurationString; export { safeURL, replaceAll, timestampHR, capitalizeFirstLetter, getDurationString }; export function autoEnableColorizationFromCommandLineArgs(): void { - cc.autoEnableFromCommandLineArgs() + cc.autoEnableFromCommandLineArgs(); } export function enableColorization( bIsEnable?: boolean ): void { cc.enable( !!bIsEnable ); @@ -1058,7 +1058,7 @@ export function verboseLevelAsTextForLog( vl: any ): string { } export function verboseName2Number( s: string ): number { const mapReversedVerbose: Map < string, number > = verboseReversed(); - const n = mapReversedVerbose.get( s ) + const n = mapReversedVerbose.get( s ); if( typeof n === "undefined" ) return 9; return n; diff --git a/src/loop.ts b/src/loop.ts index 005cc983..1754b3bb 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -143,11 +143,11 @@ export function checkTimeFraming( const s1: string = log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts ? joRuntimeOpts.joExtraSignOpts.chainNameDst - : "N/A" ) + : "N/A" ); const s2: string = log.fmtInformation( "{}", joRuntimeOpts.joExtraSignOpts ? joRuntimeOpts.joExtraSignOpts.chainIdDst - : "N/A" ) + : "N/A" ); strFrameInfo += log.fmtDebug( " S-Chain destination", "........", s1, "/", s2, "\n" ); } @@ -620,23 +620,23 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ): Promis case "init": if( !joMessage.error ) { aClient.logicalInitComplete = true; - break + break; } aClient.errorLogicalInit = joMessage.error; opts.details.critical( " Loop worker thread {} reported/returned init error: {err}", idxWorker, joMessage.error ); - break + break; case "log": log.information( "LOOP WORKER {} {}", workerData.url, joMessage.message ); - break + break; case "saveTransferError": imaTransferErrorHandling.saveTransferError( joMessage.message.category, joMessage.message.textLog, joMessage.message.ts ); - break + break; case "saveTransferSuccess": imaTransferErrorHandling.saveTransferSuccess( joMessage.message.category ); - break + break; } // switch ( joMessage.method ) } ); const jo: any = { diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 6e3efd23..e55b106f 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -62,7 +62,7 @@ function doSendMessage( type: any, endpoint: any, workerUUID: any, data: any ): class ObserverServer extends SocketServer { initComplete?: boolean; opts: loop.TParallelLoopRunOptions | null; - intervalPeriodicSchainsCaching?: number | null + intervalPeriodicSchainsCaching?: number | null; bIsPeriodicCachingStepInProgress?: boolean; constructor ( acceptor: any ) { super( acceptor ); @@ -208,7 +208,7 @@ class ObserverServer extends SocketServer { owaspUtils.toInteger( joMessage.params.ts ), joMessage.params.signature ).then( function(): void {} ).catch( function(): void {} ); - } + }; console.log( "Initialized in-worker IMA loop {} server in {}", workerData.url, threadInfo.threadDescription() ); } diff --git a/src/main.ts b/src/main.ts index 1b5ffd63..c4b2b602 100644 --- a/src/main.ts +++ b/src/main.ts @@ -187,7 +187,7 @@ function initMonitoringServer(): void { break; case "get_schain_network_info": joAnswer.schain_network_info = imaState.joSChainNetworkInfo; - break + break; case "get_runtime_params": { joAnswer.runtime_params = {}; @@ -234,7 +234,7 @@ function initMonitoringServer(): void { joMessage.isIncludeTextLog ) ) ); joAnswer.last_error_categories = imaTransferErrorHandling.getLastErrorCategories(); - break + break; default: throw new Error( `Unknown method name ${joMessage.method} was specified` ); } // switch( joMessage.method ) @@ -299,17 +299,17 @@ function initJsonRpcServer(): void { case "echo": joAnswer.result = "echo"; fnSendAnswer( joAnswer ); - break + break; case "ping": joAnswer.result = "pong"; fnSendAnswer( joAnswer ); - break + break; case "skale_imaVerifyAndSign": joAnswer = await imaBLS.handleSkaleImaVerifyAndSign( joMessage ); - break + break; case "skale_imaBSU256": joAnswer = await imaBLS.handleSkaleImaBSU256( joMessage ); - break + break; case "skale_imaNotifyLoopWork": if( await pwa.handleLoopStateArrived( imaState, @@ -322,13 +322,13 @@ function initJsonRpcServer(): void { ) ) await loop.spreadArrivedStateOfPendingWorkAnalysis( joMessage ); - break + break; case "skale_getCachedSNB": joAnswer.arrSChainsCached = skaleObserver.getLastCachedSChains(); - break + break; default: joAnswer.error = `Unknown method name ${joMessage.method} was specified`; - break + break; } // switch( joMessage.method ) if( ( !joAnswer ) || typeof joAnswer !== "object" ) { joAnswer = {}; diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 9d652460..ca64c4f3 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -741,27 +741,27 @@ export function toBNbasic( x?: any, optionalRadix?: number ): any { export function toBN( arg: any ): any { if( typeof arg === "string" || typeof arg === "number" ) { let multiplier = toBNbasic( 1 ); - const formattedString = String( arg ).toLowerCase().trim() + const formattedString = String( arg ).toLowerCase().trim(); const isHexPrefixed = formattedString.substr( 0, 2 ) === "0x" || - formattedString.substr( 0, 3 ) === "-0x" + formattedString.substr( 0, 3 ) === "-0x"; let stringArg = stripHexPrefix( formattedString ); if( stringArg.substr( 0, 1 ) === "-" ) { - stringArg = stripHexPrefix( stringArg.slice( 1 ) ) + stringArg = stripHexPrefix( stringArg.slice( 1 ) ); multiplier = toBNbasic( -1, 10 ); } stringArg = stringArg === "" ? "0" : stringArg; if( ( !stringArg.match( /^-?[0-9]+$/ ) && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) || stringArg.match( /^[a-fA-F]+$/ ) || ( isHexPrefixed && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) ) - return toBNbasic( stringArg, 16 ).mul( multiplier ) + return toBNbasic( stringArg, 16 ).mul( multiplier ); if( ( stringArg.match( /^-?[0-9]+$/ ) || stringArg === "" ) && !isHexPrefixed ) return toBNbasic( stringArg, 10 ).mul( multiplier ); } else if( typeof arg === "object" && arg.toString && ( !arg.pop && !arg.push ) ) { if( arg.toString().match( /^-?[0-9]+$/ ) && ( arg.mul || arg.dividedToIntegerBy ) ) return toBNbasic( arg.toString(), 10 ); } else if( arg ) - return toBNbasic( arg ) // try to convert as is + return toBNbasic( arg ); // try to convert as is throw new Error( "Error in owaspUtils.toBN() while converting " + diff --git a/src/socket.ts b/src/socket.ts index eff10af0..9072ffde 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -99,7 +99,7 @@ export class BasicServerAcceptor extends EventDispatcher { socketType: string; socketSubtype: string; isListening: boolean; - strEndPoint: string | null + strEndPoint: string | null; nextClientNumber: number; mapClients: any; url?: string; @@ -407,7 +407,7 @@ export const outOfWorkerAPIs: any = { case "inWorkerConnect": { if( !( jo.workerUUID in gMapAwaitingInWorkerClients ) ) return false; - const pipe: any = gMapAwaitingInWorkerClients["" + jo.workerUUID] + const pipe: any = gMapAwaitingInWorkerClients["" + jo.workerUUID]; pipe.performSuccessfulConnection(); } return true; case "inWorkerDisconnect": { @@ -1545,7 +1545,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { _onWsClose: any; _onWsError: any; _onWsMessage: any; - urlWS: string | null + urlWS: string | null; _removeWsEventListeners: any; constructor ( url: string | URL | null ) { super(); @@ -1714,8 +1714,8 @@ export class WebSocketClientPipe extends BasicSocketPipe { }; export class RTCConnection extends EventDispatcher { - strSignalingServerURL: string | null - idRtcParticipant: string | null + strSignalingServerURL: string | null; + idRtcParticipant: string | null; wasIdentified: boolean; iceComplete: any; pc: any; @@ -1905,7 +1905,7 @@ export class RTCConnection extends EventDispatcher { "WARNING: Participant \"" + this.idRtcParticipant + "\" ICE gathering state changed event with no pc\", event is:", event ); - return + return; } if( settings.logging.net.rtc.iceGatheringStateChange ) { console.log( @@ -1976,7 +1976,7 @@ export class RTCConnection extends EventDispatcher { }; export class RTCActor extends RTCConnection { - idSomebodyCreator: string | null + idSomebodyCreator: string | null; bWasImpersonated: boolean; isCreator: boolean; isJoiner: boolean; @@ -2221,7 +2221,7 @@ export class RTCActor extends RTCConnection { export class RTCServerPeer extends RTCConnection { rtcCreator: any; - idSomebodyOtherSide: string | null + idSomebodyOtherSide: string | null; idOffer: number; tsOfferCreated: any; isPublishing: boolean; @@ -2695,7 +2695,7 @@ export class RTCCreator extends RTCActor { ); } this.onError( strError ); - return + return; } const rtcPeer = this.mapServerOffers[idOffer]; // OKay, finally got answer from candida @@ -2772,7 +2772,7 @@ export class RTCCreator extends RTCActor { break; default: super.signalingPipeOnMessage( joMessage ); - break + break; } // switch( joMessage.method ) } send( data: any ): void { // implementation in RTCCreator does send to all @@ -3115,7 +3115,7 @@ export class RTCJoiner extends RTCActor { break; default: super.signalingPipeOnMessage( joMessage ); - break + break; } // switch( joMessage.method ) } }; @@ -3428,7 +3428,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { }; export class WebRTCClientPipe extends BasicSocketPipe { - strSignalingServerURL: string | null + strSignalingServerURL: string | null; idRtcParticipant: string; offerOptions: any; signalingOptions: any; diff --git a/src/state.ts b/src/state.ts index 8dbae8da..9d45d51f 100644 --- a/src/state.ts +++ b/src/state.ts @@ -528,5 +528,5 @@ export function isPreventExitAfterLastAction(): boolean { } export function setPreventExitAfterLastAction( isPrevent: any ): void { - gFlagIsPreventExitAfterLastAction = ( !!isPrevent ) + gFlagIsPreventExitAfterLastAction = ( !!isPrevent ); } diff --git a/src/threadInfo.ts b/src/threadInfo.ts index 7b6eed8a..71e54a00 100644 --- a/src/threadInfo.ts +++ b/src/threadInfo.ts @@ -33,7 +33,7 @@ const joCustomThreadProperties: any = { }; export { joCustomThreadProperties }; export const sleep = async( milliseconds: number ): Promise => { - await new Promise( resolve => setTimeout( resolve, milliseconds ) ) + await new Promise( resolve => setTimeout( resolve, milliseconds ) ); }; export function getCurrentThreadID(): number { From 062a9e1309dcccb4f07181d7d1737e4fbc567588 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 13:48:18 +0000 Subject: [PATCH 39/53] ESLint rules simplifications --- src/.eslintrc.cjs | 1 - src/eventDispatcher.ts | 9 +++ src/imaTx.ts | 2 + src/loopWorker.ts | 2 + src/socket.ts | 141 +++++++++++++++++++++++++++++++++++++++++ src/socketServer.ts | 1 + 6 files changed, 155 insertions(+), 1 deletion(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index da90d293..326c0680 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -43,7 +43,6 @@ module.exports = { "@typescript-eslint/prefer-nullish-coalescing": "off", "@typescript-eslint/strict-boolean-expressions": "off", "@typescript-eslint/no-this-alias": "off", - "@typescript-eslint/lines-between-class-members": [ "error", "never" ], "@typescript-eslint/prefer-optional-chain": "off" } }; diff --git a/src/eventDispatcher.ts b/src/eventDispatcher.ts index cc578f71..9c95e8ae 100644 --- a/src/eventDispatcher.ts +++ b/src/eventDispatcher.ts @@ -48,6 +48,7 @@ export class EventDispatcher { this.isDisposed = false; this.isDisposing = false; } + dispose(): void { if( this.isDisposed ) return; @@ -58,9 +59,11 @@ export class EventDispatcher { ); this.removeAllEventListeners(); } + hasEventListener( type: any, listener: any ): boolean { return this._listeners.some( item => item.type === type && item.listener === listener ); } + addEventListener( type: any, listener: any ): EventDispatcher { if( !this.hasEventListener( type, listener ) ) { this._listeners.push( { @@ -71,6 +74,7 @@ export class EventDispatcher { } return this; } + removeEventListener( type: any, listener: any ): EventDispatcher { while( true ) { const index = ( listener != undefined ) @@ -86,19 +90,24 @@ export class EventDispatcher { } return this; } + removeAllEventListeners(): EventDispatcher { this._listeners = []; return this; } + on( type: any, listener: any ): EventDispatcher { return this.addEventListener( type, listener ); } + off( type: any, listener: any ): EventDispatcher { return this.removeEventListener( type, listener ); } + offAll(): EventDispatcher { return this.removeAllEventListeners(); } + dispatchEvent( evt: any ): EventDispatcher { const a = this._listeners.filter( item => item.type === evt.type ); for( const item of a ) { diff --git a/src/imaTx.ts b/src/imaTx.ts index c7f389c7..5533b2fb 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -650,6 +650,7 @@ export class TransactionCustomizer { : null; // null means use current gasPrice or recommendedGasPrice this.gasMultiplier = gasMultiplier ? ( 0.0 + gasMultiplier ) : 1.25; } + async computeGasPrice( ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, maxGasPrice: any ): Promise { @@ -677,6 +678,7 @@ export class TransactionCustomizer { } else return gasPrice; } + async computeGas( details: log.TLogger, ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider, diff --git a/src/loopWorker.ts b/src/loopWorker.ts index e55b106f..36d8b857 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -212,6 +212,7 @@ class ObserverServer extends SocketServer { console.log( "Initialized in-worker IMA loop {} server in {}", workerData.url, threadInfo.threadDescription() ); } + dispose(): void { const self: any = this; self.isDisposing = true; @@ -221,6 +222,7 @@ class ObserverServer extends SocketServer { } super.dispose(); } + initLogMethods(): void { const self: any = this; if( "fatal" in self && self.fatal && typeof self.fatal === "function" ) diff --git a/src/socket.ts b/src/socket.ts index 9072ffde..988a57cb 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -112,6 +112,7 @@ export class BasicServerAcceptor extends EventDispatcher { this.nextClientNumber = 1; this.mapClients = { }; } + dispose(): void { if( this.isDisposed ) return; @@ -121,6 +122,7 @@ export class BasicServerAcceptor extends EventDispatcher { this.disposeNotifyClients(); super.dispose(); } + disposeNotifyClients(): void { for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapClients ) ) { const entry: any = entryWalk; @@ -137,6 +139,7 @@ export class BasicServerAcceptor extends EventDispatcher { } this.mapClients = { }; } + unregisterClientByKey( key: any ): void { if( key in this.mapClients ) { const entry = this.mapClients[key]; @@ -151,6 +154,7 @@ export class BasicServerAcceptor extends EventDispatcher { } } } + flush(): void { if( this.isDisposing || this.isDisposed ) return; @@ -165,6 +169,7 @@ export class BasicServerAcceptor extends EventDispatcher { } } } + newDirectConnection(): DirectPipe | null { if( this.isDisposing || this.isDisposed ) return null; @@ -214,6 +219,7 @@ export class BasicSocketPipe extends EventDispatcher { this.relayClientSocket = null; // for relay only this.mapImpersonatedEntries = { }; // for external in-app usage only } + dispose(): void { if( this.relayClientSocket ) { this.relayClientSocket.dispose(); @@ -224,6 +230,7 @@ export class BasicSocketPipe extends EventDispatcher { this.arrAccumulatedMessages = []; super.dispose(); } + disposeImpersonatedEntries(): void { // for external in-app usage only for( const [ /* keyWalk */, entryWalk ] of Object.entries( this.mapImpersonatedEntries ) ) { const entry: any = entryWalk; @@ -235,10 +242,12 @@ export class BasicSocketPipe extends EventDispatcher { } this.mapImpersonatedEntries = { }; // for app usage } + implSend( data: any ): void { throw new Error( "BasicSocketPipe.implSend() must be overridden but calling it was attempted" ); } + isAutoFlush(): boolean { if( this.maxAccumulatedMessagesCount <= 1 ) return true; @@ -247,6 +256,7 @@ export class BasicSocketPipe extends EventDispatcher { return false; return true; } + socketDescription(): string { return "" + // + this.socketType @@ -255,9 +265,11 @@ export class BasicSocketPipe extends EventDispatcher { // + " " this.url; } + socketLoggingTextPrefix( strLogEventName: string ): string { return "" + strLogEventName + " " + this.socketDescription() + " -"; } + send( data: any, isFlush?: boolean ): void { if( this.isDisposed || ( !this.isConnected ) ) return; @@ -275,6 +287,7 @@ export class BasicSocketPipe extends EventDispatcher { if( isFlush ) this.flush(); } + flush(): void { if( this.isDisposed || ( !this.isConnected ) ) return; @@ -304,11 +317,13 @@ export class BasicSocketPipe extends EventDispatcher { if( this.relayClientSocket ) this.relayClientSocket.flush(); } + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( new UniversalDispatcherEvent( "message", { socket: this, message: jo } ) ); } + receive( data: any ): void { if( settings.logging.net.socket.receiveBlock ) console.log( this.socketLoggingTextPrefix( "receive-block" ), data ); @@ -345,11 +360,14 @@ export class BasicSocketPipe extends EventDispatcher { console.log( this.socketLoggingTextPrefix( "receive" ), jo ); this.implReceive( jo ); } + disconnect(): void { this.isConnected = false; } + reconnect(): void { } + checkItself(): void { } }; @@ -362,18 +380,24 @@ export class NullSocketPipe extends BasicSocketPipe { this.url = "NullUrl"; this.isConnected = true; } + dispose(): void { this.isConnected = false; super.dispose(); } + implSend( data: any ): void { } + implReceive( data: any ): void { } + send( data: any ): void { } + receive( data: any ): void { } + flush(): void { } }; @@ -509,10 +533,12 @@ export class InWorkerServerPipe extends BasicSocketPipe { "connection", { socket: self, remoteAddress: "" + self.url } ) ); }, 0 ); } + dispose(): void { this.performDisconnect(); super.dispose(); } + handleServerDisposed(): void { this.performDisconnect(); this.isConnected = false; @@ -522,6 +548,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.url = ""; this.dispose(); } + performDisconnect(): void { if( !this.isConnected ) return; @@ -534,6 +561,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.fnSend = null; this.url = ""; } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend !== "function" ) { const s = "Cannot send messages to disconnected in-worker server pipe"; @@ -544,6 +572,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { const jo: any = socketReceivedDataReverseMarshall( data ); this.fnSend( "inWorkerMessage", this.acceptor.strEndPoint, this.clientPort, jo ); } + disconnect(): void { this.performDisconnect(); super.disconnect(); @@ -576,6 +605,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } + dispose(): void { if( this.isDisposed ) return; @@ -591,6 +621,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { } super.dispose(); } + performAccept( jo: any ): boolean { if( jo.workerUUID in this.mapClients ) return false; // TO-DO: send error answer and return true @@ -599,6 +630,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { p.checkItself(); return true; } + performDisconnect( jo: any ): boolean { if( !( jo.workerUUID in this.mapClients ) ) return false; // TO-DO: send error answer and return true @@ -606,6 +638,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { pipe.performDisconnect(); return true; } + receiveForClientPort( clientPort: any, jo: any ): boolean { if( !( clientPort in this.mapClients ) ) return false; // TO-DO: send error answer and return true @@ -638,6 +671,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.fnSend( this.worker, "inWorkerConnect", this.strEndPoint, this.clientPort, {} ); gMapAwaitingInWorkerClients["" + this.clientPort] = this; } + dispose(): void { if( this.isDisposed ) return; @@ -648,6 +682,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { delete gMapAwaitingInWorkerClients[this.clientPort]; super.dispose(); } + performDisconnect(): void { if( !this.isConnected ) return; @@ -661,6 +696,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.strEndPoint = ""; this.url = ""; } + performSuccessfulConnection(): void { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapAwaitingInWorkerClients[this.clientPort]; @@ -668,6 +704,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.isConnected = true; this.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: this } ) ); } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.worker ) || @@ -685,6 +722,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { const jo: any = socketReceivedDataReverseMarshall( data ); this.fnSend( this.worker, "inWorkerMessage", this.strEndPoint, this.clientPort, jo ); } + disconnect(): void { this.performDisconnect(); super.disconnect(); @@ -920,6 +958,7 @@ export class OutOfWorkerRelay extends EventDispatcher { }; self.acceptor.on( "connection", self.onConnection_ ); } + dispose(): void { this.isDisposing = true; if( this.acceptor ) @@ -927,6 +966,7 @@ export class OutOfWorkerRelay extends EventDispatcher { this.onConnection_ = null; super.dispose(); } + flush(): void { if( this.acceptor ) this.acceptor.flush(); @@ -1167,10 +1207,12 @@ export class OneToOneRelay extends EventDispatcher { pipeOutgoing.on( "error", _onOutgoingPipeError ); pipeOutgoing.on( "message", _onOutgoingPipeMessage ); } + dispose(): void { this.isDisposing = true; super.dispose(); } + flush(): void { if( this.pipeIncoming ) this.pipeIncoming.flush(); @@ -1221,10 +1263,12 @@ export class DirectPipe extends BasicSocketPipe { } } } + dispose(): void { this.performDisconnect(); super.dispose(); } + handleServerDisposed(): void { // this method is for using in local client/server pipe pairs this.performDisconnect(); this.isConnected = false; @@ -1235,6 +1279,7 @@ export class DirectPipe extends BasicSocketPipe { this.url = ""; this.dispose(); } + performDisconnect(): void { if( !this.isConnected ) return; @@ -1248,6 +1293,7 @@ export class DirectPipe extends BasicSocketPipe { this.clientPort = 0; this.url = ""; } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.counterPipe?.isConnected ) ) { const s = "Cannot send messages to disconnected local server pipe"; @@ -1259,6 +1305,7 @@ export class DirectPipe extends BasicSocketPipe { const jo: any = socketReceivedDataReverseMarshall( s ); this.counterPipe.receive( jo ); } + disconnect(): void { this.performDisconnect(); super.disconnect(); @@ -1281,6 +1328,7 @@ export class LocalSocketServerPipe extends DirectPipe { self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } + dispose(): void { super.dispose(); } @@ -1313,6 +1361,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } + dispose(): void { if( this.isDisposed ) return; @@ -1376,6 +1425,7 @@ export class LocalSocketClientPipe extends DirectPipe { ); }, 0 ); } + dispose(): void { super.dispose(); } @@ -1441,10 +1491,12 @@ export class WebSocketServerPipe extends BasicSocketPipe { ); }, 0 ); } + dispose(): void { this.performDisconnect(); super.dispose(); } + handleServerDisposed(): void { this.isConnected = false; this.clientNumber = 0; @@ -1454,6 +1506,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.remoteAddress = ""; this.dispose(); } + performDisconnect(): void { if( !this.isConnected ) return; @@ -1477,6 +1530,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.url = ""; this.remoteAddress = ""; } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket server pipe"; @@ -1487,10 +1541,12 @@ export class WebSocketServerPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.wsConnection.send( s ); } + disconnect(): void { this.performDisconnect(); super.disconnect(); } + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( @@ -1530,6 +1586,7 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); }, 0 ); } + dispose(): void { if( this.isDisposed ) return; @@ -1562,6 +1619,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.url = "ws_client_pipe-" + this.urlWS; this.reconnect(); } + dispose(): void { if( this.isDisposed ) return; @@ -1570,6 +1628,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.urlWS = null; super.dispose(); } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket client pipe"; @@ -1580,19 +1639,23 @@ export class WebSocketClientPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.wsConnection.send( s ); } + reconnect(): void { this.performDisconnect(); this.wsConnect( "" + this.urlWS ); } + disconnect(): void { this.performDisconnect(); super.disconnect(); } + performDisconnect(): void { if( !this.isConnected ) return; this.wsDisconnect(); } + wsConnectAttempt( url: string, reconnectAfterMilliseconds?: number, iv?: any ): boolean { const self = this; try { @@ -1669,6 +1732,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } return false; } + wsConnect( url: string ): void { if( url.length == 0 ) { const s = "Cannot connect web socket server \"" + url + "\", bad url"; @@ -1678,6 +1742,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { } this.wsConnectAttempt( url, settings.net.ws.client.reconnectAfterMilliseconds, null ); } + wsDisconnect(): void { if( this._removeWsEventListeners ) { this._removeWsEventListeners(); @@ -1706,6 +1771,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this.isConnected = false; this.url = ""; } + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( @@ -1733,6 +1799,7 @@ export class RTCConnection extends EventDispatcher { this.pc = null; this.dc = null; } + dispose(): void { if( this.isDisposed ) return; @@ -1745,6 +1812,7 @@ export class RTCConnection extends EventDispatcher { this.idRtcParticipant = null; super.dispose(); } + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { let strInstanceDescription = ( strInstanceType == null || strInstanceType == undefined || @@ -1773,6 +1841,7 @@ export class RTCConnection extends EventDispatcher { strInstanceDescription += "(" + arrProps.join( ", " ) + ")"; return strInstanceDescription; } + closeDataChannel(): void { if( this.dc ) { try { @@ -1790,6 +1859,7 @@ export class RTCConnection extends EventDispatcher { "dataChannelClose", { detail: { actor: this } } ) ); } } + closePeer(): void { if( this.pc ) { try { @@ -1808,6 +1878,7 @@ export class RTCConnection extends EventDispatcher { this.pc = null; } } + onError( err: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( @@ -1817,6 +1888,7 @@ export class RTCConnection extends EventDispatcher { this.closeDataChannel(); this.closePeer(); } + send( data: any ): void { const s = socketSentDataMarshall( data ); if( !this.dc ) { @@ -1829,22 +1901,26 @@ export class RTCConnection extends EventDispatcher { this.onError( `Failed to send message to RTC data channel: ${err}` ); } } + onDataChannelOpen( event: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelOpen", { detail: { actor: this } } ) ); } + onDataChannelClose( even: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelClose", { detail: { actor: this } } ) ); } + onDataChannelError( event: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( "dataChannelError", { detail: { actor: this } } ) ); this.onError( "Data channel error " + event.toString() ); } + onDataChannelMessage( event: any ): void { if( event.data.size ) { if( settings.logging.net.rtc.error ) { @@ -1866,8 +1942,10 @@ export class RTCConnection extends EventDispatcher { } } } + onIceComplete( event: any ): void { } + onIceConnectionStateChange( event: any ): void { // handler for self.pc.oniceconnectionstatechange, // see https://developer.mozilla.org/en-US/docs/ @@ -1895,6 +1973,7 @@ export class RTCConnection extends EventDispatcher { ); } } + onIceGatheringStateChange( event: any ): void { // handler for self.pc.onicegatheringstatechange - this is recommended to handle // in a same way as oniceconnectionstatechange, @@ -1931,6 +2010,7 @@ export class RTCConnection extends EventDispatcher { ); } } + onIceIdentifyResult( event: any ): void { // handler for self.pc.onidentityresult, // see https://developer.mozilla.org/en-US/docs/Web/API/RTCIdentityEvent @@ -1949,6 +2029,7 @@ export class RTCConnection extends EventDispatcher { } } } + onIceSignalingStateChange( event: any ): void { // handler for self.pc.onsignalingstatechange, see // https://developer.mozilla.org/en-US/docs/ @@ -1961,6 +2042,7 @@ export class RTCConnection extends EventDispatcher { "\", event is:", event ); } } + onIceNegotiationNeeded( event: any ): void { // handler for self.pc.onnegotiationneeded, // see https://developer.mozilla.org/en-US/docs/ @@ -2031,6 +2113,7 @@ export class RTCActor extends RTCConnection { this.signalingOptions.idSpace = "" + signalingOptions.idSpace; } } + dispose(): void { if( this.isDisposed ) return; @@ -2041,6 +2124,7 @@ export class RTCActor extends RTCConnection { this.bWasImpersonated = false; super.dispose(); } + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || @@ -2051,9 +2135,11 @@ export class RTCActor extends RTCConnection { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } + onError( err: any ): void { super.onError( err ); } + signalingPipeOpen(): void { try { const self = this; @@ -2081,6 +2167,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } + signalingPipeClose(): void { if( this.signalingPipe ) { try { @@ -2100,6 +2187,7 @@ export class RTCActor extends RTCConnection { "signalingClosed", { detail: { actor: this } } ) ); } } + signalingPipeOnOpen( eventData: any ): void { try { this.dispatchEvent( @@ -2130,6 +2218,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } + signalingPipeOnClose( eventData: any ): void { this.dispatchEvent( new UniversalDispatcherEvent( @@ -2142,6 +2231,7 @@ export class RTCActor extends RTCConnection { } this.signalingPipeClose(); } + signalingPipeOnError( eventData: any ): void { // alert( JSON.stringify( eventData ) ); this.dispatchEvent( @@ -2156,6 +2246,7 @@ export class RTCActor extends RTCConnection { this.onError( eventData ); this.signalingPipeClose(); } + signalingPipeOnRawMessage( eventData: any ): void { try { if( settings.logging.net.signaling.rawMessage ) { @@ -2174,6 +2265,7 @@ export class RTCActor extends RTCConnection { this.onError( err ); } } + signalingPipeOnMessage( joMessage: any ): void { switch ( joMessage.method ) { case "signalingImpersonate": @@ -2214,6 +2306,7 @@ export class RTCActor extends RTCConnection { break; } // switch( joMessage.method ) } + onImpersonationComplete(): void { } // generic implementation should never be called onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ): void { } @@ -2278,6 +2371,7 @@ export class RTCServerPeer extends RTCConnection { this.initPeer(); this.publish(); } + dispose(): void { if( this.isDisposed ) return; @@ -2304,6 +2398,7 @@ export class RTCServerPeer extends RTCConnection { this.tsOfferCreated = null; super.dispose(); } + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || @@ -2312,6 +2407,7 @@ export class RTCServerPeer extends RTCConnection { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } + initPeer(): void { if( this.isDisposed ) return; @@ -2338,6 +2434,7 @@ export class RTCServerPeer extends RTCConnection { "message", function( event: any ) { self.onDataChannelMessage( event ); } ); } } + publishCancel(): void { if( !this.isPublishing ) return; @@ -2349,6 +2446,7 @@ export class RTCServerPeer extends RTCConnection { } this.signalingNegotiationCancel(); // mutual cancel } + signalingNegotiationCancel(): void { if( !this.isSignalingNegotiation ) return; @@ -2359,6 +2457,7 @@ export class RTCServerPeer extends RTCConnection { } this.publishCancel(); // mutual cancel } + publish(): void { if( this.isDisposed || this.isPublishing || this.isSignalingNegotiation || ( !this.rtcCreator?.signalingPipe ) ) @@ -2448,6 +2547,7 @@ export class RTCServerPeer extends RTCConnection { self.onError( "Failed to create offer:" + err ); } ); } + onOtherSideIdentified( idSomebodyOtherSide: any ): void { this.publishCancel(); this.signalingNegotiationCancel(); @@ -2464,6 +2564,7 @@ export class RTCServerPeer extends RTCConnection { } ) ); } + onError( err: any ): void { if( this.rtcCreator ) { this.rtcCreator.onRtcPeerError( this, err ); @@ -2485,10 +2586,12 @@ export class RTCServerPeer extends RTCConnection { } super.onError( err ); } + onImpersonationCompleteForCreator(): void { // specific for server peer if( settings.logging.net.signaling.creatorImpersonationComplete ) console.log( "Creator impersonation complete" ); } + publishOfferOnSignalingServer(): void { const self = this; // eslint-disable-next-line no-useless-catch @@ -2547,6 +2650,7 @@ export class RTCServerPeer extends RTCConnection { throw err; } } + onIceComplete( event: any ): void { super.onIceComplete( event ); const self = this; @@ -2590,6 +2694,7 @@ export class RTCCreator extends RTCActor { self.mapServerPeers = { }; // idSomebodyOtherSide -> RTCServerPeer self.signalingPipeOpen(); } + dispose(): void { if( this.isDisposed ) return; @@ -2608,6 +2713,7 @@ export class RTCCreator extends RTCActor { this.mapServerOffers = { }; super.dispose(); } + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || strInstanceType == undefined || @@ -2616,6 +2722,7 @@ export class RTCCreator extends RTCActor { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } + onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ): void { // server peer got result if( settings.logging.net.signaling.impersonate ) { @@ -2646,6 +2753,7 @@ export class RTCCreator extends RTCActor { this.mapServerPeers["" + idSomebodyOtherSide] = rtcPeer; rtcPeer.onOtherSideIdentified( "" + idSomebodyOtherSide ); } + onRtcPeerError( rtcPeer: any, err: any ): void { if( settings.logging.net.rtc.error ) console.warn( " !!! " + this.describe() + " rtc peer error", err ); @@ -2655,6 +2763,7 @@ export class RTCCreator extends RTCActor { { detail: { actor: this, peer: rtcPeer, error: err } } ) ); } + signalingPipeOnMessage( joMessage: any ): void { const self = this; switch ( joMessage.method ) { @@ -2775,6 +2884,7 @@ export class RTCCreator extends RTCActor { break; } // switch( joMessage.method ) } + send( data: any ): void { // implementation in RTCCreator does send to all try { const s = socketSentDataMarshall( data ); @@ -2791,6 +2901,7 @@ export class RTCCreator extends RTCActor { this.onError( err ); } } + onImpersonationComplete(): void { super.onImpersonationComplete(); for( const [ /* idOfferWalk */, rtcPeerWalk ] @@ -2833,6 +2944,7 @@ export class RTCJoiner extends RTCActor { ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; } + dispose(): void { if( this.isDisposed ) return; @@ -2843,6 +2955,7 @@ export class RTCJoiner extends RTCActor { this.isAnswerPublishedOnSignalingServer = false; super.dispose(); } + describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { strInstanceType = ( strInstanceType == null || @@ -2853,6 +2966,7 @@ export class RTCJoiner extends RTCActor { : strInstanceType; return super.describe( strInstanceType, arrAdditionalProps ); } + initPeer(): void { if( this.isDisposed ) return; @@ -2927,6 +3041,7 @@ export class RTCJoiner extends RTCActor { } }; // onicecandidate } + publishSignalingAnswer( event: any ): void { const self = this; // eslint-disable-next-line no-useless-catch @@ -2963,10 +3078,12 @@ export class RTCJoiner extends RTCActor { throw err; } } + delayedInitPeer(): void { if( this.bWasImpersonated ) this.initPeer(); } + onImpersonationComplete(): void { super.onImpersonationComplete(); const joFetchOfferMessage = { @@ -2981,9 +3098,11 @@ export class RTCJoiner extends RTCActor { } this.signalingPipe.send( joFetchOfferMessage ); } + onIceComplete( event: any ): void { super.onIceComplete( event ); } + onOtherSideIdentified( idSomebodyOtherSide: any, idOffer: any ): void { // client peer got result if( settings.logging.net.signaling.impersonate ) { @@ -3005,6 +3124,7 @@ export class RTCJoiner extends RTCActor { } } ) ); } + signalingPipeOnMessage( joMessage: any ): void { const self = this; switch ( joMessage.method ) { @@ -3171,10 +3291,12 @@ export class WebRTCServerPipe extends BasicSocketPipe { new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); } ); } + dispose(): void { this.performDisconnect(); super.dispose(); } + handleServerDisposed(): void { this.performDisconnect(); this.isConnected = false; @@ -3186,6 +3308,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { // super.handleServerDisposed(); this.dispose(); } + performDisconnect(): void { if( !this.isConnected ) return; @@ -3201,6 +3324,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { this.url = ""; this.strSignalingServerURL = ""; } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const err = "Cannot send messages to disconnected WebRTC socket server pipe"; @@ -3210,13 +3334,16 @@ export class WebRTCServerPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); } + // eslint-disable-next-line n/handle-callback-err onError( err: any ): void { } + disconnect(): void { this.performDisconnect(); super.disconnect(); } + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( @@ -3319,6 +3446,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { { socket: self, message: jo, errorType: "signalingPipeError" } ) ); } ); } + dispose(): void { if( this.isDisposed ) return; @@ -3331,6 +3459,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.disposeNotifyClients(); super.dispose(); } + addPendingOffer(): void { if( this.isDisposed ) return; @@ -3389,11 +3518,13 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.mapPendingOffers[rtcPeer.idOffer] = rtcPeer; } + detachPendingOffer( idOffer: any ): void { if( idOffer in this.mapPendingOffers ) // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapPendingOffers[idOffer]; } + disposePendingOffer( idOffer: any ): void { if( idOffer in this.mapPendingOffers ) { const rtcPeer = this.mapPendingOffers[idOffer]; @@ -3402,6 +3533,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { delete this.mapPendingOffers[idOffer]; } } + removeAllPendingOffers(): void { for( const [ /* idOfferWalk */, rtcPeerWalk ] of Object.entries( this.rtcCreator.mapServerPeers ) ) { @@ -3417,6 +3549,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } this.mapPendingOffers = { }; } + updateAllPendingOffers(): void { if( this.isDisposed ) return; @@ -3466,6 +3599,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.url = "rtc_client_pipe-" + this.strSignalingServerURL; this.reconnect(); } + dispose(): void { if( this.isDisposed ) return; @@ -3474,6 +3608,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.strSignalingServerURL = null; super.dispose(); } + implSend( data: any ): void { if( ( !this.isConnected ) || ( !this.rtcPeer ) ) { const s = "Cannot send messages to disconnected WebRTC socket client pipe"; @@ -3486,19 +3621,23 @@ export class WebRTCClientPipe extends BasicSocketPipe { const s = socketSentDataMarshall( data ); this.rtcPeer.send( s ); } + reconnect(): void { this.performDisconnect(); this.rtcConnect( "" + this.strSignalingServerURL ); } + disconnect(): void { this.performDisconnect(); super.disconnect(); } + performDisconnect(): void { if( !this.isConnected ) return; this.rtcDisconnect(); } + rtcConnect( strSignalingServerURL: string ): void { if( strSignalingServerURL.length == 0 ) { const s = "Cannot connect signaling server \"" + strSignalingServerURL + "\", bad url"; @@ -3594,6 +3733,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { } } } + rtcDisconnect(): void { if( this.rtcPeer ) { this.rtcPeer.offAll(); @@ -3603,6 +3743,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.isConnected = false; this.url = ""; } + implReceive( data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); this.dispatchEvent( diff --git a/src/socketServer.ts b/src/socketServer.ts index 2b21ac1b..0a5ebde2 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -163,6 +163,7 @@ export class SocketServer extends EventDispatcher { this.dispatchEvent( new UniversalDispatcherEvent( "initialized", { detail: { ref: this } } ) ); } + dispose(): void { this.isDisposing = true; super.dispose(); From 2acad779f8a8cac19696f788eee77223d1b86f59 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 13:51:12 +0000 Subject: [PATCH 40/53] ESLint rules simplifications --- src/.eslintrc.cjs | 3 +-- src/bls.ts | 2 +- src/rpcCall.ts | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index 326c0680..b17ce0a8 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -42,7 +42,6 @@ module.exports = { "@typescript-eslint/no-non-null-asserted-nullish-coalescing": "off", "@typescript-eslint/prefer-nullish-coalescing": "off", "@typescript-eslint/strict-boolean-expressions": "off", - "@typescript-eslint/no-this-alias": "off", - "@typescript-eslint/prefer-optional-chain": "off" + "@typescript-eslint/no-this-alias": "off" } }; diff --git a/src/bls.ts b/src/bls.ts index 5adbf3d6..236d7463 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -872,7 +872,7 @@ async function checkCorrectnessOfMessagesToSign( joChainName = imaState.chainProperties.mn.strChainName; } else if( strDirection == "S2S" ) { joAccount = imaState.chainProperties.sc.joAccount; - if( ( !joExtraSignOpts ) || ( !( joExtraSignOpts.chainNameDst ) ) ) + if( ( !joExtraSignOpts?.chainNameDst ) ) throw new Error( "Missing destination chain name for BLS signing" ); joChainName = joExtraSignOpts.chainNameDst; const ethersProvider: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 9b6d6c51..db30cbba 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -403,7 +403,7 @@ export async function doCall( const response = await urllib.request( joCall.url, requestOpts as urllib.RequestOptions ); const body = response.data.toString( "utf8" ); - if( response && response.statusCode && response.statusCode !== 200 ) + if( response?.statusCode !== 200 ) log.warning( "REST call status code is {}", response.statusCode ); joOut = JSON.parse( body ); From 6f3f86705f178d7b9f543d2c1d9f4caa9a228ba9 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 14:02:42 +0000 Subject: [PATCH 41/53] ESLint rules simplifications --- src/.eslintrc.cjs | 2 -- src/bls.ts | 8 ++++---- src/cc.ts | 4 ++-- src/cli.ts | 4 ++-- src/discoveryTools.ts | 6 +++--- src/imaHelperAPIs.ts | 4 ++-- src/imaTx.ts | 4 ++-- src/log.ts | 32 ++++++++++++++++---------------- src/oracle.ts | 2 +- src/owaspUtils.ts | 13 ++++++++----- src/pwa.ts | 4 ++-- src/rpcCall.ts | 6 +++--- src/socket.ts | 15 +++++---------- src/state.ts | 26 +++++++++++++------------- src/utils.ts | 6 +++--- 15 files changed, 66 insertions(+), 70 deletions(-) diff --git a/src/.eslintrc.cjs b/src/.eslintrc.cjs index b17ce0a8..2b01af34 100644 --- a/src/.eslintrc.cjs +++ b/src/.eslintrc.cjs @@ -39,8 +39,6 @@ module.exports = { "while": { "before": false, "after": false } } } ], - "@typescript-eslint/no-non-null-asserted-nullish-coalescing": "off", - "@typescript-eslint/prefer-nullish-coalescing": "off", "@typescript-eslint/strict-boolean-expressions": "off", "@typescript-eslint/no-this-alias": "off" } diff --git a/src/bls.ts b/src/bls.ts index 236d7463..55079fa3 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -1441,7 +1441,7 @@ async function doSignMessagesImpl( strFromChainName, joExtraSignOpts, // eslint-disable-next-line n/handle-callback-err - fn: fn || async function( + fn: fn ?? async function( err: Error | string | null, jarrMessages: any[], joGlueResult: any | null ) {}, bHaveResultReportCalled: false, strLogPrefix: "", @@ -2026,7 +2026,7 @@ async function doSignReadyHashHandleCallResult( } export async function doSignReadyHash( - strMessageHash: string, isExposeOutput: any ): Promise < boolean > { + strMessageHash: string, isExposeOutput: any ): Promise < TSignResult | null > { const imaState: state.TIMAState = state.get(); const strLogPrefix = ""; const details: log.TLogger = log.createMemoryStream(); @@ -2044,7 +2044,7 @@ export async function doSignReadyHash( details.trace( "{p}hash value to sign is {}", strLogPrefix, strMessageHash ); if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "sign ready hash", details ) ) - return false; + return null; let joAccount: state.TAccount = imaState.chainProperties.sc.joAccount; if( !joAccount.strSgxURL ) { joAccount = imaState.chainProperties.mn.joAccount; @@ -2204,7 +2204,7 @@ async function prepareS2sOfSkaleImaVerifyAndSign( async function handleBlsSignMessageHashResult( optsHandleVerifyAndSign: THandleVerifyAndSignOptions, joCallData: THandleVerifyAndSignCallData, joAccount: state.TAccount, joCall: rpcCall.TRPCCall, joIn: any, joOut: any -): Promise < void > { +): Promise < TSignResult > { optsHandleVerifyAndSign.details.trace( "{p}{bright} Call to SGX done, " + "answer is: {}", optsHandleVerifyAndSign.strLogPrefix, optsHandleVerifyAndSign.strDirection, joOut ); diff --git a/src/cc.ts b/src/cc.ts index f5563e36..af109cc3 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -528,7 +528,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ // http://jsfiddle.net/KJQ9K/554 // https://qastack.ru/programming/4810841/pretty-print-json-using-javascript export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ): string { - strKeyNamePrefix = strKeyNamePrefix || ""; + strKeyNamePrefix = strKeyNamePrefix ?? ""; jo = jo.replace( /&/g, "&" ).replace( //g, ">" ); return jo.replace( // eslint-disable-next-line max-len @@ -598,7 +598,7 @@ export function j1( x?: any, n?: number, strKeyNamePrefix?: string ): string { } let s = safeStringifyJSON( x, n ); if( !gFlagIsEnabled ) - return s || ""; + return s ?? ""; s = "" + syntaxHighlightJSON( s, strKeyNamePrefix ); if( isDefaultKeyNamePrefix && s.length > 9 && s[0] == " " ) s = s.substring( 1, s.length ); diff --git a/src/cli.ts b/src/cli.ts index 4a5254eb..3b3bf329 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -46,7 +46,7 @@ const gStrVersion = function att( ...args: any[] ): string { return log.fmtAttention( ...args ); }; export function printAbout( isLog?: boolean ): boolean { - isLog = isLog || false; + isLog = isLog ?? false; const strMsg = log.fmtTrace( att( gStrAppName ), " version ", log.fmtNotice( gStrVersion ) ); if( isLog ) log.information( strMsg ); @@ -1205,7 +1205,7 @@ function parseOtherArgs( imaState: state.TIMAState, joArg: any ): boolean { export function parse( joExternalHandlers: any, argv?: any[] ): number { const imaState: state.TIMAState = state.get(); - argv = argv || process.argv; + argv = argv ?? process.argv; const cntArgs = argv.length; for( let idxArg = 2; idxArg < cntArgs; ++idxArg ) { const joArg = parseCommandLineArgument( argv[idxArg] ); diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 50cc03f2..006dfd75 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -316,7 +316,7 @@ async function handlePeriodicDiscoveryAttemptActions( const imaState: state.TIMAState = state.get(); if( !imaState.joSChainNetworkInfo ) throw new Error( "No own S-Chain network information" ); - fnAfter = fnAfter || function(): void {}; + fnAfter = fnAfter ?? function(): void {}; gFlagIsInSChainDiscovery = true; const cntNodesOnChain = getSChainNodesCount( imaState.joSChainNetworkInfo ); try { @@ -398,7 +398,7 @@ export async function continueSChainDiscoveryInBackgroundIfNeeded( ): Promise { if( gTimerSChainDiscovery != null ) return; - fnAfter = fnAfter || function(): void {}; + fnAfter = fnAfter ?? function(): void {}; const imaState: state.TIMAState = state.get(); if( imaState.joSChainDiscovery.repeatIntervalMilliseconds <= 0 ) { if( !isSilentReDiscovery ) @@ -756,7 +756,7 @@ export async function doPeriodicSChainNetworkDiscoveryIfNeeded( log.debug( "Periodic S-Chain re-discovery will be done with {} interval...", periodicDiscoveryInterval ); } - fnAfterRediscover = fnAfterRediscover || function( status: boolean ) { }; + fnAfterRediscover = fnAfterRediscover ?? function( status: boolean ) { }; gIntervalPeriodicDiscovery = setInterval( function(): void { let nCountToWait = ( cntNodesOnChain > 2 ) ? Math.ceil( cntNodesOnChain * 2 / 3 ) diff --git a/src/imaHelperAPIs.ts b/src/imaHelperAPIs.ts index ac2fe602..23cc51f2 100644 --- a/src/imaHelperAPIs.ts +++ b/src/imaHelperAPIs.ts @@ -40,14 +40,14 @@ export function getMillisecondsSleepBeforeFetchOutgoingMessageEvent(): number { return gMillisecondsSleepBeforeFetchOutgoingMessageEvent; } export function setMillisecondsSleepBeforeFetchOutgoingMessageEvent( val?: number ): void { - gMillisecondsSleepBeforeFetchOutgoingMessageEvent = val || 0; + gMillisecondsSleepBeforeFetchOutgoingMessageEvent = val ?? 0; } export function getSleepBetweenTransactionsOnSChainMilliseconds(): number { return gMillisecondsSleepBetweenTransactionsOnSChain; } export function setSleepBetweenTransactionsOnSChainMilliseconds( val?: number ): void { - gMillisecondsSleepBetweenTransactionsOnSChain = val || 0; + gMillisecondsSleepBetweenTransactionsOnSChain = val ?? 0; } export function getWaitForNextBlockOnSChain(): boolean { diff --git a/src/imaTx.ts b/src/imaTx.ts index 5533b2fb..910a23fb 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -616,8 +616,8 @@ async function tmEnsureTransaction( priority: any, txAdjusted: any, cntAttempts?: number, sleepMilliseconds?: number ): Promise { - cntAttempts = cntAttempts || 1; - sleepMilliseconds = sleepMilliseconds || ( 30 * 1000 ); + cntAttempts = cntAttempts ?? 1; + sleepMilliseconds = sleepMilliseconds ?? ( 30 * 1000 ); let txId = ""; let joReceipt = null; let idxAttempt = 0; diff --git a/src/log.ts b/src/log.ts index 7244e9c6..d6ff1b14 100644 --- a/src/log.ts +++ b/src/log.ts @@ -515,8 +515,8 @@ export function createFileOutput( const objEntry: TLogger = { id: gIdentifierAllocatorCounter++, strPath: "" + strFilePath, - nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation || 0 ), - nMaxFilesCount: 0 + ( nMaxFilesCount || 0 ), + nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation ?? 0 ), + nMaxFilesCount: 0 + ( nMaxFilesCount ?? 0 ), objStream: null, haveOwnTimestamps: false, isPausedTimeStamps: false, @@ -670,7 +670,7 @@ export function insertFileOutput( } export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): string { - strDefaultErrorText = strDefaultErrorText || "unknown error or error without a description"; + strDefaultErrorText = strDefaultErrorText ?? "unknown error or error without a description"; if( !jo ) return strDefaultErrorText; try { @@ -1025,18 +1025,18 @@ function computeVerboseAlias(): Map < string, number > { if( name ) m.set( name, key ); } - m.set( "empty", m.get( "silent" ) || 0 ); // alias - m.set( "none", m.get( "silent" ) || 0 ); // alias - m.set( "stop", m.get( "fatal" ) || 0 ); // alias - m.set( "bad", m.get( "critical" ) || 0 ); // alias - m.set( "err", m.get( "error" ) || 0 ); // alias - m.set( "warn", m.get( "warning" ) || 0 ); // alias - m.set( "attn", m.get( "attention" ) || 0 ); // alias - m.set( "info", m.get( "information" ) || 0 ); // alias - m.set( "note", m.get( "notice" ) || 0 ); // alias - m.set( "dbg", m.get( "debug" ) || 0 ); // alias - m.set( "crazy", m.get( "trace" ) || 0 ); // alias - m.set( "detailed", m.get( "trace" ) || 0 ); // alias + m.set( "empty", m.get( "silent" ) ?? 0 ); // alias + m.set( "none", m.get( "silent" ) ?? 0 ); // alias + m.set( "stop", m.get( "fatal" ) ?? 0 ); // alias + m.set( "bad", m.get( "critical" ) ?? 0 ); // alias + m.set( "err", m.get( "error" ) ?? 0 ); // alias + m.set( "warn", m.get( "warning" ) ?? 0 ); // alias + m.set( "attn", m.get( "attention" ) ?? 0 ); // alias + m.set( "info", m.get( "information" ) ?? 0 ); // alias + m.set( "note", m.get( "notice" ) ?? 0 ); // alias + m.set( "dbg", m.get( "debug" ) ?? 0 ); // alias + m.set( "crazy", m.get( "trace" ) ?? 0 ); // alias + m.set( "detailed", m.get( "trace" ) ?? 0 ); // alias return m; } let gMapReversedVerbose: Map < string, number > = new Map < string, number >(); @@ -1051,7 +1051,7 @@ export function verboseLevelAsTextForLog( vl: any ): string { if( typeof vl === "undefined" ) vl = verboseGet(); if( vl in gMapVerbose ) { - const tl = gMapVerbose.get( vl ) || 0; + const tl = gMapVerbose.get( vl ) ?? 0; return "" + tl; } return "unknown(" + JSON.stringify( vl ) + ")"; diff --git a/src/oracle.ts b/src/oracle.ts index 1ecb3692..7c46dd0c 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -39,7 +39,7 @@ const gBigNum256: any = owaspUtils.toBN( 256 ); const gBigNumUpperPart: any = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); function getUtcTimestampString( d?: Date ): string { - d = d || new Date(); // use now time if d is not specified + d = d ?? new Date(); // use now time if d is not specified const nUtcUnixTimeStampWithMilliseconds = d.getTime(); const t = "" + nUtcUnixTimeStampWithMilliseconds; return t; diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index ca64c4f3..d25b6373 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -191,7 +191,7 @@ export function toURL( s: any ): URL | null { } export function toStringURL( s?: any, defValue?: string ): string { - defValue = defValue || ""; + defValue = defValue ?? ""; try { const url = toURL( s ); if( url == null || url == undefined ) @@ -273,7 +273,7 @@ export function validateEthPrivateKey( value?: any ): boolean { export function toEthAddress( value?: any, defValue?: string ): string { try { value = "" + ( value ? ensureStartsWith0x( value.toString() ) : "" ); - defValue = defValue || ""; + defValue = defValue ?? ""; if( !validateEthAddress( value ) ) return defValue; } catch ( err ) { @@ -284,7 +284,7 @@ export function toEthAddress( value?: any, defValue?: string ): string { export function toEthPrivateKey( value?: any, defValue?: string ): string { try { value = "" + ( value ? value.toString() : "" ); - defValue = defValue || ""; + defValue = defValue ?? ""; if( !validateEthPrivateKey( value ) ) return defValue; } catch ( err ) { @@ -708,7 +708,7 @@ export function ethersProviderToUrl( "url" in ethersProvider.connection && typeof ethersProvider.connection.url === "string" ) strURL = "" + ethersProvider.connection.url; - return strURL || "N/A-URL"; + return strURL ?? "N/A-URL"; } export function isHexPrefixed( s: any ): boolean { @@ -751,10 +751,13 @@ export function toBN( arg: any ): any { multiplier = toBNbasic( -1, 10 ); } stringArg = stringArg === "" ? "0" : stringArg; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing if( ( !stringArg.match( /^-?[0-9]+$/ ) && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) || + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing stringArg.match( /^[a-fA-F]+$/ ) || ( isHexPrefixed && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) ) return toBNbasic( stringArg, 16 ).mul( multiplier ); + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing if( ( stringArg.match( /^-?[0-9]+$/ ) || stringArg === "" ) && !isHexPrefixed ) return toBNbasic( stringArg, 10 ).mul( multiplier ); } else if( typeof arg === "object" && arg.toString && ( !arg.pop && !arg.push ) ) { @@ -789,7 +792,7 @@ export function toHexStringSafe( val?: any ): string { export function setInterval2( fn: () => void, t: number, stepMilliSeconds?: number ): any { const iv: any = { real_iv: null, - stepMilliSeconds: stepMilliSeconds || 1000, + stepMilliSeconds: stepMilliSeconds ?? 1000, maxMilliSeconds: t, accumulatedMilliSeconds: 0 }; diff --git a/src/pwa.ts b/src/pwa.ts index 8e433a42..1f3592cd 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -93,7 +93,7 @@ export async function checkOnLoopStart( imaState: state.TIMAState, strLoopWorkType: string, nIndexS2S?: number ): Promise { try { - nIndexS2S = nIndexS2S || 0; // convert to number if undefined + nIndexS2S = nIndexS2S ?? 0; // convert to number if undefined if( !checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type` ); if( !imaState.isPWA ) @@ -213,7 +213,7 @@ async function notifyOnLoopImpl( ): Promise { const se = isStart ? "start" : "end"; try { - nIndexS2S = nIndexS2S || 0; // convert to number if undefined + nIndexS2S = nIndexS2S ?? 0; // convert to number if undefined if( !checkLoopWorkTypeStringIsCorrect( strLoopWorkType ) ) throw new Error( `Specified value ${strLoopWorkType} is not a correct loop work type` ); if( !imaState.isPWA ) diff --git a/src/rpcCall.ts b/src/rpcCall.ts index db30cbba..f7c6f472 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -84,8 +84,8 @@ export type TFunctionWsDone = ( nStep: number ) => Promise < void >; export async function waitWebSocketIsOpen( socket: ws.WebSocket, fnDone?: TFunctionWsDone, fnStep?: TFunctionWsStep ): Promise { - fnDone = fnDone || async function( nStep: number ) { }; - fnStep = fnStep || async function( nStep: number ) { return true; }; + fnDone = fnDone ?? async function( nStep: number ) { }; + fnStep = fnStep ?? async function( nStep: number ) { return true; }; let nStep = 0; const promiseComplete = new Promise( function( resolve, reject ) { let isInsideAsyncHandler = false; @@ -432,7 +432,7 @@ export async function rpcCallCreate( } const joCall: TRPCCall = { url: "" + strURL, - joRpcOptions: opts || null, + joRpcOptions: opts ?? null, mapPendingByCallID: new Map < TCallID, TCallHandlerEntry >(), wsConn: null, isAutoReconnect: diff --git a/src/socket.ts b/src/socket.ts index 988a57cb..bcc1ddb9 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -1237,9 +1237,7 @@ export class DirectPipe extends BasicSocketPipe { this.socketSubtype = "direct.not.initialized.yet"; this.isConnected = false; this.acceptor = null; - this.counterPipe = ( counterPipe != null && counterPipe != undefined ) - ? counterPipe - : null; // set outside after this constructor call + this.counterPipe = counterPipe ?? null; // set outside after this constructor call this.strEndPoint = this.counterPipe ? ( "2-" + this.counterPipe.strEndPoint ) : ( "1-" + utils.randomDirectPipeID() ); @@ -3252,7 +3250,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.isConnected = true; self.acceptor = acceptor; self.clientNumber = 0 + acceptor.nextClientNumber; - self.clientPort = 0 + ( self.clientNumber || 0 ); + self.clientPort = 0 + ( self.clientNumber ?? 0 ); ++acceptor.nextClientNumber; self.rtcPeer = rtcPeer; self.strSignalingServerURL = @@ -3388,16 +3386,13 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { ? peerAdditionalOptions : settings.net.rtc.peerAdditionalOptions; this.socketType = "WebRTC"; - this.maxActiveOfferCount = - ( maxActiveOfferCount != null && maxActiveOfferCount != undefined ) - ? maxActiveOfferCount - : settings.net.rtc.maxActiveOfferCount; + this.maxActiveOfferCount = maxActiveOfferCount ?? settings.net.rtc.maxActiveOfferCount; if( this.maxActiveOfferCount < 1 ) this.maxActiveOfferCount = 1; this.mapPendingOffers = { }; // idOffer -> RTCServerPeer - this.timeToPublishMilliseconds = timeToPublishMilliseconds || + this.timeToPublishMilliseconds = timeToPublishMilliseconds ?? settings.net.rtc.timeToPublishMilliseconds; - this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds || + this.timeToSignalingNegotiationMilliseconds = timeToSignalingNegotiationMilliseconds ?? settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.rtcCreator = new RTCCreator( diff --git a/src/state.ts b/src/state.ts index 9d45d51f..2e5518a6 100644 --- a/src/state.ts +++ b/src/state.ts @@ -95,17 +95,17 @@ function constructChainProperties(): TPropertiesOfChains { strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_ETHEREUM ), strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_ETHEREUM ), strPathSslKey: - ( process.env.SGX_SSL_KEY_FILE_ETHEREUM || "" ).toString().trim(), + ( process.env.SGX_SSL_KEY_FILE_ETHEREUM ?? "" ).toString().trim(), strPathSslCert: - ( process.env.SGX_SSL_CERT_FILE_ETHEREUM || "" ).toString().trim(), + ( process.env.SGX_SSL_CERT_FILE_ETHEREUM ?? "" ).toString().trim(), strBlsKeyName: owaspUtils.toStringURL( process.env.BLS_KEY_ETHEREUM ) }, transactionCustomizer: imaTx.getTransactionCustomizerForMainNet(), ethersProvider: null, strURL: owaspUtils.toStringURL( process.env.URL_W3_ETHEREUM ), strChainName: - ( process.env.CHAIN_NAME_ETHEREUM || "Mainnet" ).toString().trim(), - chainId: owaspUtils.toInteger( process.env.CID_ETHEREUM ) || -4, + ( process.env.CHAIN_NAME_ETHEREUM ?? "Mainnet" ).toString().trim(), + chainId: owaspUtils.toInteger( process.env.CID_ETHEREUM ) ?? -4, strPathAbiJson: "", joAbiIMA: { }, bHaveAbiIMA: false, @@ -133,17 +133,17 @@ function constructChainProperties(): TPropertiesOfChains { strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN ), strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN ), strPathSslKey: - ( process.env.SGX_SSL_KEY_FILE_S_CHAIN || "" ).toString().trim(), + ( process.env.SGX_SSL_KEY_FILE_S_CHAIN ?? "" ).toString().trim(), strPathSslCert: - ( process.env.SGX_SSL_CERT_FILE_S_CHAIN || "" ).toString().trim(), + ( process.env.SGX_SSL_CERT_FILE_S_CHAIN ?? "" ).toString().trim(), strBlsKeyName: owaspUtils.toStringURL( process.env.BLS_KEY_S_CHAIN ) }, transactionCustomizer: imaTx.getTransactionCustomizerForSChain(), ethersProvider: null, strURL: owaspUtils.toStringURL( process.env.URL_W3_S_CHAIN ), strChainName: - ( process.env.CHAIN_NAME_SCHAIN || "id-S-chain" ).toString().trim(), - chainId: owaspUtils.toInteger( process.env.CID_SCHAIN ) || -4, + ( process.env.CHAIN_NAME_SCHAIN ?? "id-S-chain" ).toString().trim(), + chainId: owaspUtils.toInteger( process.env.CID_SCHAIN ) ?? -4, strPathAbiJson: "", joAbiIMA: { }, bHaveAbiIMA: false, @@ -168,20 +168,20 @@ function constructChainProperties(): TPropertiesOfChains { process.env.TRANSACTION_MANAGER_URL_S_CHAIN_TARGET ), nTmPriority: owaspUtils.toInteger( - process.env.TRANSACTION_MANAGER_PRIORITY_S_CHAIN_TARGET ) || 5, + process.env.TRANSACTION_MANAGER_PRIORITY_S_CHAIN_TARGET ) ?? 5, strSgxURL: owaspUtils.toStringURL( process.env.SGX_URL_S_CHAIN_TARGET ), strSgxKeyName: owaspUtils.toStringURL( process.env.SGX_KEY_S_CHAIN_TARGET ), strPathSslKey: - ( process.env.SGX_SSL_KEY_FILE_S_CHAIN_TARGET || "" ).toString().trim(), + ( process.env.SGX_SSL_KEY_FILE_S_CHAIN_TARGET ?? "" ).toString().trim(), strPathSslCert: - ( process.env.SGX_SSL_CERT_FILE_S_CHAIN_TARGET || "" ).toString().trim(), + ( process.env.SGX_SSL_CERT_FILE_S_CHAIN_TARGET ?? "" ).toString().trim(), strBlsKeyName: owaspUtils.toStringURL( process.env.BLS_KEY_T_CHAIN ) }, transactionCustomizer: imaTx.getTransactionCustomizerForSChainTarget(), ethersProvider: null, strURL: owaspUtils.toStringURL( process.env.URL_W3_S_CHAIN_TARGET ), strChainName: - ( process.env.CHAIN_NAME_SCHAIN_TARGET || "id-T-chain" ).toString().trim(), + ( process.env.CHAIN_NAME_SCHAIN_TARGET ?? "id-T-chain" ).toString().trim(), chainId: owaspUtils.toInteger( process.env.CID_SCHAIN_TARGET ) || -4, strPathAbiJson: "", joAbiIMA: { }, @@ -470,7 +470,7 @@ export function get(): TIMAState { bHaveSkaleManagerABI: false, strChainNameOriginChain: - ( process.env.CHAIN_NAME_SCHAIN_ORIGIN || "Mainnet" ).toString().trim(), + ( process.env.CHAIN_NAME_SCHAIN_ORIGIN ?? "Mainnet" ).toString().trim(), strAddrErc20Explicit: "", strAddrErc20ExplicitTarget: "", // S<->S target diff --git a/src/utils.ts b/src/utils.ts index 984b96b7..c0cd8b04 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -72,7 +72,7 @@ export function fileExists( strPath: string ): boolean { } export function fileLoad( strPath: string, strDefault?: string | null ): string { - strDefault = strDefault || ""; + strDefault = strDefault ?? ""; if( !fileExists( strPath ) ) return strDefault; try { @@ -341,8 +341,8 @@ export function concatByte( ui8a: Uint8Array, byte: number ): Uint8Array { } export function bytesConcat( a1?: Uint8Array, a2?: Uint8Array ): Uint8Array { - a1 = a1 || new Uint8Array(); - a2 = a2 || new Uint8Array(); + a1 = a1 ?? new Uint8Array(); + a2 = a2 ?? new Uint8Array(); return concatUint8Arrays( a1, a2 ); } From b10e125f5c4213bf7296a6e159c0c3a2fb6741ec Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 15:23:31 +0000 Subject: [PATCH 42/53] ESLint rules simplifications --- src/imaCore.ts | 3 ++- src/imaTx.ts | 4 ++-- src/log.ts | 2 +- src/state.ts | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/imaCore.ts b/src/imaCore.ts index e3986839..0186ccf7 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -373,7 +373,7 @@ async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ): return joValues; } -async function gatherMessages( optsTransfer: TTransferOptions ): Promise { +async function gatherMessages( optsTransfer: TTransferOptions ): Promise { optsTransfer.arrMessageCounters = []; optsTransfer.jarrMessages = []; optsTransfer.nIdxCurrentMsgBlockStart = 0 + optsTransfer.nIdxCurrentMsg; @@ -519,6 +519,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ): Promise { }; optsTransfer.jarrMessages.push( joMessage ); } + return true; } async function preCheckAllMessagesSign( diff --git a/src/imaTx.ts b/src/imaTx.ts index 910a23fb..7a58269a 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -564,8 +564,8 @@ async function tmSend( details: log.TLogger, tx: any, priority: number = 5 ): Pr } function tmIsFinished( record: any ): boolean { - if( record == null ) - return null; + if( !record ) + return false; return [ "SUCCESS", "FAILED", "DROPPED" ].includes( record.status ); } diff --git a/src/log.ts b/src/log.ts index d6ff1b14..9c0411ed 100644 --- a/src/log.ts +++ b/src/log.ts @@ -675,7 +675,7 @@ export function extractErrorMessage( jo?: any, strDefaultErrorText?: string ): s return strDefaultErrorText; try { const isError = function( err: Error | string ): boolean { - return err && err instanceof Error && err.stack && err.message; + return !!( ( err && err instanceof Error && err.stack && err.message ) ); }; if( !isError( jo ) ) { if( "error" in jo ) { diff --git a/src/state.ts b/src/state.ts index 2e5518a6..39009665 100644 --- a/src/state.ts +++ b/src/state.ts @@ -516,7 +516,7 @@ export function get(): TIMAState { return imaState; } -export function set( imaStateNew: TIMAState ): void { +export function set( imaStateNew: TIMAState ): TIMAState { imaState = imaStateNew; return imaState; } From e5a9d16ddfea318492d844118331de1dd128dfa4 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 17:14:54 +0000 Subject: [PATCH 43/53] ESLint rules simplifications --- src/bls.ts | 47 ++-- src/cc.ts | 160 +++++++------- src/cli.ts | 346 ++++++++++-------------------- src/imaCore.ts | 20 +- src/imaEthOperations.ts | 7 +- src/imaOracleOperations.ts | 3 +- src/imaRegistrationOperations.ts | 7 +- src/imaReimbursementOperations.ts | 14 +- src/imaSgxExternalSigner.ts | 2 +- src/imaTokenOperations.ts | 57 +++-- src/imaTransferErrorHandling.ts | 14 +- src/imaTx.ts | 10 +- src/log.ts | 22 +- src/loop.ts | 8 +- src/loopWorker.ts | 2 +- src/main.ts | 12 +- src/observer.ts | 6 +- src/oracle.ts | 2 +- src/owaspUtils.ts | 13 +- src/pwa.ts | 2 +- src/rpcCall.ts | 2 +- src/socket.ts | 233 +++++++++----------- src/socketServer.ts | 8 +- src/socketUtils.ts | 40 +--- src/utils.ts | 14 +- 25 files changed, 440 insertions(+), 611 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index 55079fa3..ec83e884 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -435,7 +435,7 @@ function performBlsGlue( const cnt = arrSignResults.length; for( let i = 0; i < cnt; ++i ) { const jo: any = arrSignResults[i]; - if( ( !jo ) || typeof jo !== "object" ) + if( !jo ) throw new Error( `Failed to save BLS part ${i} because it's not JSON object` ); const strPath = strActionDir + "/sign-result" + jo.index + ".json"; details.trace( "{p}Saving {} file containing {}", strLogPrefix, strPath, jo ); @@ -525,7 +525,7 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an const cnt = arrSignResults.length; for( let i = 0; i < cnt; ++i ) { const jo: any = arrSignResults[i]; - if( ( !jo ) || typeof jo !== "object" ) + if( !jo ) throw new Error( `Failed to save BLS part ${i} because it's not JSON object` ); const strPath = strActionDir + "/sign-result" + jo.index + ".json"; details.trace( "{p}Saving {} file...", strLogPrefix, strPath ); @@ -632,7 +632,7 @@ function performBlsVerifyI( imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); imaUtils.jsonFileSave( strActionDir + "/BLS_keys" + nZeroBasedNodeIndex + ".json", joPublicKey ); - const strVerifyCommand = "" + + const strVerifyCommand = imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + @@ -690,7 +690,7 @@ function performBlsVerifyIU256( imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); imaUtils.jsonFileSave( strActionDir + "/BLS_keys" + nZeroBasedNodeIndex + ".json", joPublicKey ); - const strVerifyCommand = "" + + const strVerifyCommand = imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + @@ -765,7 +765,7 @@ function performBlsVerify( imaUtils.jsonFileSave( strActionDir + "/common_public_key.json", joCommonPublicKeyToSave ); details.trace( "{p}BLS common public key for verification is:\n{}", strLogPrefix, joCommonPublicKey ); - const strVerifyCommand = "" + + const strVerifyCommand = imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + @@ -827,7 +827,7 @@ function performBlsVerifyU256( imaUtils.jsonFileSave( strActionDir + "/common_public_key.json", joCommonPublicKeyToSave ); details.trace( "{p}BLS u256 common public key for verification is:\n{}", strLogPrefix, joCommonPublicKey ); - const strVerifyCommand = "" + + const strVerifyCommand = imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + @@ -917,7 +917,7 @@ async function checkCorrectnessOfMessagesToSign( joMessage.destinationContract, joMessage.data ); const outgoingMessageData: any = { dstChainHash: owaspUtils.ethersMod.ethers.utils.id( joChainName ), - msgCounter: 0 + idxMessage, + msgCounter: idxMessage, srcContract: joMessage.sender, dstContract: joMessage.destinationContract, data: joMessage.data @@ -998,7 +998,7 @@ async function prepareSignMessagesImpl( optsSignOperation.jarrMessages, optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.joExtraSignOpts ); - await optsSignOperation.fn( null, optsSignOperation.jarrMessages, null ); + await optsSignOperation.fn( null, optsSignOperation.jarrMessages ); return true; } await checkCorrectnessOfMessagesToSign( @@ -1225,22 +1225,22 @@ async function doSignConfigureChainAccessParams( optsSignOperation.targetChainID = -4; optsSignOperation.fromChainID = -4; if( optsSignOperation.strDirection == "M2S" ) { - optsSignOperation.targetChainName = "" + + optsSignOperation.targetChainName = ( optsSignOperation.imaState.chainProperties.sc.strChainName ? optsSignOperation.imaState.chainProperties.sc.strChainName : "" ); - optsSignOperation.fromChainName = "" + + optsSignOperation.fromChainName = ( optsSignOperation.imaState.chainProperties.mn.strChainName ? optsSignOperation.imaState.chainProperties.mn.strChainName : "" ); optsSignOperation.targetChainID = optsSignOperation.imaState.chainProperties.sc.chainId; optsSignOperation.fromChainID = optsSignOperation.imaState.chainProperties.mn.chainId; } else if( optsSignOperation.strDirection == "S2M" ) { - optsSignOperation.targetChainName = "" + + optsSignOperation.targetChainName = ( optsSignOperation.imaState.chainProperties.mn.strChainName ? optsSignOperation.imaState.chainProperties.mn.strChainName : "" ); - optsSignOperation.fromChainName = "" + + optsSignOperation.fromChainName = ( optsSignOperation.imaState.chainProperties.sc.strChainName ? optsSignOperation.imaState.chainProperties.sc.strChainName : "" ); @@ -1249,9 +1249,8 @@ async function doSignConfigureChainAccessParams( } else if( optsSignOperation.strDirection == "S2S" ) { if( !optsSignOperation.joExtraSignOpts ) throw new Error( "No S2S signing options provided" ); - optsSignOperation.targetChainName = - "" + optsSignOperation.joExtraSignOpts.chainNameDst; - optsSignOperation.fromChainName = "" + optsSignOperation.joExtraSignOpts.chainNameSrc; + optsSignOperation.targetChainName = optsSignOperation.joExtraSignOpts.chainNameDst; + optsSignOperation.fromChainName = optsSignOperation.joExtraSignOpts.chainNameSrc; optsSignOperation.targetChainID = optsSignOperation.joExtraSignOpts.chainIdDst; optsSignOperation.fromChainID = optsSignOperation.joExtraSignOpts.chainIdSrc; } else { @@ -1316,7 +1315,7 @@ async function doSignProcessHandleCall( } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); const joResultFromNode: any = { - index: "" + nZeroBasedNodeIndex, + index: nZeroBasedNodeIndex.toString(), signature: { X: arrTmp[0], Y: arrTmp[1] @@ -1356,7 +1355,7 @@ async function doSignProcessHandleCall( } if( bNodeSignatureOKay ) { optsSignOperation.arrSignResults.push( { - index: "" + nZeroBasedNodeIndex, + index: nZeroBasedNodeIndex.toString(), signature: splitSignatureShare( joOut.result.signResult.signatureShare ), fromNode: joNode, // extra, not needed for bls_glue signResult: joOut.result.signResult @@ -1403,7 +1402,7 @@ async function doSignProcessOneImpl( return; await doSignConfigureChainAccessParams( optsSignOperation ); const joParams: THandleVerifyAndSignCallDataParams = { - direction: "" + optsSignOperation.strDirection, + direction: optsSignOperation.strDirection, startMessageIdx: optsSignOperation.nIdxCurrentMsgBlockStart, dstChainName: optsSignOperation.targetChainName, srcChainName: optsSignOperation.fromChainName, @@ -1412,8 +1411,8 @@ async function doSignProcessOneImpl( messages: optsSignOperation.jarrMessages, qa: { skaledNumber: 0 + i, - "optsSignOperation.sequenceId": "" + optsSignOperation.sequenceId, - ts: "" + log.generateTimestampString( null, false ) + "optsSignOperation.sequenceId": optsSignOperation.sequenceId, + ts: log.generateTimestampString( null, false ) } }; optsSignOperation.details.trace( @@ -1655,7 +1654,7 @@ async function doSignU256OneImplHandleCallResult( } const arrTmp = joOut.result.signResult.signatureShare.split( ":" ); const joResultFromNode: any = { - index: "" + nZeroBasedNodeIndex, + index: nZeroBasedNodeIndex.toString(), signature: { X: arrTmp[0], Y: arrTmp[1] } }; optsSignU256.details.trace( "{p}Will verify sign result for node {}", @@ -1688,7 +1687,7 @@ async function doSignU256OneImplHandleCallResult( } if( bNodeSignatureOKay ) { optsSignU256.arrSignResults.push( { - index: "" + nZeroBasedNodeIndex, + index: nZeroBasedNodeIndex.toString(), signature: splitSignatureShare( joOut.result.signResult.signatureShare ), fromNode: joNode, // extra, not needed for bls_glue @@ -1927,7 +1926,7 @@ export async function doVerifyReadyHash( let isSuccess = false; const arrTmp = signature.signatureShare.split( ":" ); const joResultFromNode: any = { - index: "" + nZeroBasedNodeIndex, + index: nZeroBasedNodeIndex.toString(), signature: { X: arrTmp[0], Y: arrTmp[1] @@ -1960,7 +1959,7 @@ export async function doVerifyReadyHash( imaUtils.jsonFileSave( strActionDir + "/hash.json", joMsg ); imaUtils.jsonFileSave( strActionDir + "/BLS_keys" + nZeroBasedNodeIndex + ".json", joPublicKey ); - const strVerifyCommand = "" + + const strVerifyCommand = imaState.strPathBlsVerify + " --t " + nThreshold + " --n " + nParticipants + diff --git a/src/cc.ts b/src/cc.ts index af109cc3..f4380eb1 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -50,7 +50,7 @@ export function replaceAll( str: string, find: string, replace: string ): string } export function validateRadix( value?: any, radix?: any ): number { - value = "" + ( value ? value.toString() : "10" ); + value = ( value ? value.toString() : "10" ); value = value.trim(); radix = ( radix == null || radix == undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) @@ -62,7 +62,6 @@ export function validateRadix( value?: any, radix?: any ): number { export function validateInteger( value?: any, radix?: any ): boolean { try { - value = "" + value; value = value.trim(); if( value.length < 1 ) return false; @@ -225,22 +224,22 @@ function urlObjColorized( objURL?: any ): string { if( !objURL ) return strURL; if( objURL.protocol && objURL.protocol !== null && objURL.protocol !== undefined ) - strURL += "" + yellow( objURL.protocol ) + normal( "//" ); + strURL += yellow( objURL.protocol ) + normal( "//" ); if( objURL.username && objURL.username !== null && objURL.username !== undefined ) { - strURL += "" + magenta( objURL.username ); + strURL += magenta( objURL.username ); if( objURL.password && objURL.password !== null && objURL.password !== undefined ) strURL += normal( ":" ) + yellow( objURL.password ); strURL += normal( "@" ); } if( objURL.hostname ) - strURL += "" + magenta( logArgToStringAsIpv4( objURL.hostname ) ); + strURL += magenta( logArgToStringAsIpv4( objURL.hostname ) ); if( objURL.port && objURL.port !== null && objURL.port !== undefined ) strURL += normal( ":" ) + logArgToString( objURL.port ); if( objURL.pathname && objURL.pathname !== null && objURL.pathname !== undefined && objURL.pathname !== "/" ) - strURL += "" + yellow( replaceAll( objURL.pathname, "/", normal( "/" ) ) ); + strURL += yellow( replaceAll( objURL.pathname, "/", normal( "/" ) ) ); if( objURL.search && objURL.search !== null && objURL.search !== undefined ) - strURL += "" + magenta( objURL.search ); + strURL += magenta( objURL.search ); return strURL; } @@ -326,31 +325,31 @@ export function logArgToString( ...args: any[] ): string { for( i = 0; i < cnt; ++i ) { const arg = arguments[i]; if( arg === undefined ) { - s += "" + undefval( arg ); + s += undefval( arg ); continue; } if( arg === null ) { - s += "" + nullval( arg ); + s += nullval( arg ); continue; } if( isNaN( arg ) ) { - s += "" + nanval( arg ); + s += nanval( arg ); continue; } if( typeof arg === "boolean" ) { - s += "" + tf( arg ); + s += tf( arg ); continue; } if( typeof arg === "object" && typeof arg.valueOf() === "boolean" ) - s += "" + tf( arg.valueOf() ); + s += tf( arg.valueOf() ); if( typeof arg === "number" || typeof arg === "bigint" ) { - s += "" + number( arg ); + s += number( arg ); continue; } if( typeof arg === "object" && ( typeof arg.valueOf() === "number" || typeof arg.valueOf() === "bigint" ) ) { - s += "" + number( arg.valueOf() ); + s += number( arg.valueOf() ); continue; } if( typeof arg === "string" || arg instanceof String ) { @@ -362,26 +361,26 @@ export function logArgToString( ...args: any[] ): string { strURL += normal( anyURL.strStrippedStringComma ); if( objURL.protocol ) - strURL += "" + yellow( objURL.protocol ) + normal( "//" ); + strURL += yellow( objURL.protocol ) + normal( "//" ); if( objURL.username ) { - strURL += "" + magenta( objURL.username ); + strURL += magenta( objURL.username ); if( objURL.password ) strURL += normal( ":" ) + yellow( objURL.password ); strURL += normal( "@" ); } if( objURL.hostname ) - strURL += "" + magenta( logArgToStringAsIpv4( objURL.hostname ) ); + strURL += magenta( logArgToStringAsIpv4( objURL.hostname ) ); if( objURL.port ) strURL += normal( ":" ) + logArgToString( objURL.port ); if( objURL.pathname ) - strURL += "" + yellow( replaceAll( objURL.pathname, "/", normal( "/" ) ) ); + strURL += yellow( replaceAll( objURL.pathname, "/", normal( "/" ) ) ); if( objURL.search ) - strURL += "" + magenta( objURL.search ); + strURL += magenta( objURL.search ); if( anyURL.strStrippedStringComma ) strURL += normal( anyURL.strStrippedStringComma ); @@ -392,19 +391,19 @@ export function logArgToString( ...args: any[] ): string { if( ( arg.length > 1 && arg[0] == "-" && arg[1] != "-" ) || ( arg.length > 2 && arg[0] == "-" && arg[1] == "-" && arg[2] != "-" ) ) { - s += "" + cla( arg ); + s += cla( arg ); continue; } if( arg.length > 0 && ( arg[0] == "\"" || arg[0] == "'" ) ) { - s += "" + strval( arg ); + s += strval( arg ); continue; } if( isFloat2( arg ) ) { - s += "" + real( arg ); + s += real( arg ); continue; } if( isInt2( arg ) ) { - s += "" + number( arg ); + s += number( arg ); continue; } } @@ -412,7 +411,7 @@ export function logArgToString( ...args: any[] ): string { s += jsonColorizer.prettyPrintConsole( arg ); continue; } - s += "" + kk( arg ); + s += kk( arg ); } return s; } @@ -510,7 +509,9 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ ( jsonColorizer.cntCensoredMax > 0 ) ? jsonColorizer.censor( obj ) : null, cntSpaces ); - const s = tmp ? tmp.replace( jsonLine, jsonColorizer.replacerConsole ) : ( "" + tmp ); + const s = tmp + ? tmp.replace( jsonLine, jsonColorizer.replacerConsole ) + : ( tmp.toString() ); return s; } catch ( err ) { } obj = JSON.parse( JSON.stringify( obj, getCircularReplacerForJsonStringify() ) ); @@ -519,7 +520,7 @@ export const jsonColorizer: any = { // see http://jsfiddle.net/unLSJ/ ( jsonColorizer.cntCensoredMax > 0 ) ? jsonColorizer.censor( obj ) : null, cntSpaces ); - const s = tmp ? tmp.replace( jsonLine, jsonColorizer.replacerConsole ) : ( "" + tmp ); + const s = tmp ? tmp.replace( jsonLine, jsonColorizer.replacerConsole ) : ( tmp.toString() ); return s; } }; @@ -557,21 +558,20 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ): stri ) cls = "string"; switch ( cls ) { - case "key": - return "" + - strKeyNamePrefix + logArgToString( match.replace( /[": ]/g, "" ) ) + ": "; + case "key": return strKeyNamePrefix + + logArgToString( match.replace( /[": ]/g, "" ) ) + ": "; case "boolean": return tf( match ); case "null": - return "" + nullval( match ); + return nullval( match ); case "undefined": - return "" + undefval( match ); + return undefval( match ); case "nan": - return "" + nanval( match ); + return nanval( match ); case "string": - return "" + strval( match ); + return strval( match ); case "number": - return "" + number( match ); + return number( match ); } return logArgToString( match ); } ); @@ -579,7 +579,7 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ): stri export function safeStringifyJSON( jo?: any, n?: number ): string | undefined { try { - const s = "" + JSON.stringify( jo, getCircularReplacerForJsonStringify(), n ); + const s = JSON.stringify( jo, getCircularReplacerForJsonStringify(), n ); return s; } catch ( err ) { } @@ -587,7 +587,7 @@ export function safeStringifyJSON( jo?: any, n?: number ): string | undefined { } export function jn( x?: any ): string { - return "" + jsonColorizer.prettyPrintConsole( x ); + return jsonColorizer.prettyPrintConsole( x ); } export function j1( x?: any, n?: number, strKeyNamePrefix?: string ): string { @@ -599,7 +599,7 @@ export function j1( x?: any, n?: number, strKeyNamePrefix?: string ): string { let s = safeStringifyJSON( x, n ); if( !gFlagIsEnabled ) return s ?? ""; - s = "" + syntaxHighlightJSON( s, strKeyNamePrefix ); + s = syntaxHighlightJSON( s, strKeyNamePrefix ); if( isDefaultKeyNamePrefix && s.length > 9 && s[0] == " " ) s = s.substring( 1, s.length ); return s; @@ -661,222 +661,222 @@ export { export function normal( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgWhite + s + reset; + return fgWhite + s + reset; } export function trace( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgWhite + s + reset; + return fgWhite + s + reset; } export function debug( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgWhite + s + reset; + return fgWhite + s + reset; } export function debugDark( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgBlack + enlight + s + reset; + return fgBlack + enlight + s + reset; } export function note( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgBlue + s + reset; + return fgBlue + s + reset; } export function notice( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + s + reset; + return fgMagenta + s + reset; } export function info( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgBlue + enlight + s + reset; + return fgBlue + enlight + s + reset; } export function warning( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + s + reset; + return fgYellow + s + reset; } export function warn( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + s + reset; + return fgYellow + s + reset; } export function error( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgRed + s + reset; + return fgRed + s + reset; } export function fatal( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + bgRed + fgYellow + enlight + s + reset; + return bgRed + fgYellow + enlight + s + reset; } export function success( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + enlight + s + reset; + return fgGreen + enlight + s + reset; } export function attention( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgCyan + s + reset; + return fgCyan + s + reset; } export function bright( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgWhite + enlight + s + reset; + return fgWhite + enlight + s + reset; } export function sunny( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + enlight + s + reset; + return fgYellow + enlight + s + reset; } export function rx( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + s + reset; + return fgMagenta + s + reset; } export function rxa( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + enlight + s + reset; + return fgMagenta + enlight + s + reset; } export function tx( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + s + reset; + return fgGreen + s + reset; } export function txa( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + enlight + s + reset; + return fgGreen + enlight + s + reset; } export function date( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + s + reset; + return fgYellow + s + reset; } export function time( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + enlight + s + reset; + return fgMagenta + enlight + s + reset; } export function fracTime( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + s + reset; + return fgMagenta + s + reset; } export function yes( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + enlight + s + reset; + return fgGreen + enlight + s + reset; } export function no( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgRed + s + reset; + return fgRed + s + reset; } export function number( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgBlue + enlight + s + reset; + return fgBlue + enlight + s + reset; } export function real( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + s + reset; + return fgMagenta + s + reset; } export function undefval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + enlight + s + reset; + return fgGreen + enlight + s + reset; } export function nullval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + enlight + s + reset; + return fgGreen + enlight + s + reset; } export function nanval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgGreen + enlight + s + reset; + return fgGreen + enlight + s + reset; } export function yellow( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + s + reset; + return fgYellow + s + reset; } export function magenta( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgMagenta + s + reset; + return fgMagenta + s + reset; } export function cla( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgBlue + dim + s + reset; + return fgBlue + dim + s + reset; } export function kk( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + enlight + s + reset; + return fgYellow + enlight + s + reset; } export function strval( s?: any ): string { if( !gFlagIsEnabled ) return s ? s.toString() : JSON.stringify( s ); - return "" + fgYellow + s + reset; + return fgYellow + s + reset; } export function n2s( n: any, sz: number ): string { - let s = "" + n; + let s = n ? n.toString() : ""; while( s.length < sz ) s = "0" + s; return s; } export function timestampHR(): number { - const d = new Date(); - const ts = Math.floor( ( d ).getTime() ); + const newDateTime = new Date(); + const ts = Math.floor( ( newDateTime ).getTime() ); return ts; } export function timestampUnix(): number { - const d = new Date(); - const ts = Math.floor( ( d ).getTime() / 1000 ); + const newDateTime = new Date(); + const ts = Math.floor( ( newDateTime ).getTime() / 1000 ); return ts; } @@ -902,25 +902,25 @@ export function getDurationString( tsFrom: number, tsTo: number ): string { const secs = n % 60; n = Math.floor( n / 60 ); - s = "" + n2s( secs, 2 ) + s; + s = n2s( secs, 2 ) + s; if( n == 0 ) return trimLeftUnneededTimestampZeros( s ); s = ":" + s; const mins = n % 60; n = Math.floor( n / 60 ); - s = "" + n2s( mins, 2 ) + s; + s = n2s( mins, 2 ) + s; if( n == 0 ) return trimLeftUnneededTimestampZeros( s ); s = ":" + s; const hours = n % 24; n = Math.floor( n / 24 ); - s = "" + n2s( hours, 2 ) + s; + s = n2s( hours, 2 ) + s; if( n == 0 ) return trimLeftUnneededTimestampZeros( s ); - return "" + n + " " + ( ( n > 1 ) ? "days" : "day" ) + "," + s; + return ( n ? n.toString() : "" ) + " " + ( ( n > 1 ) ? "days" : "day" ) + "," + s; } export function capitalizeFirstLetter( s?: any ): string { diff --git a/src/cli.ts b/src/cli.ts index 3b3bf329..3bdfa11c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -63,7 +63,6 @@ export function parseCommandLineArgument( s: string ): any { try { if( !s ) return joArg; - s = "" + s; while( s.length > 0 && s[0] == "-" ) s = s.substring( 1 ); const n = s.indexOf( "=" ); @@ -126,9 +125,8 @@ export function ensureHaveCredentials( ) { ++cntAccountVariantsSpecified; ensureHaveValue( - "" + strFriendlyChainName + "/TM/URL", - joAccount.strTransactionManagerURL, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/TM/URL", + joAccount.strTransactionManagerURL, isExitIfEmpty, isPrintValue ); } if( "strSgxURL" in joAccount && typeof joAccount.strSgxURL === "string" && @@ -136,26 +134,23 @@ export function ensureHaveCredentials( ) { ++cntAccountVariantsSpecified; ensureHaveValue( - "" + strFriendlyChainName + "/SGX/URL", - joAccount.strSgxURL, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/SGX/URL", + joAccount.strSgxURL, isExitIfEmpty, isPrintValue ); if( "strPathSslKey" in joAccount && typeof joAccount.strPathSslKey === "string" && joAccount.strPathSslKey.length > 0 ) { ensureHaveValue( - "" + strFriendlyChainName + "/SGX/SSL/keyPath", - joAccount.strPathSslKey, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/SGX/SSL/keyPath", + joAccount.strPathSslKey, isExitIfEmpty, isPrintValue ); } if( "strPathSslCert" in joAccount && typeof joAccount.strPathSslCert === "string" && joAccount.strPathSslCert.length > 0 ) { ensureHaveValue( - "" + strFriendlyChainName + "/SGX/SSL/certPath", - joAccount.strPathSslCert, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/SGX/SSL/certPath", + joAccount.strPathSslCert, isExitIfEmpty, isPrintValue ); } } if( "strSgxKeyName" in joAccount && @@ -164,9 +159,8 @@ export function ensureHaveCredentials( ) { ++cntAccountVariantsSpecified; ensureHaveValue( - "" + strFriendlyChainName + "/SGX/keyName", - joAccount.strSgxKeyName, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/SGX/keyName", + joAccount.strSgxKeyName, isExitIfEmpty, isPrintValue ); } if( "privateKey" in joAccount && typeof joAccount.privateKey === "string" && @@ -174,19 +168,15 @@ export function ensureHaveCredentials( ) { ++cntAccountVariantsSpecified; ensureHaveValue( - "" + strFriendlyChainName + "/privateKey", - joAccount.privateKey, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/privateKey", + joAccount.privateKey, isExitIfEmpty, isPrintValue ); } if( "address_" in joAccount && - typeof joAccount.address_ === "string" && - joAccount.address_.length > 0 - ) { + typeof joAccount.address_ === "string" && joAccount.address_.length > 0 ) { ++cntAccountVariantsSpecified; ensureHaveValue( - "" + strFriendlyChainName + "/walletAddress", - joAccount.address_, isExitIfEmpty, isPrintValue - ); + strFriendlyChainName + "/walletAddress", + joAccount.address_, isExitIfEmpty, isPrintValue ); } if( cntAccountVariantsSpecified == 0 ) { log.error( "ARGUMENTS VALIDATION WARNING: bad credentials information " + @@ -315,19 +305,19 @@ function parseChainAccessArgs( imaState: state.TIMAState, joArg: any ): boolean function parseTransactionManagerArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "tm-url-main-net" ) { owaspUtils.verifyArgumentIsURL( joArg ); - const strURL = "" + joArg.value; + const strURL = joArg.value.toString(); imaState.chainProperties.mn.joAccount.strTransactionManagerURL = strURL; return true; } if( joArg.name == "tm-url-s-chain" ) { owaspUtils.verifyArgumentIsURL( joArg ); - const strURL = "" + joArg.value; + const strURL = joArg.value.toString(); imaState.chainProperties.sc.joAccount.strTransactionManagerURL = strURL; return true; } if( joArg.name == "tm-url-t-chain" ) { owaspUtils.verifyArgumentIsURL( joArg ); - const strURL = "" + joArg.value; + const strURL = joArg.value.toString(); imaState.chainProperties.tc.joAccount.strTransactionManagerURL = strURL; return true; } @@ -726,49 +716,49 @@ function parseTransactionArgs( imaState: state.TIMAState, joArg: any ): boolean function parsePaymentAmountArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "value" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); - imaState.nAmountOfWei = owaspUtils.parseMoneySpecToWei( "" + joArg.value, true ); + imaState.nAmountOfWei = owaspUtils.parseMoneySpecToWei( joArg.value.toString(), true ); return true; } if( joArg.name == "wei" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "wei", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "wei", true ); return true; } if( joArg.name == "babbage" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "babbage", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "babbage", true ); return true; } if( joArg.name == "lovelace" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "lovelace", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "lovelace", true ); return true; } if( joArg.name == "shannon" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "shannon", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "shannon", true ); return true; } if( joArg.name == "szabo" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "szabo", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "szabo", true ); return true; } if( joArg.name == "finney" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "finney", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "finney", true ); return true; } if( joArg.name == "ether" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nAmountOfWei = - owaspUtils.parseMoneySpecToWei( "" + joArg.value + "ether", true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString() + "ether", true ); return true; } if( joArg.name == "amount" ) { @@ -1044,7 +1034,7 @@ function parseLoggingArgs( imaState: state.TIMAState, joArg: any ): boolean { } if( joArg.name == "log" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); - imaState.strLogFilePath = "" + joArg.value; + imaState.strLogFilePath = joArg.value.toString(); return true; } return false; @@ -1057,17 +1047,17 @@ function parseBlsArgs( imaState: state.TIMAState, joArg: any ): boolean { } if( joArg.name == "bls-glue" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); - imaState.strPathBlsGlue = "" + joArg.value; + imaState.strPathBlsGlue = joArg.value.toString(); return true; } if( joArg.name == "hash-g1" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); - imaState.strPathHashG1 = "" + joArg.value; + imaState.strPathHashG1 = joArg.value.toString(); return true; } if( joArg.name == "bls-verify" ) { owaspUtils.verifyArgumentIsPathToExistingFile( joArg ); - imaState.strPathBlsVerify = "" + joArg.value; + imaState.strPathBlsVerify = joArg.value.toString(); return true; } return false; @@ -1096,13 +1086,13 @@ function parseReimbursementArgs( imaState: state.TIMAState, joArg: any ): boolea if( joArg.name == "reimbursement-recharge" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nReimbursementRecharge = - owaspUtils.parseMoneySpecToWei( "" + joArg.value, true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString(), true ); return true; } if( joArg.name == "reimbursement-withdraw" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); imaState.nReimbursementWithdraw = - owaspUtils.parseMoneySpecToWei( "" + joArg.value, true ); + owaspUtils.parseMoneySpecToWei( joArg.value.toString(), true ); return true; } if( joArg.name == "reimbursement-balance" ) { @@ -1136,7 +1126,7 @@ function parseOracleArgs( imaState: state.TIMAState, joArg: any ): boolean { function parseNetworkDiscoveryArgs( imaState: state.TIMAState, joArg: any ): boolean { if( joArg.name == "network-browser-path" ) { owaspUtils.verifyArgumentWithNonEmptyValue( joArg ); - imaState.optsS2S.strNetworkBrowserPath = "" + joArg.value; + imaState.optsS2S.strNetworkBrowserPath = joArg.value.toString(); return true; } return false; @@ -1728,12 +1718,12 @@ function commonInitCheckErc20(): void { if( isPrintGathered ) log.attention( "IMPORTANT NOTICE: S-Chain ERC20 ABI will be auto-generated" ); imaState.chainProperties.sc.strCoinNameErc20 = - "" + imaState.chainProperties.tc.strCoinNameErc20; // assume same + imaState.chainProperties.tc.strCoinNameErc20 ?? ""; // assume same imaState.chainProperties.sc.joErc20 = JSON.parse( JSON.stringify( imaState.chainProperties.mn.joErc20 ) ); // clone imaState.chainProperties.sc.joErc20[ imaState.chainProperties.sc.strCoinNameErc20 + "_address"] = - "" + imaState.strAddrErc20Explicit; // set explicit address + imaState.strAddrErc20Explicit; // set explicit address } } @@ -1885,12 +1875,12 @@ function commonInitCheckErc721(): void { if( isPrintGathered ) log.attention( "IMPORTANT NOTICE: S-Chain ERC721 ABI will be auto-generated" ); imaState.chainProperties.sc.strCoinNameErc721 = - "" + imaState.chainProperties.mn.strCoinNameErc721; // assume same + imaState.chainProperties.mn.strCoinNameErc721 ?? ""; // assume same imaState.chainProperties.sc.joErc721 = JSON.parse( JSON.stringify( imaState.chainProperties.mn.joErc721 ) ); // clone imaState.chainProperties.sc.joErc721[ imaState.chainProperties.sc.strCoinNameErc721 + "_address"] = - "" + imaState.strAddrErc721Explicit; // set explicit address + imaState.strAddrErc721Explicit; // set explicit address } } @@ -2042,12 +2032,12 @@ function commonInitCheckErc1155(): void { if( isPrintGathered ) log.attention( "IMPORTANT NOTICE: S-Chain ERC1155 ABI will be auto-generated" ); imaState.chainProperties.sc.strCoinNameErc1155 = - "" + imaState.chainProperties.mn.strCoinNameErc1155; // assume same + imaState.chainProperties.mn.strCoinNameErc1155 ?? ""; // assume same imaState.chainProperties.sc.joErc1155 = JSON.parse( JSON.stringify( imaState.chainProperties.mn.joErc1155 ) ); // clone imaState.chainProperties.sc.joErc1155[ imaState.chainProperties.sc.strCoinNameErc1155 + "_address"] = - "" + imaState.strAddrErc1155Explicit; // set explicit address + imaState.strAddrErc1155Explicit; // set explicit address } } @@ -2706,48 +2696,25 @@ function initContractsIMA(): void { if( cp.ethersProvider ) { const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = cp.joAbiIMA; - imaState.joDepositBoxETH = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_eth_address, - joABI.deposit_box_eth_abi, - ep - ); // only main net - imaState.joDepositBoxERC20 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc20_address, - joABI.deposit_box_erc20_abi, - ep - ); // only main net - imaState.joDepositBoxERC721 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc721_address, - joABI.deposit_box_erc721_abi, - ep - ); // only main net - imaState.joDepositBoxERC1155 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc1155_address, - joABI.deposit_box_erc1155_abi, - ep ); + imaState.joDepositBoxETH = new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_eth_address, joABI.deposit_box_eth_abi, ep ); // only main net + imaState.joDepositBoxERC20 = new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc20_address, joABI.deposit_box_erc20_abi, ep ); // only main net + imaState.joDepositBoxERC721 = new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc721_address, joABI.deposit_box_erc721_abi, ep + ); // only main net + imaState.joDepositBoxERC1155 = new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc1155_address, joABI.deposit_box_erc1155_abi, ep ); // only main net - imaState.joDepositBoxERC721WithMetadata = - new owaspUtils.ethersMod.ethers.Contract( - joABI.deposit_box_erc721_with_metadata_address, - joABI.deposit_box_erc721_with_metadata_abi, - ep - ); // only main net - imaState.joCommunityPool = - new owaspUtils.ethersMod.ethers.Contract( - joABI.community_pool_address, - joABI.community_pool_abi, - ep - ); // only main net - imaState.joLinker = - new owaspUtils.ethersMod.ethers.Contract( - joABI.linker_address, joABI.linker_abi, ep ); // only main net - imaState.joMessageProxyMainNet = - new owaspUtils.ethersMod.ethers.Contract( - joABI.message_proxy_mainnet_address, joABI.message_proxy_mainnet_abi, ep ); + imaState.joDepositBoxERC721WithMetadata = new owaspUtils.ethersMod.ethers.Contract( + joABI.deposit_box_erc721_with_metadata_address, + joABI.deposit_box_erc721_with_metadata_abi, ep ); // only main net + imaState.joCommunityPool = new owaspUtils.ethersMod.ethers.Contract( + joABI.community_pool_address, joABI.community_pool_abi, ep ); // only main net + imaState.joLinker = new owaspUtils.ethersMod.ethers.Contract( + joABI.linker_address, joABI.linker_abi, ep ); // only main net + imaState.joMessageProxyMainNet = new owaspUtils.ethersMod.ethers.Contract( + joABI.message_proxy_mainnet_address, joABI.message_proxy_mainnet_abi, ep ); } } if( imaState.chainProperties.sc.bHaveAbiIMA ) { @@ -2756,51 +2723,28 @@ function initContractsIMA(): void { const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider | null = cp.ethersProvider; const joABI = cp.joAbiIMA; - imaState.joTokenManagerETH = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_eth_address, - joABI.token_manager_eth_abi, - ep ); // only s-chain - imaState.joTokenManagerERC20 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc20_address, - joABI.token_manager_erc20_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_address, - joABI.token_manager_erc721_abi, - ep ); // only s-chain - imaState.joTokenManagerERC1155 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc1155_address, - joABI.token_manager_erc1155_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721WithMetadata = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_with_metadata_address, - joABI.token_manager_erc721_with_metadata_abi, - ep ); // only s-chain - imaState.joCommunityLocker = - new owaspUtils.ethersMod.ethers.Contract( - joABI.community_locker_address, - joABI.community_locker_abi, - ep ); // only s-chain - imaState.joMessageProxySChain = - new owaspUtils.ethersMod.ethers.Contract( - joABI.message_proxy_chain_address, - joABI.message_proxy_chain_abi, - ep ); - imaState.joTokenManagerLinker = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_linker_address, - joABI.token_manager_linker_abi, - ep ); - imaState.joEthErc20 = - new owaspUtils.ethersMod.ethers.Contract( - joABI.eth_erc20_address, - joABI.eth_erc20_abi, - ep ); // only s-chain + imaState.joTokenManagerETH = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_eth_address, joABI.token_manager_eth_abi, ep ); // only s-chain + imaState.joTokenManagerERC20 = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc20_address, joABI.token_manager_erc20_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721 = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_address, joABI.token_manager_erc721_abi, + ep ); // only s-chain + imaState.joTokenManagerERC1155 = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc1155_address, joABI.token_manager_erc1155_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721WithMetadata = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_with_metadata_address, + joABI.token_manager_erc721_with_metadata_abi, ep ); // only s-chain + imaState.joCommunityLocker = new owaspUtils.ethersMod.ethers.Contract( + joABI.community_locker_address, joABI.community_locker_abi, ep ); // only s-chain + imaState.joMessageProxySChain = new owaspUtils.ethersMod.ethers.Contract( + joABI.message_proxy_chain_address, joABI.message_proxy_chain_abi, ep ); + imaState.joTokenManagerLinker = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_linker_address, joABI.token_manager_linker_abi, ep ); + imaState.joEthErc20 = new owaspUtils.ethersMod.ethers.Contract( + joABI.eth_erc20_address, joABI.eth_erc20_abi, ep ); // only s-chain } } if( imaState.chainProperties.tc.bHaveAbiIMA ) { @@ -2808,51 +2752,29 @@ function initContractsIMA(): void { if( cp.ethersProvider ) { const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = cp.joAbiIMA; - imaState.joTokenManagerETHTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_eth_address, - joABI.token_manager_eth_abi, - ep ); // only s-chain - imaState.joTokenManagerERC20Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc20_address, - joABI.token_manager_erc20_abi, - ep ); // only s-chain - imaState.joTokenManagerERC721Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc721_address, - joABI.token_manager_erc721_abi, - ep ); // only s-chain - imaState.joTokenManagerERC1155Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_erc1155_address, - joABI.token_manager_erc1155_abi, - ep ); // only s-chain + imaState.joTokenManagerETHTarget = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_eth_address, joABI.token_manager_eth_abi, ep ); // only s-chain + imaState.joTokenManagerERC20Target = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc20_address, joABI.token_manager_erc20_abi, + ep ); // only s-chain + imaState.joTokenManagerERC721Target = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc721_address, joABI.token_manager_erc721_abi, + ep ); // only s-chain + imaState.joTokenManagerERC1155Target = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_erc1155_address, joABI.token_manager_erc1155_abi, + ep ); // only s-chain imaState.joTokenManagerERC721WithMetadataTarget = new owaspUtils.ethersMod.ethers.Contract( joABI.token_manager_erc721_with_metadata_address, - joABI.token_manager_erc721_with_metadata_abi, - ep ); // only s-chain - imaState.joCommunityLockerTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.community_locker_address, - joABI.community_locker_abi, - ep ); // only s-chain - imaState.joMessageProxySChainTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.message_proxy_chain_address, - joABI.message_proxy_chain_abi, - ep ); - imaState.joTokenManagerLinkerTarget = - new owaspUtils.ethersMod.ethers.Contract( - joABI.token_manager_linker_address, - joABI.token_manager_linker_abi, - ep ); - imaState.joEthErc20Target = - new owaspUtils.ethersMod.ethers.Contract( - joABI.eth_erc20_address, - joABI.eth_erc20_abi, - ep ); // only s-chain + joABI.token_manager_erc721_with_metadata_abi, ep ); // only s-chain + imaState.joCommunityLockerTarget = new owaspUtils.ethersMod.ethers.Contract( + joABI.community_locker_address, joABI.community_locker_abi, ep ); // only s-chain + imaState.joMessageProxySChainTarget = new owaspUtils.ethersMod.ethers.Contract( + joABI.message_proxy_chain_address, joABI.message_proxy_chain_abi, ep ); + imaState.joTokenManagerLinkerTarget = new owaspUtils.ethersMod.ethers.Contract( + joABI.token_manager_linker_address, joABI.token_manager_linker_abi, ep ); + imaState.joEthErc20Target = new owaspUtils.ethersMod.ethers.Contract( + joABI.eth_erc20_address, joABI.eth_erc20_abi, ep ); // only s-chain } } } @@ -2864,56 +2786,26 @@ function initContractsSkaleManager(): void { if( cp.ethersProvider ) { const ep: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = cp.ethersProvider; const joABI = imaState.joAbiSkaleManager; - imaState.joConstantsHolder = - new owaspUtils.ethersMod.ethers.Contract( - joABI.constants_holder_address, - joABI.constants_holder_abi, - ep ); - imaState.joNodes = - new owaspUtils.ethersMod.ethers.Contract( - joABI.nodes_address, - joABI.nodes_abi, - ep ); - imaState.joKeyStorage = - new owaspUtils.ethersMod.ethers.Contract( - joABI.key_storage_address, - joABI.key_storage_abi, - ep ); - imaState.joSChains = - new owaspUtils.ethersMod.ethers.Contract( - joABI.schains_address, - joABI.schains_abi, - ep ); - imaState.joSChainsInternal = - new owaspUtils.ethersMod.ethers.Contract( - joABI.schains_internal_address, - joABI.schains_internal_abi, - ep ); - imaState.joSkaleDKG = - new owaspUtils.ethersMod.ethers.Contract( - joABI.skale_d_k_g_address, - joABI.skale_d_k_g_abi, - ep ); - imaState.joSkaleManager = - new owaspUtils.ethersMod.ethers.Contract( - joABI.skale_manager_address, - joABI.skale_manager_abi, - ep ); - imaState.joSkaleToken = - new owaspUtils.ethersMod.ethers.Contract( - joABI.skale_token_address, - joABI.skale_token_abi, - ep ); - imaState.joValidatorService = - new owaspUtils.ethersMod.ethers.Contract( - joABI.validator_service_address, - joABI.validator_service_abi, - ep ); - imaState.joWallets = - new owaspUtils.ethersMod.ethers.Contract( - joABI.wallets_address, - joABI.wallets_abi, - ep ); + imaState.joConstantsHolder = new owaspUtils.ethersMod.ethers.Contract( + joABI.constants_holder_address, joABI.constants_holder_abi, ep ); + imaState.joNodes = new owaspUtils.ethersMod.ethers.Contract( + joABI.nodes_address, joABI.nodes_abi, ep ); + imaState.joKeyStorage = new owaspUtils.ethersMod.ethers.Contract( + joABI.key_storage_address, joABI.key_storage_abi, ep ); + imaState.joSChains = new owaspUtils.ethersMod.ethers.Contract( + joABI.schains_address, joABI.schains_abi, ep ); + imaState.joSChainsInternal = new owaspUtils.ethersMod.ethers.Contract( + joABI.schains_internal_address, joABI.schains_internal_abi, ep ); + imaState.joSkaleDKG = new owaspUtils.ethersMod.ethers.Contract( + joABI.skale_d_k_g_address, joABI.skale_d_k_g_abi, ep ); + imaState.joSkaleManager = new owaspUtils.ethersMod.ethers.Contract( + joABI.skale_manager_address, joABI.skale_manager_abi, ep ); + imaState.joSkaleToken = new owaspUtils.ethersMod.ethers.Contract( + joABI.skale_token_address, joABI.skale_token_abi, ep ); + imaState.joValidatorService = new owaspUtils.ethersMod.ethers.Contract( + joABI.validator_service_address, joABI.validator_service_abi, ep ); + imaState.joWallets = new owaspUtils.ethersMod.ethers.Contract( + joABI.wallets_address, joABI.wallets_abi, ep ); } } } diff --git a/src/imaCore.ts b/src/imaCore.ts index 0186ccf7..89651612 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -37,7 +37,7 @@ import * as skaleObserver from "./observer.js"; import * as threadInfo from "./threadInfo.js"; export type TFunctionAfterSigningMessages = - ( err: Error | string | null, jarrMessages: any[], joGlueResult: any | null + ( err: Error | string | null, jarrMessages: any[], joGlueResult?: any | null ) => Promise < void >; export type TFunctionDoSignMessages = ( nTransferLoopCounter: number, jarrMessages: any[], nIdxCurrentMsgBlockStart: number, @@ -411,7 +411,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ): Promise 0 ) { let bSecurityCheckPassed = true; - const strActionNameOld = "" + optsTransfer.strActionName; + const strActionNameOld = optsTransfer.strActionName; optsTransfer.strActionName = "security check: evaluate block depth"; try { const transactionHash = r[0].transactionHash; @@ -443,7 +443,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ): Promise 0 ) { let bSecurityCheckPassed = true; - const strActionNameOld = "" + optsTransfer.strActionName; + const strActionNameOld = optsTransfer.strActionName; optsTransfer.strActionName = "security check: evaluate block age"; try { const transactionHash = r[0].transactionHash; @@ -495,7 +495,7 @@ async function gatherMessages( optsTransfer: TTransferOptions ): Promise s-chain const ethersProviderSrc: owaspUtils.ethersMod.ethers.providers.JsonRpcProvider = owaspUtils.getEthersProviderFromURL( urlSrc ); const joAccountSrc = joAccountDst; // ??? - const chainNameSrc = "" + joSChain.name; - const chainIdSrc = "" + joSChain.chainId; + const chainNameSrc = joSChain.name; + const chainIdSrc = joSChain.chainId; log.information( "S2S transfer walk trough {}/{} S-Chain in {}...", chainNameSrc, chainIdSrc, threadInfo.threadDescription() ); let bOK = false; diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index 1b367255..f79ff2f2 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -267,7 +267,6 @@ export async function receiveEthPaymentFromSchainOnMainNet( try { strActionName = "Receive ETH payment from S-Chain on Main Met, getMyEth"; const arrArguments: any = []; - const weiHowMuch = undefined; const gasPrice = await transactionCustomizerMainNet.computeGasPrice( ethersProviderMainNet, 200000000000 ); details.trace( "{p}Using computed gasPrice={}", strLogPrefix, gasPrice ); @@ -275,7 +274,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( details, ethersProviderMainNet, "DepositBoxETH", joDepositBoxETH, "getMyEth", arrArguments, joAccountMN, strActionName, - gasPrice, 3000000, weiHowMuch ); + gasPrice, 3000000 ); details.trace( "{p}Using estimated gas={}", strLogPrefix, estimatedGas ); const isIgnore = false; const strErrorOfDryRun = await imaTx.dryRunCall( @@ -283,7 +282,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( "DepositBoxETH", joDepositBoxETH, "getMyEth", arrArguments, joAccountMN, strActionName, isIgnore, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); @@ -292,7 +291,7 @@ export async function receiveEthPaymentFromSchainOnMainNet( "DepositBoxETH", joDepositBoxETH, "getMyEth", arrArguments, joAccountMN, strActionName, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( joReceipt ) { jarrReceipts.push( { description: "receiveEthPaymentFromSchainOnMainNet", diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 52f629eb..25d1c50a 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -202,7 +202,6 @@ async function handleOracleSigned( ]; optsGasPriceSetup.details.debug( "{p}....debug args for : {}", optsGasPriceSetup.strLogPrefix, joDebugArgs ); - const weiHowMuch = undefined; const gasPrice = await optsGasPriceSetup.transactionCustomizerSChain.computeGasPrice( optsGasPriceSetup.ethersProviderSChain, 200000000000 ); optsGasPriceSetup.details.trace( "{p}Using computed gasPrice={}", @@ -211,7 +210,7 @@ async function handleOracleSigned( optsGasPriceSetup.details, optsGasPriceSetup.ethersProviderSChain, "CommunityLocker", optsGasPriceSetup.joCommunityLocker, "setGasPrice", arrArgumentsSetGasPrice, optsGasPriceSetup.joAccountSC, - optsGasPriceSetup.strActionName, gasPrice, 10000000, weiHowMuch ); + optsGasPriceSetup.strActionName, gasPrice, 10000000 ); optsGasPriceSetup.details.trace( "{p}Using estimated gas={}", optsGasPriceSetup.strLogPrefix, estimatedGasSetGasPrice ); const isIgnoreSetGasPrice = false; diff --git a/src/imaRegistrationOperations.ts b/src/imaRegistrationOperations.ts index a6a6e585..fbd9664e 100644 --- a/src/imaRegistrationOperations.ts +++ b/src/imaRegistrationOperations.ts @@ -174,19 +174,18 @@ export async function registerSChainInDepositBoxes( // step 1 joTokenManagerERC1155.address, // call params joTokenManagerERC721WithMetadata.address // call params ] ]; - const weiHowMuch = undefined; const gasPrice = await transactionCustomizerMainNet.computeGasPrice( ethersProviderMainNet, 200000000000 ); details.trace( "{p}Using computed gasPrice={}", strLogPrefix, gasPrice ); const estimatedGas = await transactionCustomizerMainNet.computeGas( details, ethersProviderMainNet, "Linker", joLinker, "connectSchain", arrArguments, - joAccountMN, strActionName, gasPrice, 3000000, weiHowMuch ); + joAccountMN, strActionName, gasPrice, 3000000 ); details.trace( "{p}Using estimated gas={}", strLogPrefix, estimatedGas ); const isIgnore = false; const strErrorOfDryRun = await imaTx.dryRunCall( details, ethersProviderMainNet, "Linker", joLinker, "connectSchain", arrArguments, joAccountMN, strActionName, isIgnore, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); @@ -194,7 +193,7 @@ export async function registerSChainInDepositBoxes( // step 1 details, ethersProviderMainNet, "Linker", joLinker, "connectSchain", arrArguments, joAccountMN, strActionName, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( joReceipt ) { jarrReceipts.push( { description: "registerSChainInDepositBoxes", diff --git a/src/imaReimbursementOperations.ts b/src/imaReimbursementOperations.ts index 309a9ce0..c1cc66b3 100644 --- a/src/imaReimbursementOperations.ts +++ b/src/imaReimbursementOperations.ts @@ -238,21 +238,20 @@ export async function reimbursementWalletWithdraw( owaspUtils.ensureStartsWith0x( owaspUtils.toBN( nReimbursementWithdraw ).toHexString() ) ]; - const weiHowMuch = undefined; const gasPrice = await transactionCustomizerMainNet.computeGasPrice( ethersProviderMainNet, 200000000000 ); details.trace( "{p}Using computed gasPrice={}", strLogPrefix, gasPrice ); const estimatedGas = await transactionCustomizerMainNet.computeGas( details, ethersProviderMainNet, "CommunityPool", joCommunityPool, "withdrawFunds", arrArguments, - joAccountMN, strActionName, gasPrice, 3000000, weiHowMuch ); + joAccountMN, strActionName, gasPrice, 3000000 ); details.trace( "{p}Using estimated gas={}", strLogPrefix, estimatedGas ); const isIgnore = false; const strErrorOfDryRun = await imaTx.dryRunCall( details, ethersProviderMainNet, "CommunityPool", joCommunityPool, "withdrawFunds", arrArguments, joAccountMN, strActionName, isIgnore, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); @@ -260,7 +259,7 @@ export async function reimbursementWalletWithdraw( details, ethersProviderMainNet, "CommunityPool", joCommunityPool, "withdrawFunds", arrArguments, joAccountMN, strActionName, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( joReceipt ) { jarrReceipts.push( { description: "reimbursementWalletWithdraw", @@ -304,20 +303,19 @@ export async function reimbursementSetRange( strChainNameOriginChain, owaspUtils.ensureStartsWith0x( owaspUtils.toBN( nReimbursementRange ).toHexString() ) ]; - const weiHowMuch = undefined; const gasPrice = await transactionCustomizerSChain.computeGasPrice( ethersProviderSChain, 200000000000 ); details.trace( "{p}Using computed gasPrice={}", strLogPrefix, gasPrice ); const estimatedGas = await transactionCustomizerSChain.computeGas( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, - joAccountSC, strActionName, gasPrice, 3000000, weiHowMuch ); + joAccountSC, strActionName, gasPrice, 3000000 ); details.trace( "{p}Using estimated gas={}", strLogPrefix, estimatedGas ); const isIgnore = false; const strErrorOfDryRun = await imaTx.dryRunCall( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, - joAccountSC, strActionName, isIgnore, gasPrice, estimatedGas, weiHowMuch ); + joAccountSC, strActionName, isIgnore, gasPrice, estimatedGas ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); @@ -325,7 +323,7 @@ export async function reimbursementSetRange( const joReceipt = await imaTx.payedCall( details, ethersProviderSChain, "CommunityLocker", joCommunityLocker, "setTimeLimitPerMessage", arrArguments, - joAccountSC, strActionName, gasPrice, estimatedGas, weiHowMuch, opts ); + joAccountSC, strActionName, gasPrice, estimatedGas, undefined, opts ); if( joReceipt ) { jarrReceipts.push( { description: "reimbursementSetRange", diff --git a/src/imaSgxExternalSigner.ts b/src/imaSgxExternalSigner.ts index 1415d648..0de23e31 100644 --- a/src/imaSgxExternalSigner.ts +++ b/src/imaSgxExternalSigner.ts @@ -98,7 +98,7 @@ async function run(): Promise { const joIn: any = { method: "ecdsaSignMessageHash", params: { - keyName: "" + strSgxKeyName, + keyName: strSgxKeyName.toString(), messageHash: txHash, base: 16 } diff --git a/src/imaTokenOperations.ts b/src/imaTokenOperations.ts index 409de82b..34f080e2 100644 --- a/src/imaTokenOperations.ts +++ b/src/imaTokenOperations.ts @@ -182,7 +182,7 @@ export async function doErc721PaymentFromMainNet( details, ethersProviderMainNet, "ERC721", contractERC721, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc721PaymentFromMainNet/approve", receipt: joReceiptApprove @@ -214,7 +214,7 @@ export async function doErc721PaymentFromMainNet( "DepositBoxERC721", joDepositBoxERC721, "depositERC721", arrArgumentsDepositERC721, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC721, null ); - if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { + if( joReceiptDeposit ) { jarrReceipts.push( { description: "doErc721PaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -320,7 +320,7 @@ export async function doErc20PaymentFromMainNet( details, ethersProviderMainNet, "ERC20", contractERC20, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc20PaymentFromMainNet/approve", receipt: joReceiptApprove @@ -351,7 +351,7 @@ export async function doErc20PaymentFromMainNet( "DepositBoxERC20", joDepositBoxERC20, "depositERC20", arrArgumentsDepositERC20, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC20, null ); - if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { + if( joReceiptDeposit ) { jarrReceipts.push( { description: "doErc20PaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -463,7 +463,7 @@ export async function doErc1155PaymentFromMainNet( "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc1155PaymentFromMainNet/approve", receipt: joReceiptApprove @@ -499,7 +499,7 @@ export async function doErc1155PaymentFromMainNet( "depositERC1155", arrArgumentsDepositERC1155, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC1155, null ); - if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { + if( joReceiptDeposit ) { jarrReceipts.push( { description: "doErc1155PaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -596,7 +596,7 @@ export async function doErc1155BatchPaymentFromMainNet( details, ethersProviderMainNet, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromMainNet/approve", receipt: joReceiptApprove @@ -628,7 +628,7 @@ export async function doErc1155BatchPaymentFromMainNet( "depositERC1155Batch", arrArgumentsDepositERC1155Batch, joAccountSrc, strActionName, gasPrice, estimatedGasDeposit, weiHowMuchDepositERC1155Batch, null ); - if( joReceiptDeposit && typeof joReceiptDeposit === "object" ) { + if( joReceiptDeposit ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromMainNet/deposit", receipt: joReceiptDeposit @@ -731,7 +731,7 @@ export async function doErc20PaymentFromSChain( details, ethersProviderSChain, "ERC20", contractERC20, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc20PaymentFromSChain/approve", receipt: joReceiptApprove @@ -772,7 +772,7 @@ export async function doErc20PaymentFromSChain( "exitToMainERC20", arrArgumentsExitToMainERC20, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC20, weiHowMuchExitToMainERC20, opts ); - if( joReceiptExitToMainERC20 && typeof joReceiptExitToMainERC20 === "object" ) { + if( joReceiptExitToMainERC20 ) { jarrReceipts.push( { description: "doErc20PaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC20 @@ -877,7 +877,7 @@ export async function doErc721PaymentFromSChain( details, ethersProviderSChain, "ERC721", contractERC721, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc721PaymentFromSChain/transfer-from", receipt: joReceiptApprove @@ -918,7 +918,7 @@ export async function doErc721PaymentFromSChain( "exitToMainERC721", arrArgumentsExitToMainERC721, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC721, weiHowMuchExitToMainERC721, opts ); - if( joReceiptExitToMainERC721 && typeof joReceiptExitToMainERC721 === "object" ) { + if( joReceiptExitToMainERC721 ) { jarrReceipts.push( { description: "doErc721PaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC721 @@ -1024,7 +1024,7 @@ export async function doErc1155PaymentFromSChain( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc1155PaymentFromSChain/transfer-from", receipt: joReceiptApprove @@ -1065,7 +1065,7 @@ export async function doErc1155PaymentFromSChain( "exitToMainERC1155", arrArgumentsExitToMainERC1155, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC1155, weiHowMuchExitToMainERC1155, opts ); - if( joReceiptExitToMainERC1155 && typeof joReceiptExitToMainERC1155 === "object" ) { + if( joReceiptExitToMainERC1155 ) { jarrReceipts.push( { description: "doErc1155PaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC1155 @@ -1167,7 +1167,7 @@ export async function doErc1155BatchPaymentFromSChain( details, ethersProviderSChain, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, opts ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromSChain/transfer-from", receipt: joReceiptApprove @@ -1209,9 +1209,7 @@ export async function doErc1155BatchPaymentFromSChain( "exitToMainERC1155Batch", arrArgumentsExitToMainERC1155Batch, joAccountSrc, strActionName, gasPrice, estimatedGasExitToMainERC1155Batch, weiHowMuchExitToMainERC1155Batch, opts ); - if( joReceiptExitToMainERC1155Batch && - typeof joReceiptExitToMainERC1155Batch === "object" - ) { + if( joReceiptExitToMainERC1155Batch ) { jarrReceipts.push( { description: "doErc1155BatchPaymentFromSChain/exit-to-main", receipt: joReceiptExitToMainERC1155Batch @@ -1340,7 +1338,7 @@ export async function doErc20PaymentS2S( details, ethersProviderSrc, "ERC20", contractERC20, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: `doErc20PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, receipt: joReceiptApprove @@ -1371,7 +1369,7 @@ export async function doErc20PaymentS2S( "transferToSchainERC20", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC20, null ); - if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { + if( joReceiptTransfer ) { jarrReceipts.push( { description: "doErc20PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1480,7 +1478,7 @@ export async function doErc721PaymentS2S( details, ethersProviderSrc, "ERC721", contractERC721, "approve", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: `doErc721PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, @@ -1514,7 +1512,7 @@ export async function doErc721PaymentS2S( "transferToSchainERC721", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC721, null ); - if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { + if( joReceiptTransfer ) { jarrReceipts.push( { description: "doErc721PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1626,7 +1624,7 @@ export async function doErc1155PaymentS2S( "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: `doErc1155PaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, @@ -1659,7 +1657,7 @@ export async function doErc1155PaymentS2S( "transferToSchainERC1155", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC1155, null ); - if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { + if( joReceiptTransfer ) { jarrReceipts.push( { description: "doErc1155PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1772,7 +1770,7 @@ export async function doErc1155BatchPaymentS2S( details, ethersProviderSrc, "ERC1155", contractERC1155, "setApprovalForAll", arrArgumentsApprove, joAccountSrc, strActionName, gasPrice, estimatedGasApprove, weiHowMuchApprove, null ); - if( joReceiptApprove && typeof joReceiptApprove === "object" ) { + if( joReceiptApprove ) { jarrReceipts.push( { description: `doErc1155BatchPaymentS2S/approve/${( isForward ? "forward" : "reverse" )}`, @@ -1806,7 +1804,7 @@ export async function doErc1155BatchPaymentS2S( "transferToSchainERC1155Batch", arrArgumentsTransfer, joAccountSrc, strActionName, gasPrice, estimatedGasTransfer, weiHowMuchTransferERC1155, null ); - if( joReceiptTransfer && typeof joReceiptTransfer === "object" ) { + if( joReceiptTransfer ) { jarrReceipts.push( { description: "doErc1155PaymentS2S/transfer", receipt: joReceiptTransfer @@ -1847,11 +1845,8 @@ export async function mintErc20( const details = log.createMemoryStream(); try { details.debug( "{p}Mint ERC20 token amount {}", strLogPrefix, nAmount ); - if( !( ethersProvider && joAccount && strAddressMintTo && - typeof strAddressMintTo === "string" && strAddressMintTo.length > 0 && - strTokenContractAddress && typeof strTokenContractAddress === "string" && - strTokenContractAddress.length > 0 && joTokenContractABI - ) ) + if( !( strAddressMintTo.length > 0 && strTokenContractAddress.length > 0 && + joTokenContractABI ) ) throw new Error( "Missing valid arguments" ); strActionName = "mintErc20() instantiate token contract"; const contract = new owaspUtils.ethersMod.ethers.Contract( diff --git a/src/imaTransferErrorHandling.ts b/src/imaTransferErrorHandling.ts index 7eec71c5..72a7dd96 100644 --- a/src/imaTransferErrorHandling.ts +++ b/src/imaTransferErrorHandling.ts @@ -27,7 +27,7 @@ import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher.js"; export function verifyTransferErrorCategoryName( strCategory: string ): string { - return "" + ( strCategory || "default" ); + return ( strCategory ?? "default" ); } const gMaxLastTransferErrors: number = 20; @@ -38,16 +38,16 @@ export const saveTransferEvents = new EventDispatcher(); export function saveTransferError( strCategory: string, textLog: any, ts?: any ): void { ts = ts || Math.round( ( new Date() ).getTime() / 1000 ); - const c = verifyTransferErrorCategoryName( strCategory ); + const catName = verifyTransferErrorCategoryName( strCategory ); const joTransferEventError: any = { ts, - category: "" + c, - textLog: "" + textLog.toString() + category: catName.toString(), + textLog: textLog.toString() }; gArrLastTransferErrors.push( joTransferEventError ); while( gArrLastTransferErrors.length > gMaxLastTransferErrors ) gArrLastTransferErrors.shift(); - gMapTransferErrorCategories["" + c] = true; + gMapTransferErrorCategories[catName] = true; saveTransferEvents.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -55,9 +55,9 @@ export function saveTransferError( strCategory: string, textLog: any, ts?: any ) } export function saveTransferSuccess( strCategory: string ): void { - const c = verifyTransferErrorCategoryName( strCategory ); + const catName = verifyTransferErrorCategoryName( strCategory ); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - try { delete gMapTransferErrorCategories["" + c]; } catch ( err ) { } + try { delete gMapTransferErrorCategories[catName]; } catch ( err ) { } saveTransferEvents.dispatchEvent( new UniversalDispatcherEvent( "success", diff --git a/src/imaTx.ts b/src/imaTx.ts index 7a58269a..5b1cabba 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -103,7 +103,7 @@ export async function dryRunCall( strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: string, arrArguments: any[], joAccount: state.TAccount, strActionName: string, isDryRunResultIgnore: boolean, - gasPrice: any, gasValue: any, weiHowMuch: any, + gasPrice: any, gasValue: any, weiHowMuch?: any, opts?: any ): Promise { if( !dryRunIsEnabled() ) @@ -221,7 +221,7 @@ async function payedCallTM( optsPayedCall: TRunTimePayedCallOptions ): Promise { const optsPayedCall: TRunTimePayedCallOptions = { @@ -685,7 +685,7 @@ export class TransactionCustomizer { strContractName: string, joContract: owaspUtils.ethersMod.ethers.Contract, strMethodName: string, arrArguments: any[], joAccount: state.TAccount, strActionName: string, - gasPrice: any, gasValueRecommended: any, weiHowMuch: any, + gasPrice: any, gasValueRecommended: any, weiHowMuch?: any, opts?: any ): Promise { let estimatedGas: any = 0; diff --git a/src/log.ts b/src/log.ts index 9c0411ed..dd549c24 100644 --- a/src/log.ts +++ b/src/log.ts @@ -113,7 +113,7 @@ export function setPrintTimestamps( b?: boolean ): void { } export function n2s( n: any, sz: number ): string { - let s: string = "" + n; + let s: string = n ?? ""; while( s.length < sz ) s = "0" + s; return s; @@ -131,7 +131,7 @@ export function generateTimestampString( ts?: any, isColorized?: boolean ): stri function( x?: any ): string { return isColorized ? cc.fracTime( x ) : x; }; const ccBright = function( x?: any ): string { return isColorized ? cc.bright( x ) : x; }; const s = - "" + ccDate( n2s( ts.getUTCFullYear(), 4 ) ) + + ccDate( n2s( ts.getUTCFullYear(), 4 ) ) + ccBright( "-" ) + ccDate( n2s( ts.getUTCMonth() + 1, 2 ) ) + ccBright( "-" ) + ccDate( n2s( ts.getUTCDate(), 2 ) ) + " " + ccTime( n2s( ts.getUTCHours(), 2 ) ) + @@ -250,7 +250,7 @@ export function createStandardOutputStream(): TLogger | null { open: function(): void { try { this.objStream = process.stdout; } catch ( err ) { } }, size: function(): number { return 0; }, rotate: function( nBytesToWrite: number ) { }, - toString: function(): string { return "" + this.strPath; }, + toString: function(): string { return this.strPath.toString(); }, exposeDetailsTo: function( otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters @@ -514,7 +514,7 @@ export function createFileOutput( try { const objEntry: TLogger = { id: gIdentifierAllocatorCounter++, - strPath: "" + strFilePath, + strPath: strFilePath.toString(), nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation ?? 0 ), nMaxFilesCount: 0 + ( nMaxFilesCount ?? 0 ), objStream: null, @@ -570,12 +570,14 @@ export function createFileOutput( let i = 0; const cnt = 0 + this.nMaxFilesCount; for( i = 0; i < cnt; ++i ) { const j = this.nMaxFilesCount - i - 1; - const strPath = "" + this.strPath + ( ( j === 0 ) ? "" : ( "." + j ) ); + const strPath = + this.strPath.toString() + ( ( j === 0 ) ? "" : ( "." + j ) ); if( j == ( cnt - 1 ) ) { try { fs.unlinkSync( strPath ); } catch ( err ) { } continue; } - const strPathPrev = "" + this.strPath + "." + ( j + 1 ); + const strPathPrev = + this.strPath.toString() + "." + ( j + 1 ); try { fs.unlinkSync( strPathPrev ); } catch ( err ) { } try { fs.renameSync( strPath, strPathPrev ); } catch ( err ) { } } @@ -586,7 +588,7 @@ export function createFileOutput( } catch ( err ) { } }, - toString: function(): string { return "" + strFilePath; }, + toString: function(): string { return strFilePath.toString(); }, exposeDetailsTo: function( otherStream: TLogger, strTitle: string, isSuccess: boolean ): void { }, // high-level formatters @@ -659,7 +661,7 @@ export function createFileOutput( } export function insertFileOutput( strFilePath: string, nMaxSizeBeforeRotation?: number, nMaxFilesCount?: number ): boolean { - let objEntry = getStreamWithFilePath( "" + strFilePath ); + let objEntry = getStreamWithFilePath( strFilePath.toString() ); if( objEntry !== null ) return true; objEntry = createFileOutput( strFilePath, nMaxSizeBeforeRotation, nMaxFilesCount ); @@ -1052,7 +1054,7 @@ export function verboseLevelAsTextForLog( vl: any ): string { vl = verboseGet(); if( vl in gMapVerbose ) { const tl = gMapVerbose.get( vl ) ?? 0; - return "" + tl; + return tl.toString(); } return "unknown(" + JSON.stringify( vl ) + ")"; } @@ -1065,7 +1067,7 @@ export function verboseName2Number( s: string ): number { } let gFlagIsExposeDetails = false; -let gVerboseLevel = 0 + verboseName2Number( "information" ); +let gVerboseLevel = verboseName2Number( "information" ); export function exposeDetailsGet(): boolean { return ( !!gFlagIsExposeDetails ); diff --git a/src/loop.ts b/src/loop.ts index 1754b3bb..89a4f88e 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -77,20 +77,20 @@ export interface TParallelLoopRunOptions { // Run transfer loop export function checkTimeFraming( - d: Date | null, strDirection: string, joRuntimeOpts: TRuntimeOpts ): boolean { + aDateTime: Date | null, strDirection: string, joRuntimeOpts: TRuntimeOpts ): boolean { try { const imaState: state.TIMAState = state.get(); if( imaState.nTimeFrameSeconds <= 0 || imaState.nNodesCount <= 1 ) return true; // time framing is disabled - if( d == null || d == undefined ) - d = new Date(); // now + if( aDateTime == null || aDateTime == undefined ) + aDateTime = new Date(); // now const nFrameShift = 0; // Unix UTC timestamp, see: // https://stackoverflow.com/questions/9756120/how-do-i-get-a-utc-timestamp-in-javascript - const nUtcUnixTimeStamp = Math.floor( ( d ).getTime() / 1000 ); + const nUtcUnixTimeStamp = Math.floor( ( aDateTime ).getTime() / 1000 ); const nSecondsRangeForAllSChains = imaState.nTimeFrameSeconds * imaState.nNodesCount; const nMod = Math.floor( nUtcUnixTimeStamp % nSecondsRangeForAllSChains ); diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 36d8b857..351dd5de 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -75,7 +75,7 @@ class ObserverServer extends SocketServer { self.mapApiHandlers.init = function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { joAnswer.message = { - method: "" + joMessage.method, + method: joMessage.method.toString(), error: null }; if( self.initComplete ) diff --git a/src/main.ts b/src/main.ts index c4b2b602..c6b671cb 100644 --- a/src/main.ts +++ b/src/main.ts @@ -294,7 +294,7 @@ function initJsonRpcServer(): void { if( "id" in joMessage ) joAnswer.id = joMessage.id; if( "method" in joMessage ) - joAnswer.method = "" + joMessage.method; + joAnswer.method = joMessage.method.toString(); switch ( joMessage.method ) { case "echo": joAnswer.result = "echo"; @@ -412,15 +412,17 @@ async function main(): Promise { if( strTmpAddressFromEnvMainNet && typeof strTmpAddressFromEnvMainNet === "string" && strTmpAddressFromEnvMainNet.length > 0 ) - imaState.chainProperties.mn.joAccount.address_ = "" + strTmpAddressFromEnvMainNet; + imaState.chainProperties.mn.joAccount.address_ = strTmpAddressFromEnvMainNet.toString(); if( strTmpAddressFromEnvSChain && typeof strTmpAddressFromEnvSChain === "string" && strTmpAddressFromEnvSChain.length > 0 ) - imaState.chainProperties.sc.joAccount.address_ = "" + strTmpAddressFromEnvSChain; + imaState.chainProperties.sc.joAccount.address_ = strTmpAddressFromEnvSChain.toString(); if( strTmpAddressFromEnvSChainTarget && typeof strTmpAddressFromEnvSChainTarget === "string" && - strTmpAddressFromEnvSChainTarget.length > 0 ) - imaState.chainProperties.tc.joAccount.address_ = "" + strTmpAddressFromEnvSChainTarget; + strTmpAddressFromEnvSChainTarget.length > 0 ) { + imaState.chainProperties.tc.joAccount.address_ = + strTmpAddressFromEnvSChainTarget.toString(); + } parseCommandLine(); initMonitoringServer(); initJsonRpcServer(); diff --git a/src/observer.ts b/src/observer.ts index 9b111a3b..ffdd4051 100644 --- a/src/observer.ts +++ b/src/observer.ts @@ -128,9 +128,7 @@ export function getLastCachedSChains(): TSChainInformation[] { } export function pickRandomSChainNodeIndex( joSChain: TSChainInformation ): number { - let min = 0; let max = joSChain.nodes.length - 1; - min = Math.ceil( min ); - max = Math.floor( max ); + const min = 0; const max = joSChain.nodes.length - 1; const idxNode = Math.floor( Math.random() * ( max - min + 1 ) ) + min; return idxNode; } @@ -141,5 +139,5 @@ export function pickRandomSChainNode( joSChain: TSChainInformation ): TSChainNod export function pickRandomSChainUrl( joSChain: TSChainInformation ): string { const joNode: TSChainNode = pickRandomSChainNode( joSChain ); - return "" + joNode.endpoints.ip.http; + return joNode.endpoints.ip.http.toString(); } diff --git a/src/oracle.ts b/src/oracle.ts index 7c46dd0c..8bfdb0b4 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -41,7 +41,7 @@ const gBigNumUpperPart: any = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); function getUtcTimestampString( d?: Date ): string { d = d ?? new Date(); // use now time if d is not specified const nUtcUnixTimeStampWithMilliseconds = d.getTime(); - const t = "" + nUtcUnixTimeStampWithMilliseconds; + const t = nUtcUnixTimeStampWithMilliseconds.toString(); return t; } diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index d25b6373..7b406683 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -89,7 +89,7 @@ export function parseIntOrHex( s: any ): number { } export function validateRadix( value: any, radix?: any ): boolean { - value = "" + ( value ? value.toString() : "10" ); + value = value ? value.toString() : "10"; value = value.trim(); radix = ( radix == null || radix == undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) @@ -101,7 +101,6 @@ export function validateRadix( value: any, radix?: any ): boolean { export function validateInteger( value: any, radix?: any ): boolean { try { - value = "" + value; value = value.trim(); if( value.length < 1 ) return false; @@ -272,7 +271,7 @@ export function validateEthPrivateKey( value?: any ): boolean { export function toEthAddress( value?: any, defValue?: string ): string { try { - value = "" + ( value ? ensureStartsWith0x( value.toString() ) : "" ); + value = value ? ensureStartsWith0x( value.toString() ) : ""; defValue = defValue ?? ""; if( !validateEthAddress( value ) ) return defValue; @@ -283,7 +282,7 @@ export function toEthAddress( value?: any, defValue?: string ): string { export function toEthPrivateKey( value?: any, defValue?: string ): string { try { - value = "" + ( value ? value.toString() : "" ); + value = value ? value.toString() : ""; defValue = defValue ?? ""; if( !validateEthPrivateKey( value ) ) return defValue; @@ -669,7 +668,7 @@ export function privateKeyToAccountAddress( keyPrivate: string ): string { export function fnAddressImpl_( anyThis: any ): string { if( anyThis.address_ == undefined || anyThis.address_ == null || anyThis.address_ == "" ) { if( anyThis.privateKey ) - anyThis.address_ = "" + privateKeyToAccountAddress( anyThis.privateKey ); + anyThis.address_ = privateKeyToAccountAddress( anyThis.privateKey ).toString(); } return anyThis.address_; } @@ -707,7 +706,7 @@ export function ethersProviderToUrl( "connection" in ethersProvider && typeof ethersProvider.connection === "object" && "url" in ethersProvider.connection && typeof ethersProvider.connection.url === "string" ) - strURL = "" + ethersProvider.connection.url; + strURL = ethersProvider.connection.url.toString(); return strURL ?? "N/A-URL"; } @@ -786,7 +785,7 @@ export function toHexStringSafe( val?: any ): string { return ensureStartsWith0x( val.toString( 16 ) ); if( "toString" in val && typeof val.toString === "function" ) return val.toString(); - return "" + val; + return val.toString(); } export function setInterval2( fn: () => void, t: number, stepMilliSeconds?: number ): any { diff --git a/src/pwa.ts b/src/pwa.ts index 1f3592cd..7d7ed065 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -260,7 +260,7 @@ async function notifyOnLoopImpl( method: "skale_imaNotifyLoopWork", params: { nNodeNumber: 0 + imaState.nNodeNumber, - strLoopWorkType: "" + strLoopWorkType, + strLoopWorkType: strLoopWorkType.toString(), nIndexS2S: 0 + nIndexS2S, isStart: ( !!isStart ), ts: nUtcUnixTimeStamp, diff --git a/src/rpcCall.ts b/src/rpcCall.ts index f7c6f472..d3fb898b 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -431,7 +431,7 @@ export async function rpcCallCreate( `bad parameters: ${JSON.stringify( arguments )}` ); } const joCall: TRPCCall = { - url: "" + strURL, + url: strURL.toString(), joRpcOptions: opts ?? null, mapPendingByCallID: new Map < TCallID, TCallHandlerEntry >(), wsConn: null, diff --git a/src/socket.ts b/src/socket.ts index bcc1ddb9..f51d01e5 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -72,11 +72,8 @@ export const socketReceivedDataReverseMarshall = function( data?: any ): any { export const updateSocketDataStatsForMessage = function( joMessage: any, joStats: any ): void { let strMethod = "_N/A_"; - if( "method" in joMessage && - joMessage.method && - typeof joMessage.method === "string" - ) - strMethod = "" + joMessage.method; + if( joMessage?.method ) + strMethod = joMessage.method.toString(); if( strMethod in joStats ) joStats[strMethod]++; else @@ -142,7 +139,7 @@ export class BasicServerAcceptor extends EventDispatcher { unregisterClientByKey( key: any ): void { if( key in this.mapClients ) { - const entry = this.mapClients[key]; + const entry = this.mapClients[key.toString()]; if( entry ) { if( ( "serverPipe" in entry ) && ( "clientPipe" in entry ) ) { const pair = entry; @@ -150,7 +147,7 @@ export class BasicServerAcceptor extends EventDispatcher { pair.clientPipe = null; } // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this.mapClients[key]; + delete this.mapClients[key.toString()]; } } } @@ -178,7 +175,7 @@ export class BasicServerAcceptor extends EventDispatcher { const clientPipe: DirectPipe = new DirectPipe( null, false ); const serverPipe: DirectPipe = new DirectPipe( clientPipe, false ); serverPipe.acceptor = this; - this.mapClients["" + serverPipe.clientPort] = serverPipe; + this.mapClients[serverPipe.clientPort.toString()] = serverPipe; const self = this; const iv = setTimeout( function(): void { clearTimeout( iv ); @@ -187,7 +184,7 @@ export class BasicServerAcceptor extends EventDispatcher { self.dispatchEvent( new UniversalDispatcherEvent( "connection", - { socket: serverPipe, remoteAddress: "" + self.url } ) ); + { socket: serverPipe, remoteAddress: self.url ? self.url.toString() : "" } ) ); clientPipe.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: clientPipe } ) ); }, 0 ); @@ -267,7 +264,7 @@ export class BasicSocketPipe extends EventDispatcher { } socketLoggingTextPrefix( strLogEventName: string ): string { - return "" + strLogEventName + " " + this.socketDescription() + " -"; + return strLogEventName + " " + this.socketDescription() + " -"; } send( data: any, isFlush?: boolean ): void { @@ -431,7 +428,7 @@ export const outOfWorkerAPIs: any = { case "inWorkerConnect": { if( !( jo.workerUUID in gMapAwaitingInWorkerClients ) ) return false; - const pipe: any = gMapAwaitingInWorkerClients["" + jo.workerUUID]; + const pipe: any = gMapAwaitingInWorkerClients[jo.workerUUID.toString()]; pipe.performSuccessfulConnection(); } return true; case "inWorkerDisconnect": { @@ -519,10 +516,10 @@ export class InWorkerServerPipe extends BasicSocketPipe { this.socketSubtype = "server"; this.isConnected = true; this.acceptor = acceptor; - this.clientPort = "" + clientPort; + this.clientPort = clientPort.toString(); this.fnSend = fnSend || inWorkerAPIs.onSendMessage; this.url = "in_worker_server_pipe://" + acceptor.strEndPoint + ":" + clientPort; - this.acceptor.mapClients[this.clientPort] = this; + this.acceptor.mapClients[this.clientPort.toString()] = this; this.fnSend( "inWorkerConnect", this.acceptor.strEndPoint, this.clientPort, {} ); const self = this; const iv = setTimeout( function(): void { @@ -530,7 +527,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( - "connection", { socket: self, remoteAddress: "" + self.url } ) ); + "connection", { socket: self, remoteAddress: self.url.toString() } ) ); }, 0 ); } @@ -566,7 +563,7 @@ export class InWorkerServerPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.fnSend ) || typeof this.fnSend !== "function" ) { const s = "Cannot send messages to disconnected in-worker server pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } const jo: any = socketReceivedDataReverseMarshall( data ); @@ -593,7 +590,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { "Cannot start in-worker socket server on already listening \"" + this.strEndPoint + "\" endpoint"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } gMapLocalServers[this.strEndPoint] = this; @@ -626,7 +623,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { if( jo.workerUUID in this.mapClients ) return false; // TO-DO: send error answer and return true const p: InWorkerServerPipe = - new InWorkerServerPipe( this, "" + jo.workerUUID, this.fnSend ); + new InWorkerServerPipe( this, jo.workerUUID.toString(), this.fnSend ); p.checkItself(); return true; } @@ -634,7 +631,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { performDisconnect( jo: any ): boolean { if( !( jo.workerUUID in this.mapClients ) ) return false; // TO-DO: send error answer and return true - const pipe = this.mapClients[jo.workerUUID]; + const pipe = this.mapClients[jo.workerUUID.toString()]; pipe.performDisconnect(); return true; } @@ -642,7 +639,7 @@ export class InWorkerSocketServerAcceptor extends BasicServerAcceptor { receiveForClientPort( clientPort: any, jo: any ): boolean { if( !( clientPort in this.mapClients ) ) return false; // TO-DO: send error answer and return true - const pipe = this.mapClients[clientPort]; + const pipe = this.mapClients[clientPort.toString()]; pipe.receive( jo ); return true; } @@ -669,7 +666,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.url = "out_of_worker_client_pipe://" + this.strEndPoint + ":" + this.clientPort; this.fnSend = fnSend || outOfWorkerAPIs.onSendMessage; this.fnSend( this.worker, "inWorkerConnect", this.strEndPoint, this.clientPort, {} ); - gMapAwaitingInWorkerClients["" + this.clientPort] = this; + gMapAwaitingInWorkerClients[this.clientPort.toString()] = this; } dispose(): void { @@ -688,7 +685,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { return; this.isConnected = false; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete gMapConnectedInWorkerClients["" + this.clientPort]; + delete gMapConnectedInWorkerClients[this.clientPort.toString()]; this.fnSend( this.worker, "inWorkerDisconnect", this.strEndPoint, this.clientPort, {} ); this.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: this } ) ); this.worker = null; @@ -700,7 +697,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { performSuccessfulConnection(): void { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete gMapAwaitingInWorkerClients[this.clientPort]; - gMapConnectedInWorkerClients["" + this.clientPort] = this; + gMapConnectedInWorkerClients[this.clientPort.toString()] = this; this.isConnected = true; this.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: this } ) ); } @@ -715,7 +712,7 @@ export class OutOfWorkerSocketClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { socket: this, message: "" + s } ) + { socket: this, message: s.toString() } ) ); throw new Error( s ); } @@ -742,18 +739,9 @@ export class OutOfWorkerRelay extends EventDispatcher { isAutoFlushIncoming: boolean, isAutoFlushOutgoing: boolean ) { super(); const self = this; - self.strRelayName = ( strRelayName != null && strRelayName != undefined && - typeof strRelayName === "string" && strRelayName.length > 0 ) - ? ( "" + strRelayName ) - : "unnamed"; - self.isAutoFlushIncoming = - ( isAutoFlushIncoming == null || isAutoFlushIncoming == undefined ) - ? true - : ( !!isAutoFlushIncoming ); - self.isAutoFlushOutgoing = - ( isAutoFlushOutgoing == null || isAutoFlushOutgoing == undefined ) - ? true - : ( !!( isAutoFlushOutgoing ) ); + self.strRelayName = strRelayName ? strRelayName.toString() : "unnamed"; + self.isAutoFlushIncoming = isAutoFlushIncoming ? true : ( !!isAutoFlushIncoming ); + self.isAutoFlushOutgoing = isAutoFlushOutgoing ? true : ( !!( isAutoFlushOutgoing ) ); if( !acceptor ) { throw new Error( `OutOfWorkerRelay ${self.strRelayName} needs acceptor ` + "for normal functionality" ); @@ -782,7 +770,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "connection", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString() } ) ); // 1) configure incoming pipe let _offAllPipeEventListeners: any = null; @@ -796,7 +784,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "close", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: true } ) ); if( _offAllPipeEventListeners ) { @@ -814,7 +802,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "close", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: false } ) ); if( _offAllPipeEventListeners ) { @@ -832,7 +820,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "error", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: true } ) ); if( _offAllPipeEventListeners ) { @@ -850,7 +838,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "error", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: false } ) ); if( _offAllPipeEventListeners ) { @@ -876,7 +864,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "message", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: true, message: joMessage } ) ); @@ -902,7 +890,7 @@ export class OutOfWorkerRelay extends EventDispatcher { "message", { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: false, message: joMessage } ) ); @@ -986,29 +974,19 @@ export class OneToOneRelay extends EventDispatcher { ) { super(); const self = this; - self.strRelayName = - ( strRelayName != null && strRelayName != undefined && - typeof strRelayName === "string" && strRelayName.length > 0 ) - ? ( "" + strRelayName ) - : "unnamed"; - self.isAutoFlushIncoming = - ( isAutoFlushIncoming == null || isAutoFlushIncoming == undefined ) - ? true - : ( !!isAutoFlushIncoming ); - self.isAutoFlushOutgoing = - ( isAutoFlushOutgoing == null || isAutoFlushOutgoing == undefined ) - ? true - : ( !!isAutoFlushIncoming ); + self.strRelayName = strRelayName ? strRelayName.toString() : "unnamed"; + self.isAutoFlushIncoming = isAutoFlushIncoming ? true : ( !!isAutoFlushIncoming ); + self.isAutoFlushOutgoing = isAutoFlushOutgoing ? true : ( !!isAutoFlushIncoming ); self.pipeIncoming = pipeIncoming; self.pipeOutgoing = pipeOutgoing; if( ( !( "strSavedRemoteAddress" in pipeIncoming ) ) || pipeIncoming.strSavedRemoteAddress == null || pipeIncoming.strSavedRemoteAddress == undefined ) - pipeIncoming.strSavedRemoteAddress = "" + pipeIncoming.constructor.name; + pipeIncoming.strSavedRemoteAddress = pipeIncoming.constructor.name.toString(); if( ( !( "strSavedRemoteAddress" in pipeOutgoing ) ) || pipeOutgoing.strSavedRemoteAddress == null || pipeOutgoing.strSavedRemoteAddress == undefined ) - pipeOutgoing.strSavedRemoteAddress = "" + pipeOutgoing.constructor.name; + pipeOutgoing.strSavedRemoteAddress = pipeOutgoing.constructor.name.toString(); // 1) configure incoming pipe let _offAllPipeEventListeners: any = null; @@ -1024,7 +1002,7 @@ export class OneToOneRelay extends EventDispatcher { { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: true } ) ); @@ -1045,7 +1023,7 @@ export class OneToOneRelay extends EventDispatcher { { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: false } ) ); @@ -1068,7 +1046,7 @@ export class OneToOneRelay extends EventDispatcher { { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: true } ) ); @@ -1091,7 +1069,7 @@ export class OneToOneRelay extends EventDispatcher { { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: false } ) ); @@ -1124,7 +1102,7 @@ export class OneToOneRelay extends EventDispatcher { { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: true, message: joMessage } ) @@ -1157,7 +1135,7 @@ export class OneToOneRelay extends EventDispatcher { { relay: self, socket: pipeIncoming, - remoteAddress: "" + pipeIncoming.strSavedRemoteAddress, + remoteAddress: pipeIncoming.strSavedRemoteAddress.toString(), isExternalSocket: false, message: joMessage } ) @@ -1296,7 +1274,7 @@ export class DirectPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.counterPipe?.isConnected ) ) { const s = "Cannot send messages to disconnected local server pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -1319,7 +1297,7 @@ export class LocalSocketServerPipe extends DirectPipe { this.acceptor = acceptor; this.clientPort = 0 + clientPort; this.url = "local_server_pipe://" + acceptor.strEndPoint + ":" + clientPort; - this.acceptor.mapClients["" + clientPort] = this; + this.acceptor.mapClients[clientPort.toString()] = this; const self = this; const iv = setTimeout( function(): void { clearTimeout( iv ); @@ -1347,7 +1325,7 @@ export class LocalSocketServerAcceptor extends BasicServerAcceptor { "Cannot start local socket server on already listening \"" + this.strEndPoint + "\" endpoint"; this.dispatchEvent( new UniversalDispatcherEvent( - "error", { socket: this, message: "" + s } ) ); + "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } gMapLocalServers[this.strEndPoint] = this; @@ -1397,7 +1375,7 @@ export class LocalSocketClientPipe extends DirectPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { socket: this, message: "" + s } ) ); + { socket: this, message: s.toString() } ) ); throw new Error( s ); } this.acceptor = gMapLocalServers[this.strEndPoint]; @@ -1408,7 +1386,7 @@ export class LocalSocketClientPipe extends DirectPipe { const serverPipe = new LocalSocketServerPipe( this, this.acceptor, 0 + this.clientPort ); serverPipe.counterPipe = this; this.counterPipe = serverPipe; - this.acceptor.mapClients[0 + this.clientPort] = { + this.acceptor.mapClients[this.clientPort.toString()] = { serverPipe, clientPipe: this }; @@ -1419,7 +1397,7 @@ export class LocalSocketClientPipe extends DirectPipe { self.acceptor.dispatchEvent( new UniversalDispatcherEvent( "connection", - { socket: serverPipe, remoteAddress: "" + self.url } ) + { socket: serverPipe, remoteAddress: self.url.toString() } ) ); }, 0 ); } @@ -1478,14 +1456,14 @@ export class WebSocketServerPipe extends BasicSocketPipe { wsConnection.addEventListener( "close", this._onWsClose ); wsConnection.addEventListener( "error", this._onWsError ); wsConnection.addEventListener( "message", this._onWsMessage ); - this.acceptor.mapClients["" + this.clientPort] = this; + this.acceptor.mapClients[this.clientPort.toString()] = this; const iv = setTimeout( function(): void { clearTimeout( iv ); self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( "connection", - { socket: self, remoteAddress: "" + remoteAddress } ) + { socket: self, remoteAddress: remoteAddress.toString() } ) ); }, 0 ); } @@ -1533,7 +1511,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket server pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -1563,8 +1541,8 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { cert != null && cert != undefined && typeof cert === "string" && cert.length > 0 ) { const server = httpsModule.createServer( { - key: "" + key, - cert: "" + cert + key: key.toString(), + cert: cert.toString() // , ca: ... } ); server.listen( nTcpPort ); @@ -1574,7 +1552,7 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { const self = this; self.wsServer.on( "connection", function( wsConnection: any, req: any ) { - wsConnection.strSavedRemoteAddress = "" + req.connection.remoteAddress; + wsConnection.strSavedRemoteAddress = req?.connection?.remoteAddress?.toString(); wsConnection.serverPipe = new WebSocketServerPipe( self, wsConnection, req.connection.remoteAddress ); } ); @@ -1613,7 +1591,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { this._onWsError = null; this._onWsMessage = null; this.urlWS = - "" + ( ( url != null && url != undefined && typeof url === "string" ) ? url : "" ); + ( url ? url.toString() : "" ); this.url = "ws_client_pipe-" + this.urlWS; this.reconnect(); } @@ -1631,7 +1609,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { if( ( !this.isConnected ) || ( !this.wsConnection ) ) { const s = "Cannot send messages to disconnected web socket client pipe"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -1640,7 +1618,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { reconnect(): void { this.performDisconnect(); - this.wsConnect( "" + this.urlWS ); + this.wsConnect( this.urlWS ? this.urlWS.toString() : "" ); } disconnect(): void { @@ -1665,7 +1643,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { { tlsOptions: { rejectUnauthorized: false } } ) // server side : new WebSocket( url ); // client side - this.url = "" + url; + this.url = url ? url.toString() : ""; this._onWsOpen = function(): void { self.isConnected = true; self.dispatchEvent( @@ -1735,7 +1713,7 @@ export class WebSocketClientPipe extends BasicSocketPipe { if( url.length == 0 ) { const s = "Cannot connect web socket server \"" + url + "\", bad url"; this.dispatchEvent( - new UniversalDispatcherEvent( "error", { socket: this, message: "" + s } ) ); + new UniversalDispatcherEvent( "error", { socket: this, message: s.toString() } ) ); throw new Error( s ); } this.wsConnectAttempt( url, settings.net.ws.client.reconnectAfterMilliseconds, null ); @@ -1787,11 +1765,7 @@ export class RTCConnection extends EventDispatcher { constructor ( strSignalingServerURL?: string, idRtcParticipant?: string ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); - this.idRtcParticipant = "" + - ( ( idRtcParticipant != null && idRtcParticipant != undefined && - typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) - ? idRtcParticipant - : utils.UUIDv4() ); + this.idRtcParticipant = ( idRtcParticipant ? idRtcParticipant.toString() : utils.UUIDv4() ); this.wasIdentified = false; this.iceComplete = false; this.pc = null; @@ -1812,11 +1786,9 @@ export class RTCConnection extends EventDispatcher { } describe( strInstanceType?: string, arrAdditionalProps?: any[] ): string { - let strInstanceDescription = - ( strInstanceType == null || strInstanceType == undefined || - ( typeof strInstanceType !== "string" ) || strInstanceType.length == 0 ) - ? "participant" - : ( "" + strInstanceType ); + let strInstanceDescription = ( !strInstanceType ) + ? "participant" + : strInstanceType.toString(); if( typeof this.idRtcParticipant === "string" && this.idRtcParticipant.length > 0 ) strInstanceDescription += " " + this.idRtcParticipant; const arrProps: any[] = []; @@ -2095,20 +2067,20 @@ export class RTCActor extends RTCConnection { } this.signalingOptions = { - idCategory: "" + settings.rtcSpace.defaultSpaceCategory, - idSpace: "" + settings.rtcSpace.defaultSpaceName + idCategory: settings.rtcSpace.defaultSpaceCategory.toString(), + idSpace: settings.rtcSpace.defaultSpaceName.toString() }; if( signalingOptions ) { if( "idCategory" in signalingOptions && typeof signalingOptions.idCategory === "string" && signalingOptions.idCategory.length > 0 ) - this.signalingOptions.idCategory = "" + signalingOptions.idCategory; + this.signalingOptions.idCategory = signalingOptions.idCategory.toString(); if( "idSpace" in signalingOptions && typeof signalingOptions.idSpace === "string" && signalingOptions.idSpace.length > 0 ) - this.signalingOptions.idSpace = "" + signalingOptions.idSpace; + this.signalingOptions.idSpace = signalingOptions.idSpace.toString(); } } @@ -2199,9 +2171,9 @@ export class RTCActor extends RTCConnection { const joImpersonateMessage = { id: utils.randomCallID(), method: "signalingImpersonate", - idCategory: "" + this.signalingOptions.idCategory, - idSpace: "" + this.signalingOptions.idSpace, - idRtcParticipant: "" + this.idRtcParticipant, + idCategory: this.signalingOptions.idCategory.toString(), + idSpace: this.signalingOptions.idSpace.toString(), + idRtcParticipant: this.idRtcParticipant ? this.idRtcParticipant.toString() : "", role: this.isCreator ? "creator" : "joiner" }; if( settings.logging.net.signaling.message ) @@ -2549,7 +2521,7 @@ export class RTCServerPeer extends RTCConnection { onOtherSideIdentified( idSomebodyOtherSide: any ): void { this.publishCancel(); this.signalingNegotiationCancel(); - this.idSomebodyOtherSide = "" + idSomebodyOtherSide; + this.idSomebodyOtherSide = idSomebodyOtherSide ? idSomebodyOtherSide.toString() : ""; this.wasIdentified = true; this.dispatchEvent( new UniversalDispatcherEvent( @@ -2557,7 +2529,8 @@ export class RTCServerPeer extends RTCConnection { { detail: { participant: this, - idSomebodyOtherSide: "" + idSomebodyOtherSide + idSomebodyOtherSide: + idSomebodyOtherSide ? idSomebodyOtherSide.toString() : "" } } ) ); @@ -2604,7 +2577,7 @@ export class RTCServerPeer extends RTCConnection { id: utils.randomCallID(), method: "signalingPublishOffer", offer: self.pc.localDescription, - idSomebodyCreator: "" + self.rtcCreator.idRtcParticipant, + idSomebodyCreator: self.rtcCreator.idRtcParticipant.toString(), idOffer: 0 + ( self.idOffer || 0 ) }; if( settings.logging.net.signaling.message ) { @@ -2748,8 +2721,8 @@ export class RTCCreator extends RTCActor { } // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.mapServerOffers[idOffer]; - this.mapServerPeers["" + idSomebodyOtherSide] = rtcPeer; - rtcPeer.onOtherSideIdentified( "" + idSomebodyOtherSide ); + this.mapServerPeers[idSomebodyOtherSide.toString()] = rtcPeer; + rtcPeer.onOtherSideIdentified( idSomebodyOtherSide.toString() ); } onRtcPeerError( rtcPeer: any, err: any ): void { @@ -2789,7 +2762,7 @@ export class RTCCreator extends RTCActor { break; case "signalingPublishAnswer": // server peer got result if( joMessage.error == null ) { - const idSomebodyOtherSide = "" + joMessage.idSomebody_joiner; + const idSomebodyOtherSide = joMessage.idSomebody_joiner.toString(); const idOffer = 0 + joMessage.idOffer; if( !( idOffer in this.mapServerOffers ) ) { const strError = "not a registered pending offer(signalingPublishAnswer)"; @@ -2817,8 +2790,8 @@ export class RTCCreator extends RTCActor { { detail: { actor: this, - idSomebodyOtherSide: "" + idSomebodyOtherSide, - idOffer: 0 + idOffer + idSomebodyOtherSide: idSomebodyOtherSide.toString(), + idOffer } } ) ); @@ -3059,9 +3032,11 @@ export class RTCJoiner extends RTCActor { id: utils.randomCallID(), method: "signalingPublishAnswer", answer: self.pc.localDescription, - idRtcParticipant: "" + self.idRtcParticipant, - idSomebodyCreator: "" + self.idSomebodyCreator, - idOffer: 0 + self.idOffer + idRtcParticipant: + self.idRtcParticipant ? self.idRtcParticipant.toString() : "", + idSomebodyCreator: + self.idSomebodyCreator ? self.idSomebodyCreator.toString() : "", + idOffer: self.idOffer }; if( settings.logging.net.signaling.message ) { console.log( @@ -3109,8 +3084,8 @@ export class RTCJoiner extends RTCActor { idSomebodyOtherSide + "\" via offer ID " + idOffer.toString() ); } - this.idSomebodyOtherSide = "" + idSomebodyOtherSide; - this.idOffer = 0 + idOffer; + this.idSomebodyOtherSide = idSomebodyOtherSide.toString(); + this.idOffer = idOffer; this.wasIdentified = true; this.dispatchEvent( new UniversalDispatcherEvent( @@ -3118,7 +3093,7 @@ export class RTCJoiner extends RTCActor { { detail: { participant: this, - idSomebodyOtherSide: "" + idSomebodyOtherSide + idSomebodyOtherSide: idSomebodyOtherSide.toString() } } ) ); } @@ -3130,8 +3105,8 @@ export class RTCJoiner extends RTCActor { if( joMessage.error == null ) { // OKay, fetched offer from creator this.delayedInitPeer(); - this.idSomebodyCreator = "" + joMessage.idSomebodyCreator; - const idSomebodyOtherSide = "" + joMessage.idSomebodyCreator; + this.idSomebodyCreator = joMessage.idSomebodyCreator.toString(); + const idSomebodyOtherSide = joMessage.idSomebodyCreator.toString(); const idOffer = 0 + joMessage.idOffer; if( settings.logging.net.signaling.generic ) { console.log( @@ -3144,8 +3119,8 @@ export class RTCJoiner extends RTCActor { { detail: { actor: this, - idSomebodyOtherSide: "" + idSomebodyOtherSide, - idOffer: 0 + idOffer + idSomebodyOtherSide: idSomebodyOtherSide.toString(), + idOffer } } ) ); const offer = joMessage.offer; @@ -3258,12 +3233,12 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.url = "rtc_server_pipe(" + self.clientNumber + ")://" + strSignalingServerURL; self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { self.isConnected = true; - self.acceptor.mapClients["" + self.clientPort] = self; + self.acceptor.mapClients[self.clientPort.toString()] = self; self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); self.acceptor.dispatchEvent( new UniversalDispatcherEvent( "connection", - { socket: self, strSignalingServerURL: "" + strSignalingServerURL } ) ); + { socket: self, strSignalingServerURL: strSignalingServerURL.toString() } ) ); } ); self.rtcPeer.on( "dataChannelMessage", function( jo: any ) { self.receive( jo.detail.data ); @@ -3370,11 +3345,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); - this.idRtcParticipant = "" + - ( ( idRtcParticipant != null && idRtcParticipant != undefined && - typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) - ? idRtcParticipant - : utils.UUIDv4() ); + this.idRtcParticipant = idRtcParticipant ? idRtcParticipant.toString() : utils.UUIDv4(); this.offerOptions = offerOptions || null; this.signalingOptions = signalingOptions || null; this.peerConfiguration = @@ -3396,8 +3367,8 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { settings.net.rtc.timeToSignalingNegotiationMilliseconds; this.rtcCreator = new RTCCreator( - "" + this.strSignalingServerURL, - "" + this.idRtcParticipant, + this.strSignalingServerURL.toString(), + this.idRtcParticipant.toString(), this.offerOptions, this.signalingOptions ); this.isListening = true; @@ -3570,11 +3541,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { ) { super(); this.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); - this.idRtcParticipant = "" + - ( ( idRtcParticipant != null && idRtcParticipant != undefined && - typeof idRtcParticipant === "string" && idRtcParticipant.length > 0 ) - ? idRtcParticipant - : utils.UUIDv4() ); + this.idRtcParticipant = idRtcParticipant ? idRtcParticipant.toString() : utils.UUIDv4(); this.offerOptions = offerOptions || null; this.signalingOptions = signalingOptions || null; this.peerConfiguration = @@ -3610,7 +3577,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { socket: this, message: "" + s, errorType: "dataSendError" } ) ); + { socket: this, message: s.toString(), errorType: "dataSendError" } ) ); throw new Error( s ); } const s = socketSentDataMarshall( data ); @@ -3619,7 +3586,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { reconnect(): void { this.performDisconnect(); - this.rtcConnect( "" + this.strSignalingServerURL ); + this.rtcConnect( this.strSignalingServerURL ? this.strSignalingServerURL.toString() : "" ); } disconnect(): void { @@ -3639,7 +3606,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { this.dispatchEvent( new UniversalDispatcherEvent( "error", - { socket: this, message: "" + s, errorType: "badSignalingServerURL" } ) ); + { socket: this, message: s.toString(), errorType: "badSignalingServerURL" } ) ); throw new Error( s ); } const self = this; @@ -3649,7 +3616,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.rtcDisconnect(); self.rtcPeer = new RTCJoiner( - "" + strSignalingServerURL, "" + self.idRtcParticipant, + strSignalingServerURL.toString(), self.idRtcParticipant.toString(), self.offerOptions, self.signalingOptions, self.peerConfiguration, self.peerAdditionalOptions ); // client side diff --git a/src/socketServer.ts b/src/socketServer.ts index 0a5ebde2..4078854a 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -55,8 +55,10 @@ export class SocketServer extends EventDispatcher { eventData.remoteAddress == null || eventData.remoteAddress == undefined ) socket.strSavedRemoteAddress = socket.constructor.name; - else - socket.strSavedRemoteAddress = "" + eventData.remoteAddress; + else { + socket.strSavedRemoteAddress = + eventData.remoteAddress ? eventData.remoteAddress.toString() : ""; + } if( self.isLogAcceptedSocket ) { self.log( log.fmtInformation( "New socket {url} was {bright}", socket.strSavedRemoteAddress, "accepted" ) ); @@ -123,7 +125,7 @@ export class SocketServer extends EventDispatcher { joMessage.method, err, err ) ); } joAnswer = utils.prepareAnswerJSON( joMessage ); - joAnswer.error = "" + err.toString(); + joAnswer.error = err ? err.toString() : "N/A error"; } if( joAnswer != null && joAnswer != undefined ) { diff --git a/src/socketUtils.ts b/src/socketUtils.ts index 06e46809..08b4c551 100644 --- a/src/socketUtils.ts +++ b/src/socketUtils.ts @@ -129,18 +129,8 @@ export const randomDirectPipeID = function(): string { export const prepareAnswerJSON = function( joMessage: any ): any { const joAnswer: any = { - id: "" + - ( ( joMessage != null && - joMessage != undefined && - typeof joMessage.id === "string" ) - ? joMessage.id - : randomCallID() ), - method: "" + - ( ( joMessage != null && - joMessage != undefined && - typeof joMessage.method === "string" ) - ? joMessage.method - : "" ), + id: joMessage?.id ? joMessage.id.toString() : randomCallID(), + method: joMessage?.method ? joMessage.method.toString() : "", error: null }; return joAnswer; @@ -148,20 +138,15 @@ export const prepareAnswerJSON = function( joMessage: any ): any { export const makeValidSignalingServerURL = function( strSignalingServerURL?: string ): string { const proto = settings.net.secure ? "wss" : "ws"; - return "" + - ( ( strSignalingServerURL != null && - strSignalingServerURL != undefined && - typeof strSignalingServerURL === "string" && - strSignalingServerURL.length > 0 ) - ? "" + strSignalingServerURL - : "" + proto + "://" + settings.net.hostname + ":" + settings.net.ports.signaling - ); + return strSignalingServerURL + ? strSignalingServerURL.toString() + : proto + "://" + settings.net.hostname + ":" + settings.net.ports.signaling; }; export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ): string { if( val == null || val == undefined ) return val; - let s = "" + val; + let s = val.toString(); while( s.length < cntCharsNeeded ) s = "0" + s; return s; @@ -169,7 +154,7 @@ export const zeroPaddingLeft = function( val: any, cntCharsNeeded: number ): str export const zeroPaddingRight = function( val: any, cntCharsNeeded: number ): string { if( val == null || val == undefined ) return val; - let s = "" + val; + let s = val.toString(); while( s.length < cntCharsNeeded ) s = s + "0"; return s; @@ -223,7 +208,7 @@ export const formatDateTime = function( sepDate = ( sepDate == null || sepDate == undefined || ( typeof sepDate !== "string" ) ) ? "/" : sepDate; - const strDate = "" + + const strDate = zeroPaddingLeft( dt.getFullYear(), 4 ) + sepDate + zeroPaddingLeft( dt.getMonth() + 1, 2 ) + @@ -236,15 +221,10 @@ export const formatDateTime = function( ? ":" : sepTime; if( isDate ) { - sepBetween = - ( sepBetween == null || - sepBetween == undefined || - ( typeof sepBetween !== "string" ) ) - ? "-" - : sepBetween; + sepBetween = sepBetween ?? "-"; s += sepBetween; } - let strTime = "" + + let strTime = zeroPaddingLeft( dt.getHours(), 2 ) + sepDate + zeroPaddingLeft( dt.getMinutes(), 2 ) + diff --git a/src/utils.ts b/src/utils.ts index c0cd8b04..6130225f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -55,7 +55,7 @@ export function normalizePath( strPath: string ): string { export function getRandomFileName(): string { const timestamp = new Date().toISOString().replace( /[-:.]/g, "" ); - const random = ( "" + Math.random() ).substring( 2, 8 ); + const random = Math.random().toString().substring( 2, 8 ); const randomNumber = timestamp + random; return randomNumber; } @@ -200,7 +200,7 @@ export async function waitForClonedTokenAppearErc20( const addressOnSChain = await waitForClonedTokenToAppear( sc, "erc20", addressCallFrom, 40, tokensMN, strMainnetName ); tokenERC20SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC20_abi ) ); - tokenERC20SC.address = "" + addressOnSChain; + tokenERC20SC.address = addressOnSChain ? addressOnSChain.toString() : ""; } export async function waitForClonedTokenAppearErc721( @@ -218,7 +218,7 @@ export async function waitForClonedTokenAppearErc721( await waitForClonedTokenToAppear( sc, "erc721", addressCallFrom, 40, tokensMN, strMainnetName ); tokenERC721SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC721_abi ) ); - tokenERC721SC.address = "" + addressOnSChain; + tokenERC721SC.address = addressOnSChain ? addressOnSChain.toString() : ""; } export async function waitForClonedTokenAppearErc721WithMetadata( @@ -237,7 +237,7 @@ export async function waitForClonedTokenAppearErc721WithMetadata( sc, "erc721_with_metadata", addressCallFrom, 40, tokensMN, strMainnetName ); tokenERC721SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC721_with_metadata_abi ) ); - tokenERC721SC.address = "" + addressOnSChain; + tokenERC721SC.address = addressOnSChain ? addressOnSChain.toString() : ""; } export async function waitForClonedTokenAppearErc1155( @@ -254,7 +254,7 @@ export async function waitForClonedTokenAppearErc1155( const addressOnSChain = await waitForClonedTokenToAppear( sc, "erc1155", addressCallFrom, 40, tokensMN, strMainnetName ); tokenERC1155SC.abi = JSON.parse( JSON.stringify( ( tokensMN.joABI as any ).ERC1155_abi ) ); - tokenERC1155SC.address = "" + addressOnSChain; + tokenERC1155SC.address = addressOnSChain ? addressOnSChain.toString() : ""; } export function hexToBytes( @@ -263,8 +263,8 @@ export function hexToBytes( isInversiveOrder = !!( ( isInversiveOrder != null && isInversiveOrder != undefined && isInversiveOrder ) ); - strHex = strHex || ""; - strHex = "" + strHex; + strHex = strHex ?? ""; + strHex = strHex.toString(); strHex = strHex.trim().toLowerCase(); if( strHex.length > 1 && strHex[0] == "0" && ( strHex[1] == "x" || strHex[1] == "X" ) ) strHex = strHex.substr( 2, strHex.length - 2 ); From 5b3840e188228f95e34f214e63d39f0de7f13542 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 17:20:26 +0000 Subject: [PATCH 44/53] ESLint rules simplifications --- src/imaEthOperations.ts | 4 ++-- src/imaOracleOperations.ts | 4 ++-- src/loop.ts | 28 +++++++++++++++++++++------- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/imaEthOperations.ts b/src/imaEthOperations.ts index f79ff2f2..fa8dedc6 100644 --- a/src/imaEthOperations.ts +++ b/src/imaEthOperations.ts @@ -96,14 +96,14 @@ export async function doEthPaymentFromMainNet( details, ethersProviderMainNet, "DepositBox", joDepositBox, "deposit", arrArguments, joAccountSrc, strActionName, - gasPrice, 3000000, weiHowMuch ); + gasPrice, 3000000 ); details.trace( "{p}Using estimated gas={}", strLogPrefix, estimatedGas ); const isIgnore = false; const strErrorOfDryRun = await imaTx.dryRunCall( details, ethersProviderMainNet, "DepositBox", joDepositBox, "deposit", arrArguments, joAccountSrc, strActionName, isIgnore, - gasPrice, estimatedGas, weiHowMuch ); + gasPrice, estimatedGas ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 25d1c50a..267aad4a 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -219,7 +219,7 @@ async function handleOracleSigned( "CommunityLocker", optsGasPriceSetup.joCommunityLocker, "setGasPrice", arrArgumentsSetGasPrice, optsGasPriceSetup.joAccountSC, optsGasPriceSetup.strActionName, - isIgnoreSetGasPrice, gasPrice, estimatedGasSetGasPrice, weiHowMuch ); + isIgnoreSetGasPrice, gasPrice, estimatedGasSetGasPrice ); if( strErrorOfDryRun ) throw new Error( strErrorOfDryRun ); const opts: imaTx.TCustomPayedCallOptions = { @@ -230,7 +230,7 @@ async function handleOracleSigned( "CommunityLocker", optsGasPriceSetup.joCommunityLocker, "setGasPrice", arrArgumentsSetGasPrice, optsGasPriceSetup.joAccountSC, optsGasPriceSetup.strActionName, - gasPrice, estimatedGasSetGasPrice, weiHowMuch, opts ); + gasPrice, estimatedGasSetGasPrice, undefined, opts ); if( joReceipt ) { optsGasPriceSetup.jarrReceipts.push( { description: "doOracleGasPriceSetup/setGasPrice", diff --git a/src/loop.ts b/src/loop.ts index 89a4f88e..4d19f579 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -196,8 +196,12 @@ async function singleTransferLoopPartOracle( imaState.chainProperties.sc.transactionCustomizer, imaState.joCommunityLocker, imaState.chainProperties.sc.joAccount, - imaState.chainProperties.mn.chainId.toString(), - imaState.chainProperties.sc.chainId.toString(), + imaState.chainProperties.mn.chainId + ? imaState.chainProperties.mn.chainId.toString() + : "", + imaState.chainProperties.sc.chainId + ? imaState.chainProperties.sc.chainId.toString() + : "", imaBLS.doSignU256 ); imaState.loopState.oracle.isInProgress = false; @@ -255,8 +259,12 @@ async function singleTransferLoopPartM2S( imaState.chainProperties.sc.joAccount, imaState.chainProperties.mn.strChainName, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.mn.chainId.toString(), - imaState.chainProperties.sc.chainId.toString(), + imaState.chainProperties.mn.chainId + ? imaState.chainProperties.mn.chainId.toString() + : "", + imaState.chainProperties.sc.chainId + ? imaState.chainProperties.sc.chainId.toString() + : "", null, imaState.joTokenManagerETH, // for logs validation on s-chain imaState.nTransferBlockSizeM2S, @@ -328,8 +336,12 @@ async function singleTransferLoopPartS2M( imaState.chainProperties.sc.strChainName, imaState.chainProperties.mn.strChainName, - imaState.chainProperties.sc.chainId.toString(), - imaState.chainProperties.mn.chainId.toString(), + imaState.chainProperties.sc.chainId + ? imaState.chainProperties.sc.chainId.toString() + : "", + imaState.chainProperties.mn.chainId + ? imaState.chainProperties.mn.chainId.toString() + : "", imaState.joDepositBoxETH, // for logs validation on mainnet null, @@ -386,7 +398,9 @@ async function singleTransferLoopPartS2S( imaState.joMessageProxySChain, imaState.chainProperties.sc.joAccount, imaState.chainProperties.sc.strChainName, - imaState.chainProperties.sc.chainId.toString(), + imaState.chainProperties.sc.chainId + ? imaState.chainProperties.sc.chainId.toString() + : "", imaState.joTokenManagerETH, // for logs validation on s-chain imaState.nTransferBlockSizeS2S, imaState.nTransferStepsS2S, From a81fd7dbb8526d2f35cc093b56aa688e1f808b41 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 19:33:49 +0000 Subject: [PATCH 45/53] ESLint rules simplifications --- src/cc.ts | 2 +- src/loop.ts | 1 - src/loopWorker.ts | 5 +++-- src/main.ts | 9 +++++++-- src/owaspUtils.ts | 6 ++++-- src/pwa.ts | 3 +++ 6 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/cc.ts b/src/cc.ts index f4380eb1..ca756636 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -62,7 +62,7 @@ export function validateRadix( value?: any, radix?: any ): number { export function validateInteger( value?: any, radix?: any ): boolean { try { - value = value.trim(); + value = value ? value.toString().trim() : ""; if( value.length < 1 ) return false; radix = validateRadix( value, radix ); diff --git a/src/loop.ts b/src/loop.ts index 4d19f579..2c26485e 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -294,7 +294,6 @@ async function singleTransferLoopPartM2S( strLogPrefix, threadInfo.threadDescription(), b1 ); } else log.debug( "{p}Skipped M2S transfer in {}.", strLogPrefix, threadInfo.threadDescription() ); - return b1; } diff --git a/src/loopWorker.ts b/src/loopWorker.ts index 351dd5de..bd3cee55 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -209,8 +209,9 @@ class ObserverServer extends SocketServer { joMessage.params.signature ).then( function(): void {} ).catch( function(): void {} ); }; - console.log( "Initialized in-worker IMA loop {} server in {}", - workerData.url, threadInfo.threadDescription() ); + console.log( + `Initialized in-worker IMA loop ${workerData.url} server ` + + `in ${threadInfo.threadDescription()}` ); } dispose(): void { diff --git a/src/main.ts b/src/main.ts index c6b671cb..1e93f451 100644 --- a/src/main.ts +++ b/src/main.ts @@ -152,8 +152,13 @@ function initMonitoringServer(): void { log.trace( "{p}Will start monitoring WS server on port {}", strLogPrefix, imaState.nMonitoringPort ); } - gServerMonitoringWS = new ws.WebSocketServer( { port: 0 + imaState.nMonitoringPort } ); - gServerMonitoringWS.on( "connection", function( wsPeer: any, req: any ) { + try { + gServerMonitoringWS = new ws.WebSocketServer( { port: imaState.nMonitoringPort } ); + } catch ( err ) { + log.error( "Failed start monitoring WS server on port {}, error is: {err}", + imaState.nMonitoringPort, err ); + } + gServerMonitoringWS.on( "connection", function( wsPeer: any, req: any ): void { let ip = req.socket.remoteAddress; if( "headers" in req && req.headers && typeof req.headers === "object" && "x-forwarded-for" in req.headers && req.headers["x-forwarded-for"] ) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 7b406683..31c5f524 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -90,7 +90,7 @@ export function parseIntOrHex( s: any ): number { export function validateRadix( value: any, radix?: any ): boolean { value = value ? value.toString() : "10"; - value = value.trim(); + value = value ? value.toString().trim() : ""; radix = ( radix == null || radix == undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) ? 16 @@ -101,7 +101,7 @@ export function validateRadix( value: any, radix?: any ): boolean { export function validateInteger( value: any, radix?: any ): boolean { try { - value = value.trim(); + value = value ? value.toString().trim() : ""; if( value.length < 1 ) return false; radix = validateRadix( value, radix ); @@ -228,6 +228,8 @@ export function isUrlWS( strURL?: any ): boolean { export function toBoolean( value?: any ): boolean { let b = false; try { + if( value === null || value === undefined ) + return false; if( typeof value === "boolean" ) return value; if( typeof value === "string" ) { diff --git a/src/pwa.ts b/src/pwa.ts index 7d7ed065..a3170609 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -31,6 +31,9 @@ import type * as state from "./state.js"; import type * as discoveryTools from "./discoveryTools.js"; function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): number[] { + if( nNodeNumber === null || nNodeNumber === undefined || + nNodesCount === undefined ) + return []; if( nNodesCount <= 1 ) return []; // PWA is N/A if( !( nNodeNumber >= 0 && nNodeNumber < nNodesCount ) ) From 9aa88242aa6a8c24875ffd0ec2254b2113cec6ee Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 19:58:28 +0000 Subject: [PATCH 46/53] ESLint rules simplifications --- src/bls.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index ec83e884..d121527e 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -94,6 +94,7 @@ export interface TSignOperationOptions { export interface TBSU256CallData { params: { valueToSign: string + qa?: TQAInformation } } @@ -2214,8 +2215,8 @@ async function handleBlsSignMessageHashResult( if( joOut.signResult != null && joOut.signResult != undefined && typeof joOut.signResult === "object" ) joSignResult = joOut.signResult; - if( "qa" in optsHandleVerifyAndSign.joCallData ) - optsHandleVerifyAndSign.joRetVal.qa = optsHandleVerifyAndSign.joCallData.qa; + if( "qa" in optsHandleVerifyAndSign.joCallData.params ) + optsHandleVerifyAndSign.joRetVal.qa = optsHandleVerifyAndSign.joCallData.params.qa; if( !joSignResult ) { const strError = "No signature arrived"; optsHandleVerifyAndSign.joRetVal.error = strError; @@ -2240,8 +2241,8 @@ async function handleBlsSignMessageHashResult( } optsHandleVerifyAndSign.isSuccess = true; optsHandleVerifyAndSign.joRetVal.result = { signResult: joSignResult }; - if( "qa" in optsHandleVerifyAndSign.joCallData ) - optsHandleVerifyAndSign.joRetVal.qa = optsHandleVerifyAndSign.joCallData.qa; + if( "qa" in optsHandleVerifyAndSign.joCallData.params ) + optsHandleVerifyAndSign.joRetVal.qa = optsHandleVerifyAndSign.joCallData.params.qa; await joCall.disconnect(); return joSignResult; } @@ -2412,8 +2413,8 @@ async function handleBlsSignMessageHash256Result( } optsBSU256.isSuccess = true; optsBSU256.joRetVal.result = { signResult: joSignResult }; - if( "qa" in optsBSU256.joCallData ) - optsBSU256.joRetVal.qa = optsBSU256.joCallData.qa; + if( "qa" in optsBSU256.joCallData.params ) + optsBSU256.joRetVal.qa = optsBSU256.joCallData.params.qa; await joCall.disconnect(); return joSignResult; } From 2cc5f2f2a8651512d3ac0b96907ea31bd3abf78f Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Tue, 2 Jan 2024 20:09:00 +0000 Subject: [PATCH 47/53] ESLint rules simplifications --- src/discoveryTools.ts | 33 ++++++++-------------- src/rpcCall.ts | 1 + src/utils.ts | 66 ++++++++++--------------------------------- 3 files changed, 28 insertions(+), 72 deletions(-) diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index 006dfd75..d62cb197 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -75,6 +75,7 @@ export interface TSChainNode { httpRpcPort6?: number httpsRpcPort?: number httpsRpcPort6?: number + imaAgentRpcPort?: number ip?: string ip6?: string nodeID: number @@ -170,34 +171,24 @@ function getSChainNodesCount( joSChainNetworkInfo: TSChainNetworkInfo ): number export function isSChainNodeFullyDiscovered( joNode: TSChainNode ): boolean { if( !joNode ) return false; - if( joNode && "imaInfo" in joNode && typeof joNode.imaInfo === "object" && - "t" in joNode.imaInfo && typeof joNode.imaInfo.t === "number" && - joNode.imaInfo.t > 0 && - "n" in joNode.imaInfo && typeof joNode.imaInfo.n === "number" && - joNode.imaInfo.n > 0 && - "BLSPublicKey0" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey0 === "string" && + if( joNode && "imaInfo" in joNode && joNode?.imaInfo && + "t" in joNode.imaInfo && joNode.imaInfo?.t && joNode.imaInfo.t > 0 && + "n" in joNode.imaInfo && joNode.imaInfo?.n && joNode.imaInfo.n > 0 && + "BLSPublicKey0" in joNode.imaInfo && joNode.imaInfo?.BLSPublicKey0 && joNode.imaInfo.BLSPublicKey0.length > 0 && - "BLSPublicKey1" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey1 === "string" && + "BLSPublicKey1" in joNode.imaInfo && joNode.imaInfo?.BLSPublicKey1 && joNode.imaInfo.BLSPublicKey1.length > 0 && - "BLSPublicKey2" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey2 === "string" && + "BLSPublicKey2" in joNode.imaInfo && joNode.imaInfo?.BLSPublicKey2 && joNode.imaInfo.BLSPublicKey2.length > 0 && - "BLSPublicKey3" in joNode.imaInfo && - typeof joNode.imaInfo.BLSPublicKey3 === "string" && + "BLSPublicKey3" in joNode.imaInfo && joNode.imaInfo?.BLSPublicKey3 && joNode.imaInfo.BLSPublicKey3.length > 0 && - "commonBLSPublicKey0" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey0 === "string" && + "commonBLSPublicKey0" in joNode.imaInfo && joNode.imaInfo?.commonBLSPublicKey0 && joNode.imaInfo.commonBLSPublicKey0.length > 0 && - "commonBLSPublicKey1" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey1 === "string" && + "commonBLSPublicKey1" in joNode.imaInfo && joNode.imaInfo?.commonBLSPublicKey1 && joNode.imaInfo.commonBLSPublicKey1.length > 0 && - "commonBLSPublicKey2" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey2 === "string" && + "commonBLSPublicKey2" in joNode.imaInfo && joNode.imaInfo?.commonBLSPublicKey2 && joNode.imaInfo.commonBLSPublicKey2.length > 0 && - "commonBLSPublicKey3" in joNode.imaInfo && - typeof joNode.imaInfo.commonBLSPublicKey3 === "string" && + "commonBLSPublicKey3" in joNode.imaInfo && joNode.imaInfo?.commonBLSPublicKey3 && joNode.imaInfo.commonBLSPublicKey3.length > 0 ) return true; diff --git a/src/rpcCall.ts b/src/rpcCall.ts index d3fb898b..6ba4d8a1 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -34,6 +34,7 @@ export interface TRPCCallOpts { cert?: string key?: string ca?: string + isAutoReconnect?: boolean } export type TFunctionConnectionResultHandler = diff --git a/src/utils.ts b/src/utils.ts index 6130225f..e68bfdd7 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -412,41 +412,24 @@ export function checkKeysExistInABI( } export function composeSChainNodeUrl( joNode: discoveryTools.TSChainNode ): string { - if( "ip" in joNode && typeof joNode.ip === "string" && joNode.ip.length > 0 ) { - if( "httpRpcPort" in joNode && - typeof joNode.httpRpcPort === "number" && - joNode.httpRpcPort > 0 ) + if( "ip" in joNode && joNode?.ip && joNode.ip.length > 0 ) { + if( "httpRpcPort" in joNode && joNode?.httpRpcPort && joNode.httpRpcPort > 0 ) return "http://" + joNode.ip + ":" + joNode.httpRpcPort; - if( "wsRpcPort" in joNode && - typeof joNode.wsRpcPort === "number" && - joNode.wsRpcPort > 0 ) + if( "wsRpcPort" in joNode && joNode?.wsRpcPort && joNode.wsRpcPort > 0 ) return "ws://" + joNode.ip + ":" + joNode.wsRpcPort; - if( "httpsRpcPort" in joNode && - typeof joNode.httpsRpcPort === "number" && - joNode.httpsRpcPort > 0 ) + if( "httpsRpcPort" in joNode && joNode?.httpsRpcPort && joNode.httpsRpcPort > 0 ) return "https://" + joNode.ip + ":" + joNode.httpsRpcPort; - if( "wssRpcPort" in joNode && - typeof joNode.wssRpcPort === "number" && - joNode.wssRpcPort > 0 ) + if( "wssRpcPort" in joNode && joNode?.wssRpcPort && joNode.wssRpcPort > 0 ) return "wss://" + joNode.ip + ":" + joNode.wssRpcPort; } - if( "ip6" in joNode && typeof joNode.ip6 === "string" && - joNode.ip6.length > 0 ) { - if( "httpRpcPort6" in joNode && - typeof joNode.httpRpcPort6 === "number" && - joNode.httpRpcPort6 > 0 ) + if( "ip6" in joNode && joNode?.ip6 && joNode.ip6.length > 0 ) { + if( "httpRpcPort6" in joNode && joNode?.httpRpcPort6 && joNode.httpRpcPort6 > 0 ) return "http://[" + joNode.ip6 + "]:" + joNode.httpRpcPort6; - if( "wsRpcPort6" in joNode && - typeof joNode.wsRpcPort6 === "number" && - joNode.wsRpcPort6 > 0 ) + if( "wsRpcPort6" in joNode && joNode?.wsRpcPort6 && joNode.wsRpcPort6 > 0 ) return "ws://[" + joNode.ip6 + "]:" + joNode.wsRpcPort6; - if( "httpsRpcPort6" in joNode && - typeof joNode.httpsRpcPort6 === "number" && - joNode.httpsRpcPort6 > 0 ) + if( "httpsRpcPort6" in joNode && joNode?.httpsRpcPort6 && joNode.httpsRpcPort6 > 0 ) return "https://[" + joNode.ip6 + "]:" + joNode.httpsRpcPort6; - if( "wssRpcPort6" in joNode && - typeof joNode.wssRpcPort6 === "number" && - joNode.wssRpcPort6 > 0 ) + if( "wssRpcPort6" in joNode && joNode?.wssRpcPort6 && joNode.wssRpcPort6 > 0 ) return "wss://[" + joNode.ip6 + "]:" + joNode.wssRpcPort6; } return ""; @@ -455,10 +438,7 @@ export function composeSChainNodeUrl( joNode: discoveryTools.TSChainNode ): stri export function composeImaAgentNodeUrl( joNode: discoveryTools.TSChainNode, isThisNode: boolean ): string { let nPort = -1; - if( "imaAgentRpcPort" in joNode && - typeof joNode.imaAgentRpcPort === "number" && - joNode.imaAgentRpcPort > 0 - ) + if( "imaAgentRpcPort" in joNode && joNode?.imaAgentRpcPort && joNode.imaAgentRpcPort > 0 ) nPort = joNode.imaAgentRpcPort; // PROPOSAL = 0 // CATCHUP = 1 @@ -471,29 +451,13 @@ export function composeImaAgentNodeUrl( // HTTPS_JSON = 8 // INFO_HTTP_JSON = 9 // IMA_AGENT_JSON = 10 - if( nPort < 0 && - "httpRpcPort" in joNode && - typeof joNode.httpRpcPort === "number" && - joNode.httpRpcPort > 0 - ) + if( nPort < 0 && joNode?.httpRpcPort && joNode.httpRpcPort > 0 ) nPort = joNode.httpRpcPort - 3 + 10; - if( nPort < 0 && - "wsRpcPort" in joNode && - typeof joNode.wsRpcPort === "number" && - joNode.wsRpcPort > 0 - ) + if( nPort < 0 && joNode?.wsRpcPort && joNode.wsRpcPort > 0 ) nPort = joNode.wsRpcPort - 2 + 10; - if( nPort < 0 && - "httpsRpcPort" in joNode && - typeof joNode.httpsRpcPort === "number" && - joNode.httpsRpcPort > 0 - ) + if( nPort < 0 && joNode?.httpsRpcPort && joNode.httpsRpcPort > 0 ) nPort = joNode.httpsRpcPort - 8 + 10; - if( nPort < 0 && - "wssRpcPort" in joNode && - typeof joNode.wssRpcPort === "number" && - joNode.wssRpcPort > 0 - ) + if( nPort < 0 && joNode?.wssRpcPort && joNode.wssRpcPort > 0 ) nPort = joNode.wssRpcPort - 7 + 10; if( nPort > 0 ) { const strNodeIP = isThisNode ? "127.0.0.1" : joNode.ip; From feb8069cd8c204bc72d0fe02d04a79f198d557fc Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 3 Jan 2024 11:48:23 +0000 Subject: [PATCH 48/53] ESLint rules simplifications --- src/bls.ts | 24 ++++--- src/cc.ts | 2 +- src/cli.ts | 2 + src/discoveryTools.ts | 8 +-- src/imaCore.ts | 2 +- src/imaOracleOperations.ts | 5 +- src/log.ts | 2 +- src/loop.ts | 4 +- src/loopWorker.ts | 40 ++++++----- src/main.ts | 12 ++-- src/owaspUtils.ts | 18 +++-- src/pwa.ts | 2 +- src/rpcCall.ts | 68 ++++++++++-------- src/socket.ts | 142 +++++++++++++++++++------------------ src/socketServer.ts | 6 +- 15 files changed, 183 insertions(+), 154 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index d121527e..1c56972b 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -1107,7 +1107,7 @@ async function gatherSigningCheckFinish( optsSignOperation.jarrMessages, joGlueResult ); optsSignOperation.fn( strError, optsSignOperation.jarrMessages, joGlueResult ) - .catch( function( err: Error | string ) { + .catch( function( err: Error | string ): void { optsSignOperation.details.critical( "Problem(2) in BLS sign result handler: {err}", err ); optsSignOperation.errGathering = "Problem(2) in BLS sign " + @@ -1125,7 +1125,7 @@ async function gatherSigningCheckOverflow( `signature error(2), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, optsSignOperation.jarrMessages, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(3) in BLS sign result handler, not enough successful BLS signature " + @@ -1157,7 +1157,7 @@ async function gatherSigningStartImpl( `signature error(3), got ${optsSignOperation.joGatheringTracker.nCountErrors}` + ` errors(s) for ${optsSignOperation.jarrNodes.length} node(s)`, optsSignOperation.jarrMessages, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.critical( "Problem(4) in BLS sign result handler, not enough successful BLS signature " + @@ -1184,7 +1184,7 @@ async function gatherSigningFinishImpl( `${JSON.stringify( optsSignOperation.joGatheringTracker )} , ` + `error is: ${optsSignOperation.errGathering.toString()}`, optsSignOperation.jarrMessages, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(5) in BLS sign result handler, not enough successful BLS " + @@ -1206,7 +1206,7 @@ async function gatherSigningFinishImpl( `Failed to gather BLS signatures in ${optsSignOperation.jarrNodes.length} node(s), ` + `tracker data is: ${JSON.stringify( optsSignOperation.joGatheringTracker )}`, optsSignOperation.jarrMessages, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const cntSuccess = optsSignOperation.arrSignResults.length; optsSignOperation.details.error( "Problem(6) in BLS sign result handler, not enough successful BLS signature " + @@ -1388,7 +1388,8 @@ async function doSignProcessOneImpl( optsSignOperation.sequenceId ); const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; const joCall = - await rpcCall.create( strNodeURL, rpcCallOpts ).catch( function( err: Error | string ) { + await rpcCall.create( strNodeURL, rpcCallOpts + ).catch( function( err: Error | string ): void { ++optsSignOperation.joGatheringTracker.nCountReceived; ++optsSignOperation.joGatheringTracker.nCountErrors; optsSignOperation.details.error( @@ -1442,7 +1443,8 @@ async function doSignMessagesImpl( joExtraSignOpts, // eslint-disable-next-line n/handle-callback-err fn: fn ?? async function( - err: Error | string | null, jarrMessages: any[], joGlueResult: any | null ) {}, + err: Error | string | null, jarrMessages: any[], joGlueResult: any | null + ): Promise < void > {}, bHaveResultReportCalled: false, strLogPrefix: "", strLogPrefixA: "", @@ -1518,7 +1520,7 @@ async function doSignMessagesImpl( optsSignOperation.bHaveResultReportCalled = true; await optsSignOperation.fn( "Failed BLS sign due to exception: " + `${owaspUtils.extractErrorMessage( err )}`, optsSignOperation.jarrMessages, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { log.critical( "Failed BLS sign due to error-reporting callback exception: {err}", err ); if( optsSignOperation.details ) { @@ -1803,7 +1805,7 @@ async function gatherSigningCheckFinish256( "glue result is {}", strError ? ( " with error " + log.fmtError( "{err}", strError ) ) : "", optsSignU256.u256, joGlueResult ); optsSignU256.fn( strError, optsSignU256.u256, joGlueResult ) - .catch( function( err: Error | string ) { + .catch( function( err: Error | string ): void { optsSignU256.details.critical( "Problem(2) in BLS u256 sign result handler: {err}", err ); optsSignU256.errGathering = "Problem(2) in BLS u256 sign result " + @@ -1820,7 +1822,7 @@ async function gatherSigningCheckOverflow256( "signature error(2, u256), got " + `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.critical( "Problem(3) in BLS u256 sign result handler, not enough successful BLS " + @@ -1851,7 +1853,7 @@ async function doSignU256Gathering( optsSignU256: TSignU256Options ): Promise < `${optsSignU256.joGatheringTracker.nCountErrors} errors(s) for ` + `${optsSignU256.jarrNodes.length} node(s)`, optsSignU256.u256, null - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const cntSuccess = optsSignU256.arrSignResults.length; optsSignU256.details.error( "Problem(4) in BLS u256 sign result handler, not enough successful BLS " + diff --git a/src/cc.ts b/src/cc.ts index ca756636..d4befdfa 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -534,7 +534,7 @@ export function syntaxHighlightJSON( jo?: any, strKeyNamePrefix?: string ): stri return jo.replace( // eslint-disable-next-line max-len /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, - function( match: any ) { + function( match: any ): string { if( !gFlagIsEnabled ) return match; let cls = "number"; diff --git a/src/cli.ts b/src/cli.ts index 3bdfa11c..ce00c54f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -931,7 +931,9 @@ function parseTransferArgs( imaState: state.TIMAState, joArg: any ): boolean { } if( joArg.name == "node-number" ) { owaspUtils.verifyArgumentIsInteger( joArg ); + console.log( "------------------------ joArg.value ---", joArg.value ); imaState.nNodeNumber = owaspUtils.toInteger( joArg.value ); + console.log( "------------------------ imaState.nNodeNumber ---", imaState.nNodeNumber ); return true; } if( joArg.name == "nodes-count" ) { diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index d62cb197..b7c04af4 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -241,7 +241,7 @@ export async function waitUntilSChainStarted(): Promise { let isError = false; const joSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, null, nCountToWait - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { log.critical( "S-Chain network discovery attempt failed: {err}", err ); isError = true; } ); @@ -347,7 +347,7 @@ async function handlePeriodicDiscoveryAttemptActions( let isError = false; const joSChainNetworkInfo: TSChainNetworkInfo = await discoverSChainNetwork( null, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { isError = true; log.critical( "S-Chain network re-discovery failed: {err}", err ); } ) as TSChainNetworkInfo; @@ -630,7 +630,7 @@ async function handleDiscoverSkaleNodesRpcInfoResult( if( optsDiscover.fnAfter ) optsDiscover.fnAfter( null, optsDiscover.joSChainNetworkInfo ); rv = true; - } ).catch( function( err: Error | string ) { + } ).catch( function( err: Error | string ): void { log.error( "Failed to wait until S-chain discovery complete, reported error is: {err}", err ); if( optsDiscover.fnAfter ) @@ -676,7 +676,7 @@ export async function discoverSChainNetwork( const joOut = await joCall.call( joIn ); await handleDiscoverSkaleNodesRpcInfoResult( optsDiscover, scURL, joCall, joIn, joOut - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { log.critical( "{p}JSON RPC call(in discoverSChainNetwork) error: {err}, stack is:\n{stack}", optsDiscover.strLogPrefix, err, err ); diff --git a/src/imaCore.ts b/src/imaCore.ts index 89651612..ee27d980 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -699,7 +699,7 @@ async function handleAllMessagesSigning( optsTransfer: TTransferOptions ): Promi optsTransfer.chainNameSrc, optsTransfer.joExtraSignOpts, async function( err: Error | string | null, jarrMessages: any[], joGlueResult: any ) { await callbackAllMessagesSign( optsTransfer, err, jarrMessages, joGlueResult ); - } ).catch( function( err: Error | string ) { + } ).catch( function( err: Error | string ): void { // callback fn as argument of optsTransfer.fnSignMessages optsTransfer.bErrorInSigningMessages = true; optsTransfer.details.error( "{p}Problem in transfer handler(in signer): {err}", diff --git a/src/imaOracleOperations.ts b/src/imaOracleOperations.ts index 267aad4a..10d1b153 100644 --- a/src/imaOracleOperations.ts +++ b/src/imaOracleOperations.ts @@ -280,7 +280,7 @@ export async function doOracleGasPriceSetup( optsGasPriceSetup.strLogPrefix ); optsGasPriceSetup.fnSignMsgOracle = async function( u256: any, details: log.TLogger, - fnAfter: IMA.TFunctionAfterSigningMessages ) { + fnAfter: IMA.TFunctionAfterSigningMessages ): Promise { details.trace( "{p}u256 signing callback was not provided", optsGasPriceSetup.strLogPrefix ); await fnAfter( null, u256, null ); // null - no error, null - no signatures @@ -296,7 +296,8 @@ export async function doOracleGasPriceSetup( await optsGasPriceSetup.fnSignMsgOracle( optsGasPriceSetup.gasPriceOnMainNet, optsGasPriceSetup.details, async function( - strError: Error | string | null, u256: any, joGlueResult: any | null ) { + strError: Error | string | null, u256: any, joGlueResult: any | null + ): Promise { await handleOracleSigned( optsGasPriceSetup, strError, u256, joGlueResult ); } ); } catch ( err ) { diff --git a/src/log.ts b/src/log.ts index dd549c24..e48f104a 100644 --- a/src/log.ts +++ b/src/log.ts @@ -733,7 +733,7 @@ function tryToSplitFormatString( strFormat?: string, cntArgsMax?: number ): any[ } export function fmtArgumentsArray( arrArgs: any[], fnFormatter?: any ): string { - fnFormatter = fnFormatter || function( arg: any ) { return arg; }; + fnFormatter = fnFormatter || function( arg: any ): any { return arg; }; const arrParts = ( arrArgs && arrArgs.length > 0 ) ? tryToSplitFormatString( arrArgs[0], arrArgs.length - 1 ) : null; diff --git a/src/loop.ts b/src/loop.ts index 2c26485e..6e5ffcd3 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -619,7 +619,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ): Promis workerData } ) ); - gArrWorkers[idxWorker].on( "message", function( jo: any ) { + gArrWorkers[idxWorker].on( "message", function( jo: any ): void { networkLayer.outOfWorkerAPIs.onMessage( gArrWorkers[idxWorker], jo ); } ); const aClient = new networkLayer.OutOfWorkerSocketClientPipe( @@ -627,7 +627,7 @@ export async function ensureHaveWorkers( opts: TParallelLoopRunOptions ): Promis gArrClients.push( aClient ); aClient.logicalInitComplete = false; aClient.errorLogicalInit = null; - aClient.on( "message", async function( eventData: any ) { + aClient.on( "message", async function( eventData: any ): Promise { const joMessage = eventData.message; switch ( joMessage.method ) { case "init": diff --git a/src/loopWorker.ts b/src/loopWorker.ts index bd3cee55..db98ff31 100644 --- a/src/loopWorker.ts +++ b/src/loopWorker.ts @@ -73,7 +73,7 @@ class ObserverServer extends SocketServer { self.intervalPeriodicSchainsCaching = null; self.bIsPeriodicCachingStepInProgress = false; self.mapApiHandlers.init = - function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { + function( joMessage: any, joAnswer: any, eventData: any, socket: any ): any { joAnswer.message = { method: joMessage.method.toString(), error: null @@ -110,22 +110,24 @@ class ObserverServer extends SocketServer { log.enableColorization( joMessage.message.colorization.isEnabled ); log.verboseSet( self.opts.imaState.verbose_ ); log.exposeDetailsSet( self.opts.imaState.expose_details_ ); - imaTransferErrorHandling.saveTransferEvents.on( "error", function( eventData: any ) { - const jo: any = { - method: "saveTransferError", - message: eventData.detail - }; - const isFlush = true; - socket.send( jo, isFlush ); - } ); - imaTransferErrorHandling.saveTransferEvents.on( "success", function( eventData: any ) { - const jo: any = { - method: "saveTransferSuccess", - message: eventData.detail - }; - const isFlush = true; - socket.send( jo, isFlush ); - } ); + imaTransferErrorHandling.saveTransferEvents.on( "error", + function( eventData: any ): void { + const jo: any = { + method: "saveTransferError", + message: eventData.detail + }; + const isFlush = true; + socket.send( jo, isFlush ); + } ); + imaTransferErrorHandling.saveTransferEvents.on( "success", + function( eventData: any ): void { + const jo: any = { + method: "saveTransferSuccess", + message: eventData.detail + }; + const isFlush = true; + socket.send( jo, isFlush ); + } ); self.opts.imaState.chainProperties.mn.joAccount.address = function(): string { return owaspUtils.fnAddressImpl_( this ); }; self.opts.imaState.chainProperties.sc.joAccount.address = @@ -187,7 +189,7 @@ class ObserverServer extends SocketServer { return joAnswer; }; self.mapApiHandlers.spreadUpdatedSChainNetwork = - function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { + function( joMessage: any, joAnswer: any, eventData: any, socket: any ): void { self.initLogMethods(); self.debug( "New own S-Chains network information is arrived to {} loop worker " + @@ -197,7 +199,7 @@ class ObserverServer extends SocketServer { imaState.joSChainNetworkInfo = joMessage.joSChainNetworkInfo; }; self.mapApiHandlers.skale_imaNotifyLoopWork = - function( joMessage: any, joAnswer: any, eventData: any, socket: any ) { + function( joMessage: any, joAnswer: any, eventData: any, socket: any ): void { self.initLogMethods(); pwa.handleLoopStateArrived( // NOTICE: no await here, executed async imaState, diff --git a/src/main.ts b/src/main.ts index 1e93f451..ddbe6af8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -47,7 +47,7 @@ process.on( "unhandledRejection", function( reason: any, p: any ): void { log.fatal( "CRITICAL ERROR: unhandled rejection with reason {} and promise {}", reason, p ); -} ).on( "uncaughtException", function( err: any ) { +} ).on( "uncaughtException", function( err: any ): void { log.fatal( "CRITICAL ERROR: uncaught exception: {err}, stack is:\n{stack}", err, err ); @@ -169,7 +169,7 @@ function initMonitoringServer(): void { ip = "N/A"; if( imaState.bLogMonitoringServer ) log.debug( "{p}New connection from {}", strLogPrefix, ip ); - wsPeer.on( "message", function( message: any ) { + wsPeer.on( "message", function( message: any ): void { const joAnswer: any = { method: null, id: null, @@ -269,11 +269,11 @@ function initJsonRpcServer(): void { gExpressJsonRpcAppIMA = express(); gExpressJsonRpcAppIMA.use( bodyParser.urlencoded( { extended: true } ) ); gExpressJsonRpcAppIMA.use( bodyParser.json() ); - gExpressJsonRpcAppIMA.post( "/", async function( req: any, res: any ) { + gExpressJsonRpcAppIMA.post( "/", async function( req: any, res: any ): Promise { const isSkipMode = false; const message = JSON.stringify( req.body ); const ip = req.connection.remoteAddress.split( ":" ).pop(); - const fnSendAnswer: any = function( joAnswer: any ) { + const fnSendAnswer: any = function( joAnswer: any ): void { try { res.header( "Content-Type", "application/json" ); res.status( 200 ).send( JSON.stringify( joAnswer ) ); @@ -460,7 +460,7 @@ async function main(): Promise { const nCountToWait = -1; discoveryTools.discoverSChainNetwork( function( err?: Error | string | null, - joSChainNetworkInfo?: discoveryTools.TSChainNetworkInfo | null ) { + joSChainNetworkInfo?: discoveryTools.TSChainNetworkInfo | null ): void { if( joSChainNetworkInfo ) { handleFirstSChainDiscoveryAttemptDone( err, joSChainNetworkInfo, isSilentReDiscovery, @@ -470,7 +470,7 @@ async function main(): Promise { // Finish of IMA Agent startup, // everything else is in async calls executed later }, isSilentReDiscovery, imaState.joSChainNetworkInfo, nCountToWait - ).catch( function( err: Error | string ) { + ).catch( function( err: Error | string ): void { const strError = owaspUtils.extractErrorMessage( err ); log.critical( "S-Chain network discovery failed: {err}", strError ); doTheJob().then( function(): void {} ).catch( function(): void {} ); diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 31c5f524..8401c3c9 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -89,9 +89,8 @@ export function parseIntOrHex( s: any ): number { } export function validateRadix( value: any, radix?: any ): boolean { - value = value ? value.toString() : "10"; - value = value ? value.toString().trim() : ""; - radix = ( radix == null || radix == undefined ) + value = ( value ? value.toString() : "10" ).trim(); + radix = ( radix === null || radix === undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) ? 16 : 10 ) @@ -101,8 +100,10 @@ export function validateRadix( value: any, radix?: any ): boolean { export function validateInteger( value: any, radix?: any ): boolean { try { - value = value ? value.toString().trim() : ""; - if( value.length < 1 ) + if( value === 0 || value === 0.0 ) + return true; + const s = value ? value.toString().trim() : ""; + if( s.length < 1 ) return false; radix = validateRadix( value, radix ); if( ( !isNaN( value ) ) && @@ -117,6 +118,9 @@ export function validateInteger( value: any, radix?: any ): boolean { export function toInteger( value: any, radix?: any ): number { try { + if( value === 0 || value === 0.0 || value === null || value === undefined ) + return 0; + value = ( value ? value.toString().trim() : "" ).trim(); radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) return NaN; @@ -128,6 +132,8 @@ export function toInteger( value: any, radix?: any ): number { export function validateFloat( value: any ): boolean { try { + if( value === 0 || value === 0.0 ) + return true; const f = parseFloat( value ); if( isNaN( f ) ) return false; @@ -139,6 +145,8 @@ export function validateFloat( value: any ): boolean { export function toFloat( value: any ): number { try { + if( value === 0 || value === 0.0 || value === null || value === undefined ) + return 0.0; const f = parseFloat( value ); return f; } catch ( err ) { diff --git a/src/pwa.ts b/src/pwa.ts index a3170609..18957a00 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -249,7 +249,7 @@ async function notifyOnLoopImpl( const rpcCallOpts: rpcCall.TRPCCallOpts | null = null; const joCall = await rpcCall.create( strNodeURL, rpcCallOpts ) - .catch( async function( err: Error | string ) { + .catch( async function( err: Error | string ): Promise { log.error( "PWA failed to perform] loop-{} notification RPC call to node " + "#{} with URL {url}, error is: {err}", diff --git a/src/rpcCall.ts b/src/rpcCall.ts index 6ba4d8a1..ec8be354 100644 --- a/src/rpcCall.ts +++ b/src/rpcCall.ts @@ -181,9 +181,9 @@ export async function doConnect( } } ); await waitWebSocketIsOpen( joCall.wsConn, - async function( nStep: number ) { // work done handler + async function( nStep: number ): Promise { // work done handler }, - async function( nStep: number ) { // step handler + async function( nStep: number ): Promise { // step handler if( strWsError && typeof strWsError === "string" && strWsError.length > 0 ) { log.error( "{url} web socket wait error detected: {err}", joCall.url, strWsError ); @@ -246,15 +246,16 @@ async function doReconnectWsStep( joCall: TRPCCall, opts: TRPCCallOpts | null, return; if( joCall.isDisconnectMode ) return; - doConnect( joCall, opts, async function( joCall: TRPCCall, err: Error | string | null ) { - if( err ) { - doReconnectWsStep( joCall, opts ) - .then( function(): void {} ).catch( function(): void {} ); - return; - } - if( fn ) - await fn( joCall, null ); - } ).then( function(): void {} ).catch( function(): void {} ); + doConnect( joCall, opts, + async function( joCall: TRPCCall, err: Error | string | null ): Promise { + if( err ) { + doReconnectWsStep( joCall, opts ) + .then( function(): void {} ).catch( function(): void {} ); + return; + } + if( fn ) + await fn( joCall, null ); + } ).then( function(): void {} ).catch( function(): void {} ); } async function doDisconnect( @@ -334,7 +335,7 @@ export async function doCall( try { const req = https.request( options as https.RequestOptions, ( res: any ) => { res.setEncoding( "utf8" ); - res.on( "data", function( body: any ) { + res.on( "data", function( body: any ): void { accumulatedBody += body; } ); res.on( "end", function(): void { @@ -355,7 +356,7 @@ export async function doCall( } } ); } ); - req.on( "error", function( err ) { + req.on( "error", function( err ): void { log.error( "{url} REST error {err}", joCall.url, err as any ); joOut = null; errCall = `HTTP(S)/RPC call(event) error: ${err as any}`; @@ -370,7 +371,7 @@ export async function doCall( reject( errCall ); } } ); - await promiseComplete.catch( function( err: Error | string ) { + await promiseComplete.catch( function( err: Error | string ): void { log.error( "{url} HTTP call error {err}", joCall.url, err ); if( !errCall ) errCall = `HTTP(S)/RPC call(catch) error: ${err as any}`; @@ -439,17 +440,20 @@ export async function rpcCallCreate( isAutoReconnect: !!( ( opts && "isAutoReconnect" in opts && opts.isAutoReconnect ) ), isDisconnectMode: false, - reconnect: async function( fnAfter: TFunctionConnectionResultHandler ) { + reconnect: + async function( fnAfter: TFunctionConnectionResultHandler ): Promise { await doConnect( joCall, opts, fnAfter ); }, - reconnectIfNeeded: async function( fnAfter: TFunctionConnectionResultHandler ) { + reconnectIfNeeded: + async function( fnAfter: TFunctionConnectionResultHandler ): Promise { await doConnectIfNeeded( joCall, opts, fnAfter ); }, - call: async function( joIn: any, fnAfter?: TFunctionCallResultHandler ) { + call: + async function( joIn: any, fnAfter?: TFunctionCallResultHandler ): Promise { const self = this; - const promiseComplete = new Promise < any >( function( resolve, reject ) { + const promiseComplete = new Promise < any >( function( resolve, reject ): void { self.reconnectIfNeeded( - async function( joCall: TRPCCall, err: Error | string | null ) { + async function( joCall: TRPCCall, err: Error | string | null ): Promise { if( err ) { if( fnAfter ) await fnAfter( joIn, null, err ); @@ -457,7 +461,9 @@ export async function rpcCallCreate( return; } await doCall( joCall, joIn, - async function( joIn: any, joOut: any, err: Error | string | null ) { + async function( + joIn: any, joOut: any, err: Error | string | null + ): Promise { if( fnAfter ) await fnAfter( joIn, joOut, err ); if( err ) @@ -475,7 +481,8 @@ export async function rpcCallCreate( "{url} JSON RPC call(awaiter) error: {err}", strURL, err ); } ); }, - disconnect: async function( fnAfter?: TFunctionConnectionResultHandler ) { + disconnect: + async function( fnAfter?: TFunctionConnectionResultHandler ): Promise { await doDisconnect( joCall, fnAfter ); } }; @@ -595,16 +602,17 @@ export async function checkTcpPromise( `default TCP connection to ${strHost}:${nPort} timeout...` ); } } - conn.on( "timeout", function( err: Error | string | null ) { - if( isLog ) { - console.log( - `${gStrTcpConnectionHeader}TCP connection ` + + conn.on( "timeout", + function( err: Error | string | null ): void { + if( isLog ) { + console.log( + `${gStrTcpConnectionHeader}TCP connection ` + `to ${strHost}:${nPort} timed out` ); - } - conn.destroy(); - reject( err ); - } ); - conn.on( "error", function( err: Error | string ) { + } + conn.destroy(); + reject( err ); + } ); + conn.on( "error", function( err: Error | string ): void { if( isLog ) { console.log( `${gStrTcpConnectionHeader}TCP connection ` + diff --git a/src/socket.ts b/src/socket.ts index f51d01e5..5115d233 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -464,7 +464,7 @@ export const outOfWorkerAPIs: any = { } }; export const inWorkerAPIs: any = { - onMessage: function( data: any ) { + onMessage: function( data: any ): boolean { const jo: any = socketReceivedDataReverseMarshall( data ); if( !( "workerMessageType" in jo ) || typeof jo.workerMessageType !== "string" || @@ -492,7 +492,7 @@ export const inWorkerAPIs: any = { return false; // TO-DO: send error answer and return true } // switch( jo.workerMessageType ) }, - onSendMessage: function( type: any, endpoint: any, workerUUID: any, data: any ) { + onSendMessage: function( type: any, endpoint: any, workerUUID: any, data: any ): void { const jo: any = socketReceivedDataReverseMarshall( data ); const joSend: any = { workerMessageType: @@ -753,7 +753,7 @@ export class OutOfWorkerRelay extends EventDispatcher { self.acceptor = acceptor; self.fnCreateClient = fnCreateClient; // eslint-disable-next-line max-lines-per-function - self.onConnection_ = function( eventData: any ) { + self.onConnection_ = function( eventData: any ): void { const pipeIncoming: any = eventData.socket; let pipeOutgoing: any = null; if( ( !( "remoteAddress" in eventData ) ) || @@ -810,7 +810,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onExternalPipeError: any = function( eventData: any ) { + let _onExternalPipeError: any = function( eventData: any ): void { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + "\" external-client socket error \"" + @@ -828,7 +828,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onRelayPipeError: any = function( eventData: any ) { + let _onRelayPipeError: any = function( eventData: any ): void { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + "\" relay-client socket error \"" + @@ -846,7 +846,7 @@ export class OutOfWorkerRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onExternalPipeMessage: any = function( eventData: any ) { + let _onExternalPipeMessage: any = function( eventData: any ): void { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" external-client socket \"" + eventData.strSavedRemoteAddress + "\" raw message", eventData ); @@ -872,7 +872,7 @@ export class OutOfWorkerRelay extends EventDispatcher { if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); }; - let _onRelayPipeMessage: any = function( eventData: any ) { + let _onRelayPipeMessage: any = function( eventData: any ): void { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" relay-client socket \"" + eventData.strSavedRemoteAddress + "\" raw message", eventData ); @@ -1032,7 +1032,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onIncomingPipeError: any = function( eventData: any ) { + let _onIncomingPipeError: any = function( eventData: any ): void { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + @@ -1055,7 +1055,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onOutgoingPipeError: any = function( eventData: any ) { + let _onOutgoingPipeError: any = function( eventData: any ): void { if( settings.logging.net.relay.error ) { console.warn( "Relay client \"" + self.strRelayName + @@ -1078,7 +1078,7 @@ export class OneToOneRelay extends EventDispatcher { _offAllPipeEventListeners = null; } }; - let _onIncomingPipeMessage: any = function( eventData: any ) { + let _onIncomingPipeMessage: any = function( eventData: any ): void { if( settings.logging.net.relay.rawMessage ) { console.log( "Relay \"" + self.strRelayName + "\" incoming-client socket \"" + @@ -1111,7 +1111,7 @@ export class OneToOneRelay extends EventDispatcher { if( self.isAutoFlushIncoming ) pipeOutgoing.flush(); }; - let _onOutgoingPipeMessage: any = function( eventData: any ) { + let _onOutgoingPipeMessage: any = function( eventData: any ): void { if( settings.logging.net.relay.rawMessage ) { console.log( `Relay ${self.strRelayName}` + "\" outgoing-client socket \"" + @@ -1551,7 +1551,7 @@ export class WebSocketServerAcceptor extends BasicServerAcceptor { this.wsServer = new wsModule.WebSocketServer( { port: nTcpPort } ); const self = this; - self.wsServer.on( "connection", function( wsConnection: any, req: any ) { + self.wsServer.on( "connection", function( wsConnection: any, req: any ): void { wsConnection.strSavedRemoteAddress = req?.connection?.remoteAddress?.toString(); wsConnection.serverPipe = new WebSocketServerPipe( self, wsConnection, req.connection.remoteAddress ); @@ -1650,21 +1650,21 @@ export class WebSocketClientPipe extends BasicSocketPipe { new UniversalDispatcherEvent( "open", { socket: self } ) ); }; - this._onWsClose = function( event: any ) { + this._onWsClose = function( event: any ): void { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self, message: event } ) ); }; - this._onWsError = function( event: any ) { + this._onWsError = function( event: any ): void { // alert( JSON.stringify( event ) ); self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: self, message: event } ) ); }; - this._onWsMessage = function( event: any ) { + this._onWsMessage = function( event: any ): void { self.receive( event.data ); }; this._removeWsEventListeners = function(): void { @@ -2119,13 +2119,19 @@ export class RTCActor extends RTCConnection { "signalingWillStart", { detail: { actor: this } } ) ); self.signalingPipe = new WebSocketClientPipe( self.strSignalingServerURL ); self.signalingPipe.on( - "open", function( eventData: any ) { self.signalingPipeOnOpen( eventData ); } ); + "open", function( eventData: any ): void { + self.signalingPipeOnOpen( eventData ); + } ); self.signalingPipe.on( - "close", function( eventData: any ) { self.signalingPipeOnClose( eventData ); } ); + "close", function( eventData: any ): void { + self.signalingPipeOnClose( eventData ); + } ); self.signalingPipe.on( - "error", function( eventData: any ) { self.signalingPipeOnError( eventData ); } ); + "error", function( eventData: any ): void { + self.signalingPipeOnError( eventData ); + } ); self.signalingPipe.on( - "message", function( eventData: any ) { + "message", function( eventData: any ): void { self.signalingPipeOnRawMessage( eventData ); } ); self.dispatchEvent( @@ -2395,13 +2401,13 @@ export class RTCServerPeer extends RTCConnection { self.pc.createDataChannel( settings.net.rtc.dataChannel.label, settings.net.rtc.dataChannel.opts ); self.dc.addEventListener( - "open", function( event: any ) { self.onDataChannelOpen( event ); } ); + "open", function( event: any ): void { self.onDataChannelOpen( event ); } ); self.dc.addEventListener( - "close", function( event: any ) { self.onDataChannelClose( event ); } ); + "close", function( event: any ): void { self.onDataChannelClose( event ); } ); self.dc.addEventListener( - "error", function( event: any ) { self.onDataChannelError( event ); } ); + "error", function( event: any ): void { self.onDataChannelError( event ); } ); self.dc.addEventListener( - "message", function( event: any ) { self.onDataChannelMessage( event ); } ); + "message", function( event: any ): void { self.onDataChannelMessage( event ); } ); } } @@ -2463,15 +2469,15 @@ export class RTCServerPeer extends RTCConnection { new UniversalDispatcherEvent( "publishStart", { detail: { participant: self } } ) ); self.pc.oniceconnectionstatechange = - function( event: any ) { self.onIceConnectionStateChange( event ); }; + function( event: any ): void { self.onIceConnectionStateChange( event ); }; self.pc.onicegatheringstatechange = - function( event: any ) { self.onIceGatheringStateChange( event ); }; + function( event: any ): void { self.onIceGatheringStateChange( event ); }; self.pc.onidentityresult = - function( event: any ) { self.onIceIdentifyResult( event ); }; + function( event: any ): void { self.onIceIdentifyResult( event ); }; self.pc.onsignalingstatechange = - function( event: any ) { self.onIceSignalingStateChange( event ); }; + function( event: any ): void { self.onIceSignalingStateChange( event ); }; self.pc.onnegotiationneeded = - function( event: any ) { self.onIceNegotiationNeeded( event ); }; + function( event: any ): void { self.onIceNegotiationNeeded( event ); }; self.pc.createOffer( self.offerOptions ).then( function( offerDescription: any ) { // success @@ -2500,17 +2506,17 @@ export class RTCServerPeer extends RTCConnection { "localDescriptionSet", { detail: { participant: self } } ) ); - self.pc.onicecandidate = function( event: any ) { + self.pc.onicecandidate = function( event: any ): void { self.iceComplete = true; self.onIceComplete( event ); }; // onicecandidate - }, function( err: any ) { + }, function( err: any ): void { // error of setLocalDescription self.publishCancel(); self.signalingNegotiationCancel(); self.onError( "Failed to set local description: " + err ); } ); - }, function( err: any ) { + }, function( err: any ): void { self.publishCancel(); self.signalingNegotiationCancel(); // error of createOffer @@ -2831,7 +2837,7 @@ export class RTCCreator extends RTCActor { ); self.onOtherSideIdentified( idSomebodyOtherSide, idOffer ); // server peer got result - }, function( err: any ) { + }, function( err: any ): void { // error self.onError( "Failed to set remote description: " + err ); } ); @@ -2947,23 +2953,23 @@ export class RTCJoiner extends RTCActor { self.pc = new webRtcModule.RTCPeerConnection( self.peerConfiguration, self.peerAdditionalOptions ); - self.pc.addEventListener( "track", function( event: any ) { + self.pc.addEventListener( "track", function( event: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "trackAvailable", { detail: { participant: self, event } } ) ); } ); self.pc.oniceconnectionstatechange = - function( event: any ) { self.onIceConnectionStateChange( event ); }; + function( event: any ): void { self.onIceConnectionStateChange( event ); }; self.pc.onicegatheringstatechange = - function( event: any ) { self.onIceGatheringStateChange( event ); }; + function( event: any ): void { self.onIceGatheringStateChange( event ); }; self.pc.onidentityresult = - function( event: any ) { self.onIceIdentifyResult( event ); }; + function( event: any ): void { self.onIceIdentifyResult( event ); }; self.pc.onsignalingstatechange = - function( event: any ) { self.onIceSignalingStateChange( event ); }; + function( event: any ): void { self.onIceSignalingStateChange( event ); }; self.pc.onnegotiationneeded = - function( event: any ) { self.onIceNegotiationNeeded( event ); }; - self.pc.ondatachannel = function( event: any ) { + function( event: any ): void { self.onIceNegotiationNeeded( event ); }; + self.pc.ondatachannel = function( event: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "dataChannelAvailable", @@ -2973,18 +2979,18 @@ export class RTCJoiner extends RTCActor { self.dc = dataChannel; self.dc.addEventListener( "open", - function( event: any ) { self.onDataChannelOpen( event ); } ); + function( event: any ): void { self.onDataChannelOpen( event ); } ); self.dc.addEventListener( "close", - function( event: any ) { self.onDataChannelClose( event ); } ); + function( event: any ): void { self.onDataChannelClose( event ); } ); self.dc.addEventListener( "error", - function( event: any ) { self.onDataChannelError( event ); } ); + function( event: any ): void { self.onDataChannelError( event ); } ); self.dc.addEventListener( "message", - function( event: any ) { self.onDataChannelMessage( event ); } ); + function( event: any ): void { self.onDataChannelMessage( event ); } ); }; - self.pc.onicecandidate = function( event: any ) { + self.pc.onicecandidate = function( event: any ): void { self.iceComplete = true; self.onIceComplete( event ); try { @@ -3145,7 +3151,7 @@ export class RTCJoiner extends RTCActor { "remoteDescriptionSet", { detail: { participant: self } } ) ); self.pc.createAnswer( self.offerOptions ).then( - function( answerDescription: any ) { + function( answerDescription: any ): void { // success self.tsAnswerCreated = new Date(); if( settings.logging.net.signaling.answer ) { @@ -3173,7 +3179,7 @@ export class RTCJoiner extends RTCActor { self.onOtherSideIdentified( idSomebodyOtherSide, idOffer ); // client peer got result - }, function( err: any ) { + }, function( err: any ): void { // error of setLocalDescription self.onError( "Failed to set local description " + @@ -3181,13 +3187,13 @@ export class RTCJoiner extends RTCActor { idSomebodyOtherSide + "\"): " + err.toString() ); } ); - }, function( err: any ) { + }, function( err: any ): void { // error of createAnswer self.onError( "Failed to create answer (while fetching offer for \"" + idSomebodyOtherSide + "\"): " + err ); } ); - }, function( err: any ) { + }, function( err: any ): void { // error of setLocalDescription self.onError( "Failed to set remote description: (while fetching offer for \"" + @@ -3231,7 +3237,7 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); self.url = "rtc_server_pipe(" + self.clientNumber + ")://" + strSignalingServerURL; - self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { + self.rtcPeer.on( "dataChannelOpen", function( jo: any ): void { self.isConnected = true; self.acceptor.mapClients[self.clientPort.toString()] = self; self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) ); @@ -3240,25 +3246,25 @@ export class WebRTCServerPipe extends BasicSocketPipe { "connection", { socket: self, strSignalingServerURL: strSignalingServerURL.toString() } ) ); } ); - self.rtcPeer.on( "dataChannelMessage", function( jo: any ) { + self.rtcPeer.on( "dataChannelMessage", function( jo: any ): void { self.receive( jo.detail.data ); } ); - self.rtcPeer.on( "rtcParticipantError", function( jo: any ) { + self.rtcPeer.on( "rtcParticipantError", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: self, message: jo } ) ); } ); - self.rtcPeer.on( "dataChannelError", function( jo: any ) { + self.rtcPeer.on( "dataChannelError", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", { socket: self, message: jo } ) ); } ); - self.rtcPeer.on( "dataChannelClose", function( jo: any ) { + self.rtcPeer.on( "dataChannelClose", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); } ); - self.rtcPeer.on( "peerClose", function( jo: any ) { + self.rtcPeer.on( "peerClose", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); @@ -3373,20 +3379,20 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.signalingOptions ); this.isListening = true; const self = this; - this.rtcCreator.on( "signalingPassedImpersonation", function( eventData: any ) { + this.rtcCreator.on( "signalingPassedImpersonation", function( eventData: any ): void { self.updateAllPendingOffers(); self.dispatchEvent( new UniversalDispatcherEvent( "signalingPassedImpersonation", { detail: { acceptor: self } } ) ); } ); - this.rtcCreator.on( "signalingFailedImpersonation", function( eventData: any ) { + this.rtcCreator.on( "signalingFailedImpersonation", function( eventData: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "signalingFailedImpersonation", { detail: { acceptor: self } } ) ); } ); - this.rtcCreator.on( "error", function( eventData: any ) { + this.rtcCreator.on( "error", function( eventData: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3398,13 +3404,13 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { } } ) ); } ); - this.rtcCreator.on( "close", function( eventData: any ) { + this.rtcCreator.on( "close", function( eventData: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "close", { detail: { acceptor: self, eventData } } ) ); } ); - self.rtcCreator.on( "signalingPipeError", function( jo: any ) { + self.rtcCreator.on( "signalingPipeError", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( @@ -3435,7 +3441,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { this.timeToSignalingNegotiationMilliseconds, this.peerConfiguration, this.peerAdditionalOptions ); const self = this; - rtcPeer.on( "identified", function( event: any ) { + rtcPeer.on( "identified", function( event: any ): void { if( rtcPeer.isDisposing || rtcPeer.isDisposed ) return; if( settings.logging.net.signaling.generic ) { @@ -3450,7 +3456,7 @@ export class WebRTCServerAcceptor extends BasicServerAcceptor { new UniversalDispatcherEvent( "identified", { detail: { peer: rtcPeer } } ) ); self.updateAllPendingOffers(); } ); - rtcPeer.on( "localDescriptionSet", function( event: any ) { + rtcPeer.on( "localDescriptionSet", function( event: any ): void { self.dispatchEvent( new UniversalDispatcherEvent( "peerLocalDescriptionSet", @@ -3622,7 +3628,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { ); // client side self.strSignalingServerURL = utils.makeValidSignalingServerURL( strSignalingServerURL ); - self.rtcPeer.on( "identified", function( event: any ) { + self.rtcPeer.on( "identified", function( event: any ): void { if( settings.logging.net.signaling.generic ) { console.log( self.rtcPeer.describe() + " is now identified peer", @@ -3630,7 +3636,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { ); } } ); - self.rtcPeer.on( "dataChannelOpen", function( jo: any ) { + self.rtcPeer.on( "dataChannelOpen", function( jo: any ): void { self.isConnected = true; self.dispatchEvent( new UniversalDispatcherEvent( "open", { socket: self } ) @@ -3646,10 +3652,10 @@ export class WebRTCClientPipe extends BasicSocketPipe { self.rtcPeer.signalingPipeClose(); } } ); - self.rtcPeer.on( "dataChannelMessage", function( jo: any ) { + self.rtcPeer.on( "dataChannelMessage", function( jo: any ): void { self.receive( jo.detail.data ); } ); - self.rtcPeer.on( "rtcParticipantError", function( jo: any ) { + self.rtcPeer.on( "rtcParticipantError", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3660,7 +3666,7 @@ export class WebRTCClientPipe extends BasicSocketPipe { } ) ); } ); - self.rtcPeer.on( "dataChannelError", function( jo: any ) { + self.rtcPeer.on( "dataChannelError", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", @@ -3671,13 +3677,13 @@ export class WebRTCClientPipe extends BasicSocketPipe { } ) ); } ); - self.rtcPeer.on( "dataChannelClose", function( jo: any ) { + self.rtcPeer.on( "dataChannelClose", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "close", { socket: self, message: jo } ) ); } ); - self.rtcPeer.on( "signalingPipeError", function( jo: any ) { + self.rtcPeer.on( "signalingPipeError", function( jo: any ): void { self.isConnected = false; self.dispatchEvent( new UniversalDispatcherEvent( "error", diff --git a/src/socketServer.ts b/src/socketServer.ts index 4078854a..d5ea0e17 100644 --- a/src/socketServer.ts +++ b/src/socketServer.ts @@ -49,7 +49,7 @@ export class SocketServer extends EventDispatcher { self.isLogSocketErrors = true; self.isLogSocketTraffic = false; self.isLogSocketTrafficRaw = false; - acceptor.on( "connection", function( eventData: any ) { + acceptor.on( "connection", function( eventData: any ): void { const socket = eventData.socket; if( ( !( "remoteAddress" in eventData ) ) || eventData.remoteAddress == null || @@ -77,7 +77,7 @@ export class SocketServer extends EventDispatcher { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete self.mapAcceptedPipes[socket]; }; - let _onPipeError: any = function( eventData: any ) { + let _onPipeError: any = function( eventData: any ): void { if( self.isLogSocketErrors ) { self.log( log.fmtError( "Socket {url} error {err}", socket.strSavedRemoteAddress, eventData ) ); @@ -89,7 +89,7 @@ export class SocketServer extends EventDispatcher { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete self.mapAcceptedPipes[socket]; }; - let _onPipeMessage: any = function( eventData: any ) { + let _onPipeMessage: any = function( eventData: any ): void { if( self.isLogSocketTrafficRaw ) { self.log( log.fmtInformation( "Socket {url} did received {sunny} {}", socket.strSavedRemoteAddress, "raw-message", eventData ) ); From 5e57feb49a07dd4dd7ee4f8755aeff1f51af56ef Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 3 Jan 2024 14:04:48 +0000 Subject: [PATCH 49/53] ESLint rules simplifications --- src/bls.ts | 10 ++++----- src/cc.ts | 38 ++++++++++++++++++++----------- src/discoveryTools.ts | 3 ++- src/imaCore.ts | 4 ++-- src/imaTx.ts | 4 ++-- src/log.ts | 52 +++++++++++++++++++++++++++++++++++++++---- src/oracle.ts | 2 +- src/owaspUtils.ts | 10 ++++++--- src/pwa.ts | 15 +++++++------ src/socket.ts | 27 ++++++++++++---------- src/state.ts | 2 +- 11 files changed, 116 insertions(+), 51 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index 1c56972b..c42cccf6 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -1036,7 +1036,7 @@ async function prepareSignMessagesImpl( optsSignOperation.jarrMessages, null ); return false; } - optsSignOperation.nCountOfBlsPartsToCollect = 0 + optsSignOperation.nThreshold; + optsSignOperation.nCountOfBlsPartsToCollect = optsSignOperation.nThreshold; optsSignOperation.details.trace( "{p}Will BLS-collect {} from {} nodes, sequence ID is {}", optsSignOperation.strLogPrefix, optsSignOperation.nCountOfBlsPartsToCollect, optsSignOperation.jarrNodes.length, optsSignOperation.sequenceId ); @@ -1056,7 +1056,7 @@ async function gatherSigningCheckFinish( optsSignOperation.nCountOfBlsPartsToCollect, cntSuccess, optsSignOperation.joGatheringTracker.nCountErrors ); optsSignOperation.joGatheringTracker.nCountReceivedPrevious = - 0 + optsSignOperation.joGatheringTracker.nCountReceived; + owaspUtils.toInteger( optsSignOperation.joGatheringTracker.nCountReceived ); } if( cntSuccess < optsSignOperation.nCountOfBlsPartsToCollect ) return false; @@ -1412,7 +1412,7 @@ async function doSignProcessOneImpl( srcChainID: optsSignOperation.fromChainID.toString(), messages: optsSignOperation.jarrMessages, qa: { - skaledNumber: 0 + i, + skaledNumber: owaspUtils.toInteger( i ), "optsSignOperation.sequenceId": optsSignOperation.sequenceId, ts: log.generateTimestampString( null, false ) } @@ -1600,7 +1600,7 @@ async function prepareSignU256( optsSignU256: TSignU256Options ): Promise < bool optsSignU256.u256, null ); return false; } - optsSignU256.nCountOfBlsPartsToCollect = 0 + optsSignU256.nThreshold; + optsSignU256.nCountOfBlsPartsToCollect = optsSignU256.nThreshold; optsSignU256.details.trace( "{p}Will(optsSignU256.u256) collect {} from {} nodes", optsSignU256.strLogPrefix, optsSignU256.nCountOfBlsPartsToCollect, optsSignU256.jarrNodes.length ); @@ -1761,7 +1761,7 @@ async function gatherSigningCheckFinish256( optsSignU256.nCountOfBlsPartsToCollect, cntSuccess, optsSignU256.joGatheringTracker.nCountErrors ); optsSignU256.joGatheringTracker.nCountReceivedPrevious = - 0 + optsSignU256.joGatheringTracker.nCountReceived; + owaspUtils.toInteger( optsSignU256.joGatheringTracker.nCountReceived ); } if( cntSuccess < optsSignU256.nCountOfBlsPartsToCollect ) return false; diff --git a/src/cc.ts b/src/cc.ts index d4befdfa..29149b58 100644 --- a/src/cc.ts +++ b/src/cc.ts @@ -49,10 +49,9 @@ export function replaceAll( str: string, find: string, replace: string ): string return str.replace( new RegExp( find, "g" ), replace ); } -export function validateRadix( value?: any, radix?: any ): number { - value = ( value ? value.toString() : "10" ); - value = value.trim(); - radix = ( radix == null || radix == undefined ) +export function validateRadix( value: any, radix?: any ): boolean { + value = ( value ? value.toString() : "10" ).trim(); + radix = ( radix === null || radix === undefined ) ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) ? 16 : 10 ) @@ -60,10 +59,14 @@ export function validateRadix( value?: any, radix?: any ): number { return radix; } -export function validateInteger( value?: any, radix?: any ): boolean { +export function validateInteger( value: any, radix?: any ): boolean { try { - value = value ? value.toString().trim() : ""; - if( value.length < 1 ) + if( value === null || value === undefined ) + return false; + if( value === 0 || value === 0.0 ) + return true; + const s = value ? value.toString().trim() : ""; + if( s.length < 1 ) return false; radix = validateRadix( value, radix ); if( ( !isNaN( value ) ) && @@ -76,20 +79,27 @@ export function validateInteger( value?: any, radix?: any ): boolean { return false; } -export function toInteger( value?: any, radix?: any ): number { +export function toInteger( value: any, radix?: any ): number { try { + if( value === 0 || value === 0.0 || value === null || value === undefined ) + return 0; + value = ( value ? value.toString().trim() : "" ).trim(); radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) return NaN; - return parseInt( value, radix ); + return parseInt( value.toString().trim(), radix ); } catch ( err ) { } return 0; } -export function validateFloat( value?: any ): boolean { +export function validateFloat( value: any ): boolean { try { - const f = parseFloat( value ); + if( value === null || value === undefined ) + return false; + if( value === 0 || value === 0.0 ) + return true; + const f = parseFloat( value.toString().trim() ); if( isNaN( f ) ) return false; return true; @@ -98,9 +108,11 @@ export function validateFloat( value?: any ): boolean { return false; } -function toFloat( value?: any ): number { +export function toFloat( value: any ): number { try { - const f = parseFloat( value ); + if( value === 0 || value === 0.0 || value === null || value === undefined ) + return 0.0; + const f = parseFloat( value.toString().trim() ); return f; } catch ( err ) { } diff --git a/src/discoveryTools.ts b/src/discoveryTools.ts index b7c04af4..a37cfcae 100644 --- a/src/discoveryTools.ts +++ b/src/discoveryTools.ts @@ -28,6 +28,7 @@ import * as rpcCall from "./rpcCall.js"; import * as state from "./state.js"; import * as imaUtils from "./utils.js"; import * as threadInfo from "./threadInfo.js"; +import * as owaspUtils from "./owaspUtils.js"; export type TFunctionAfterDiscovery = ( err?: Error | string | null, @@ -450,7 +451,7 @@ function handleDiscoverSkaleImaInfoResult( async function discoverSChainWalkNodes( optsDiscover: TDiscoveryOptions ): Promise { optsDiscover.cntFailed = 0; for( let i = 0; i < optsDiscover.cntNodes; ++i ) { - const nCurrentNodeIdx = 0 + i; + const nCurrentNodeIdx = owaspUtils.toInteger( i ); const joNode = optsDiscover.jarrNodes[nCurrentNodeIdx]; const strNodeURL = imaUtils.composeSChainNodeUrl( joNode ); const strNodeDescColorized = log.fmtAttention( "#{}({url})", nCurrentNodeIdx, strNodeURL ); diff --git a/src/imaCore.ts b/src/imaCore.ts index ee27d980..bc698ddd 100644 --- a/src/imaCore.ts +++ b/src/imaCore.ts @@ -376,7 +376,7 @@ async function analyzeGatheredRecords( optsTransfer: TTransferOptions, r: any ): async function gatherMessages( optsTransfer: TTransferOptions ): Promise { optsTransfer.arrMessageCounters = []; optsTransfer.jarrMessages = []; - optsTransfer.nIdxCurrentMsgBlockStart = 0 + optsTransfer.nIdxCurrentMsg; + optsTransfer.nIdxCurrentMsgBlockStart = owaspUtils.toInteger( optsTransfer.nIdxCurrentMsg ); let r; optsTransfer.cntAccumulatedForBlock = 0; for( let idxInBlock = 0; // inner loop wil create block of transactions @@ -1044,7 +1044,7 @@ export async function doTransfer( joExtraSignOpts, transactionCustomizerDst, imaState: state.get(), - nTransferLoopCounter: 0 + gTransferLoopCounter, + nTransferLoopCounter: owaspUtils.toInteger( gTransferLoopCounter ), strTransferErrorCategoryName: "loop-" + strDirection, strGatheredDetailsName: "", details: log.globalStream(), diff --git a/src/imaTx.ts b/src/imaTx.ts index 5b1cabba..2820aa0f 100644 --- a/src/imaTx.ts +++ b/src/imaTx.ts @@ -646,9 +646,9 @@ export class TransactionCustomizer { gasMultiplier: any; constructor ( gasPriceMultiplier: any, gasMultiplier: any ) { this.gasPriceMultiplier = gasPriceMultiplier - ? ( 0.0 + gasPriceMultiplier ) + ? owaspUtils.toFloat( gasPriceMultiplier ) : null; // null means use current gasPrice or recommendedGasPrice - this.gasMultiplier = gasMultiplier ? ( 0.0 + gasMultiplier ) : 1.25; + this.gasMultiplier = gasMultiplier ? owaspUtils.toFloat( gasMultiplier ) : 1.25; } async computeGasPrice( diff --git a/src/log.ts b/src/log.ts index e48f104a..f100383f 100644 --- a/src/log.ts +++ b/src/log.ts @@ -94,6 +94,50 @@ const getDurationString = cc.getDurationString; export { safeURL, replaceAll, timestampHR, capitalizeFirstLetter, getDurationString }; +export function validateRadix( value: any, radix?: any ): boolean { + value = ( value ? value.toString() : "10" ).trim(); + radix = ( radix === null || radix === undefined ) + ? ( ( value.length > 2 && value[0] == "0" && ( value[1] == "x" || value[1] == "X" ) ) + ? 16 + : 10 ) + : parseInt( radix, 10 ); + return radix; +} + +export function validateInteger( value: any, radix?: any ): boolean { + try { + if( value === null || value === undefined ) + return false; + if( value === 0 || value === 0.0 ) + return true; + const s = value ? value.toString().trim() : ""; + if( s.length < 1 ) + return false; + radix = validateRadix( value, radix ); + if( ( !isNaN( value ) ) && + ( parseInt( value, radix ) == value || radix !== 10 ) && + ( !isNaN( parseInt( value, radix ) ) ) + ) + return true; + } catch ( err ) { + } + return false; +} + +export function toInteger( value: any, radix?: any ): number { + try { + if( value === 0 || value === 0.0 || value === null || value === undefined ) + return 0; + value = ( value ? value.toString().trim() : "" ).trim(); + radix = validateRadix( value, radix ); + if( !validateInteger( value, radix ) ) + return NaN; + return parseInt( value.toString().trim(), radix ); + } catch ( err ) { + } + return 0; +} + export function autoEnableColorizationFromCommandLineArgs(): void { cc.autoEnableFromCommandLineArgs(); } @@ -515,8 +559,8 @@ export function createFileOutput( const objEntry: TLogger = { id: gIdentifierAllocatorCounter++, strPath: strFilePath.toString(), - nMaxSizeBeforeRotation: 0 + ( nMaxSizeBeforeRotation ?? 0 ), - nMaxFilesCount: 0 + ( nMaxFilesCount ?? 0 ), + nMaxSizeBeforeRotation: cc.toInteger( nMaxSizeBeforeRotation ?? 0 ), + nMaxFilesCount: cc.toInteger( nMaxFilesCount ?? 0 ), objStream: null, haveOwnTimestamps: false, isPausedTimeStamps: false, @@ -567,7 +611,7 @@ export function createFileOutput( this.open(); return; } - let i = 0; const cnt = 0 + this.nMaxFilesCount; + let i = 0; const cnt = cc.toInteger( this.nMaxFilesCount ); for( i = 0; i < cnt; ++i ) { const j = this.nMaxFilesCount - i - 1; const strPath = @@ -1077,7 +1121,7 @@ export function exposeDetailsSet( isExpose: any ): void { } export function verboseGet(): number { - return 0 + gVerboseLevel; + return cc.toInteger( gVerboseLevel ); } export function verboseSet( vl?: any ): void { gVerboseLevel = parseInt( vl ); diff --git a/src/oracle.ts b/src/oracle.ts index 8bfdb0b4..99793704 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -56,7 +56,7 @@ export function findPowNumber( if( isVerbose ) details.debug( "source t={}, this is UTC timestamp", t ); for( ; i < gConstMaxPowResultLimit; ++i ) { - n = 0 + i; + n = owaspUtils.toInteger( i ); s = "{" + strRequestPart + ",\"time\":" + t + ",\"pow\":" + n + "}"; const hash = new Keccak( 256 ); diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index 8401c3c9..c811032d 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -100,6 +100,8 @@ export function validateRadix( value: any, radix?: any ): boolean { export function validateInteger( value: any, radix?: any ): boolean { try { + if( value === null || value === undefined ) + return false; if( value === 0 || value === 0.0 ) return true; const s = value ? value.toString().trim() : ""; @@ -124,7 +126,7 @@ export function toInteger( value: any, radix?: any ): number { radix = validateRadix( value, radix ); if( !validateInteger( value, radix ) ) return NaN; - return parseInt( value, radix ); + return parseInt( value.toString().trim(), radix ); } catch ( err ) { } return 0; @@ -132,9 +134,11 @@ export function toInteger( value: any, radix?: any ): number { export function validateFloat( value: any ): boolean { try { + if( value === null || value === undefined ) + return false; if( value === 0 || value === 0.0 ) return true; - const f = parseFloat( value ); + const f = parseFloat( value.toString().trim() ); if( isNaN( f ) ) return false; return true; @@ -147,7 +151,7 @@ export function toFloat( value: any ): number { try { if( value === 0 || value === 0.0 || value === null || value === undefined ) return 0.0; - const f = parseFloat( value ); + const f = parseFloat( value.toString().trim() ); return f; } catch ( err ) { } diff --git a/src/pwa.ts b/src/pwa.ts index 18957a00..5355df0a 100644 --- a/src/pwa.ts +++ b/src/pwa.ts @@ -29,6 +29,7 @@ import * as imaBLS from "./bls.js"; import * as imaUtils from "./utils.js"; import type * as state from "./state.js"; import type * as discoveryTools from "./discoveryTools.js"; +import * as owaspUtils from "./owaspUtils.js"; function computeWalkNodeIndices( nNodeNumber: number, nNodesCount: number ): number[] { if( nNodeNumber === null || nNodeNumber === undefined || @@ -187,13 +188,13 @@ export async function handleLoopStateArrived( "signature is {}", se, nNodeNumber, joNode.pwaState, signature ); } const strMessageHash = imaBLS.keccak256ForPendingWorkAnalysis( - nNodeNumber, strLoopWorkType, isStart, 0 + ts ); + nNodeNumber, strLoopWorkType, isStart, owaspUtils.toInteger( ts ) ); const isSignatureOK = await imaBLS.doVerifyReadyHash( strMessageHash, nNodeNumber, signature, imaState.isPrintPWA ); if( !isSignatureOK ) throw new Error( "BLS verification failed" ); joProps.isInProgress = ( !!isStart ); - joProps.ts = 0 + ts; + joProps.ts = owaspUtils.toInteger( ts ); if( imaState.isPrintPWA ) { log.success( "PWA loop-{} state successfully verified for node {}, now have PWA state {}, " + @@ -232,9 +233,9 @@ async function notifyOnLoopImpl( throw new Error( "S-Chain network info is not available yet to PWA" ); const nUtcUnixTimeStamp = Math.floor( ( new Date() ).getTime() / 1000 ); - const strMessageHash = - imaBLS.keccak256ForPendingWorkAnalysis( - 0 + imaState.nNodeNumber, strLoopWorkType, isStart, nUtcUnixTimeStamp ); + const strMessageHash = imaBLS.keccak256ForPendingWorkAnalysis( + owaspUtils.toInteger( imaState.nNodeNumber ), + strLoopWorkType, isStart, nUtcUnixTimeStamp ); const signature = await imaBLS.doSignReadyHash( strMessageHash, imaState.isPrintPWA ); await handleLoopStateArrived( imaState, imaState.nNodeNumber, strLoopWorkType, @@ -262,9 +263,9 @@ async function notifyOnLoopImpl( const joIn: any = { method: "skale_imaNotifyLoopWork", params: { - nNodeNumber: 0 + imaState.nNodeNumber, + nNodeNumber: owaspUtils.toInteger( imaState.nNodeNumber ), strLoopWorkType: strLoopWorkType.toString(), - nIndexS2S: 0 + nIndexS2S, + nIndexS2S: owaspUtils.toInteger( nIndexS2S ), isStart: ( !!isStart ), ts: nUtcUnixTimeStamp, signature diff --git a/src/socket.ts b/src/socket.ts index 5115d233..f4b1ba14 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -26,6 +26,7 @@ import { UniversalDispatcherEvent, EventDispatcher } from "./eventDispatcher.js"; import { settings } from "./socketSettings.js"; import * as utils from "./socketUtils.js"; +import * as cc from "./cc.js"; export let httpsModule: any = null; // server side only export let wsModule: any = null; // server side only @@ -212,7 +213,8 @@ export class BasicSocketPipe extends EventDispatcher { this.url = "N/A"; this.isConnected = true; this.arrAccumulatedMessages = []; - this.maxAccumulatedMessagesCount = 0 + settings.net.pipe.maxAccumulatedMessagesCount; + this.maxAccumulatedMessagesCount = + cc.toInteger( settings.net.pipe.maxAccumulatedMessagesCount ); this.relayClientSocket = null; // for relay only this.mapImpersonatedEntries = { }; // for external in-app usage only } @@ -1295,7 +1297,7 @@ export class LocalSocketServerPipe extends DirectPipe { this.socketSubtype = "server"; this.isConnected = true; this.acceptor = acceptor; - this.clientPort = 0 + clientPort; + this.clientPort = cc.toInteger( clientPort ); this.url = "local_server_pipe://" + acceptor.strEndPoint + ":" + clientPort; this.acceptor.mapClients[clientPort.toString()] = this; const self = this; @@ -1379,11 +1381,12 @@ export class LocalSocketClientPipe extends DirectPipe { throw new Error( s ); } this.acceptor = gMapLocalServers[this.strEndPoint]; - this.clientPort = 0 + this.acceptor.nextClientPort; + this.clientPort = cc.toInteger( this.acceptor.nextClientPort ); ++this.acceptor.nextClientPort; this.url = "local_client_pipe://" + this.strEndPoint + ":" + this.clientPort; this.isConnected = true; - const serverPipe = new LocalSocketServerPipe( this, this.acceptor, 0 + this.clientPort ); + const serverPipe = + new LocalSocketServerPipe( this, this.acceptor, cc.toInteger( this.clientPort ) ); serverPipe.counterPipe = this; this.counterPipe = serverPipe; this.acceptor.mapClients[this.clientPort.toString()] = { @@ -1422,8 +1425,8 @@ export class WebSocketServerPipe extends BasicSocketPipe { const self = this; this.isConnected = true; this.acceptor = acceptor; - this.clientNumber = 0 + acceptor.nextClientNumber; - this.clientPort = 0 + this.clientNumber; + this.clientNumber = cc.toInteger( acceptor.nextClientNumber ); + this.clientPort = cc.toInteger( this.clientNumber ); ++acceptor.nextClientNumber; this.wsConnection = wsConnection; this.remoteAddress = "" + remoteAddress; @@ -2319,7 +2322,7 @@ export class RTCServerPeer extends RTCConnection { this.tsOfferCreated = null; if( settings.logging.net.signaling.offerRegister ) console.log( "Register offer", this.idOffer, "(RTCServerPeer constructor)" ); - this.rtcCreator.mapServerOffers[0 + this.idOffer] = this; + this.rtcCreator.mapServerOffers[cc.toInteger( this.idOffer )] = this; this.isPublishing = false; this.isSignalingNegotiation = false; this.isPublishTimeout = false; @@ -2584,7 +2587,7 @@ export class RTCServerPeer extends RTCConnection { method: "signalingPublishOffer", offer: self.pc.localDescription, idSomebodyCreator: self.rtcCreator.idRtcParticipant.toString(), - idOffer: 0 + ( self.idOffer || 0 ) + idOffer: cc.toInteger( self.idOffer ?? 0 ) }; if( settings.logging.net.signaling.message ) { console.log( @@ -2769,7 +2772,7 @@ export class RTCCreator extends RTCActor { case "signalingPublishAnswer": // server peer got result if( joMessage.error == null ) { const idSomebodyOtherSide = joMessage.idSomebody_joiner.toString(); - const idOffer = 0 + joMessage.idOffer; + const idOffer = cc.toInteger( joMessage.idOffer ); if( !( idOffer in this.mapServerOffers ) ) { const strError = "not a registered pending offer(signalingPublishAnswer)"; if( settings.logging.net.signaling.error ) { @@ -3113,7 +3116,7 @@ export class RTCJoiner extends RTCActor { this.delayedInitPeer(); this.idSomebodyCreator = joMessage.idSomebodyCreator.toString(); const idSomebodyOtherSide = joMessage.idSomebodyCreator.toString(); - const idOffer = 0 + joMessage.idOffer; + const idOffer = cc.toInteger( joMessage.idOffer ); if( settings.logging.net.signaling.generic ) { console.log( "Success, " + this.describe() + " fetched offer from creator (step 2)" @@ -3230,8 +3233,8 @@ export class WebRTCServerPipe extends BasicSocketPipe { self.socketSubtype = "server"; self.isConnected = true; self.acceptor = acceptor; - self.clientNumber = 0 + acceptor.nextClientNumber; - self.clientPort = 0 + ( self.clientNumber ?? 0 ); + self.clientNumber = cc.toInteger( acceptor.nextClientNumber ); + self.clientPort = cc.toInteger( self.clientNumber ?? 0 ); ++acceptor.nextClientNumber; self.rtcPeer = rtcPeer; self.strSignalingServerURL = diff --git a/src/state.ts b/src/state.ts index 39009665..6cbde66d 100644 --- a/src/state.ts +++ b/src/state.ts @@ -399,7 +399,7 @@ export function get(): TIMAState { isEnabledMultiCall: true, bNoWaitSChainStarted: false, - nMaxWaitSChainAttempts: 0 + Number.MAX_SAFE_INTEGER, // 20 + nMaxWaitSChainAttempts: Number.MAX_SAFE_INTEGER, // 20 nAmountOfWei: 0, nAmountOfToken: 0, From 1c71c4c81c761d709ff506c44715cbbd2f4d5dd3 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Wed, 3 Jan 2024 15:16:19 +0000 Subject: [PATCH 50/53] ESLint rules simplifications --- src/socket.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/socket.ts b/src/socket.ts index f4b1ba14..9b9ab60f 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -257,12 +257,8 @@ export class BasicSocketPipe extends EventDispatcher { } socketDescription(): string { - return "" + - // + this.socketType - // + " " - // + this.socketSubtype - // + " " - this.url; + // return this.socketType + " " + this.socketSubtype + " " + this.url.toString(); + return this.url.toString(); } socketLoggingTextPrefix( strLogEventName: string ): string { @@ -762,7 +758,7 @@ export class OutOfWorkerRelay extends EventDispatcher { eventData.remoteAddress == null || eventData.remoteAddress == undefined ) pipeIncoming.strSavedRemoteAddress = pipeIncoming.constructor.name; else - pipeIncoming.strSavedRemoteAddress = "" + eventData.remoteAddress; + pipeIncoming.strSavedRemoteAddress = eventData.remoteAddress.toString(); if( settings.logging.net.relay.connect ) { console.log( "Relay \"" + self.strRelayName + "\" got new external-client connection \"" + @@ -1429,7 +1425,7 @@ export class WebSocketServerPipe extends BasicSocketPipe { this.clientPort = cc.toInteger( this.clientNumber ); ++acceptor.nextClientNumber; this.wsConnection = wsConnection; - this.remoteAddress = "" + remoteAddress; + this.remoteAddress = remoteAddress.toString(); this.url = "ws_server_pipe(" + this.clientNumber + ")://" + remoteAddress; this._onWsClose = function(): void { self.dispatchEvent( From ac6de5557c71182622b46ccbc0ba650be3f227a0 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Fri, 5 Jan 2024 20:00:15 +0000 Subject: [PATCH 51/53] ESLint rules simplifications --- src/bls.ts | 4 ++-- src/cli.ts | 2 -- src/oracle.ts | 6 +++--- src/socket.ts | 3 +-- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/bls.ts b/src/bls.ts index c42cccf6..bc505cc5 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -42,7 +42,7 @@ import type * as IMA from "./imaCore.js"; export interface TQAInformation { skaledNumber: number - "optsSignOperation.sequenceId": string + sequenceId: string ts: string } @@ -1413,7 +1413,7 @@ async function doSignProcessOneImpl( messages: optsSignOperation.jarrMessages, qa: { skaledNumber: owaspUtils.toInteger( i ), - "optsSignOperation.sequenceId": optsSignOperation.sequenceId, + sequenceId: optsSignOperation.sequenceId, ts: log.generateTimestampString( null, false ) } }; diff --git a/src/cli.ts b/src/cli.ts index ce00c54f..3bdfa11c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -931,9 +931,7 @@ function parseTransferArgs( imaState: state.TIMAState, joArg: any ): boolean { } if( joArg.name == "node-number" ) { owaspUtils.verifyArgumentIsInteger( joArg ); - console.log( "------------------------ joArg.value ---", joArg.value ); imaState.nNodeNumber = owaspUtils.toInteger( joArg.value ); - console.log( "------------------------ imaState.nNodeNumber ---", imaState.nNodeNumber ); return true; } if( joArg.name == "nodes-count" ) { diff --git a/src/oracle.ts b/src/oracle.ts index 99793704..bee4ec22 100644 --- a/src/oracle.ts +++ b/src/oracle.ts @@ -38,9 +38,9 @@ const gBigNum2: any = owaspUtils.toBN( 2 ); const gBigNum256: any = owaspUtils.toBN( 256 ); const gBigNumUpperPart: any = gBigNum2.pow( gBigNum256 ).sub( gBigNum1 ); -function getUtcTimestampString( d?: Date ): string { - d = d ?? new Date(); // use now time if d is not specified - const nUtcUnixTimeStampWithMilliseconds = d.getTime(); +function getUtcTimestampString( aDate?: Date ): string { + aDate = aDate ?? new Date(); // use now time if aDate is not specified + const nUtcUnixTimeStampWithMilliseconds = aDate.getTime(); const t = nUtcUnixTimeStampWithMilliseconds.toString(); return t; } diff --git a/src/socket.ts b/src/socket.ts index 9b9ab60f..db5a731f 100644 --- a/src/socket.ts +++ b/src/socket.ts @@ -257,7 +257,6 @@ export class BasicSocketPipe extends EventDispatcher { } socketDescription(): string { - // return this.socketType + " " + this.socketSubtype + " " + this.url.toString(); return this.url.toString(); } @@ -739,7 +738,7 @@ export class OutOfWorkerRelay extends EventDispatcher { const self = this; self.strRelayName = strRelayName ? strRelayName.toString() : "unnamed"; self.isAutoFlushIncoming = isAutoFlushIncoming ? true : ( !!isAutoFlushIncoming ); - self.isAutoFlushOutgoing = isAutoFlushOutgoing ? true : ( !!( isAutoFlushOutgoing ) ); + self.isAutoFlushOutgoing = isAutoFlushOutgoing ? true : ( !!isAutoFlushOutgoing ); if( !acceptor ) { throw new Error( `OutOfWorkerRelay ${self.strRelayName} needs acceptor ` + "for normal functionality" ); From c526be33396d2e796a371e37bb80d9e6318e7bff Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Mon, 8 Jan 2024 13:40:04 +0000 Subject: [PATCH 52/53] BLS code cleanup --- IMA | 2 +- src/bls.ts | 108 ++++++++++++++++------------------------------------- 2 files changed, 33 insertions(+), 77 deletions(-) diff --git a/IMA b/IMA index 43f1a98a..97d1ded9 160000 --- a/IMA +++ b/IMA @@ -1 +1 @@ -Subproject commit 43f1a98a3480ddc0e82418e9355804ce82c98bc9 +Subproject commit 97d1ded9deceed549865dd58cb6173c6b290c35f diff --git a/src/bls.ts b/src/bls.ts index bc505cc5..4d7be1b7 100644 --- a/src/bls.ts +++ b/src/bls.ts @@ -316,17 +316,13 @@ function keccak256Message( const cnt = jarrMessages.length; for( let i = 0; i < cnt; ++i ) { const joMessage = jarrMessages[i]; - let bytesSender = imaUtils.hexToBytes( joMessage.sender.toString() ); bytesSender = imaUtils.bytesAlignLeftWithZeroes( bytesSender, 32 ); arrBytes = imaUtils.bytesConcat( arrBytes, bytesSender ); - - let bytesDestinationContract = - imaUtils.hexToBytes( joMessage.destinationContract ); + let bytesDestinationContract = imaUtils.hexToBytes( joMessage.destinationContract ); bytesDestinationContract = imaUtils.bytesAlignLeftWithZeroes( bytesDestinationContract, 32 ); arrBytes = imaUtils.bytesConcat( arrBytes, bytesDestinationContract ); - const bytesData = imaUtils.hexToBytes( joMessage.data ); arrBytes = imaUtils.bytesConcat( arrBytes, bytesData ); arrBytes = arrayToKeccak256( arrBytes ); @@ -336,13 +332,11 @@ function keccak256Message( export function keccak256U256( u256: any, isHash: boolean ): string { let arrBytes = new Uint8Array(); - let bytesU256 = imaUtils.hexToBytes( u256 ); bytesU256 = bytesU256.reverse(); bytesU256 = imaUtils.bytesAlignLeftWithZeroes( bytesU256, 32 ); bytesU256 = bytesU256.reverse(); arrBytes = imaUtils.bytesConcat( arrBytes, bytesU256 ); - let strMessageHash = ""; if( isHash ) { const hash = new Keccak( 256 ); @@ -419,17 +413,13 @@ function performBlsGlue( details.debug( "{p}Discovered number of BLS participants is {}.", strLogPrefix, nParticipants ); if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS glue", details ) ) return null; - const strMessageHash = - owaspUtils.removeStarting0x( - keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) - ); + const strMessageHash = owaspUtils.removeStarting0x( + keccak256Message( jarrMessages, nIdxCurrentMsgBlockStart, strFromChainName ) ); details.debug( "{p}Message hash to sign is {}", strLogPrefix, strMessageHash ); const strActionDir = allocBlsTmpActionDir(); details.trace( "{p}{sunny} will work in {} director with {} sign results...", strLogPrefix, "performBlsGlue", strActionDir, arrSignResults.length ); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; const strOutput = ""; try { let strInput = ""; @@ -508,8 +498,7 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); details.debug( "{p}Discovered BLS threshold is {}.", strLogPrefix, nThreshold ); details.debug( "{p}Discovered number of BLS participants is {}.", strLogPrefix, nParticipants ); - if( !checkBlsThresholdAndBlsParticipants( - nThreshold, nParticipants, "BLS glue-256", details ) ) + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS glue-256", details ) ) return null; details.trace( "{p}Original long message is {}", strLogPrefix, keccak256U256( u256, false ) ); const strMessageHash = keccak256U256( u256, true ); @@ -517,9 +506,7 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an const strActionDir = allocBlsTmpActionDir(); details.trace( "{p}performBlsGlueU256 will work in {} director with {} sign results...", strLogPrefix, strActionDir, arrSignResults.length ); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; try { let strInput = ""; @@ -557,9 +544,8 @@ function performBlsGlueU256( details: log.TLogger, u256: any, arrSignResults: an " --t " + nThreshold + " --n " + nParticipants; details.trace( "{p}Will execute HashG1 command: {}", strLogPrefix, strHasG1Command ); - strOutput = - childProcessModule.execSync( strHasG1Command, { cwd: strActionDir } ) - .toString( "utf8" ); + strOutput = childProcessModule.execSync( strHasG1Command, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}HashG1 output is:\n{raw}", strLogPrefix, strOutput || "<>" ); const joResultHashG1 = imaUtils.jsonFileLoad( path.join( strActionDir, "g1.json" ) ); details.trace( "{p}HashG1 result is: {}", strLogPrefix, joResultHashG1 ); @@ -605,13 +591,10 @@ function performBlsVerifyI( const strLogPrefix = `${strDirection}/BLS/#${nZeroBasedNodeIndex}: `; const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( !checkBlsThresholdAndBlsParticipants( - nThreshold, nParticipants, "BLS verify-I", details ) ) + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS verify-I", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; try { details.trace( "{p}BLS node #{} - first message nonce is {}", @@ -639,12 +622,10 @@ function performBlsVerifyI( " --n " + nParticipants + " --j " + nZeroBasedNodeIndex + " --input " + strSignResultFileName; - details.trace( "{p}Will execute node #{} BLS verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); - strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) - .toString( "utf8" ); + strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -677,9 +658,7 @@ function performBlsVerifyIU256( nThreshold, nParticipants, "BLS verify-I-U256", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; try { const joMsg = { message: keccak256U256( u256, true ) }; @@ -697,12 +676,10 @@ function performBlsVerifyIU256( " --n " + nParticipants + " --j " + nZeroBasedNodeIndex + " --input " + strSignResultFileName; - details.trace( "{p}Will execute node #{} BLS u256 verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); - strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) - .toString( "utf8" ); + strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS u256 node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS u256 node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -730,13 +707,10 @@ function performBlsVerify( throw new Error( "No own S-Chain network information" ); const nThreshold = discoverBlsThreshold( imaState.joSChainNetworkInfo ); const nParticipants = discoverBlsParticipants( imaState.joSChainNetworkInfo ); - if( !checkBlsThresholdAndBlsParticipants( - nThreshold, nParticipants, "BLS verify", details ) ) + if( !checkBlsThresholdAndBlsParticipants( nThreshold, nParticipants, "BLS verify", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; const strLogPrefix = `${strDirection}/BLS/Summary: "`; try { @@ -771,12 +745,10 @@ function performBlsVerify( " --t " + nThreshold + " --n " + nParticipants + " --input " + "./glue-result.json"; - details.trace( "{p}Will execute BLS/summary verify command: {}", strLogPrefix, strVerifyCommand ); - strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) - .toString( "utf8" ); + strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); details.success( "{p}BLS/summary verify success", strLogPrefix ); @@ -806,9 +778,7 @@ function performBlsVerifyU256( nThreshold, nParticipants, "BLS verify-U256", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; const strLogPrefix = "BLS u256/Summary: "; try { @@ -833,12 +803,10 @@ function performBlsVerifyU256( " --t " + nThreshold + " --n " + nParticipants + " --input " + "./glue-result.json"; - details.trace( "{p}Will execute BLS u256/summary verify command: {}", strLogPrefix, strVerifyCommand ); - strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) - .toString( "utf8" ); + strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS u256/summary verify output is:\n{raw}", strLogPrefix, strOutput || "<>" ); details.success( "{p}BLS u256/summary verify success", strLogPrefix ); @@ -1085,8 +1053,7 @@ async function gatherSigningCheckFinish( optsSignOperation.nIdxCurrentMsgBlockStart, optsSignOperation.strFromChainName, joCommonPublicKey ) ) { - strSuccessfulResultDescription = - "Got successful summary BLS verification result"; + strSuccessfulResultDescription = "Got successful summary BLS verification result"; optsSignOperation.details.success( "{p}{bright}", optsSignOperation.strLogPrefixB, strSuccessfulResultDescription ); } else { @@ -1482,10 +1449,9 @@ async function doSignMessagesImpl( nWaitIntervalStepMilliseconds: 500, nWaitIntervalMaxSteps: 10 * 60 * 3 // 10 is 1 second }; - optsSignOperation.details = - optsSignOperation.imaState.isDynamicLogInBlsSigner - ? log.globalStream() - : log.createMemoryStream(); + optsSignOperation.details = optsSignOperation.imaState.isDynamicLogInBlsSigner + ? log.globalStream() + : log.createMemoryStream(); optsSignOperation.strGatheredDetailsName = optsSignOperation.strDirection + "-" + "doSignMessagesImpl-#" + optsSignOperation.nTransferLoopCounter + "-" + optsSignOperation.strFromChainName + "-msg#" + @@ -1943,9 +1909,7 @@ export async function doVerifyReadyHash( nThreshold, nParticipants, "verify ready hash", details ) ) return false; const strActionDir = allocBlsTmpActionDir(); - const fnShellRestore = function(): void { - shell.rm( "-rf", strActionDir ); - }; + const fnShellRestore = function(): void { shell.rm( "-rf", strActionDir ); }; let strOutput = ""; try { const joPublicKey = discoverPublicKeyByIndex( @@ -1968,12 +1932,10 @@ export async function doVerifyReadyHash( " --n " + nParticipants + " --j " + nZeroBasedNodeIndex + " --input " + strSignResultFileName; - details.trace( "{p}Will execute node #{} BLS verify command: {}", strLogPrefix, nZeroBasedNodeIndex, strVerifyCommand ); - strOutput = - childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) - .toString( "utf8" ); + strOutput = childProcessModule.execSync( strVerifyCommand, { cwd: strActionDir } ) + .toString( "utf8" ); details.trace( "{p}BLS node #{} verify output is:\n{raw}", strLogPrefix, nZeroBasedNodeIndex, strOutput || "<>" ); details.success( "{p}BLS node #{} verify success", strLogPrefix, nZeroBasedNodeIndex ); @@ -2066,7 +2028,6 @@ export async function doSignReadyHash( }; } else details.warning( "Will sign via SGX without SSL options" ); - const signerIndex = imaState.nNodeNumber; joCall = await rpcCall.create( joAccount.strSgxURL, rpcCallOpts ); if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); @@ -2078,8 +2039,7 @@ export async function doSignReadyHash( keyShareName: joAccount.strBlsKeyName, messageHash: strMessageHash, n: nParticipants, - t: nThreshold, - signerIndex // 1-based + t: nThreshold } }; details.trace( "{p}Will invoke SGX with call data {}", strLogPrefix, joIn ); @@ -2305,7 +2265,6 @@ export async function handleSkaleImaVerifyAndSign( }; } else optsHandleVerifyAndSign.details.warning( "Will sign via SGX without SSL options" ); - const signerIndex = optsHandleVerifyAndSign.imaState.nNodeNumber; joCall = await rpcCall.create( joAccount.strSgxURL, rpcCallOpts ); if( !joCall ) throw new Error( `Failed to create JSON RPC call object to ${joAccount.strSgxURL}` ); @@ -2317,8 +2276,7 @@ export async function handleSkaleImaVerifyAndSign( keyShareName: joAccount.strBlsKeyName, messageHash: optsHandleVerifyAndSign.strMessageHash, n: optsHandleVerifyAndSign.nParticipants, - t: optsHandleVerifyAndSign.nThreshold, - signerIndex // 1-based + t: optsHandleVerifyAndSign.nThreshold } }; optsHandleVerifyAndSign.details.trace( @@ -2456,7 +2414,6 @@ export async function handleSkaleImaBSU256( }; } else optsBSU256.details.warning( "Will sign via SGX without SSL options" ); - const signerIndex = optsBSU256.imaState.nNodeNumber; joCall = await rpcCall.create( optsBSU256.joAccount.strSgxURL, rpcCallOpts ); if( !joCall ) { throw new Error( "Failed to create JSON RPC call object " + @@ -2470,8 +2427,7 @@ export async function handleSkaleImaBSU256( keyShareName: optsBSU256.joAccount.strBlsKeyName, messageHash: optsBSU256.strMessageHash, n: optsBSU256.nParticipants, - t: optsBSU256.nThreshold, - signerIndex // 1-based + t: optsBSU256.nThreshold } }; optsBSU256.details.trace( "{p}Will invoke SGX with call data {}", From 79e645c6b4ea718388d94667f5224251bcca7c75 Mon Sep 17 00:00:00 2001 From: Sergiy Lavrynenko Date: Mon, 8 Jan 2024 17:15:59 +0000 Subject: [PATCH 53/53] ESLint rules simplifications --- src/owaspUtils.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/owaspUtils.ts b/src/owaspUtils.ts index c811032d..38039064 100644 --- a/src/owaspUtils.ts +++ b/src/owaspUtils.ts @@ -764,14 +764,12 @@ export function toBN( arg: any ): any { multiplier = toBNbasic( -1, 10 ); } stringArg = stringArg === "" ? "0" : stringArg; - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - if( ( !stringArg.match( /^-?[0-9]+$/ ) && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) || - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - stringArg.match( /^[a-fA-F]+$/ ) || - ( isHexPrefixed && stringArg.match( /^[0-9A-Fa-f]+$/ ) ) ) + const isMatchN: boolean = !!stringArg.match( /^-?[0-9]+$/ ); + const isMatchX: boolean = !!stringArg.match( /^[0-9A-Fa-f]+$/ ); + const isMatchA: boolean = !!stringArg.match( /^[a-fA-F]+$/ ); + if( ( ( !isMatchN ) && isMatchX ) || isMatchA || ( isHexPrefixed && isMatchX ) ) return toBNbasic( stringArg, 16 ).mul( multiplier ); - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - if( ( stringArg.match( /^-?[0-9]+$/ ) || stringArg === "" ) && !isHexPrefixed ) + if( ( isMatchN || stringArg === "" ) && ( !isHexPrefixed ) ) return toBNbasic( stringArg, 10 ).mul( multiplier ); } else if( typeof arg === "object" && arg.toString && ( !arg.pop && !arg.push ) ) { if( arg.toString().match( /^-?[0-9]+$/ ) && ( arg.mul || arg.dividedToIntegerBy ) )